text:
Q: Graduated transition from Green - Yellow - Red I am having algorithm mental block in designing a way to transition from Green to Red, as smoothly as possible with a, potentially, unknown length of time to transition.
For testing purposes, I will be using 300 as my model timespan but the methodology algorithm design needs to be flexible enough to account for larger or even smaller timespans.
Figured using RGB would probably be the best to transition with, but open to other color creation types, assuming its native to.Net (VB/C#).
Currently I have:
t = 300
x = t/2
z = 0
low = Green (0, 255, 0)
mid = Yellow (255, 255, 0)
high = Red (255, 0, 0)

Lastly, sort of an optional piece, is to account for the possibility of the low, mid, and high color's to be flexible as well.  I assume that there would need to be a check to make sure that someone isn't putting in low = (255,0,0), mid=(254,0,0), and high=(253,0,0). Outside of this anomaly, which I will handle myself based on the best approach to evaluate a color.
Question:

*

*What would be the best approach to do the transition from low to mid and then from mid to high?

*What would be some potential pitfalls of implementing this type of design, if any?

A: While you can do the transition in RGB space (using component-wise linear interpolation), this might cause unnaturally-looking transitions; most noticably, the brightness and saturation may bump between control points. If it this is acceptable, just do it this way. Mapping the values through some sort of gamma function before interpolating and then reverting the gamma on the interpolated values may alleviate the bumps a bit.
If that's not good enough, convert your colors into a color space closer to how the human perception works, such as HSI (hue - saturation - intensity). Then apply the same interpolation, but do keep in mind that the hue component is circular, that is, if you have hues ranging from 0 to 100, and your input colors are at 95 and 5, you want to move forward and then wrap around (thus 95 up to 100 and then "jump" to 0, continuing up to 5) instead of going down from 95 to 5 - think of the hue axis as a circle along which you travel; your interpolation should take the shorter route along the circle's edge.
The HSI calculation is more expensive, because you have to convert the interpolated HSI value back to RGB for display on each frame, but it yields much better results, because the hue, brightness and saturation transition independently without causing perceived artifacts.

A: You can't really do it smoothly using the RGB color space, but it's easier when done with HSV.
See HSL and HSV
Using HSV space you can transition from Green to Yellow to Red along a single float value for Hue while keeping the saturation/value constant.


text:
Q: How to manage conflicting dev environments when building slack slash commands? I have a team of 3-4 people contributing to a slack app (built with Bolt) using slash commands.  The app basically boils down to the following:
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

# Get SLACK_APP_TOKEN and SLACK_BOT_TOKEN

app = App(token=SLACK_BOT_TOKEN)

@app.command("/the-bot")
def the_bot_slash_command(ack, body, client, respond):
    ack()

    if body["text"] == "foo":
        do_foo()
    else:
        respond("HELP TEXT HERE")

slack = SocketModeHandler(app, SLACK_APP_TOKEN)

We have a free slack workspace to test in, and each dev has set up their own version of the app.  The problem is that now we have 3-4 people each running a different bot but with the same slash command.  and according to the docs:

Multiple commands may occupy the same name. If it happens and a user tries to invoke the command, Slack will always invoke the one that was installed most recently.

So: is there a correct "The Slack Way" structure to allow individual devs to do dev work on the same slash command?
Obviously I don't want to just have devs running a unique command that they just have to remember not to accidentally commit.  The best I've got so far is making @app.command("/the-bot") something more like @app.command(SLASH_COMMAND) and pulling SLASH_COMMAND out of an env variable, allowing individual devs to set their personal test slash command?

A: Unfortunately not. The best option you have is to all set up your own workspaces, or use different slash commands in your staging applications. It's a pain that Slack doesn't make this available via an environment variable in your app, so all this needs to be configured on the api.slack.com site.
A way of doing this might be to request a free testing enterprise grid instance, and then set up numbered workspaces inside of it. This might also help you understand problems with your app that would only occur in an enterprise context, should you want to develop there in the future.
Another, significantly more hacky way, of handling this might be to create a forwarding application that listens for invocations of the slash command, and then forwards the event to the correct staging environment based on some characteristic of the message (eg. what channel it is invoked in).

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript work queue I've created this object which contains an array, which serves as a work queue.
It kind of works like this:
var work1 = new Work();
var work2 = new Work();
var queue = Workqueue.instance();

queue.add(work1) // Bluebird promise.
.then(function addWork2() {
  return queue.add(work2);
})
.then(function toCommit() {
  return queue.commit();
})
.then(function done(results) {
  // obtain results here.
})
.catch(function(err){});

It works in that case and I can commit more than one task before I call the commit.
However if it's like this:
var work1 = new Work();
var work2 = new Work();
var queue = Workqueue.instance();

queue.add(work1)
.then(function toCommit1() {
  return queue.commit();
})
.then(function done1(result1) {
  // obtain result1 here.
})
.catch(function(err){});

queue.add(work2)
.then(function toCommit2() {
  return queue.commit();
})
.then(function done2(result2) {
  // obtain result2 here.
})
.catch(function(err){});

Something may go wrong, because if the first commit is called after the second commit (two works/tasks are already added), the first commit handler expects a result but they all go to the second commit handler.
The task involves Web SQL database read and may also involves network access. So it's basically a complicated procedure so the above described problem may surface. If only I can have a addWorkAndCommit() implemented which wraps the add and commit together, but still there is no guarantee because addWorkAndCommit() cannot be "atomic" in a sense because they involves asynchronous calls. So even two calls to addWorkAndCommit() may fail. (I don't know how to describe it other than by "atomic", since JavaScript is single-threaded, but this issue crops up).
What can I do?

A: The problem is that there is a commit() but no notion of a transaction, so you cannot explicitly have two isolated transactions running in parallel. From my understanding the Javascript Workqueue is a proxy for a remote queue and the calls to add() and commit() map directly to some kind of remote procedure calls having a similar interface without transactions. I also understand that you would not care if the second add() actually happened after the first commit(), you just want to write two simple subsequent addWorkAndCommit() statements without synchronizing the underlying calls in client code.
What you can do is write a wrapper around the local Workqueue (or alter it directly if it is your code), so that each update of the queue creates a new transaction and a commit() always refers to one such transaction. The wrapper then delays new updates until all previous transactions are committed (or rolled back).

A: Adopting Benjamin Gruenbaum's recommendation to use a disposer pattern, here is one, written as an adapter method for Workqueue.instance() :
Workqueue.transaction = function (work) { // `work` is a function
    var queue = this.instance();
    return Promise.resolve(work(queue)) // `Promise.resolve()` avoids an error if `work()` doesn't return a promise.
    .then(function() {
        return queue.commit();
    });
}

Now you can write :
// if the order mattters,
// then add promises sequentially.
Workqueue.transaction(function(queue) {
    var work1 = new Work();
    var work2 = new Work();
    return queue.add(work1)
    .then(function() {
        return queue.add(work2);
    });
});
// if the order doesn't mattter,
// add promises in parallel.
Workqueue.transaction(function(queue) {
    var work1 = new Work();
    var work2 = new Work();
    var promise1 = queue.add(work1);
    var promise2 = queue.add(work2);
    return Promise.all(promise1, promise2);
});
// you can even pass `queue` around
Workqueue.transaction(function(queue) {
    var work1 = new Work();
    var promise1 = queue.add(work1);
    var promise2 = myCleverObject.doLotsOfAsyncStuff(queue);
    return Promise.all(promise1, promise2);
});

In practice, an error handler should be included like this - Workqueue.transaction(function() {...}).catch(errorHandler);
Whatever you write, all you need to do is ensure that the callback function returns a promise that is an aggregate of all the component asynchronisms (component promises). When the aggregate promise resolves, the disposer will ensure that the transaction is committed.
As with all disposers, this one doesn't do anything you can't do without it. However it :

*

*serves as a reminder of what you are doing by providing a named .transaction() method,

*enforces the notion of a single transaction by constraining a Workqueue.instance() to one commit.

If for any reason you should ever need to do two or more commits on the same queue (why?), then you can always revert to calling Workqueue.instance() directly.


text:
Q: Add JSON class folder and import in Java and Eclipse as IDE I'm new to Java and have searched for quite a time now on the internet to a solution to my problem. I'm trying to add the JSON classes folder to my web app. The folder for JSON classes can be retrieved from this link: http://www.json.org/java/. What I did is copied the folder to my WEB-INF/lib folder and added that folder to my classpath by rightclick on Libraries -> Build Path -> Configure Build Path -> Add Class Folder. Ok so far so good! Btw, is this the right procedure for adding class folders? But what shall I type in a new Java class?
I have tried import JSONArray, but it is not working. Could you please give the right syntax for importing the JSON classes?

A: You need to use the fully-qualified class name, which includes the package:
import org.json.JSONArray;

(And yes, that is the correct way to add classes/jars to your project's classpath in Eclipse.)

A: If you wana to use servlets in tomcat you also have to copy the org.json.jar to lib in tomcat folder. If not eclipse will not give you any error but tomcat will.


text:
Q: Heron's Method: prove convergence in $\mathbb{Q}$. Let $x,y\in\mathbb{Q}$ with $x>0,y>0$ and $f:\mathbb{N}\rightarrow\mathbb{Q}$ where $f(0)=1$ and $f(n+1)=\frac{1}{2}\left(f(n)+\frac{4}{f(n)}\right)$. I want to show that f converges in $\mathbb{Q}$.
For this, I used that $f(n)>0\; \forall n\in\mathbb{N}$, which implies $f(n)\geq 2$ for all $n\neq 0$ and further $f(n)^2\geq 4$ for all $n\neq 0$. Using this I showed that f is monotonically decreasing. So in $\mathbb{R}$ the limit exists (because the sequence is bounded). By using that $\lim_{n\mapsto \infty} f(n+1)=\lim_{n\mapsto \infty} f(n)$ i got an equation which I then solved for the limit.
Long story short: How can I prove that $f$ converges in $\mathbb{Q}$ (and what the limit was) without using anything that has to do with $\mathbb{R}$?
My idea for proving that $f$ converges is, to show that f is a cauchy-sequence (in $\mathbb{Q})$. Can anyone assist in finding a way to do so? I am stuck...
Thanks!


text:
Q: Alfresco: Get list of nodes with updated ACL/permission I am exploring Alfresco Web scripts and CMIS API's, and looking for an API or some way to figure out the nodes whose ACL/permission is modified after some specified time/timestamp in Alfresco.
I am able to get nodes with modified metadata using CMIS QUERY API, but regarding only ACL/permission modification its not working.
For now, I am crawling all nodes and checking its modification date with respect to earlier/last crawl datetime. This doesn't seem to be a proper approach.
For more details, here is the link of query posted earlier on alfresco forum:Fetch the list of nodes whose permission is updated/modified
Could anyone please assist.

A: I have figured out the solution, using CMISChangeLog application, which need to be enabled on Alfresco server. Also, with the help of CMIS 1.1 Atom Api's, the CMIS change log query works fine on both the Alfresco version, 4.x and 5.x.


text:
Q: Is it possible to move OEM Office to another hard drive by copying the OS using Acronis or similar? I have run out of space on my current hard drive and purchased a new larger drive.  My old OS has an OEM install of Office 2013.  If I use Acronis or a similar disk copying tool to move the OS to the larger drive, will my copy of Office still be licensed?
I cannot re-activate Office. The key was only good for a single activation.

A: You should not need to re-activate. I use a tool called Partition Magic all the time. I connect the two drives via USB to another computer and run the wizard. The activations with Windows and other microsoft products are usually tied to an HAL file which is a hardware identifier. Basically this won't change for a hard drive swap. It will kick in if you try to take your hard drive and plug it into another computer since the hardware obviously changed.


text:
Q: Database and OOP Practices in PHP Its difficult to explain this situation but please see the example.
I have coded a website where the page loads, I initialize a database class. I sent this class as a function parameter to any functions that needs to access database.
I know this is bad approach but currently I have no clue how to do this any other way. Can you please help me.
Example
class sms {

    function log_sms($message, $db) {

        $sql = "INSERT INTO `smslog` SET
            `mesasge` = '$message'
            ";
        $db->query($sql);

        if ($db->result)
            return true;
        return false;
    }

}

then on the main page..
$db = new db(username,pass,localhost,dbname);

$sms = new sms;

$sms->log_sms($message, $db);

Is there any better approach than this ?

A: there are number of options how to resolve dependencies problem (object A requires object B):
constructor injection
  class Sms {
        function __construct($db) ....
  }

  $sms = new Sms (new MyDbClass);

setter injection
  class Sms {
        protected $db;
  }
  $sms = new Sms;
  $sms->db = new MyDbClass;

'registry' pattern
 class Registry {
     static function get_db() {
          return new MyDbClass;
 }}

 class Sms {
      function doSomething() {
          $db = Registry::get_db();
          $db->....
  }}

'service locator' pattern
 class Loader {
     function get_db() {
          return new MyDbClass;
 }}

 class Sms {
      function __construct($loader) {
         $this->loader = $loader;

      function doSomething() {
          $db = $this->loader->get_db();
          $db->....
  }}

  $sms = new Sms(new Loader);

automated container-based dependency injection, see for example http://www.sitepoint.com/blogs/2009/05/11/bucket-is-a-minimal-dependency-injection-container-for-php
   interface DataSource {...}
   class MyDb implements DataSource {...}

    class Sms {
        function __construct(DataSource $ds) ....

    $di = new Dependecy_Container;
    $di->register('DataSource', 'MyDb');
    $sms = $di->get('Sms');

to name a few ;)
also the Fowler's article i gave you before is really worth reading

A: For starters you can make a protected $db variable in each of your classes that need to utilize the database.  You could then pass $db in to the class constructor.  Here's the updated code:
$db = new db(username,pass,localhost,dbname);
$sms = new sms($db);
$sms->log_sms($message);

class sms {

    protected $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function log_sms($message) {
        $sql = "INSERT INTO `smslog` SET
                `mesasge` = '$message'
                ";
        $this->db->query($sql);

        if ($this->db->result)
                return true;
        return false;
    }
}

This example is in PHP 5.

A: Singleton is also good practice in application design. They are very useful to avoid repeated queries or calculations during one call.
Passing Database object to every method or constructor is not a very good idea, use Singleton instead.
extend your database, or insert static method inside your db class. (I would also call for config within db constructor method)
class database extends db
{
    public static function instance()
    {
        static $object;

        if(!isset($object))
        {
            global $config;

            $object = new db($config['username'],$config['pass'],$config['localhost'],['dbname']);
        }

        return $object;
    }
}

make your method static
class sms {

    public static function log($message) {

        $sql = "INSERT INTO `smslog` SET `mesasge` = '$message'";

        database::instance()->query($sql);

        return (bool) database::instance()->result;
    }
}

Next time you need to log sms just do static call like this
sms::log($message);

A: You could either have a static class that has two lists, one of available connections, the other of handed out connections, and just have a connection pool.
Or, if you are using something that has a quick connection time, such as MySQL, then just create the connection in your database class, do all the queries needed for that functionality, then close it. This is my preferred approach.


text:
Q: Focus Edit Text Programmatically (Kotlin) I have a createEditText function that creates an EditText and adds it to the view. My issue is that once it is added to the view, the user has to tap the EditText in order for the keyboard to be called and editing to work. What I am trying to do is to have it so that once the EditText is created, the user is automatically taken to the edit mode.
In IOS programming, there is a function called becomeFirstResponder() which achieves this. What would the android equivalent be?
Things I have tried:
myEditText.requestFocus()
myEditText.isActivated
myEditText.isFocused
myEditText.isSelected
myEditText.isEnabled

A: Unfortunately it is not enough to call only EditText#requestFocus. In addition to this you also have to call the InputMethodManager#showSoftInput. Following utility method should work:
fun openSoftKeyboard(context: Context, view: View) {
    view.requestFocus()
    // open the soft keyboard
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

A: This is just an idea (a bit pseudo-code just to clarify things):
myEditText.requestFocus()
(activity or dialog).window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

You must take care of not showing the soft keyboard if there is a hardware keyboard connected

A: Add <requestFocus /> in your your EditText view in xml file of layout.


text:
Q: Modelling work-flow plus interaction with a database - quick and accessible options I'm wanting to model a (proposed) manufacturing line, with specific emphasis on interaction with a traceability database. That is, various process engineers have already mapped the manufacturing process - I'm only interested in the various stations along the line that have to talk to the DB.
The intended audience is a mixture of project managers, engineers and IT people - the purpose is to identify:

*

*points at which the line interacts with the DB (perhaps going so far as indicating the Store Procs called at each point, perhaps even which parameters are passed.)

*the communication source (PC/Handheld device/PLC)

*the communication medium (wireless/fibre/copper)

*control flow (if leak test fails, unit is diverted to repair station)

Basically, the model will be used as a focus different groups on outstanding tasks; for example, I'm interested in the DB and any front-end app needed, process engineers need to be thinking about the workflow and liaising with the PLC suppliers, the other IT guys need to make sure we have the hardware and comms in place.
Obviously I could just improvise in Visio, but I was wondering if there was a particular modelling technique that might particularly suit my needs or my audience. I'm thinking of a visual model with supporting documentation (as little as possible, as much as is necessary).
Clearly, I don't want something that will take me ages to (effectively) learn, nor one that will alienate non-technical members of the project team.
So far I've had brief looks at BPMN, EPC Diagrams, standard Flow Diagrams... and I've forgotten most of what I used to know about UML... And I'm not against picking and mixing... as long as it is quick, clear and effective.
Conclusion:
In the end, I opted for a quasi-workflow/dataflow diagram. I mapped out the parts of the manufacturing process that interact with the traceability DB, and indicated in a significantly-simplified form, the data flows and DB activity. Alongside which, I have a supporting document which outlines each process, the data being transacted for each process (a 'data dictionary' of sorts) and details of hardware and connectivity required.
I can't decide whether is a product of genius or a crime against established software development practices, but I do think that is will hit the mark for this particular audience.

A: It will be difficult to produce one diagram of sufficient detail to satisfy managers, engineers, and IT people. The IT people will want to know the sproc parameters, the engineers will be concerned about fault cases, and the managers will get bored by all the details and start fiddling with their Blackberrys.
What is the point of the presentation? You said -
 the model will be used as a focus different groups on outstanding tasks; for example, I'm interested in the DB and any front-end app needed, process engineers need to be thinking about the workflow and liaising with the PLC suppliers, the other IT guys need to make sure we have the hardware and comms in place.
First, think of the presentation as a map, not a project plan. Make it simple enough that the managers can understand it, and you can be certain that the engineers and IT people will also understand it. (The converse is not true.)
Second, use the simplest, most obvious diagram possible. Annotate the diagram with footnotes for the details so the diagram does not become cluttered or grow too large.
I'm assuming that the purpose of the initial presentation is to achieve a common group comprehension of the overall project. To that end, I suggest using pictures of each component with lightning-bolt lines to indicate points of DB interaction (don't clutter the diagram with a bunch of DB icons, or try to tie all the interaction lines back to one DB icon, that will clutter the diagram and add no value). Just put a footnote number on each interaction line, and print the footnotes on a separate page for reference. Do not display the footnotes on your presentation slides, but just talk about them and refer to the diagram. Make the footnotes available as handouts or post/email them later. Keep the audience focused on understanding the big picture. Let the focus teams work out the details once they reach a common understanding.

A: Trying to find a single model to effectively communicate an entire system is a fool's errand. I know that RUP has fallen out of favor with Agilists. But I think the real problem is the same problem I see with some Agile projects. People attempted to use an approach without fully understanding it.
You mentioned that you only want to create as much documentation as is necessary to effectively communicate the design to the audience. This is RUP in a nutshell. You aren't required to fill out every artifact in the catalog. It just provides a number of artifacts and templates as a starting point for communicating. It's up to the individual to decide which ones are necessary.
There is a great book, Agile Modeling, that discusses this approach (called eXtreme Unified Process), written by Scott Ambler.
Edit: I haven't read it yet, but there also appears to be a sister book to Agile Modeling called Agile Documentation

A: Looks like you're wanting to cover both the physical and logical architecture.  So just use whatever is easiest for you and make sure the labeling and the keys are clear!

A: Omondo did an ambitious try to cover physical (e.g. database) and logical (e.g UML object) integration by creating a Database profile.
I used the tool and must admit it really worked well. The idea is to create java annotation in code live synchronized with the model and database stereotypes.
What I like with this tool is the full pojo support. From object to database and from database to model. Just marvelous for me !!


text:
Q: How do you bind user control properties to properties of an observable object contained in observable collection I am using MVVMLight and need to be able to make programmatic edits to the properties about 12 toggle boxes during the initialization of a View. Since there are so many of them and I would like to iterate through the linked properties I am trying to use an ObservableCollection of an ObservableObject containing the values to be bound to the properties of the toggle buttons. I am unsure if this is a binding issue or incorrect implementation of the INotifyPropertyChanged interface inherited from the ObservableObject.
Here is the class containing the properties I wish to bind to:
public class CavitySelect : ObservableObject
{
    private string _Text;
    public string Text
    {
        get { return _Text; }
        set
        {
            _Text = value;
            RaisePropertyChanged("Text");
        }
    }
    private bool _Visible;
    public bool Visible
    {
        get { return _Visible; }
        set
        {
            _Visible = value;
            RaisePropertyChanged("Visible");
        }
    }
    private bool _Toggle;

    public bool Toggle
    {
        get { return _Toggle; }
        set
        {
            _Toggle = value;
            RaisePropertyChanged("Toggle");
        }
    }

    public CavitySelect()
    {
        Text = "";
        Visible = false;
        Toggle = false;
    }
}

Here is the instantiation of my ObservableCollection:
private ObservableCollection<CavitySelect> _CavTogglesProperties;
public ObservableCollection<CavitySelect> CavTogglesProperties
{
    get { return _CavTogglesProperties; }
    set
    {
        _CavTogglesProperties = value;
        RaisePropertyChanged("CavTogglesProperties");
    }
}

public MyViewModel()
{
    this.CavTogglesProperties = GetCavities();
}

public ObservableCollection<CavitySelect> GetCavities()
{
    CavitySelect t11 = new CavitySelect();
    CavitySelect t12 = new CavitySelect();
    CavitySelect t13 = new CavitySelect();
    CavitySelect t14 = new CavitySelect();
    CavitySelect t15 = new CavitySelect();
    CavitySelect t16 = new CavitySelect();
    CavitySelect t26 = new CavitySelect();
    CavitySelect t21 = new CavitySelect();
    CavitySelect t22 = new CavitySelect();
    CavitySelect t23 = new CavitySelect();
    CavitySelect t24 = new CavitySelect();
    CavitySelect t25 = new CavitySelect();
    ObservableCollection<CavitySelect> temp = new ObservableCollection<CavitySelect>() {t11,t12,t13,t14,t15,t16,t21,t22,t23,t24,t25,t26};
    return temp;
}

And here is how I am attempting to bind it:
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVisibilty"/>
</Window.Resources>
<Grid Background="#FFF4F4F5" Margin="8,165,8,8"  DataContext="{Binding CavTogglesProperties}">
    <ToggleButton DataContext="{Binding t11}" Content="{Binding Text}" IsChecked="{Binding Toggle}" Visibility="{Binding Visible,Converter={StaticResource BoolToVisibilty}}"/>
</Grid>

I have confirmed the binding of the View to the ViewModel class is working properly. I have also tried binding without setting the DataContext of the containing Grid first, like:
<ToggleButton DataContext="{Binding CavTogglesProperties[t11]}" ... />

For clarification:
Each one of CavitySelect items is related to a toggle button in a GridView, and the properties will be initialized based on an input not shown.

A: Displaying a collection of items
Your question doesn't make it perfectly clear, but I believe you want to show a list of items in your UI; however, as currently implemented, your XAML is really structured to show a single item.
To show a list, you'll want to look at any of the variety of collection views (e.g. ListView, GridView, etc.).
For example:
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVisibilty"/>
</Window.Resources>
<Grid Background="#FFF4F4F5" Margin="8,165,8,8">
  <ListView ItemsSource="{Binding CavTogglesProperties}">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ToggleButton Content="{Binding Text}" IsChecked="{Binding Toggle}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</Grid>

To only show specific items, you should filter the list in the ViewModel, rather than binding the visibility. If the items visible doesn't change while being displayed, simply filter the list when you're populating it.
If, however, the visibilities will change and you want the view to reflect those changes, look at implementing a filter for your items source as explained in this question: How do I Filter ListView in WPF?.
As you're already using an ObservableCollection and ObservableObject, everything should automatically update.
Showing a single item from a collection
If I read your question wrong and you want to know how to show a single item from a collection, there's a couple of different ways of approaching this:

*

*Expose the individual item as a property on the ViewModel so the View doesn't have to dig into the list.

*Create a converter that takes in the collection and index, then pulls out the correct item.

I would highly recommend going with option 1, though, as it most conforms with MVVM, producing the cleanest and most testable code.
For example:
private ObservableCollection<CavitySelect> _CavTogglesProperties;
public ObservableCollection<CavitySelect> CavTogglesProperties
{
    get { return _CavTogglesProperties; }
    set
    {
        _CavTogglesProperties = value;
        RaisePropertyChanged("CavTogglesProperties");
    }
}

private CavitySelect _SpecificCavToggle;
public CavitySelect SpecificCavToggle
{
    get { return _SpecificCavToggle; }
    set
    {
        _SpecificCavToggle= value;
        RaisePropertyChanged("SpecificCavToggle");
    }
}

public MyViewModel()
{
    this.CavTogglesProperties = GetCavities();
    this.SpecificCavToggle = this.CavTogglesProperties[0];
}

public ObservableCollection<CavitySelect> GetCavities()
{
    CavitySelect t11 = new CavitySelect();
    CavitySelect t12 = new CavitySelect();
    CavitySelect t13 = new CavitySelect();
    CavitySelect t14 = new CavitySelect();
    CavitySelect t15 = new CavitySelect();
    CavitySelect t16 = new CavitySelect();
    CavitySelect t26 = new CavitySelect();
    CavitySelect t21 = new CavitySelect();
    CavitySelect t22 = new CavitySelect();
    CavitySelect t23 = new CavitySelect();
    CavitySelect t24 = new CavitySelect();
    CavitySelect t25 = new CavitySelect();
    ObservableCollection<CavitySelect> temp = new ObservableCollection<CavitySelect>() {t11,t12,t13,t14,t15,t16,t21,t22,t23,t24,t25,t26};
    return temp;
}


text:
Q: CCSprites in NSMutableArray does not reappear after scene change I am making a game and i am putting CCSprites in a NSMutableArray.
When i start the game for the first time the sprites are appearing on screen, everything seems to work fine.
But when i change to another scene and come back, none of the sprites are visible on screen.
Here below is the code to initialize the Sprites.
-(void spritesInit)
    gpsUsersSpritesArray        = [[NSMutableArray alloc]init];
   for (int i = 0 ; i < [userArray count] ; i++){
      playerSprite = [CCSprite spriteWithFile:@"greenspot.png"];
      playerSprite.position = ccp( winSize.width/2, winSize.height/2);
      [self addChild:playerSprite z:5];
      [gpsUsersSpritesArray addObject:playerSprite];
      [playerSprite release];
   }
}

The above method is run every time the scene is called.
I run the action below on the sprites, that works also fine the first time, but again not when i leave and return to the scene. The sprites seems to be loaded and the code itterates through the NSMutableArray in question without a crash, and this leaves me puzzled.
for (CCSprite *userspot in gpsUsersSpritesArray){
   id fadein  = [CCFadeTo actionWithDuration:0.05 opacity:255];
   id fadeout = [CCFadeTo actionWithDuration:dotFadeTime opacity:30];
   id seq2 = [CCSequence actions:fadein, fadeout,nil ];
   [userspot runAction:seq2];
}

I have tried to retain the NSMutableArray, but that dit not help either.
Also i have tried to force the sprites to be visible and make sure the opacity of the sprites is set to 255, but still no luck.
I may have overlooked something, but i do not think so.
Who helps me out?
Many thanks in advance.

A: You should not be releasing your sprite. I would think that would cause a crash but it could account for your issue.
When you create a sprite using something like:
CCSprite* mysprite = [CCSprite spriteWithFile:@"whatever.png"];

You NEVER should be releasing that. When coding in Objective-C the rule to remember when not using ARC is that you release objects that you alloc/init, new, retain, and copy yourself. You don't do that in your example code. Inside that method it calls autorelease, making your release invalid. The same with adding objects to containers. Those containers take care of themselves and you should not be releasing or doing anything to the retain count outside of those containers on their behalf if you are using convenience methods that call autorelease, like you are in this case. That is invalid. It would be fine if you were using, for example, alloc/init rather than the spriteWithFile method.


text:
Q: gyp: binding.gyp not found I am trying to install the necessary modules for running my web application. I am getting the following error while running $npm install :
john@mylaptop frontend % npm install

> fsevents@2.3.2 install /Users/john/workspace/myproject/frontend/node_modules/watchpack/node_modules/fsevents
> node-gyp rebuild

gyp: binding.gyp not found (cwd: /Users/john/workspace/myproject/frontend/node_modules/watchpack/node_modules/fsevents) while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/Users/john/.nvm/versions/node/v6.11.0/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:305:16)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Darwin 21.3.0
gyp ERR! command "/Users/john/.nvm/versions/node/v6.11.0/bin/node" "/Users/john/.nvm/versions/node/v6.11.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/john/workspace/myproject/frontend/node_modules/watchpack/node_modules/fsevents
gyp ERR! node -v v6.11.0
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/watchpack/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
john@mylaptop frontend % node-gyp rebuild --verbose
gyp info it worked if it ends with ok
gyp verb cli [ '/Users/john/.nvm/versions/node/v6.11.0/bin/node',
gyp verb cli   '/Users/john/.nvm/versions/node/v6.11.0/bin/node-gyp',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose' ]
gyp info using node-gyp@8.4.1
gyp info using node@6.11.0 | darwin | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp ERR! UNCAUGHT EXCEPTION
gyp ERR! stack /Users/john/.nvm/versions/node/v6.11.0/lib/node_modules/node-gyp/lib/create-config-gypi.js:18
gyp ERR! stack async function getBaseConfigGypi ({ gyp, nodeDir }) {
gyp ERR! stack       ^^^^^^^^
gyp ERR! stack SyntaxError: Unexpected token function
gyp ERR! stack     at createScript (vm.js:56:10)
gyp ERR! stack     at Object.runInThisContext (vm.js:97:10)
gyp ERR! stack     at Module._compile (module.js:542:28)
gyp ERR! stack     at Object.Module._extensions..js (module.js:579:10)
gyp ERR! stack     at Module.load (module.js:487:32)
gyp ERR! stack     at tryModuleLoad (module.js:446:12)
gyp ERR! stack     at Function.Module._load (module.js:438:3)
gyp ERR! stack     at Module.require (module.js:497:17)
gyp ERR! stack     at require (internal/module.js:20:19)
gyp ERR! stack     at Object.<anonymous> (/Users/john/.nvm/versions/node/v6.11.0/lib/node_modules/node-gyp/lib/configure.js:10:26)
gyp ERR! System Darwin 21.3.0
gyp ERR! command "/Users/john/.nvm/versions/node/v6.11.0/bin/node" "/Users/john/.nvm/versions/node/v6.11.0/bin/node-gyp" "rebuild" "--verbose"
gyp ERR! cwd /Users/john/workspace/myproject/frontend
gyp ERR! node -v v6.11.0
gyp ERR! node-gyp -v v8.4.1
gyp ERR! Node-gyp failed to build your package.
gyp ERR! Try to update npm and/or node-gyp and if it does not help file an issue with the package author.

This is the node version I am using :
john@mylaptop frontend % npm version
{ frontend: '0.0.0',
  npm: '3.10.10',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '58.2',
  modules: '48',
  node: '6.11.0',
  openssl: '1.0.2k',
  uv: '1.11.0',
  v8: '5.1.281.102',
  zlib: '1.2.11' }

I don't want to upgrade npm or node versions for compatibility reasons with angular 4.4.6. Any help please. node was installed via nvm and not with brew.

A: Add file binding.gyp

{
  'targets': [
    {
      'target_name': 'bindings',
      'sources': [ 'bindings.node' ],
      'cflags!': [ '-fno-exceptions' ],
      'cflags_cc!': [ '-fno-exceptions' ],
      'conditions': [
        ['OS=="mac"', {
          'xcode_settings': {
            'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
          }
        }]
      ]
    }
  ]
}

and rebuid node-gyp. $ node-gyp rebuild


text:
Q: Asp.Net Mvc get image from gravatar? I want to show user profile pic from gravatar.com like this site. In this site users change images from gravatar.com. Is there any article or tutorial about this topic.(With asp.net mvc).
Thanks.

A: Quick Google search: http://hackingon.net/post/ASPNET-MVC-Gravatar-Helpers.aspx or http://www.fatlemon.co.uk/2012/01/gravatar-htmlhelper-for-asp-net-mvc/


text:
Q: How can I reset NX sessions? I am running Ubuntu 12.04 and x2goserver.  The x2go sessions boot into openbox, which starts a java program as defined in its autostart profile.
Question is, if I make an update to this java program, how do I force all the open x2go sessions to close down such that the java program is closed, session is terminated and they would have to reconnect and promptly experienced an updated java program?

A: You can view all sessions with x2golistsessions_root and kill sessions with x2goterminate-session <session id>. I don't believe you can force them to re-connect automatically. To kill all the sessions, you could run this as root:
x2golistsessions_root | awk -F'|' '{ print $2 }' | xargs -I % x2goterminate-session %


text:
Q: how to write multiple endpoint for request with identical namespace and local part using spring WS? This is my sample code
@Endpoint
public class NotificationEndPoint {

    private static final String NAMESPACE_URI = "http://soap.sforce.com/2005/09/outbound";

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "notifications")
    @SoapAction("Events")
    @ResponsePayload
    public NotificationsResponse handleEventRequest(@RequestPayload Notifications notificationsRequest) throws Exception {}

}

A: i am able to find a similar question which is a bit too tricky to execute but i ll try. anyone looking for similar issue can try this out.
How can i have two separate web services with identical name space and local name requests be routed to different end points?


text:
Q: WPF - ItemTemplate not acting as expected I have a UserControl which I'm using to display a list of UIElements.  The control consists of a single ItemsControl with it's ItemPanelTemplate switched for a horizontal StackPanel, its ItemsSource bound to a DependencyProperty exposed by the UserControl and its ItemTemplate set in the UserControl.Resources.
Everything works fine except the ItemTemplate never get's applied and I can't see why.  The full source is below.
UserControl.xaml -
<UserControl x:Name="UC" x:FieldModifier="private" x:Class="ContentSliderControl.ContentSlider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>

    <DataTemplate x:Key="pageTemplate">
        <Border CornerRadius="10" Padding="5" Height="200" Width="200" Background="#333">
            <ContentControl Content="{Binding}"/>
        </Border>
    </DataTemplate>

    <ItemsPanelTemplate x:Key="template">
        <StackPanel IsItemsHost="True"
            Orientation="Horizontal"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled"
            ScrollViewer.VerticalScrollBarVisibility="Disabled"/>
    </ItemsPanelTemplate>
</UserControl.Resources>

<ItemsControl ItemsPanel="{StaticResource template}"
              ItemTemplate="{StaticResource pageTemplate}"
              ItemsSource="{Binding ElementName=UC,Path=Pages}"/>

UserControl.xaml.cs -
[ContentProperty("Pages")]
public partial class ContentSlider : UserControl
{

    public List<UIElement> Pages
    {
        get { return (List<UIElement>)GetValue(PagesProperty); }
        //set { SetValue(PagesProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Pages.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PagesProperty =
        DependencyProperty.Register("Pages", typeof(List<UIElement>), typeof(ContentSlider), new UIPropertyMetadata(null));

    public ContentSlider()
    {
        InitializeComponent();
    }
}

}
I consume the control in my main window like this -
    <slider:ContentSlider >
    <slider:ContentSlider.Pages>
        <Button>1</Button>
        <Button>2</Button>
        <Button>3</Button>
        <Button>4</Button>
    </slider:ContentSlider.Pages>
</slider:ContentSlider>

The buttons appear fine but not inside the 200px square border.
Any help would be greatlly appriciated.
Thanks.

A: Nir is correct, ItemsControl will add item directly to its Panel if they are UIElements.  I couldn't find any mention of this behavior in MSDN, but Dr. WPF mentions it in his article on item containers:

If a UIElement is added to the Items collection of an explicit ItemsControl instance (as opposed to an instance of a derived class like ListBox), it will become a direct child of the items panel. If a non-UIElement is added, it will be wrapped within a ContentPresenter.

Your solution is probably to use a ListBox instead, and set ItemContainerStyle to a new Style for ListBoxItem, and in that style, use a ControlTemplate with your Border in it.

A: It's because it's a list of UIElement, the item template is only applied if the items can't be displayed directly.

A: Nir is right, this custom ItemsControl implementation will solve the issue and let use your own ItemTemplate:
public class ItemsControlForUIElement : ItemsControl
{
   protected override DependencyObject GetContainerForItemOverride()
   {
       return new ContentPresenter();
   }
   protected override bool IsItemItsOwnContainerOverride(object item)
   {
       return false;
   }
}

A: Robert Macnee nailed the reason on the head.  His solution involves using the control template which might be overkill for a given scenario.  Alternatively, use a ListBox - set the ItemContainerStyle to a new Style for ListBoxItem, and in that style, set the ContentTemplate to the DataTemplate that you wanted to use in the ListBox ItemTemplate.

A: If you set the DataType property on the DataTemplate it would start working.


text:
Q: Wordpress Plugin - change dynamic styles sheet to load under https I am trying to integrate the foodpress app into my multisite installation. I'm currently have wildcard ssl installed.
This error comes up when I inspect the frontpage of the site in chrome. foodpress_dynamic_styles.css Failed to load resource: the server responded with a status of 404 (Not Found)
I need to change this section of code so it will load https instead of http so it works properly. (I would ask the developer but the said they no longer support wordpress.)
     public function register_fp_dynamic_styles(){
        $opt= $this->fpOpt;

        if(!empty($opt['fp_css_head']) && $opt['fp_css_head'] =='no' ||
     empty($opt['fp_css_head'])){
            if(is_multisite()) {
                $uploads = wp_upload_dir();
                wp_register_style('foodpress_dynamic_styles', $uploads['baseurl'] . '/foodpress_dynamic_styles.css', 'style');
            } else {
                wp_register_style('foodpress_dynamic_styles',
                    FP_URL. '/assets/css/foodpress_dynamic_styles.css', 'style');
            }
        }
    }

A: You can change http to https by finding the code where FP_URL  is defined
Or Try below code for quick and dirty method
  public function register_fp_dynamic_styles(){
            $opt= $this->fpOpt;

            if(!empty($opt['fp_css_head']) && $opt['fp_css_head'] =='no' ||
         empty($opt['fp_css_head'])){
                if(is_multisite()) {
                    $uploads = wp_upload_dir();
                    wp_register_style('foodpress_dynamic_styles', $uploads['baseurl'] . '/foodpress_dynamic_styles.css', 'style');
                } else {
    $httpsurl = str_replace("http:","https:",FP_URL. '/assets/css/foodpress_dynamic_styles.css';
    wp_register_style('foodpress_dynamic_styles',$httpsurl,'style');
                }
            }


text:
Q: Why does the position of my prefab is changed when dropped in the scene? I have a problem, I made a prefab of a cube that I want to place on a platform.
The y value of my prefab is 1. However, when I try to place it on the platform the cube takes the y value of 0.5 which puts it inside of the ground.
I tried to reset the transform in the prefab, the ground and the cubes but none of that worked.
Screenshots of my unity window with both the prefab and how its value is changed.

A: I'm assuming you're dragging the prefab into the Scene window without using code or anything like that.

Why does the position get modified
The reason your cube is halfway into the ground likely is due to Unity trying to have it centered on the Y axis on the ground object you have in the scene since that's likely the object you're dragging your prefabs on.
Solution 1
If you wish to drag things into the Scene window but wish to avoid the cubes going into the ground, one solution is to change the center position of the cubes. One way of doing that is by putting the cube into an empty GameObject and modify the cube's position inside it and use this GameObject as a prefab. Here's a screenshot illustrating how your modified version of the prefab would look like:

Solution 2
If wish to move a cube into the scene without any position modifications, drag it into the Hierarchy window instead.

Solution 3
Create a custom script that modifies the Y position of your cube prefab instance. OnValidate() may be something worth looking into for this solution.

A: You need to "freeze" the mesh (recalculate the vertices of the mesh) relative to the position of the transform so it fits your needs.
This is usually done in the program that generated the mesh but you could also use a simple editor script inside Unity. There are probably several very good ones if you google - but here is the code I use myself when I need to adjust or freeze a mesh.

In your case, you simply want to align the mesh at the bottom, so you can select "Min" for "Align y" (let the checkboxes beside x, y, and z be unchecked). This will put all the mesh above the transform position. (Align is a simple way of freezing without the need to first manually position the mesh as desired).
Place the following two scripts in a folder with the name "Editor" (so it can be used as a Unity editor). You will then have a new menu option in Unity "Tools - Simple Mesh Editor".
SimpleMeshEditor.cs
using UnityEditor;
using UnityEngine;

namespace com.andulfgames
{
    public class SimpleMeshEditor : EditorWindow
    {
        [MenuItem("Tools/Simple Mesh Editor")]
        public static void ShowWindow()
        {
            GetWindow<SimpleMeshEditor>(false, "Simple Mesh Editor", true);
        }

        bool freezeRotation = true;

        SimpleMeshTools.MeshAlign alignX;
        SimpleMeshTools.MeshAlign alignY;
        SimpleMeshTools.MeshAlign alignZ;

        bool freezeX = false;
        bool freezeY = false;
        bool freezeZ = false;

        bool adjustColliders = true;

        void OnGUI()
        {
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Freeze", EditorStyles.boldLabel);
            freezeRotation = EditorGUILayout.Toggle("Rotation", freezeRotation);
            freezeX = EditorGUILayout.Toggle("x", freezeX );
            freezeY = EditorGUILayout.Toggle("y", freezeY);
            freezeZ = EditorGUILayout.Toggle("z", freezeZ);
            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Align", EditorStyles.boldLabel);
            alignX = (SimpleMeshTools.MeshAlign)EditorGUILayout.EnumPopup("Align x", alignX);
            alignY = (SimpleMeshTools.MeshAlign)EditorGUILayout.EnumPopup("Align y", alignY);
            alignZ = (SimpleMeshTools.MeshAlign)EditorGUILayout.EnumPopup("Align z", alignZ);

            EditorGUILayout.Space();
            EditorGUILayout.LabelField("Colliders", EditorStyles.boldLabel);
            adjustColliders = EditorGUILayout.Toggle("Adjust colliders", adjustColliders);

            if (GUILayout.Button("UpdateMesh"))
            {
                UpdateMesh();
            }
        }

        private void UpdateMesh()
        {
            foreach (GameObject obj in Selection.gameObjects)
            {
                MeshFilter meshFilter = obj.GetComponent<MeshFilter>(); //6

                if (meshFilter != null)
                {
                    SimpleMeshTools.FreezeTransformation(obj, freezeRotation, freezeX, alignX, freezeY, alignY, freezeZ, alignZ, adjustColliders);
                }
            }
        }
    }
}

SimpleMeshEditor.cs
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

namespace com.andulfgames
{
    public static class SimpleMeshTools
    {
        public static void FreezeTransformation(GameObject gameObject,
            bool freezeRotation,
            bool freezeX, MeshAlign meshPositionX,
            bool freezeY, MeshAlign meshPositionY,
            bool freezeZ, MeshAlign meshPositionZ,
            bool adjustColliders)
        {
            MeshFilter meshFilter = gameObject.GetComponent<MeshFilter>();
            Mesh newMesh = GameObject.Instantiate<Mesh>(meshFilter.sharedMesh);
            Quaternion originalRotation = meshFilter.transform.rotation;
            // If we should not freeze the rotation we have to temporarly turn the mesh
            // back to it's identity rotation before we freeze the vertizes.
            if (!freezeRotation)
                meshFilter.transform.rotation = Quaternion.identity;

            Vector3[] vertices = newMesh.vertices;

            Vector3 freeze = new Vector3(
                freezeX ? 0 : gameObject.transform.position.x,
                freezeY ? 0 : gameObject.transform.position.y,
                freezeZ ? 0 : gameObject.transform.position.z);
            Debug.Log("Freeze: " + freeze.ToString());
            Vector3 diff = gameObject.transform.position - freeze;

            Vector3 alignMin = newMesh.bounds.min;
            Vector3 alignCenter = newMesh.bounds.center;
            Vector3 alignMax = newMesh.bounds.max;

            Vector3 align = new Vector3(
                meshPositionX == MeshAlign.KeepCurrent ? 0 :
                (meshPositionX == MeshAlign.Min ? alignMin.x :
                (meshPositionX == MeshAlign.Center ? alignCenter.x : alignMax.x)),

                meshPositionY == MeshAlign.KeepCurrent ? 0 :
                (meshPositionY == MeshAlign.Min ? alignMin.y :
                (meshPositionY == MeshAlign.Center ? alignCenter.y : alignMax.y)),

                meshPositionZ == MeshAlign.KeepCurrent ? 0 :
                (meshPositionZ == MeshAlign.Min ? alignMin.z :
                (meshPositionZ == MeshAlign.Center ? alignCenter.z : alignMax.z)));

            Debug.Log("Freeze by " + diff.ToString() + " and align by " + align.ToString() + ", in total " + (diff + align).ToString());

            Debug.Log("Adjust: " + align.ToString());

            for (int i = 0; i < vertices.Length; i++)
                vertices[i] = gameObject.transform.TransformPoint(newMesh.vertices[i]) - freeze - align;

            newMesh.vertices = vertices;

            // Note that we can't rotate box- or sphere colliders

            BoxCollider boxCollider = adjustColliders ? gameObject.GetComponent<BoxCollider>() : null;
            SphereCollider sphereCollider = adjustColliders ? gameObject.GetComponent<SphereCollider>() : null;
            CapsuleCollider capsuleCollider = adjustColliders ? gameObject.GetComponent<CapsuleCollider>() : null;

            if (adjustColliders && diff + align != Vector3.zero)
            {
                Debug.Log("Adjusting colliders by " + (diff + align).ToString());
                if (boxCollider != null)
                    boxCollider.center += diff + align;
                if (sphereCollider != null)
                    sphereCollider.center += diff + align;
                if (capsuleCollider != null)
                    capsuleCollider.center += diff + align;
            }

            if (freezeRotation && gameObject.transform.rotation != Quaternion.identity)
            {
                Debug.Log("Freezing current rotation which is " + gameObject.transform.rotation.ToString());
                if (boxCollider != null)
                    Debug.LogWarning("Can't rotate box-colliders. They are fixed with the transform.");
                if (sphereCollider != null)
                    Debug.LogWarning("Can't rotate sphere-colliders. They are fixed with the transform.");
                if (capsuleCollider != null)
                    Debug.LogWarning("Can't rotate capsule-colliders. They are fixed with the transform.");

                Vector3[] normals = newMesh.normals;
                if (normals != null)
                {
                    for (int i = 0; i < normals.Length; i++)
                        normals[i] = gameObject.transform.rotation * newMesh.normals[i];
                    newMesh.normals = normals;
                }
            }

            newMesh.RecalculateBounds();
            newMesh.RecalculateNormals();

            Mesh savedMesh = SaveMesh(newMesh, gameObject.name);
            if (savedMesh != null)
                meshFilter.sharedMesh = savedMesh;

            if (freezeRotation)
                meshFilter.transform.rotation = Quaternion.identity;
            else
                meshFilter.transform.rotation = originalRotation; // Restore

            meshFilter.transform.localScale = new Vector3(1, 1, 1);
            meshFilter.transform.position -= diff - align;
        }
    }
}


text:
Q: Adding values to an undefined index array in PHP I'm working on learning php by creating a webpage completely based on php and dynamic to the content of a database. In the code snippet below, I query the amount of navigation links in the mainMenu table and return the link title and url to their respective arrays. However, the code is broken and the webpage doesn't load. I'm almost 100% certain it is the way I am declaring the arrays, or the way I am trying to pass the data from the database to the array but after some research I can't figure it out.
include('config.php');

$urls = array();
$navs = array();
$num = 1;

$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
    //die("Connection failed: " . $conn->connect_error);
    die("Connection failed");
}
if ($result = $conn->query("SELECT * FROM mainMenu")) {
    /* determine number of rows result set */
    $row_cnt = $result->num_rows;
    /* close result set */
    //$result->close();
}

while ($num <= $row_cnt) {
    $sqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if ($sqli->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    //Site Title
    $sql = "SELECT title,url FROM mainMenu WHERE navID=" . $num;
    $result = $sqli->query($sql);
    while($row = $result->fetch_assoc()) {
        $navs[$num] = $row["title"];
        $urls[$num] = $row["url"];
    }
    $sqli->close();
    $num++;
}

A: After reviewing an answer that was posted and then deleted, this seemed to be the solution.
<?php
include('config.php');
$urls = array(); // you shouldn't do "new array()", this is javascript
$navs = array();
$num = 1;
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
    //die("Connection failed: " . $conn->connect_error);
    die("Connection failed");
}
if ($result = $conn->query("SELECT * FROM mainMenu")) {
    /* determine number of rows result set */
    $row_cnt = $result->num_rows;
    /* close result set */
    //$result->close();
}
while ($num <= $row_cnt) {
    //Site Title
    $sql = "SELECT title,url FROM mainMenu WHERE navID=" . $num;
    $result = $conn->query($sql);
    while($row = $result->fetch_assoc()) {
        if(!isset($navs[$num])) { $navs[$num] = array(); } // do this to define the index before using it
        if(!isset($urls[$num])) { $urls[$num] = array(); }
        $navs[$num] = $row["title"];
        $urls[$num] = $row["url"];
    }
    $num++;
}

$conn->close();
define('urlArray', $urls);
printf($urls);
?>


text:
Q: Auto Layout: understanding the behavior of attributes and items I use Auto Layout programmatically a lot but there are still two things that I do not understand.

*

*What is the difference between leading and left attribute/anchor and between trailing and right attribute/anchor?

To me there seem to be the same but according to the docs:

However, Auto Layout does not allow constraints that mix leading and trailing attributes with left or right attributes. As a result, this constraint crashes at runtime.

*The order of the the items inside the NSLayoutConstraint does not matter for the Auto Layout system at all, am I right? (At least for .Equal relation.)

Do not get confused about the attributes for each individual item, I'm aware of that.

A: Left and right are always left and right.
Leading and trailing are not. From Working with Constraints in Interface Builder:

If you lay out your views using leading and trailing constraints, the views automatically flip positions when switching between left-to-right languages (like English) and right-to-left languages (like Arabic). However, some interface elements should not change their position based on the reading direction. For example, buttons that are based on physical directions (up, down, left, and right) should always stay in the same relative orientation.

The order of items for an equal relation is irrelevant.

A: The difference between leading and left is important when taking into account RTL languages, such as Hebrew. In that case, the UI is inverted to complement text direction, and so are the UI elements with constraints. In this case, leading means the side where text starts. left is always left, for text direction agnostic UIs, such as media playback controls.
The order constraints are placed in does not matter. If there are conflicting constraints, the behavior is undefined.


text:
Q: Android Studio Apache functions I've been trying to create DefaultHttpClient object with:
HttpClient client = new DefaultHttpClient();

but I'm unable to find this class can't be resolved in my Android Studio.
After googling this class, the first result shows the following URL:Link
and it's 404: not found page.
Does anyone know how I can use this function and similar function such as HttpGet?

A: Use urlconnection. If i remember correctly, defaulthttpclient is deprecated.
URL url = new URL("http://stackoverflow.com");
URLConnection conn = url.openConnection();
InputStream in = new BufferedInputStream(conn.getInputStream());


text:
Q: How can I remove datetime elements of a list outside of a specified startdate and enddate period? I have a list of datetime objects called 'date', and I am trying to remove the elements of the list which are outside of a startdate and an enddate. Can anyone help me understand how to properly do this and why I am getting this list index out of range error? I feel like I am so close!
My code:
startDate = datetime.strptime('1948-1-1',"%Y-%m-%d")
endDate = datetime.strptime('1950-2-1',"%Y-%m-%d")

for row in range(0,len(date)):
  if date[row] < startDate:
    del date[row]
  elif date[row] > endDate:
    del date[row]

I have also tried the following way and it runs but does not delete the list elements:
count = 0

for row in date:
  if row < startDate:
    del date[count]
  elif row > endDate:
    del date[count]
  count += 1

A: as you are looping through the list and deleting the same list, which is making it out of the index. think like,  you are looping through len(list) but the list is not of the same length as deleted some entries.
so list comprehension can be helpful here, pls note I changed > and < to other way for the expected result, please see the example below:
from datetime import datetime
# datasetup
date=['1947-01-01','1948-01-01','1948-02-02','1951-01-01']
date=[datetime.strptime(each,"%Y-%m-%d") for each in date]
#Control date
startDate = datetime.strptime('1948-1-1',"%Y-%m-%d")
endDate = datetime.strptime('1950-2-1',"%Y-%m-%d")
#list comprehension
date = [each for each in date if  each >= startDate and each <= endDate ]

taking a solution to further, download the data from google drive, filter the needed data using pandas, and then plot it for analysis.
step 1- download the data
import pandas as pd
import requests
from io import StringIO

gd_url='https://drive.google.com/file/d/1N2J136mog2CZK_XRyL3pxocaoUV8DByS/view?usp=sharing'
file_id = gd_url.split('/')[-2]
download_url='https://drive.google.com/uc?export=download&id=' + file_id
url = requests.get(download_url).text # get the file
csv_raw = StringIO(url)
df = pd.read_csv(csv_raw)
print(df.head(1))

Step 2: filter the data
#Control date
startDate = '1948-01-01'
endDate = '1950-02-01'
df_new=df.loc[(df['DATE'] >= startDate) & (df['DATE'] <= endDate)] # as doing string compare, make sure that
#data looks okay otherwise change it to date for comparision

Step 3: show the graph.
import pandas as pd
import matplotlib.pyplot as plt
df_new.plot()
plt.show()

A: Here is a similar snippet of code with the same problem as yours.
numbers = list(range(10))

for i in range(len(numbers)):
    if numbers[i] < 3:
        del numbers[i]
    elif numbers[i] > 7:
        del numbers[i]

The problem with this is that the range(len(numbers)) is created right at the beginning of the loop, and it doesn't notice that the length of numbers has changed as it iterates.
This could be fixed with a while loop:
numbers = list(range(10))

i = 0
while i < len(numbers):
    if numbers[i] < 2:
        del numbers[i]
    elif numbers[i] > 7:
        del numbers[i]
    else:
        i += 1

print(numbers)

Note that i is only incremented if nothing is deleted from the list, since if say, index 1 is deleted, then the item from index 2 will move left to fill the gap, so index 1 needs to be checked again.
However this solution is verbose and not very Pythonic, and quite inefficient (O(n^2) complexity, since deleting an item from a list is O(n), and it may be done n times).
I would recommend you use a list comprehension to filter values like this:
numbers = list(range(10))

print([number for number in numbers if 2 <= number <= 7])

Or, if more complex computation is needed inside the loop, you could append to a new list (O(n) complexity in total):
numbers = list(range(10))
new_numbers = []
for i in range(len(numbers)):
    do_delete = False
    if numbers[i] < 2:
        do_delete =True
    elif numbers[i] > 7:
        do_delete = True

    if not do_delete:
        new_numbers.append(numbers[i])

print new_numbers

Or you could use a generator function (also O(n)):
numbers = list(range(10))

def my_filter(numbers):
    for i in range(len(numbers)):
        do_delete = False
        if numbers[i] < 2:
            do_delete = True
        elif numbers[i] > 7:
            do_delete = True

        if not do_delete:
            yield numbers[i]

print(list(my_filter(numbers)))

A: Use below sample code
from datetime import datetime

startDate = datetime.strptime('1948-1-1',"%Y-%m-%d")
endDate = datetime.strptime('1950-2-1',"%Y-%m-%d")

date_list = []

date_list.append( datetime.strptime('1949-1-1',"%Y-%m-%d"))
date_list.append( datetime.strptime('1949-2-1',"%Y-%m-%d"))
date_list.append( datetime.strptime('1949-2-3',"%Y-%m-%d"))
date_list.append( datetime.strptime('1950-2-3',"%Y-%m-%d"))
date_list.append( datetime.strptime('1950-2-1',"%Y-%m-%d"))
date_list.append( datetime.strptime('1999-2-1',"%Y-%m-%d"))
date_list.append( datetime.strptime('1993-2-1',"%Y-%m-%d"))
date_list.append( datetime.strptime('1995-2-1',"%Y-%m-%d"))

new_list = copy.deep_copy(date_list)

for idx, date in enumerate(ll):
    if not date < startDate or not date > endDate:
        new_list.append(date)

print(new_list)


text:
Q: Angularjs) selecting entire number upon focusing on input I have an input with type=number which I want to have the entire number selected upon the user touching the input. How would I go about doing this?
I'm getting errors that type=number doesn't support selection - I'm finding this difficult to get around. If anyone can handle this in terms of an Angularjs directive, that would be ideal.
Thanks,

A: Try using input type="tel". It may have been fixed I've never gone back to explore but at one point in time Angular and type="number" did not combine well at all.
It has to do with the way the browser handles its own processes and a collision with Angular doing the same.


text:
Q: swap bit i and j of an integer Given an integer, swap the i-th and j-th bit.
I have tried solving this question myself. Do you guys think it is too "wordy" (long)?
int swap_bit(int num, int i, int j){
    int a=(num>>i) & 1; //i-th bit
    int b=(num>>j) & 1; //j-th bit

    int mask1=~(1<<i); // create mask to clear i-th bit
    int mask2=~(1<<j); // create mask to clear j-th bit

    num=num & mask1 & mask2;
    num=num | (a<<j);
    num=num | (b<<i);
    return num;
}

A: I always refer to https://graphics.stanford.edu/~seander/bithacks.html for anything bit-related.
Swapping individual bits with XOR
unsigned int i, j; // positions of bit sequences to swap
unsigned int n;    // number of consecutive bits in each sequence
unsigned int b;    // bits to swap reside in b
unsigned int r;    // bit-swapped result goes here

unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));

As an example of swapping ranges of bits suppose we have have b = 00101111 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would be r = 11100011 (binary).
This method of swapping is similar to the general purpose XOR swap trick, but intended for operating on individual bits.  The variable x stores the result of XORing the pairs of bit values we want to swap, and then the bits are set to the result of themselves XORed with x.  Of course, the result is undefined if the sequences overlap.

For the special case where n = 1 the code reduces to:
unsigned int i, j; // positions of bit sequences to swap
unsigned int b;    // bits to swap reside in b
unsigned int r;    // bit-swapped result goes here

unsigned int x = ((b >> i) ^ (b >> j)) & 1U; // XOR temporary
r = b ^ ((x << i) | (x << j));


text:
Q: Problem application Rails 2 using bundler I am using Rails 2.3.11 end the error is:
NoMethodError in Configurations#index
Showing rails/ruby/1.8/gems/actionpack-2.3.11/lib/action_controller/templates/rescues/diagnostics.erb where line #7 raised:
private method `gsub' called for nil:NilClass
Extracted source (around line #7):
4: in <%=h request.parameters['controller'].humanize %>Controller<% if request.parameters['action'] %>#<%=h request.parameters['action'] %><% end %>
5: <% end %>
6:

7:
<%=h @exception.clean_message %>

8:
9: <%= render :file => @rescues_path["rescues/_trace.erb"] %>
10:

A: My feeling is that @exception is null, since no exceptions were raised on page.
Try something like:
<% if !@exception.nil? %>
   <%=h @exception.clean_message %>
<% end %>


text:
Q: The probability of i errors in specified positions In a binary code of length n
p(exactly i errors in specified positions)=$t^i (1-t)^{n-i}$.
I have an example where $C=\{000,111\}$, the binary repetition code of length 3.
Suppose 111 is transmitted.
Then the received words will be decoded as 111 are
${111,011,101,110}$
Why does P$($decoding as $111$ $)$= $(1-t)^3+3t(1-t)^2$ ?

A: P(decoded as 111 ) = P(111 transmitted) + P(one zero transmitted)
Assuming probability of transmitting zero is $t$ we have
P(111 transmitted) = $ (1-t)^3$
P(one zero transmitted) =  ${3}\choose{1}$ $ t (1-t)^2 $


text:
Q: Problema con array multidimensionales 3x3 funcion de borrar item Buen día colegas, tengo un problema con arrays que me está rompiendo la cabeza, resulta que tengo este arreglo dimensional.
 array(3) {
[1]=> array(1) {["PC150"]=>
array(7) { [0]=> string(5) "HABPC" [1]=> string(2) "PC" [2]=> string(1) "2"
[3]=> string(24) "EXTRACTOR PREMIUM CHOICE" [4]=> string(5) "Pieza" [5]=>
string(1) "2" [6]=> string(13) " $ 154.00 USD" } }
[2]=> array(1) { ["5PC-ACC01"]=>
array(7) { [0]=> string(5) "HABPC" [1]=> string(2) "PC" [2]=> string(1)
"3" [3]=> string(24) "EXTRACTOR PREMIUM CHOICE" [4]=> string(5) "Pieza"
[5]=>
string(1) "3" [6]=> string(12) " $ 39.00 USD" } }
[3]=> array(1) { ["5PC-ACC05"]=>
array(7) { [0]=> string(5) "HABPC" [1]=> string(2) "PC" [2]=> string(1)
"3" [3]=> string(24) "EXTRACTOR PREMIUM CHOICE" [4]=> string(5) "Pieza"
[5]=> string(1) "3" [6]=> string(11) " $ 7.00 USD" } } }

En un archivo json quedaría mas entendible de la siguiente manera.
{"1":{"PC150":
["HABPC","PC","2","EXTRACTOR PREMIUM CHOICE","Pieza","2"," $ 154.00
USD"]},
"2":{"5PC-ACC01":
 ["HABPC","PC","3","EXTRACTOR PREMIUM
CHOICE","Pieza","3"," $ 39.00 USD"]},
"3":{"5PC-ACC05":
["HABPC","PC","3","EXTRACTOR PREMIUM CHOICE","Pieza","3"," $ 7.00 USD"]}}

Lo que necesito es iterar el arreglo y borrar el index y volver a reordenar los index.
Lo estoy haciendo de esta manera:
La variable modelo es el identificador que le paso ejemplo [PC150] o [5PC-ACC01], para poder borrarlo.
eliminar($modelo){
  //lo obtengo de una cookie y lo guaro en arreglo

  $aCarrito = json_decode($_COOKIE['carrito'], true);
  $c  = $_COOKIE['contItems']; //tambien obtengo mi contador de articulos
 //itero la primer vez
foreach ($aCarrito as $key => $ubc) {
//en $key se guardan 1,2,3,4 $ubc es otro array
    //itero ubx para obtener el modelo
     foreach ($ubc as $mode => $mod) {
        //hago coincidir los modelos con el modelo pasado en la funcion
        if ($mode == $modelo) {
             // elimino la posicion del arreglo
            unset($aCarrito[$i][$modelo]);

        }

    }
    $i++;
}
  }

Y queda el arreglo de la siguiente manera cuando se elimina(eso si funciona, borrar el contenido en ese index).
{"1":[ ],"2":[ ],"3":[ ]} , pero yo quiero que se borre completo con el index también probé con  unset($aCarrito[ $i ]);, y también elimina el index completo(como deseo), pero necesito que se vuelva a reordenar el array.
¿Alguna idea para borrar el array pasándole la variable $modelo y reordenar todo?

A: Una función para ti..
/* Array de Ejemplo */
$array = array(array('PC150'=>['HABPC', 'PC']),
               array('5PC-ACC01'=>['HABPC', 'PC']),
               array('5PC-ACC05'=>['HABPC', 'PC']),
               array('5PC-ACC06'=>['HABPC', 'PC']));

function deleteIdx( array $arr, string $whatever ) {
    $idk = array_map(function($e) use ($whatever){
        return key($e) == $whatever ? false : $e;
    }, $arr);
    return array_values(array_filter($idk));
}

$newArr = deleteIdx($array, 'PC150');

Esta función se puede utilizar en otros arreglos similares, y permite especificar el indice a borrar en el segundo parámetro. Lo único que debes hacer es almacenar el array filtrado en una variable.


text:
Q: Hot to "flatten" an ObjectProperty of an ObjectProperty in TornadoFX (JavaFX extension)? Let's say I have three classes:
class A {
    val bProperty: ObjectProperty<B> = SimpleObjectProperty(B(C("test")))

    val cObservable: ObservableValue<C> = ???
}

class B(initialC: C) {
    val cProperty: ObjectProperty<C> = SimpleObjectProperty(initialC)
}

class C(val string: String)

As you may have seen, in class A I want to have a cObservable, which updates its value either when the value of bProperty changed or when the value of cProperty in the current bProperty.value changed.
The closest I got to was something like this:
val cObservable: ObservableValue<ObjectProperty<C>> = nonNullObjectBinding(bProperty) {
        value.cProperty
    }

But this gives me an ObservableValue of an ObservableValue of C and not an ObservableValue of C. So this is nothing I can work with.
Thanks for your help in advance.

A: You can use the select extension method:
val cObservable: ObservableValue<C> = bProperty.select { it.cProperty }

or:
val cObservable: ObservableValue<C> = bProperty.select (B::cProperty)


text:
Q: fuse utimensat problem I am developing fuse fs at python (with fuse-python bindings). What method I need to implement that touch correctly work? At present I have next output:

$ touch m/My\ files/d3elete1.me
touch: setting times of `m/My files/d3elete1.me': Invalid argument

File exists "d3elete1.me":

$ ls -l m/My\ files/d3elete1.me
-rw-rw-rw- 1 root root 0 Jul 28 15:28 m/My files/d3elete1.me

Also I was trying to trace system calls:

$ strace touch m/My\ files/d3elete1.me
...
open("m/My files/d3elete1.me", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK|O_LARGEFILE, 0666) = 3
dup2(3, 0)                              = 0
close(3)                                = 0
utimensat(0, NULL, NULL, 0)             = -1 EINVAL (Invalid argument)
close(0)                                = 0
...

As you see utimensat failed. I was trying to implement empty utimens and utime but its are not even called.

A: Try launching fuse with the -f option. Fuse will stay in foreground and you can see errors in the console.

A: You must implement utimens and getattr. Not all the system calls necessarily map directly to the C calls you might be expecting. Many of them are used internally by FUSE to check and navigate your filesystem, depending on which FUSE options are set.
I believe in your case FUSE is preceding it's interpretation of utimesat to utimens, with a getattr check to verify that the requested file is present, and has the expected attributes.
Update0
This is a great coincidence. There is a comment below suggestion that the issue likes with the fact that FUSE does not support utimensat. This is not the case. I had the exact same traceback you've provided while using fuse-python on Ubuntu 10.04. I poked around a little, it would appear that the fuse-python 0.2 bindings are for FUSE 2.6, it may be that a slight change has introduced this error (FUSE is now at version 2.8). My solution was to stop using fuse-python (the code is an ugly mess), and I found an alternate binding fusepy. I've not looked back, and had no trouble since.
I highly recommend you take a look, your initialization code will be cleaner, and minimal changes are required to adapt to to the new binding. Best of all, it's only one module, and an easy read.


text:
Q: How to deactivate all firebase users without logged in?
*

*I have a try to deactivate account from firebase, But I have faced a
scenario like if I want to deactivate account in firebase at time I
have to logged in with that use.

*But if I am admin and I want to
deactivate other user account than how can I logged in with that
user,it's seems like manual process to logged in than deactivate
account.
1) I also have question if this overcome from triggering cloud function like when in firebase database->user(child node)->"isuser_deactivate -> yes/no" than trigger cloud function without logged in.
2) Any of api functionality that overcome that problem so please give me
    reference.

A: You can do this , as you said by using a child isuser_deactivate : yes/no.
The problem you are facing is you have written rules such that  only repective users can access their childs.
".read" : "$uid === auth.uid",
".write" : "$uid === auth.uid"

change this rules to
".read" : "$uid === auth.uid || $uid === adminUID",
".write" : "$uid === auth.uid || $uid === adminUID"

Now you will be able to access their tree from you custom admin panel


text:
Q: FileReadingMessageSource.WatchServiceDirectoryScanner: turn off recursive descent into sub-directories? Versions:
Spring: 5.2.16.RELEASE
Spring Integrations: 5.3.9.RELEASE
macOS Big Sur: 11.6

I am using XML to set up the directory scanner FileReadingMessageSource.WatchServiceDirectoryScanner like so:
<int-file:inbound-channel-adapter id="channelIn" directory="${channel.dir}" auto-create-directory="false" use-watch-service="true" filter="channelFilter" watch-events="CREATE,MODIFY">
  <int-file:nio-locker ref="channelLocker"/>
  <int:poller fixed-delay="${channel.polling.delay}" max-messages-per-poll="${channel.polling.maxmsgs}"></int:poller>
</int-file:inbound-channel-adapter>

with the following bean definitions:
<bean id="channelLocker" class="org.springframework.integration.file.locking.NioFileLocker"/>
<bean id="channelFilter" class="org.springframework.integration.file.filters.ChainFileListFilter">
  <constructor-arg>
    <list>
      <bean class="org.springframework.integration.file.filters.SimplePatternFileListFilter">
        <constructor-arg value="SpreadSheets*.xls" />
      </bean>
      <bean id="filter" class="org.springframework.integration.file.filters.LastModifiedFileListFilter">
        <property name="age" value="${channel.filter.age}" />
      </bean>
      <ref bean="persistentFilter" />
    </list>
  </constructor-arg>
</bean>

<bean id="persistentFilter" class="org.springframework.integration.file.filters.FileSystemPersistentAcceptOnceFileListFilter">
  <constructor-arg index="0" ref="metadataStore" />
  <constructor-arg index="1" name="prefix" value="" />
  <property name="flushOnUpdate" value="false" />
</bean>

If I look at logs for org.springframework.integration.file.FileReadingMessageSource, I notice that we register both the specified directory (ie, ${channel.dir}) as well as any of its sub-directories.  That is, I see logs like this:
15:44:45.706 [main] DEBUG org.springframework.integration.file.FileReadingMessageSource - registering: /Users/kc/scan.here for file events
15:44:45.711 [main] DEBUG org.springframework.integration.file.FileReadingMessageSource - registering: /Users/kc/scan.here/and.here for file events

I've looked Spring docs as well as API docs for the relevant software modules (Eg, FileReadingMessageSource), but I don't see any property or configuration option for turning off recursive descent into sub-directories.
What is the recommended practice here for scanning only files within the specified directory, but not recursing any deeper than that?

A: If you don't a recursion and scan the whole file tree, just don't use that watch service!
For the create and modify events you can configure a FileSystemPersistentAcceptOnceFileListFilter which checks for the file.lastModified(). I see you do that anyway, therefore it is not clear why do you need a watch service at all?
See some related discussed here: https://github.com/spring-projects/spring-integration/issues/3557.
If you still have some reasonable argument to use watch service for only a root dir, please add a comment into that issue and we will revise it respectively.


text:
Q: Syntax highlighting for embedded languages in VS Code I am busy making my own grammar extension in Visual Studio Code. The language is called Snake, say, and the grammar kicks in when a file of the kind "*.snk" is opened, for instance "hello-world.snk". So far, so good. I can teach VS Code the syntax highlighting for Snake in a grammar file, and it all works.
But I can't get embedded language syntax highlighting to work.
Inside a ".snk" file, it is possible to include javascript codeblocks. I am able to get VS Code to give programmatic language support  for javascript (like snippets) inside these embedded javascript codeblocks to work (via the embeddedLanguages property in the tmLanguage.json file). But I can't get javascript syntax highlighting to work inside the javascript codeblocks.
In fact, the documentation is entirely silent on getting syntax highlighting for embedded languages to work. It only talks about programmatic features  like commenting code and triggering snippets.
Can anyone help me?

A: in packages.json
     "embeddedLanguages": {
                    "source.js": "javascript",
                    "meta.embedded.block.javascript": "javascript"
      }

in your syntax def file:
 "jscode": {
            "patterns": [
                {
                    "name": "js.block.sl",
                    "begin": "js:\\s*{{{",
                    "end": "^\\s*}}}\\s*$",
                    "patterns": [
                        {
                            "begin": "(^|\\G)(\\s*)(.*)",
                            "end": "^\\s*}}}\\s*$",
                            "contentName": "meta.embedded.block.javascript",
                            "patterns": [
                                {
                                    "include": "source.js"
                                }
                            ]
                        }
                    ]
                }
            ]
        },

Adjust the begin and end pattern.
in short, you need match the begin and end of your block. then in the matched block, match js and include all js highlight pattern.
How I learn this ? from vscode source code.
https://github.com/microsoft/vscode/blob/master/extensions/markdown-basics/package.json
https://github.com/microsoft/vscode/blob/master/extensions/markdown-basics/syntaxes/markdown.tmLanguage.json#L959

A: I was looking for something similar and here's what struck me.
This is a sample pattern from the .tmLanguage.json for my language "mylang". It's for strings, that begin with a ' or " and end with the same character. Within the string, there are escape characters coloured differently, and because "mylang" supports string interpolation, you can have stuff like "value is $value", where the variable references should be coloured differently (compared to the overall string colour).
This is basic embedded highlighting, and if you have clear anchors that mark the start and end of your embedded language snippet, you can adjust the begin and end and it should work.
"strings": {
            "name": "string.quoted.double.mylang",
            "begin": "(\"|')",
            "end": "\\1",
            "patterns": [
                {
                    "name": "constant.character.escape.mylang",
                    "match": "\\{[a-z.0-9,A-Z*_/~-]*\\}|\\\\|\\\\0\\d\\d|\\\\\\w"
                },
                {
                    "name": "variable.name.mylang",
                    "match": "\\$[a-z][a-z.0-9A-Z]*|\\$\\([a-z.0-9,A-Z-]*\\)(\\([.0-9-]+\\))?"
                }
            ]
        }

Now if I were to define a new object in my code, say, using the following syntax:
var mjs = JSON('{"value": 42}')

var is a language keyword, JSON is a class/type name. The JSON constructor takes a string containing the JSON text, and parses it to a tree.
They have their own highlight colours. The string within '' has its own overall colour. I would now want everything between the regexes JSON\\(' and '\\) to be coloured based on various sub-patterns (e.g. keys might be ".*"\s+: and so on)
Note that if I literally specified JSON\\( as the begin pattern, the JSON would be part of it, and not be highlighted with the colour for type names. It might help to use a lookbehind instead: (?<JSON)\\( if memory serves right.
And repeat the whole thing for YAML('...'), XML('...'), ...


text:
Q: Batch How to clear clipboard after get copy from clipboard using CreateObject( htmlfile ) ClipboardData This question is based on my previous question here .
Major of these below codes are combination from @Hackoo answer(many thanks to Him) and some other users from SO. And I made a very little effort to combine them with other's codes to arrange a simple tutorial board which can  :

*

*paste user input(hidden) using number 1 and automatically entered without pressing enter.

*typewriting the input with type writer.

*read and speak the input.

For now, it is working as intended. The full codes is as follow :
@echo off
title %~nx0
color 0a
setlocal EnableDelayedExpansion
set color_white=%ESC%[37m
set color_black=%ESC%[30m
:menuLOOP
Color 0A & Mode con cols=78 lines=25
echo(
echo(       ===============================================================
::set choice=
choice /c 12345 /n /m "   "

IF errorlevel 5 goto choice5
IF errorlevel 4 goto choice4
IF errorlevel 3 goto choice3
IF errorlevel 2 goto choice2
IF errorlevel 1 goto choice1

:choice1 INPUT TYpewriter
call :menu_[1]
GOTO:menuLOOP
:choice2 PLAY TYpewriter Audio
call :menu_[2]
GOTO:menuLOOP
:choice3 STOP TYpewriter Audio
call :menu_[3]
GOTO:menuLOOP
:choice4 PLAYLoop TYpewriter Audio
call :menu_[4]
GOTO:menuLOOP
:choice5
call :menu_[5]
GOTO:menuLOOP

::********************************************************************************************
:menu_[1] input
cls
echo:
set SendKeys=CScript //nologo //E:JScript "%~F0"
echo pasteclip= CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text") > temp.vbs
echo WScript.Echo pasteclip >> temp.vbs
cscript //nologo temp.vbs > temp.txt

set color_white=%ESC%[37m
set color_black=%ESC%[30m

REM for /f "Tokens=* Delims=" %%x in (temp.txt) do set SendPaste=%%x

REM set "text=%SendPaste%"%color_black%

set "File2Read=temp.txt"
rem This will read a file into an array of variables and populate it
setlocal EnableExtensions EnableDelayedExpansion
for /f "delims=" %%a in ('Type "%File2Read%"') do (
    set /a count+=1
    set "Line[!count!]=%%a"
)
rem Display array elements
@For /L %%i in (1,1,%Count%) do (
    :: You should call this Call :Typewriter "!Line[%%i]!" inside the loop for /L
    Call :Typewriter "!Line[%%i]!"

)

GOTO:menuLOOP

::********************************************************************************************
:menu_[2] Play TYpewriter Audio
cls & color 0A
Call:SkipLine 10
Call:Tab 3
::echo %x% Please Wait for a while .. Launching DJ Buzz Radio ...
Taskkill /IM "wscript.exe" /F >nul 2>&1
Set vbsfile=%temp%\DJBuzzRadio.vbs
Set URL=Typewriter-sound.mp3
Call:Play %URL% %vbsfile%
Start %vbsfile%
TimeOut /T 1 /NoBreak>nul
GOTO:menuLOOP
::********************************************************************************************

:menu_[3] Stop the music
cls & color 0C
Call:SkipLine 10
Call:Tab 3
::echo  %x% Please Wait for a while .. Stopping the music ...
Taskkill /IM "wscript.exe" /F >nul 2>&1
TimeOut /T 1 /NoBreak>nul
GOTO:menuLOOP

::********************************************************************************************
:menu_[4] PlayLoop TYpewriter Audio
cls & color 0A
Call:SkipLine 10
Call:Tab 3
::echo %x% Please Wait for a while .. Launching DJ Buzz Radio ...
Taskkill /IM "wscript.exe" /F >nul 2>&1
Set vbsfile=%temp%\DJBuzzRadio.vbs
Set URL=Typewriter-sound.mp3
Call:PlayLoop %URL% %vbsfile%
Start %vbsfile%
TimeOut /T 1 /NoBreak>nul
GOTO:menuLOOP
::********************************************************************************************
::********************************************************************************************
:Play
(
echo Play "%~1"
echo Sub Play(URL^)
echo    Dim Sound
echo    Set Sound = CreateObject("WMPlayer.OCX"^)
echo    Sound.URL = URL
echo    Sound.settings.volume = 100
echo    Sound.Controls.play
echo    do while Sound.currentmedia.duration = 0
echo        wscript.sleep 100
echo    loop
echo    wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000
echo End Sub
)>%~2
::*********************************************************************************************

::********************************************************************************************
:PlayLoop
(
echo Play "%~1"
echo Sub Play(URL^)
echo    Dim Sound
echo    Set Sound = CreateObject("WMPlayer.OCX"^)
echo    Sound.URL = URL
echo    Sound.settings.volume = 100
echo    Sound.settings.setMode "loop", True
echo    Sound.Controls.play
echo    While Sound.playState ^<^> 1
echo        WScript.Sleep 100
echo    Wend
echo End Sub
)>%~2
::*********************************************************************************************
::*********************************************************************************************
:Tab
set "x="
For /L %%I In (1,1,%1) Do Set "x=!x!    "
REM                                  ^-- this is a TAB
goto :eof
::*********************************************************************************************
:SkipLine
    For /L %%I In (1,1,%1) Do Echo(
    Goto:Eof
:EOF
EXIT
::*********************************************************************************************

::*********************************************************************
:TypeWriter
Cls
echo(
(
echo strText=wscript.arguments(0^)
echo intTextLen = Len(strText^)
echo intPause = 150
echo For x = 1 to intTextLen
echo     strTempText = Mid(strText,x,1^)
echo     WScript.StdOut.Write strTempText
echo     WScript.Sleep intPause
echo Next
echo Set Voice=CreateObject("SAPI.SpVoice"^)
echo voice.speak strText
)>%tmp%\%~n0.vbs
@cScript.EXE /noLogo "%tmp%\%~n0.vbs" ^" ^
%empty line%
^
%empty line%
     %~1^"

exit /b
::*********************************************************************

:: Most helpful references to arrange this batch:
::https://stackoverflow.com/questions/28369536/batch-file-typewriter-effect
::https://stackoverflow.com/questions/664957/can-i-mask-an-input-text-in-a-bat-file?lq=1
::https://stackoverflow.com/a/63847096/9222942 mask with black
::https://stackoverflow.com/a/24792070/9222942 can-i-mask-an-input-text-in-a-bat-file
::https://stackoverflow.com/a/62121081/9222942 how-can-you-get-the-clipboard-contents-with-a-windows-command
::https://stackoverflow.com/a/31880899/9222942 how-to-play-invisible-music-in-a-batch-file
::https://stackoverflow.com/a/21205537/9222942 automatically-accept-user-input-windows-batch
::https://stackoverflow.com/a/16116676/9222942%20how-to-read-file-contents-into-a-variable-in-a-batch-file

But a problem is that, this batch store every clipboard beginning from running the first command 1.
Let say, for the first time i copied sentence 1 with text "Summarize the problem".
After running the batch, by pressing 1 , the input sentence 1 should then be typewritten to cmd.
Then when i copied sentence 2 with text let say "describe what you've tried" , it will repeat the sentence 1 , and only after finishing the sentence 1 it will write sentence 2.
Even when I do copy for the third time, the forth, it will also repeat from the very first clipboard(i.e sentece 1, sentence 2 and so on)
My question is, how to stop the repeatation of the first clipboard sentence?
I've tried manually delete the temp.txt and the temp.vbs after running the first command but didnt help.
Also i've tried using cmd /c "echo off | clip" which is from here .
I've applied it as follow :
@For /L %%i in (1,1,%Count%) do (
    :: You should call this Call :Typewriter "!Line[%%i]!" inside the loop for /L
    Call :Typewriter "!Line[%%i]!"
    cmd.exe /c echo.|clip

)

, but also didnt work.
Could someone please help on how to clear the the repeatation?

A: As instructed by Sir Stephan(all credit goes to Him), all i need to do is add set "Count=0" before the 1st for loop that counts the lines :
setlocal EnableExtensions EnableDelayedExpansion
set "Count=0"
for /f "delims=" %%a in ('Type "%File2Read%"') do (
    set /a count+=1
    set "Line[!count!]=%%a"
)
rem Display array elements
@For /L %%i in (1,1,%Count%) do (
    :: You should call this Call :Typewriter "!Line[%%i]!" inside the loop for /L
    Call :Typewriter "!Line[%%i]!"


text:
Q: nodemon not restarting froze at "[nodemon] restarting due to changes..." im having this issue, currenly im developing a express.js app with babel and nodemon. but resenly when i try to restart the server, it froze at [nodemon] restarting due to changes... and dosent restart. the command im using is npm run dev for develop. i tried every single solution "change to nodemon 2.0.7", "npm clean cache --force", "install @babel/cli, @babel/node, etc", "uninstall nodemon and then install it" and nothing work
Im using Windows 10 and .env files
Console
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `npx babel-node src/index.js`
Server listen on port 4000
Db is connected
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...

package.json
{
  "name": "scrap-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "babel src --out-dir build",
    "dev": "nodemon --exec npx babel-node src/index.js",
    "start": "node build/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "bcryptjs": "^2.4.3",
    "core-js": "^3.22.5",
    "cors": "^2.8.5",
    "dotenv": "^16.0.0",
    "express": "^4.17.3",
    "helmet": "^5.0.2",
    "jsonwebtoken": "^8.5.1",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.7",
    "pg": "^8.7.3",
    "regenerator-runtime": "^0.13.9"
  },
  "devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/core": "^7.17.10",
    "@babel/node": "^7.17.10",
    "@babel/plugin-transform-runtime": "^7.17.10",
    "@babel/preset-env": "^7.16.11",
    "babel-plugin-transform-runtime": "^6.23.0"
  }
}

.babelsrc file
    {
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": ["@babel/transform-runtime"]

}

right now is very frustrating because i have to stop the server and run it over and over again.
any sugestion apart of the mentioned, are welcome ):
Thanks!


text:
Q: Run a detached process with fabric and screen According to the FAQ, from the recommended ways to run a detached process, the only one that works for me is screen since I cannot install programs on the server and can't seem to make nohup work. I would like to:

*

*run(command) so that the command keeps running without blocking.

*Know the pid of the process I am running so I can kill it later.

No combination of nohup redirections and screen -md command has worked for me so far.
In particular, running this command line does work when executed directly on the server but not trough the run function of fabric. I believe the process is closed when the function returns and I have no time to see it:

nohup /opt/logstash/bin/logstash agent -f /home/unicryo/PVSS_projects/GenerateErrors/logstash_conf/logstash-config-minimum.cfg >> test.out 2>&1 &

A: You have been unable to nohup the process because it's not really supported by Fabric.
I'd strongly advise running this command via a process manager (see Fabric's documentation suggestions) because it's far easier to manage (e.g. service logstash stop versus finding the running command in a screen session) and cleaner, but you should be able to get away with something like the following via Fabric:
run("screen -d -m '/opt/logstash/bin/logstash agent -f /home/unicryo/PVSS_projects/GenerateErrors/logstash_conf/logstash-config-minimum.cfg'")


text:
Q: Medir caracteres en Bash Tengo que medir la longitud de los caracteres de 1 o más argumentos introducidos por la terminal, si la suma de los caracteres es mayor que 80, entonces decir cuantas columnas ocupa.
Esto es lo que he intentado, pero no acaba de funcionar completamente:
#!/bin/bash

clear

if test $# -lt 1; then
echo No has indicado uno o más argumentos
exit 3
fi

len= echo $(expr length $#)
echo "La longitud de caracteres de los parámetros pasados es de: $len"

if [ $len -lt "80" ];
then
echo "El número de filas ocupado por los parámetros introducidos es 1"
else
echo "El número de filas ocupado por los parámetros introducidos es mayor "
fi

A: Espero haber entendido bien tu problema, en tal caso el código que lo resuelve sería:
#!/bin/bash

clear

amount_args=$#
if test $amount_args -lt 1; then
  echo "No has indicado uno o más argumentos"
  exit 3
fi

all_args=$*
len=${#all_args}

# Le quito los espacios entre los argumentos de entrada
let "len = len - amount_args + 1"

echo "La suma de la longitud de caracteres de los argumentos pasados es de: $len"

if [ $len -lt "80" ];
then
  echo "El número de filas ocupado por los argumentos introducidos es 1"
else
  (($len % 80)) && let "rows = (len / 80) + 1" || let "rows = (len / 80)"
  echo "El número de filas ocupado por los argumentos introducidos es: $rows"
fi

Ojala te sirva, saludos :)