text:
Q: Load ResourceDictionary item dynamically based on property value Is it possible to load one of my stackpanels based on a string property inside my viewmodel? So if string is MyStackPanel1 then the appropiate stackpanel will be injected into the grid of my mainwindow.
My ResourceDictionary
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <StackPanel x:Key="MyStackPanel1" Background="{Binding Color}">
       // Has some content
    </StackPanel>

    <StackPanel x:Key="MyStackPanel2" Background="{Binding Color}">
     // Has some other content
    </StackPanel>
</ResourceDictionary>

My MainWindow:
<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid>

    </Grid>
</Window>

Here an idea of the viewmodel:
public class ViewModel : INotifyPropertyChanged {
  public event PropertyChangedEventHandler PropertyChanged;
  public string StackPanelName { get; set; };
  public string Color { get; set; };

   private void ChangedHandler(string propertyToBeChanged) {

   }
}

A: I think I have an idea how to solve this. First I define a list of resources:
In XAML I write:
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

<Grid x:Name="Body">
    <ContentControl x:Name="Sample" ContentTemplate="{StaticResource MyResource1}"/>
</Grid>

Now in my resource dictionary:
<DataTemplate x:Key="MyResource1" x:Shared="false">
    <StackPanel>
        <TextBlock Background="{Binding background}">Hello World</TextBlock>
    </StackPanel>
</DataTemplate>

// Resource2 and so on

Then In my view I can do the following:
public void SwapResource(ContentControl contentControl, string resourceName) {
    contentControl.ContentTemplate = (DataTemplate)FindResource(resourceName);
}

Problem is that the bindings wont work...

A: You could use a ContentControl with ContentTemplates but for the bindings to work you should set the Content property of the ContentControl:
<Window.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="MyResource1" x:Shared="false">
            <StackPanel>
                <TextBlock Background="{Binding background}">Hello World</TextBlock>
            </StackPanel>
        </DataTemplate>

        <!-- Resource2 and so on -->
    </ResourceDictionary>
</Window.Resources>

<Grid x:Name="Body">
    <!-- "background" is a property of the view model -->
    <ContentControl x:Name="Sample" Content="{Binding}" ContentTemplate="{StaticResource MyResource1}"/>
</Grid>


text:
Q: NullReferenceException vb.net Unit testing error Doing some homework on unit testing and in all honestly i just don't get why i get this error.
i got a simple method that select all text when tab and testing if the actually textbox1 is selected. I just don't get why i'm getting a nullReferenceException at target.txtbox1_Enter(sender, e)
I'm getting really mad because this seem so easy.
any help i would appreciate it.
Private Sub txtbox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtbox1.enter
    Dim txtBox As TextBox
    txtBox = CType(sender, TextBox)
    txtBox.SelectAll()
End Sub

    <TestMethod(), DeploymentItem("frmtesting.exe")>
Public Sub txtCustomer_EnterTest()
    Dim target As frmtesting_Accessor = New frmtesting_Accessor ' TODO: Initialize to an appropriate value
    Dim sender As Object = Nothing ' TODO: Initialize to an appropriate value
    Dim e As EventArgs = Nothing ' TODO: Initialize to an appropriate value

    Dim expected As String
    Dim actual As String
    target.txtbox1.Text = "bob"
    target.txtbox1.SelectAll()
    expected = "bob"

    target.txtbox1_Enter(sender, e)

    actual = target.txtbox1.SelectedText
    Assert.AreEqual(expected, actual, "not equal")
End Sub

A: This would be the correct way of doing it.
'''<summary>
    '''A test for TextBox1_Enter
    '''</summary>
    <TestMethod(), _
     DeploymentItem("frmtesting.exe")> _
    Public Sub TextBox1_EnterTest()
        Dim target As frmtesting.exe_Accessor = New frmtesting.exe_Accessor()
        Dim sender As Object = target.TextBox1
        Dim e As EventArgs = Nothing

        target.txtBox1.Text = "bob"

        target.txtBox1_Enter(sender, e)

        Assert.AreEqual("bob", target.txtBox1.SelectedText, "not equal")

    End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to support multiple environments/DNS in Selenium Grid? I have a suite of automated tests that run on a Selenium Grid. I have a need now to run these tests in multiple environments (QA, Stage, Production). The environments will be set up using a different DNS server for each one. So a test targeting the QA environment should use the QA DNS, Stage tests should use the Stage DNS, etc.
Ideally, I would like my test suite (which runs in Jenkins and accepts a parameter for which environment to target) to be able to tell the grid to allocate a node, set its DNS servers to (whatever), run the test, then put the DNS servers back the way it found them.
I don't see anything in Selenium's documentation about changing DNS settings on the individual nodes. I also tried looking for browser capabilities that could handle this, but no luck there either. What's the cleanest way to make this happen?
EDIT: The requirement to switch DNS servers is a new one, so there's currently no method in place (manual or automatic) for doing it. Before using this DNS-based method of differentiating environments, we were using environment-specific hostfiles, and switching between them with a custom service that listened on each node for a hostfile-switch request. We might have to create a similar service for switching DNS settings, but I was hoping there was something more "official" than that.

A: We worked around this issue by setting up a proxy server for each environment, and configuring the proxy servers to use the environment-specific DNS settings. Selenium permits setting a proxy on the individual nodes, so this was a way to programatically modify those settings.


text:
Q: SyntaxError: Cannot use import statement outside a module - Firebase with NodeJS Node.js Code I have in index.js
let express = require('express')
const path = require('path');
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
const firebaseConfig = {
    ...
};
const firebaseApp = initializeApp(firebaseConfig);
const database = getDatabase(firebaseApp);

let app = express()
const port = 8080
app.get('/updateRelay/:relayId/:status', function (req, res) {
    const relayId = req.params["relayId"]
    const status = req.params["status"]
    console.log(relayId,status)
    let updateObject = {}
    updateObject[relayId] = status
    database.ref("iot-device-001/status").set(updateObject, function(error) {
        if (error) {
            // The write failed...
            console.log("Failed with error: " + error)
        } else {
            // The write was successful...
            console.log("success")
        }
    })
});

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, '/index.html'));
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

I cannot for the love of God figure out what is wrong with this code. I have tried every documentation and tutorial available and end up with some unexplainable error. Its either this or its Module Not Found. Here is the link for the tutorial I followed which gave me Module Not Found error
Here is the error I have right now
import { initializeApp } from 'firebase/app';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

A: It seems that your function is not defined as being a module so you can't use importinside of it. You'll have to use require
You might solve your issue by replacing
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database"

by
var initializeApp = require('firebase/app')
var getDatabase = require('firebase/database')

You will find more explanation here : https://flexiple.com/javascript-require-vs-import/

A: It is often a bit confusing how to implement it from Node JS. The easiest way is to follow this guide for the installation in NodeJS, once the SDK is installed in your local project it is necessary to initialize it.
For that, you should follow the instructions to generate a Private key that you have to add to your project to call the services from it
Even so, it is still a bit confusing but I found a very simple guide that explains in a visual and detailed way how to do it.

A: Here is a solution that worked for me, replace
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database"

with
var {initializeApp} = require('firebase/app')
var {getDatabase} = require('firebase/database')


text:
Q: How can I retrieve a nested type with its fully qualified name? I cannot seem to retrieve a nested class using Roslyn's Compilation.GetTypeByMetaDataName() method.
For example:
var tree = CSharpSyntaxTree.ParseText(@"
using System;
namespace MyNamespace
{
    public class MyClass
    {
        public class MyInnerClass
        {
        }
    }
}
");

var Mscorlib = new MetadataFileReference(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });

//Correctly retrieves outer type.
var outerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass");
//Cannot correctly retrieve inner type (returns null)
var innerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass.MyInnerClass");

Is it possible to retrieve nested types using their fully qualified names?
I realize one work around would be to first check if the containing type contained any types using INamespaceorTypeSymbol.GetTypeMembers(), but I would much rather not go down that path. I'd assume the GetTypeByMetaDataName() method should work for any type, nested or otherwise.

A: Try using + to separate inner classes:
var innerClass = compilation.GetTypeByMetadataName("MyNamespace.MyClass+MyInnerClass");

The documentation for the Type.GetType method discusses the syntax used for naming nested types.


text:
Q: UISlider alpha stuck at 0.5 I have a UISlider inside a cell and I set its alpha to 1 but when the slider is displayed the alpha is stuck at 0.5. How do I change it?

lazy var videoSlider: UISlider = {
    let slider = UISlider()
    slider.translatesAutoresizingMaskIntoConstraints = false
    slider.minimumTrackTintColor = UIColor.orange
    slider.maximumTrackTintColor = UIColor.white
    slider.setThumbImage(UIImage(named: "sliderThumb"), for: .normal)
    slider.isEnabled = false
    slider.alpha = 1.0 // set at 1 here and never changed
    return slider
}()

I also tried:
override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = UIColor.black

    videoSlider.alpha = 0
    UIView.animate(withDuration: 0.33, animations: {
        self.videoSlider.alpha = 1
    })
}

A: It was the period  time observer that was causing the problem. As the time progressed and the track moved along for some reason the slider color was getting reset to 0.5. To fix it I updated the alpha on the main queue.
timeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { [weak self](progressTime) in

    let seconds: Float64 = CMTimeGetSeconds(progressTime)

    if let duration = self?.player?.currentItem?.duration {

        let durationSeconds: Float64 = CMTimeGetSeconds(duration)

        // even though this is already happening on the main queue it didn't work without it
        DispatchQueue.main.async {
            self?.videoSlider.alpha = 1
        }

        self.videoSlider.value = Float(seconds / durationSeconds)
    }
})


text:
Q: RMI multiple clients Does RMI handles multiple clients by itself? i.e.

*

*is it possible to use a server function by multiple clients at the same time?

*if no, how can I do such a thing?

*if yes, how it works? does it make a new thread for each call? if one clients blocks the function what would happen with the next client? etc.

A: yes

how it works? does it make a new thread for each call? if one clients blocks the function what would happen with the next client? etc.

It creates a thread for each client connection.
If one client calls a synchronized method or one which blocks other calls, calls made by other threads will block until that call releases the resource.
It sounds like you already worked out the answers, do you have a more specific doubt?

A: Yes  RMI does handles multiple clients, but you must make your server threadsafe , RMI will  dispatch multiple threads into a single server object if multiple clients simultanuosly
make methods call on it so if your server isn't threadsafe your application will fail.


text:
Q: How can I check if a string already contains a character in Swift I would like to check in my app, if there is already a - character in the textField.
How can I do this?

A: You can use contains() method
let myString = "test"
if myString.contains("e"){
   let index = myString.index(of: "e")
   myString.remove(at: index!)
}

p.s you can get myString from textField.text

A: You can simply:
var yourTextFieldString: String = textField.text

yourTextFieldString.contains("-")

It returns a Bool.


text:
Q: AR mode doesn't find Pokemon When I find a wild Pokemon, it shows in the app but when I set AR on, it doesn't show anymore. I can catch it only when the AR is off and I cannot take real world pictures with the pokemon. What's wrong?

A: Depending on the phone you have.
I have a Sony C4, and the same problems occurs for me. So I have to play without the AR mode, it's not really embarrassing and the game is still awesome.
The problem is the gyroscope. This little thing controlled by the accelerometer, will make the Pokémon appear in AR mode.
Here is the link to the App (Play Store) to check if you do have a gyroscope or if you don't. Sensor Kinetics
If you want to know a bit more, here's the reddit source.
Hope it helps.


text:
Q: Fastest way to remove inline CSS of an element and all its children? I want to delete all inline CSS from an element and all its children.
Now I do in this way:

$('#element').attr('style', '');
$('#element').find('div').attr('style', '');
$('#element').find('a').attr('style', '');
$('#element').find('span').attr('style', '');
$('#element').find('p').attr('style', '');

    bla bla

But that is a lot of code.... Is there a faster way?

A: you can just:
$('#element, #element *').attr('style','');

you can achieve alot from css selector, read more about it here

The 30 CSS Selectors you Must Memorize,
  here.

A: The simplest way would be:

$('#element, #element *').removeAttr('style');

    bla bla

Literally - find #element, and any elements under it, then remove any style attributes they might have.

A: You could just select all the descendant elements using the universal selector and then use the .addBack() method to add back the initial element:
$('*', '#element').addBack().removeAttr('style');

or:
$('#element').find('*').addBack().removeAttr('style');


text:
Q: Uniting JsonResult why can't I get access through dynamic if the items are an anonymous type I had a method looking like:
public JsonResult GetSpecies()
        {
            var species = new List<SpeciesType> {
                                                new SpeciesType{ Id=1, Name="Giraffe" },
                                                new SpeciesType{ Id=2, Name="Wolf" }
                                            };

            return Json(new { Species = species });
        }

Then I had the assembly this is in make its internals visible to my test project and had a test:
[TestMethod]
        public void GetSpecies_ReturnsJsonVersionOfNameAndId()
        {
            ...

            var result = controller.GetSpecies();

            dynamic data = result.Data;

            Assert.AreEqual(1, data.Species[0].Id);
            Assert.AreEqual("Giraffe", data.Species[0].Name);
            Assert.AreEqual(2, data.Species[1].Id);
            Assert.AreEqual("Wolf", data.Species[1].Name);
        }

So this worked fine.
I altered the method to return anonymous types in the array:
public JsonResult GetSpecies()
            {
                var species = new List<SpeciesType> {
                                                    new SpeciesType{ Id=1, Name="Giraffe" },
                                                    new SpeciesType{ Id=2, Name="Wolf" }
                                                }.Select(x => new { Id = x.Id, Name = x.Name });

                return Json(new { Species = species });
            }

The test now throws exceptions.
Can anyone explain why this is happening and how to fix?

A: You're now not providing a List<T> - your Species property is just a sequence. I don't know how it's representing in JSON, and if it actually went across the wire, it might be okay - but it's probably simplest to just make sure that the Species value is actually a list:
var species = new List<SpeciesType> {
                                    new SpeciesType{ Id=1, Name="Giraffe" },
                                    new SpeciesType{ Id=2, Name="Wolf" }
                                }
    .Select(x => new { Id = x.Id, Name = x.Name })
    .ToList();


text:
Q: WSO2 Kafka Inbound Endpoint Retry on Error We try to use Kafka with WSO2 ESB server.
We've implemented and API which puts incoming messages to Kafka.
Then we've implemented an inbound endpoint that retrieves messages from Kafka and transfer these messages to other external sytems.
Everything works very well in happy path but when we test the "external systems down" scenario failed messages are not delivered when external systems up again.
How can we send failed messages to external systems?
API config:
<?xml version="1.0" encoding="UTF-8"?>
<api context="/api/event" name="EventAPI" xmlns="http://ws.apache.org/ns/synapse">
    <resource methods="POST">
        <inSequence>
            <log category="DEBUG" description="" level="full"/>
            <kafkaTransport.init>
                <bootstrapServers>localhost:9092</bootstrapServers>
                <keySerializerClass>org.apache.kafka.common.serialization.StringSerializer</keySerializerClass>
                <valueSerializerClass>org.apache.kafka.common.serialization.StringSerializer</valueSerializerClass>
                <maxPoolSize>20</maxPoolSize>
            </kafkaTransport.init>
            <kafkaTransport.publishMessages>
                <topic>event_topic</topic>
            </kafkaTransport.publishMessages>
            <loopback/>
        </inSequence>
        <outSequence>
            <payloadFactory media-type="json">
                <format>{"result" : "OK"}</format>
            </payloadFactory>
            <property name="messageType" scope="axis2" type="STRING" value="application/json"/>
            <send/>
        </outSequence>
    </resource>
</api>

Inbound config:
<?xml version="1.0" encoding="UTF-8"?>
<inboundEndpoint name="EventTransmitter" protocol="kafka"
    sequence="transmit_sequence" suspend="false" onError="fault"
    xmlns="http://ws.apache.org/ns/synapse">
    <parameters>

        <parameter name="interval">10</parameter>
        <parameter name="coordination">true</parameter>
        <parameter name="sequential">true</parameter>
        <parameter name="zookeeper.connect">localhost:2181</parameter>
        <parameter name="consumer.type">highlevel</parameter>
        <parameter name="content.type">application/json</parameter>
        <parameter name="topics">event_topic</parameter>
        <parameter name="group.id">myconsumer</parameter>
        <parameter name="consumer.id">myconsumer</parameter>

        <parameter name="dual.commit.enabled">true</parameter>
        <parameter name="auto.offset.reset">largest</parameter>

    </parameters>
</inboundEndpoint>

Sequence:
<?xml version="1.0" encoding="UTF-8"?>
<sequence name="transmit_sequence" onError="fault" trace="disable" xmlns="http://ws.apache.org/ns/synapse">

    <send receive="event_transmit_out_sequence">
        <endpoint key="gov:endpoints/HandlerEndpoint.xml"/>
    </send>

</sequence>


text:
Q: PHP Sort Array Returned From FTP Server I have this array returned from my home NAS FTP server:
$arr = array (
  0 => 'FOLDER./Vacation.Paris.2018.5Month-Kodak[town]',
  1 => './Vacation.Paris.2018.5Month-Kodak[town]/DESC.txt',
  2 => './Vacation.Paris.2018.5Month-Kodak[town]/NUMBERS_CONTACT.vbs',
  3 => './Vacation.Paris.2018.5Month-Kodak[town]/paris.vacation.2018.5month-kodak.mkv',
  4 => './Vacation.Paris.2018.5Month-Kodak[town]/paris.vacation.2018.5month-kodak.dbs',
  5 => 'FOLDER./Vacation.Dubai.2018-Kodak',
  6 => './Vacation.Dubai.2018-Kodak/DESC.txt',
  7 => './Vacation.Dubai.2018-Kodak/NUMBERS_CONTACT.vbs',
  8 => 'FOLDER./Vacation.Dubai.2018-Kodak/Family',
  9 => './Vacation.Dubai.2018-Kodak/Subs/2_IMG00536.jpg',
  10 => './Vacation.Dubai.2018-Kodak/Subs/3_IMG00537.jpg',
  11 => './Vacation.Paris.2018.5Month-Kodak[town]/Vacation.Dubai.2018.Center-Kodak.mp4',
  12 => './Vacation.2019.5Month.Sweden-Kodak.mp4',
);

As you can see i have many folders of my vacation and now i im writing html/css/jquery photo album but i need to get first in php correct order above needs to output:
[0] => FOLDER./Vacation.Paris.2018.5Month-Kodak[town]
[1] => ./Vacation.Paris.2018.5Month-Kodak[town]/DESC.txt
[2] => ./Vacation.Paris.2018.5Month-Kodak[town]/NUMBERS_CONTACT.vbs
[3] => ./Vacation.Paris.2018.5Month-Kodak[town]/paris.vacation.2018.5month-kodak.mkv
[4] => ./Vacation.Paris.2018.5Month-Kodak[town]/paris.vacation.2018.5month-kodak.dbs
[5] => ./Vacation.Paris.2018.5Month-Kodak[town]/Vacation.Dubai.2018.Center-Kodak.mp4
[6] => FOLDER./Vacation.Dubai.2018-Kodak
[7] => ./Vacation.Dubai.2018-Kodak/DESC.txt
[8] => ./Vacation.Dubai.2018-Kodak/NUMBERS_CONTACT.vbs
[9] => FOLDER./Vacation.Dubai.2018-Kodak/Family
[10] => ./Vacation.Dubai.2018-Kodak/Subs/2_IMG00536.jpg
[11] => ./Vacation.Dubai.2018-Kodak/Subs/3_IMG00537.jpg
[12] => ./Vacation.2019.5Month.Sweden-Kodak.mp4

This is code that member from this forum try but it is not working correctly:
https://3v4l.org/208ol
So if you could help me modify above code so that i can get desired output.
Thanks

A: This uses usort to do the work and there is a bit of fiddling needed to get the sort order your after.
The first part is extracting the year from the string - it's assumed that it will be something like xxxxx 2020 xxxxx which is why it uses the second element from the regex used here.  Then it will remove FOLDER only from the front of the string to ensure it isn't removed anywhere else.  Then to get the order 'right', it uses the year followed by the processed string...
usort($arr, function($a, $b) {
    $f = "FOLDER";
    if ( substr( $a, 0, strlen($f)) == $f ) {
        $a = substr( $a, strlen($f));
    }
    $y1 = preg_split("/\D+/", $a)[1];
    if ( substr( $b, 0, strlen($f)) == $f ) {
        $b = substr( $b, strlen($f));
    }
    $y2 = preg_split("/\D+/", $b)[1];
    return $y1.$a <=> $y2.$b;
});
print_r($arr);

This uses the spaceship operator for the comparison, which is PHP 7+ only.


text:
Q: Object creation for nested data structures, an avoidable hit on performance? From Android's Performance Tips:

Object creation is never free. ... As you allocate more objects in your app, you will force a periodic garbage collection, creating little "hiccups" in the user experience.

My app periodically collects GPS data, along with some meta data. For each location request, it should add the result to a data object:
"data": {
    "timestamp": {
      "lat": "value",
      "lng": "value"
      "meta": "value"
    }
    "timestamp": {
      "lat": "value",
      "lng": "value"
      "meta": "value"
    }
    ...
}

Then after the object reaches a certain size, or when the device has better connectivity, the app will stream the full data object to my server, clear it, and re-use the empty object.
While re-using the outer data object would yield better performance, and surely isn't that difficult to accomplish, it seems impossible to re-use the inner timestamp objects. Could I re-use the inner objects that turn out to be useful in the next round of GPS data collection, and let any remaining inner objects be garbage collected?

A:
Could I re-use the inner objects that turn out to be useful in the next round of GPS Data collection, and let any remaining inner objects be garbage collected?

Yes, potentially. But do you have any indication that it's actually a good idea to do so? How often are you collecting this data? You mentioned "periodically" earlier - that doesn't sound like you're getting a huge amount of turnover.
Micro-optimization like this can certainly be important in applications where smooth performance is absolutely critical - such as mobile games - but in many other apps it's just unnecessary, and hurts the readability and maintainability of the code.
I suggest you measure the performance of your app before making a decision either way. Is garbage collection actually hurting you? Is this type a source of these problems? (There's not much point in recycling this particular type if it's only a tiny part of your GC issues.)


text:
Q: Magento 2 - Form Validation is there a overview for the new form validation attributes in Magento 2?

A: There are 3 different ways to use form validation in magento 2
To enable javascript validation use following code in your template
<form class="form" id="custom-form" method="post" autocomplete="off">
 <fieldset class="fieldset">
     <legend class="legend"><?php echo __('Personal Information') ?></legend>

          <?php echo __('Email') ?>

              <input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">

 </fieldset>

          <button type="submit" class="action submit primary" title="<?php  echo __('Submit') ?>"><?php echo __('Submit') ?></button>

</form>

1

2
<form data-mage-init='{"validation": {}}' class="form" id="custom-form" method="post" autocomplete="off">

3

*custom-form is form id you can replace it with your form id
List of form validation rules
To wrap up this article, a list of validation rule names is provided here as a quick reference toward the official documentation:
Magento rules:
validate-no-html-tags

validate-select

validate-no-empty

validate-alphanum-with-spaces

validate-data

validate-street

validate-phoneStrict

validate-phoneLax

validate-fax

validate-email

validate-emailSender

validate-password

validate-admin-password

validate-customer-password

validate-url

validate-clean-url

validate-xml-identifier

validate-ssn

validate-zip-us

validate-date-au

validate-currency-dollar

validate-not-negative-number

validate-zero-or-greater

validate-greater-than-zero

validate-css-length

validate-number

required-number

validate-number-range

validate-digits

validate-digits-range

validate-range

validate-alpha

validate-code

validate-alphanum

validate-date

validate-date-range

validate-cpassword

validate-identifier

validate-zip-international

validate-one-required

validate-state

required-file

validate-ajax-error

validate-optional-datetime

validate-required-datetime

validate-one-required-by-name

less-than-equals-to

greater-than-equals-to

validate-emails

validate-cc-type-select

validate-cc-number

validate-cc-type

validate-cc-exp

validate-cc-cvn

validate-cc-ukss

validate-length

required-entry

not-negative-amount

validate-per-page-value-list

validate-per-page-value

validate-new-password

required-if-not-specified

required-if-all-sku-empty-and-file-not-loaded

required-if-specified

required-number-if-specified

datetime-validation

required-text-swatch-entry

required-visual-swatch-entry

required-dropdown-attribute-entry

Validate-item-quantity

validate-grouped-qty

validate-one-checkbox-required-by-name

validate-date-between

validate-dob

max-words

min-words

range-words

letters-with-basic-punc

alphanumeric

letters-only

no-whitespace

zip-range

integer

vinUS

dateITA

dateNL

time

time12h

phoneUS

phoneUK

mobileUK

stripped-min-length

email2

url2

credit-card-types

ipv4

ipv6

pattern

allow-container-className

jQuery rules:
required,

remote,

email,

url,

date,

dateISO,

number,

digits,

creditcard,

equalTo,

maxlength,

minlength,

rangelength,

range,

max,

min

refer http://inchoo.net/magento-2/validate-custom-form-in-magento-2/

A: You can add class for validation in Magento 2. See example bellow. There is almost 72 rules (validation class) you can use:
$fieldset->addField(
    'email_from',
    'text',
    ['name' => 'email_from', 'label' => __('Email From'), 'title' => __('Email From'), 'required' => true, 'class' => 'validate-email']
);

See blog for list of available rules for more info:

Here is list of validations classes rules supported by magento 2. You
  just need to add css class for the rule to apply.
min_text_length
max_text_length
max-words
min-words
range-words
letters-with-basic-punc
alphanumeric
letters-only
no-whitespace
zip-range
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
stripped-min-length
email2
url2
credit-card-types
ipv4
ipv6
pattern
validate-no-html-tags
validate-select
validate-no-empty
validate-alphanum-with-spaces
validate-data
validate-street
validate-phoneStrict
validate-phoneLax
validate-fax
validate-email
validate-emailSender
validate-password
validate-admin-password
validate-url
validate-clean-url
validate-xml-identifier
validate-ssn
validate-zip-us
validate-date-au
validate-currency-dollar
validate-not-negative-number
validate-zero-or-greater
validate-greater-than-zero
validate-css-length
validate-number
validate-number-range
validate-digits
validate-digits-range
validate-range
validate-alpha
validate-code
validate-alphanum
validate-date
validate-identifier
validate-zip-international
validate-state
less-than-equals-to
greater-than-equals-to
validate-emails
validate-cc-number
validate-cc-ukss
required-entry
checked
not-negative-amount
validate-per-page-value-list
validate-new-password
validate-item-quantity
equalTo

A: When use UI components to make form, we could use the validation like below, it works in Magento 2.1.x, I doesn't test it in other version yet.
<field name="priority">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">Priority</item>
            <item name="formElement" xsi:type="string">input</item>
            <item name="source" xsi:type="string">module_name</item>
            <item name="dataScope" xsi:type="string">priority</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
                <item name="validate-integer" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>

Notice the validation item, in it we could add validation rules, like required-entry, validate-integer etc.
<item name="validation" xsi:type="array">
     <item name="required-entry" xsi:type="boolean">true</item>
     <item name="validate-integer" xsi:type="boolean">true</item>
     <item name="validation_rule_name" xsi:type="boolean">true</item>
     ...
</item>

All validation rules you could find in file vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js, like validate-date, validate-emails etc.

A: If you take reference of /customer/account/create page, you can see the following piece of code underneath the form:

And if you check at form's input attributes, you can see Magento 1 like class attribute values along with new data-validate attribute.
This can be the basis to step up.
Keys files for Validation:

*

*https://raw.githubusercontent.com/magento/magento2/develop/lib/web/jquery/jquery.validate.js

*https://raw.githubusercontent.com/magento/magento2/develop/lib/web/mage/validation.js

*https://raw.githubusercontent.com/magento/magento2/develop/lib/web/mage/validation/validation.js

A: In UI components it can be used by following sample config (Magento v2.2.0):
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="general">
        <field name="priority" sortOrder="1000" formElement="input">
            <settings>
                <validation>
                    <rule name="not-negative-amount" xsi:type="boolean">true</rule>
                </validation>
                [...]
            </settings>
        </field>
    </fieldset>
</form>

See more examples in file:
vendor/magento/module-cms/view/adminhtml/ui_component/cms_page_form.xml
The validators list in UI Components it can be found in vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js.
Just wrote this script to grab all keys with error messages for explanation:

*

*required-entry:
This is a required field.

*validate-alphanum-with-spaces:
Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field.

*phoneUK:
Please specify a valid phone number

*validate-email:
Please enter a valid email address (Ex: johndoe@domain.com).

*ipv4:
Please enter a valid IP v4 address.

*checked:
This is a required field.

*validate-select:
Please select an option.

*ipv6:
Please enter a valid IP v6 address.

*time:
Please enter a valid time, between 00:00 and 23:59

*validate-number:
Please enter a valid number in this field.

*validate-phoneLax:
Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

*dateITA:
Please enter a correct date

*validate-xml-identifier:
Please enter a valid XML-identifier (Ex: something_1, block5, id-4).

*validate-clean-url:
Please enter a valid URL. For example http://www.example.com or www.example.com.

*validate-admin-password:
Please enter 7 or more characters, using both numeric and alphabetic.

*validate-no-html-tags:
HTML tags are not allowed.

*validate-integer:
Please enter a valid integer in this field.

*validate-data:
Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.

*validate-cc-ukss:
Please enter issue number or start date for switch/solo card type.

*min-words:
Please enter at least {0} words.

*alphanumeric:
Letters, numbers, spaces or underscores only please

*validate-identifier:
Please enter a valid URL Key (Ex: "example-page", "example-page.html" or "anotherlevel/example-page").

*validate-street:
Please use only letters (a-z or A-Z), numbers (0-9), spaces and "#" in this field.

*validate-zip-international:
Please enter a valid zip code.

*validate-date:
Please enter a valid date.

*validate-greater-than-zero:
Please enter a number greater than 0 in this field.

*validate-digits:
Please enter a valid number in this field.

*validate-ssn:
Please enter a valid social security number (Ex: 123-45-6789).

*not-negative-amount:
Please enter positive number in this field.

*validate-max-size:
File you are trying to upload exceeds maximum file size limit.

*validate-fax:
Please enter a valid fax number (Ex: 123-456-7890).

*validate-if-tag-script-exist:
Please use tag SCRIPT with SRC attribute or with proper content to include JavaScript to the document.

*min_text_length:
Please enter more or equal than {0} symbols.

*validate-date-au:
Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.

*mobileUK:
Please specify a valid mobile number

*letters-with-basic-punc:
Letters or punctuation only please

*validate-number-range:
The value is not within the specified range.

*phoneUS:
Please specify a valid phone number

*date_range_max:
The date is not within the specified range.

*validate-range:
The value is not within the specified range.

*vinUS:
The specified vehicle identification number (VIN) is invalid.

*range-words:
Please enter between {0} and {1} words.

*validate-zip-us:
Please enter a valid zip code (Ex: 90602 or 90602-1234).

*validate-emails:
Please enter valid email addresses, separated by commas. For example, johndoe@domain.com, johnsmith@domain.com.

*validate-css-length:
Please input a valid CSS-length (Ex: 100px, 77pt, 20em, .5ex or 50%).

*zip-range:
Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx

*validate-phoneStrict:
Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

*dateNL:
Vul hier een geldige datum in.

*letters-only:
Letters only please

*max_text_length:
Please enter less or equal than {0} symbols.

*validate-not-negative-number:
Please enter a number 0 or greater in this field.

*validate-per-page-value-list:
Please enter a valid value, ex: 10,20,30

*no-whitespace:
No white space please

*validate-state:
Please select State/Province.

*validate-url:
Please enter a valid URL. Protocol is required (http://, https:// or ftp://).

*date_range_min:
The date is not within the specified range.

*validate-digits-range:
The value is not within the specified range.

*greater-than-equals-to:
Please enter a value greater than or equal to {0}.

*validate-no-empty:
Empty Value.

*validate-zero-or-greater:
Please enter a number 0 or greater in this field.

*validate-cc-number:
Please enter a valid credit card number.

*validate-emailSender:
Please enter a valid email address (Ex: johndoe@domain.com).

*validate-new-password:
Please enter 6 or more characters. Leading and trailing spaces will be ignored.

*validate-customer-password:
Minimum length of this field must be equal or greater than %1 symbols. Leading and trailing spaces will be ignored.

*validate-password:
Please enter 6 or more characters. Leading and trailing spaces will be ignored.

*less-than-equals-to:
Please enter a value less than or equal to {0}.

*validate-currency-dollar:
Please enter a valid $ amount. For example $100.00.

*time12h:
Please enter a valid time, between 00:00 am and 12:00 pm

*validate-alphanum:
Please use only letters (a-z or A-Z) or numbers (0-9) in this field. No spaces or other characters are allowed.

*validate-item-quantity:
We don\'t recognize or support this file extension type.

*validate-code:
Please use only letters (a-z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.

*email2:
Please enter a valid credit card number.

*max-words:
Please enter {0} words or less.

*stripped-min-length:
Please enter at least {0} characters

*validate-alpha:
Please use letters only (a-z or A-Z) in this field.

*pattern:
Invalid format.

*integer:
A positive or negative non-decimal number please

The script:
declare -A list
key=''
while IFS= read -r line; do
#  echo "${line} -"
  if [ -z "${key:-}" ]; then
    # match validation key
    match=$(echo "${line}" | grep -Eo "^        ['\"]([A-Za-z0-9-]|_)+" | tr -d "' ")
    if [ -n "${match}" ]; then
      key=${match}
    fi
  else
    # match message
    match=$(echo "${line}" | sed -rn "s|.*\\$\.mage\.__[(]['\"](.*)['\"][)].*|\1|p")
    if [ -n "${match}" ]; then
      list[${key}]=${match}
      key=''
    fi
  fi
done < "${DOCROOT_DIR:-/var/www/html}/vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js"

for i in "${!list[@]}"
do
  printf "%s:\n    %s\n" "${i}" "${list[$i]}"
done

A: I have same requirement for Magento2 Form Validation and i did this code
First we will setup a test form

<form class="form" id="custom-form-id" method="post" autocomplete="off">
   <fieldset class="fieldset">
       <legend class="legend"><?php echo __('User Personal Information') ?></legend>

            <?php echo __('Email') ?>

                <input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">

   </fieldset>

            <button type="submit" class="action submit primary" title="<?php  echo __('Submit') ?>"><?php echo __('Submit') ?></button>

</form>

To enable javascript validation for Magento2 Form Validation

Reference :: http://www.onlinecode.org/magento2-form-validation-example/

A: "no-whitespace" option does not work correctly (at least on Magento 2.1). It triggers an error message on any type of "space" character.
Values "test me" and "  test me   " will return the same error.


text:
Q: typescript callback parameter type by callback arguments function funcOne<T extends boolean = false>(isTrue: T) {
  type RETURN = T extends true ? string : number;
  return (isTrue ? "Cool" : 10) as RETURN;
}

function funcCb<T>(cb: (isTrue: boolean) => T) {
  const getFirst = () => cb(true);
  const getSecond = () => cb(false);

  return {
    getFirst,
    getSecond
  };
}

const result = funcCb((isTrueInCb) => {
  return funcOne(isTrueInCb);
});

funcCb return type,  which I get
  const result: {
    getFirst: () => string | number;
    getSecond: () => string | number;
}

But how can I achieve this
 const result: {
    getFirst: () => string;
    getSecond: () => number;
}

I don't want to use as like   const getFirst = () => cb(true) as string;.
I want to it automatically infer the type based on funcCb argument value. funcCb may be used with other functions like
function funcTwo<T extends boolean = false>(isTrue: T) {
  type RETURN = T extends true ? Date : string;
  return (isTrue ? new Date() : new Date().toString()) as RETURN;
}

A: I tried something like this and it seems to be working =)
function funcOne<T extends boolean = false>(isTrue: T) {
  type RETURN = T extends true ? string : number;
  return (isTrue ? "Cool" : 10) as RETURN;
}

function funcCb<T>(cb: (isTrueInCb: false) => number): { getString: string, getNumber: number }
function funcCb<T>(cb: (isTrueInCb: true) => string): { getString: string, getNumber: number }
function funcCb<T>(cb: (isTrueInCb: any) => T): { getString: T, getNumber: T } {
  const getString = cb(true);
  const getNumber = cb(false);

  return {
    getString,
    getNumber
  };
}

const result = funcCb((isTrueInCb) => {
  return funcOne(isTrueInCb);
});

here a playground on TS site:


text:
Q: How to recover from a diskpart clean command I have two hard drives and an ssd in my computer, I accidently ran clean on one of the hard drives.
The disks were both dynamic and had a spanned partiton on it between them.
I accidently ran the clean command on diskpart on one of those hard drives and I've tried multiple pieces of data recovery software but only found one that has managed to get the data back from the non cleaned, but still inaccesible (failed spanned partition) disk, I was using "GetDataBack" from runtime. Is it possible to get my data back from the other hard drive that was cleaned? Most software I've found dosen't support dynamic disks.
Can some one help me?

A: Yes, it is recoverable
This is definitely a tough situation because as you know with dynamic disks in a spanned volume, this combines the disk space available in two or more hard disks to create a dynamic volume. In a way, the data is "cut in half" in both hard drives and typically when one drive fails (or in this case is cleaned), the data is gone if it wasn't backed up.
Here is a picture of for reference.
In my experience, i recommend using TestDisk. Its a freeware that uses the CLI.
https://www.cgsecurity.org/wiki/TestDisk_Download


text:
Q: Linux backdoors I should be wary of I'm new to the server management realm and I'm sure my server is very insecure.  I've gone through the WHM CPanel security check but I'm sure to the real gurus, that check is stupid and nowhere near what it needs to be.  What are a few things I should look out for?

A: I answered a similar question the other day here:
Secure LAMP server for production use
To check for compromise..
Suspicious files in /tmp.  Files in the Web tree unexpected.
Kernel modules loaded that look suspicious. (lsmod)
Processes running that shouldn't be. (ps aufx)
Active network connections. (netstat)
Currently open file descriptors. (lsof)
Ultimately, if the server is compromised, the proper thing to do is to isolate, image, and rebuild.
Edit 1
Bart brought up very good points; especially that you can't trust the local system at all if believed to be compromised.
Once imaged, you can manipulate the image (and filesystems) using known trusted utilities for further forensics.
Dumping traffic on a switch or running a tcpdump on the local system could be useful as well.
Edit 2
I've actually copied utilities from a known good system and used on a remote server before.  Not ideal, but better than nothing.

A: I already made some points in comments, but to consolidate some thoughts...
You're asking about what, potential attack vectors?
Out of box, there's not a lot on today's Linux installs that you normally need to worry about right away. Most people introduce holes in their Linux systems by installing new programs and altering configs.
In order to give you better advice, you need to clarify what you're doing. A home server? A database server? Web server? Workstation?
A system with all patches and updates will still expose information if you're running a database server that doesn't clean up input and manages to have an SQL injection attack against a backend database.
Generally, you do what you need to do on any other system. Update regularly. Use the least privileges necessary to do something (don't run as root all the time). Don't login with cleartext passwords (use SSH to remotely administer the system). Don't run unnecessary services (turn off remote desktop/VNC if you're not using it, don't run a web server if you're not using it, etc.) Use strong passwords. Check logs regularly for unusual behavior. Get to know how your system acts so you know what's "weird". Monitor logs for unusual access attempts. Install denyhosts and configure it to lock out IP's that try knocking on SSH for login access, or move it a few ports so it's not open to bot attack. Use NMAP to check what ports you have open (from another machine). Audit your machine with something like SAINT (google for vulnerability auditing tools). Don't leave your workstation logged in when you walk away.
Things like chkrootkit and rkhunter help give some guidance and peace of mind, as do hashing utilities like tripwire, but they add to your maintenance. You need to sit down and balance usability with security needs, and apply them as needed (is it worth the extra hash generation and storage each time you alter a set of files or run system updates, vs. what you have to potentially lose in time and money if the server is lost?)
Make sure you have a good backup routine. A copy of live data is no good if someone compromises the server and your oldest backups contain the compromise.
Never trust a system if you think it has been compromised. I like using devil linux for appliance purposes because it is impossible to crack outside of data scratch areas (things like proxy servers); it boots and runs from CD, so no one can replace the binaries. I suppose they can patch them in memory, but a reboot clears it.
If you are dealing with heavier security needs, echo your logs to another server. Don't use the same password for everything. If your server is compromised, they get access to all passwords (I read once about someone setting up a porn site, then watching logins and email addresses and such coming into the logs...they figured they could then turn around and use those same passwords to crack into other sites, since most people use the same password scheme in the workplace and home as they do for commercial sites).
Those are the big ones. Again it's all a matter of balancing usability with security and how much you have to lose if you lose the server, but also things on your network. If someone takes over a humble little file server or hardly used in-house web server, Linux can easily be used to redirect ARP requests and act as a router to sniff traffic so it can see other things on your network, so even an insignificant server can become a significant threat. Since you didn't say what the server and role was or what the location is, it's hard to tell you specifics (like, "Whoa! you don't want to touch credit card information storage if you have to ask about it! That stuff is heavily regulated!" or, "Never store passwords unhashed. Never store as plain text, ever.")

A: chkrootkit and rkhunter

A: While this is wildly complicated (Dont say i didn't warn you). NeXpose has a Community Edition[rapid7.com] you can use to scan for vulnerabilities. You can also integrate it with Metasploit[www.metaploit.com]. Be prepared to do some heavy reading. But if you wade through it, you will be wiser. These are even tools used by some security professionals.
Engage the community and study! Being compromised (and to compromise) can be very intricate.
Best bet if you are or suspect that you are compromised, reinstall from backups or make  a clean install. Use sources that provides checksums[en.wikipedia.com] for downloads
If they know what they are doing, they could even modify compilers on your system to compile in "malware" on new compiles.
EDIT: These are tools to check if you can be exploited. They will not check if you are compromised.


text:
Q: Angular 6 cookie expire or change event in angular 6 Are there any events to invoke when cookie expires or while changing the cookie value in angular 4 and latest.
I don't want to use a timer or interval?
To set and manage cookie I am using @angular2-cookie.

A: I found a workaround for this using ng-idle https://hackedbychinese.github.io/ng2-idle/
where I can manage cookies expiry and update on interrupts or in timeouts


text:
Q: Too many columns specified in Dask data frame I am calling the following data frame here and after following the answer at this section, I tried to compute the dataset to read into memory:
computed_result = dask.compute(dataset)

I get the following error:

ParserError: Too many columns specified: expected 6 and found 3

To make sure I have the right amount of columns:
year                 int64
species             object
occurrenceStatus    object
individualCount      int64
decimalLongitude     int64
decimalLatitde       int64
dtype: object

Any idea as to why I am getting this error - have I gone wrong during the Dask.dataframe part of my code, and I should specify more clearly or in a different way usecols? any help would be appreciated.

A: The column loading appears to be correct. To check that the error is not at the step of creating the dask dataframe, try running: dataset.head(). If that shows a pandas object, then the dataframe was created correctly.


text:
Q: MediaExtractor throws IllegalArgumentException when used with wav file I am using the Android MediaExtractor like this:
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource("path/to/my/wav/file.wav");
extractor.selectTrack(0);

ByteBuffer inputBuffer = codec.getInputBuffer(inputBufferIndex);
int sampleSize =  extractor.readSampleData(inputBuffer, 0);

The inputBuffer is provided by MediaCodec which is configured as AAC Encoder. The goal is to convert the wave file to aac. The above code is abbreviated, of course, but I tracked the error down to the last line.
It also only occurs when using the MediaExtractor with a wav file. For example, I used a .m4a instead and everything worked fine.
The documentation of MediaExtractor says:

MediaExtractor facilitates extraction of demuxed, typically encoded, media data from a data source.

"typically encdoded" does not exclude un-encodec PCM audio....right? Anyone tried this before or knows another stable(!) way to:

*

*extract the audio samples from a wav (excluding 44byte or 46byte header)?

*convert an wav file to aac on Android?

UPDATE
Here is the logcat:
W/System.err: java.lang.IllegalArgumentException
W/System.err:     at android.media.MediaExtractor.readSampleData(Native Method)
W/System.err:     at com.myproject.android.audiosandbox.convert.MediaEncoder2.encodeLollipopStyle(MediaEncoder2.java:247)
W/System.err:     at com.myproject.android.audiosandbox.convert.MediaEncoder2.encodeSong(MediaEncoder2.java:119)
W/System.err:     at com.myproject.android.audiosandbox.convert.MediaEncoder2.encode(MediaEncoder2.java:70)
W/System.err:     at com.myproject.android.audiosandbox.fragments.AudioConvertFragment$1.onClick(AudioConvertFragment.java:40)
W/System.err:     at android.view.View.performClick(View.java:4763)
W/System.err:     at android.view.View$PerformClick.run(View.java:19821)
W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err:     at android.os.Looper.loop(Looper.java:135)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5272)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)

I am using API 16, so MediaMuxer is not an option (was added in API 18).

A: I could not figure out "if" or "why not" the MediaExtractor seems to be unable to read data from a simple wav file, so I chose a different approach. Since WAV file don't really need to be decoded, I now use a simple FileInputStream and skip the 44-byte header.
I got a working sample published in this gist:
https://gist.github.com/muetzenflo/3e83975aba6abe63413abd98bb33c401
After almost one week of research, try and error, this piece of code seems to be rare. I documented almost every line and hope that I can help others who struggle with the MediaCodec class on Android.

A: Before calling decoder.configure(format, ...), I suggest to call format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 65536);, it will make decoder use bigger buffers.
This should fix the issue. If not, try to increase buffer size.


text:
Q: SingleCertValidatingFactory not working with AWS RDS global-bundle.pem? I want to use the https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem which is stored in my application jar i.e. using classpath. So I tried using the below jdbc url
jdbc:postgresql://<db-endpoint>:5432/pgdb?ssl=true&sslmode=verify-full&sslfactory=org.postgresql.ssl.SingleCertValidatingFactory&sslfactoryarg=classpath:global-bundle.pem

However, I am getting an exception
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Instead of classpath: I tried file: as well but same exception.
Without using SingleCertValidatingFactory, the .pem file works with file system path like below
jdbc:postgresql://<db-endpoint>:5432/pgdb?ssl=true&sslmode=verify-full&sslrootcert=/app/certs/global-bundle.pem

Does SingleCertValidatingFactory not work with .pem files? What do I need to do to make it work. Any help is appreciated.

A: SingleCertValidatingFactory does seem to work with us-east-1-bundle.pem. It seems to be having issue with global-bundle-pem which has all regional certificates combined. Another solution is to follow this doc to import each certificate into the JDK cacerts
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html#UsingWithRDS.SSL-certificate-rotation-sample-script
And then use
jdbc:postgresql://<db-endpoint>:5432/pgdb?ssl=true&sslmode=verify-full&sslfactory=org.postgresql.ssl.DefaultJavaSSLFactory


text:
Q: Dealloc is being deferred I am initializing an object and then configuring it inline. But instead of the previous instance (if previously allocated) being deallocated before configuring it (on the directly following lines), the deallocation is being deferred. So all the configuring I do to it ends up being a deallocated object - which of course is not what I want.
For instance, if I run this code:
if paintingView != nil {
   paintingView.removeFromSuperview()
}

print("^^^^^^^^^^^^^ About to init")
paintingView = PaintingView(frame: TDTDeviceUtilites.screenFrame())

print("^^^^^^^^^^^^^ About to add view")
view.addSubview(paintingView)

print("^^^^^^^^^^^^^ About to configure")
self.configurePaintingView()

I will see the following messages in the Console:
^^^^^^^^^^^^^ About to init
^^^^^^^^^^^^^ About to add view
^^^^^^^^^^^^^ About to configure
***** Painting View Dealloc ***** //message from the dealloc method of the PaintingView class.

I would expect the dealloc to happen directly following the init line. What is going on? Note that this code is being called in NSOperationQueue().
How can I make sure the dealloc happens first, and why isn't that already the case?

A: Apple does things behind your back to make all apps more efficient. Sometimes what actually happens is surprising. However, it's always things that shouldn't really affect you.
One possible optimisation (and I haven't checked personally whether Apple does this or not) is deallocating things on a background thread. An object gets deallocated when its reference count goes down to zero. When that happens, it is marked as "this object will be deallocated", and it will be deallocated. But not necessarily in the thread that set the reference count to 0. Doing the actual dealloc on a separate thread makes better use of multiple processors and makes your foreground app run faster.
It shouldn't make any difference to your code.


text:
Q: ScrollView makes content disappear I am trying to put a custom listView into a scrollView and when I scroll down and up I lose the top items in the listView which are a TextView and a CheckBox for some reason.
Here's my code:
activity_program.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_program_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.10"
        android:text="Program name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/tv_program_info"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_weight="0.20"
        android:text="program info, talk abt sets, reps, weight etc..." />

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="395dp" >
    </ListView>

    <Button
        android:id="@+id/bt_savework"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.10"
        android:text="Save Workout" />

</LinearLayout>

My custom listView contains these:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp" >

    <TextView
        android:id="@+id/tv_exercice_title"
        android:layout_width="270dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/cb_exercicedone"
        android:layout_alignParentTop="true"
        android:gravity="center_vertical"
        android:text="Exercice title"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_exercice_title"
        android:orientation="horizontal" >

        <CheckBox
            android:id="@+id/cb_setdone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="7dp"
            android:text="Set" />

        <TextView
            android:id="@+id/tv_set_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="3dp"
            android:text="1" />

        <TextView
            android:id="@+id/tv_reps"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="15dp"
            android:text="Reps x" />

        <EditText
            android:id="@+id/et_reps_number"
            android:layout_width="47dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />

        <TextView
            android:id="@+id/tv_weight"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="15dp"
            android:text="Weight" />

        <EditText
            android:id="@+id/et_weight_number"
            android:layout_width="65dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />

        <TextView
            android:id="@+id/tv_kgorlbs"
            android:layout_width="59dp"
            android:layout_height="wrap_content"
            android:text="kg/lbs"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </LinearLayout>

    <CheckBox
        android:id="@+id/cb_exercicedone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/linearLayout1" />

</RelativeLayout>

In my ListActivity I use a custom adapter to fill the ListView with the above template and only edit the tv_set_number (for now) then set the tv_exercice_title's visibility to "gone" to add more sets.
If you think the problem could be in my java code let me know in the comment and I will post it.
Please tell me what's the problem.
Here's some screenshots:
Before I scroll:
image 1
After I scroll:
image 2

A: Seems to me you are using the ListView to generate different kinds of rows and you're missing some steps. You could also consider to rethink the structure, as maybe this would better fit into a ExpandableListView: from the screenshots you post seems like you'd have a set of rows that hierarchically belong to a group view.
The ExpandableListView would fit this purpose, and also allow to collapse/expand the groups. I'd take a look at it, it's really easy, you'd only have to make the adapter descend from ExpandableListViewAdapter and provide methods to obtain the Group views (Your title & checkbox) and the item views (the sets with reps, weight, etc...)
If, on the contrary, you want to make it with a ListView, there are some issues to care about (I'll call TITLE ROWS to those with the title & checkbox, and regular rows to the regular ones)
What is happening now is, when you create a view  and this view is not a TITLE ROW, you are setting the visibility of the title to GONE. But if you scroll, ie., DOWN and a TITLE row has to appear from the upper edge, the View you are given to recycle is the one that just left the screen by the lower edge, that was probably a REGULAR ROW. So in getView() you not only have to set Visibility to GONE for regular rows, but also back to VISIBLE for Title Rows. Google an explanation on how View recycling works for ListView and you'll understand it right away.
ListView provides a mechanism to help in these cases: The View Types:

*

*You declare 2 "row types" overriding getViewTypeCount() and getItemViewType(int position) in your adapter. Type 0 will be TITLE ROWS, and Type 1 would be REGULAR ROWS.

*In getView / convertView you'll generate / reuse the 2 different views separately based on the type.
.
@Override
public int getViewTypeCount() {
     return 2; // you have 2 different types
}

@Override
public int getItemViewType(int position) {
     if (position IS A TITLE ROW) return 0; else return 1;
}

... and then in getView() {
if (getItemViewType(position) == 0) {

      // it's a TITLE ROW, create / reuse it accordingly

} else {

      // it's a REGULAR ROW, create / reuse it accordingly
}

This has the advantage that ListView does some of the dirty work for you, so you'll be given the correct view type to recycle.


text:
Q: chrome:headless (MacOS) results with ' 1) AssertionError: expected 'about:blank' to include $target page' I am using TestCafe in combination with gherkinTestcafe (steps) / cucumber.
I am also using environment variables so that i can run my tests on 2 different environments.
My code is as follows, although through debugging, i don't believe this is something strictly code related, as much as it is related to:

*

*chrome:headless

*environment

*version of chrome / MacOS

import Enviorments from "../../../../../../AEM_Engine/Enviorment/Enviorments";
import { Helper } from "../../../../../TestActions/Test_specific/Career_helper";
import {AddAuthCredentialsHook} from "../../../../../TestActions/BasicAuth";

const {Before, Given, Then} = require('cucumber');
let publisher = new Publish();
let aemEnv = new Enviorments();
let helper = new Helper;

let careersPage = '/career';

Before('@basicAuth', async testController => {
    const addAuthCredentialsHook = new AddAuthCredentialsHook('$someUserName', '$somePassword');
    await testController.addRequestHooks(addAuthCredentialsHook);
});

Before('@disableCookie', async testController => {
    await testController.addRequestHooks(publisher.mockCookieResponse);
});

Given('I am at Careers page', async testController => {
    await publisher.Navigate(testController, aemEnv.frontEndURL + careersPage);
    await publisher.verifyURL(testController, aemEnv.frontEndURL + careersPage);
});

.
.
.

When i wait for the script to run i have
 1) AssertionError: expected 'about:blank' to include $expectedPage

As i mentioned, i don't believe the problem is in the code. Even if i remove the step for verifying the current URL location, the test fails on the next step after.
Tests pass on

*

*Chrome (with UI shell)

*Other browsers (firefox, safari), headless or with UI shell

*Second (staging) environment

When Tests are run and TestCafe starts, i get the following info
 Running tests in:
 - HeadlessChrome 99.0.4844 / Mac OS X 10.15.7

 Feature: Careers Page Available
(node:87344) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.

I tried re-installing some packages, re-writing some of the steps, adding some flags to clear cache, change chrome port or similar, but nothing worked.
Any thoughts on what might be causing this and how to solve it?


text:
Q: WordPress.com button is going away from login/signup screens If you are not currently using WordPress credentials to sign in, you can safely ignore this post. Otherwise, read on...
Wordpress.com has retired OpenID support for blogs created after January 2, 2016. Blogs created before then should still be usable as OpenID credentials, but even then, the support has been getting more and more brittle over the years. In particular, if you have a custom domain for your wordpress.com blog, you can't use that blog to sign in to Stack Exchange. Why? Not entirely sure, to be honest. There's a redirect somewhere that's busted, and as far as I can tell the issue isn't on our end at this point.
With this in mind, we're removing the WordPress button from the login and signup UI to avoid even implying that WordPress is a viable option for signing in if you haven't already:

If you are currently able to log in using WordPress credentials, they will continue to work for as long as WordPress supports them. To log in with your existing WordPress credentials, enter your blog URL into the freeform OpenID field. I strongly encourage you to consider adding another credential as a backup option as well, or at least make sure you have a valid email set in your profile to enable account recovery.
These changes took effect on Monday, November 21, 2016, and are now live.

A: If you set up your account with WordPress OpenID like I did and want to create a regular Stack Exchange OpenID (a.k.a. "log in with email") for your account, follow these directions.
You can also follow these directions to add another OpenID, such as Google or Facebook, to your account.
Theoretically, you can have as many OpenIDs and email logins associated with your account as you want.

A: Based on the reasons given, it sounds like a reasonable step to remove WordPress as a standard selection option (although with a less than optimal short notice!).
However, having to type in something manually each time will be a pain, so I would suggest that you replace the button with a "My Favorite OpenID Provider" button, which then fills in a user configurable setting.
This will make the issue of What OpenID providers should we feature on the login page? much less of an issue because it would more or less only affect people using OpenID the very first time. This will benefit all non-default selection OpenID users, not just WordPress.
Logic something like the following:
if (login_method == openid && !user_settings.contains(favourite_openid_provider)
{
   answer = ask("Do you want to save " + sanitize(url) + " as your favorite...")
   if (answer == yes)
   {
       user_settings.save(favourite_openid_provider, url)
   }
}

A: What about inferring the OpenID URL from the e-mail address itself?
When an e-mail someone@example.com is entered, a request to the site is made in the background to see if the page includes the required OpenID elements, and if so, allow to use it right away by clicking on the login button without filling in the OpenID URL explicitly?
That would make it a lot easier to use a custom OpenID.

A: I guess 2000 people discovering the button for their login method (WordPress) is gone and not knowing how to work-around that, and not knowing if that login method is just somehow no longer supported at all, could end up to be a support issue.
I'd suggest that at least for a while (indefinitely), add a note (and link) below the remaining login buttons like: "Looking for the WordPress OpenID login button? Click here for the story".


text:
Q: Clojure Cursive noob load into repl and cannot run hello world Exploring Clojure - I am working through Clojure For The Brave And True. I created the hello world (in this case, I'm a little teapot). I can run it from lein repl just as the book suggests.
The author of the book appears to be a big emacs fan. I am comfortable with Intellij Idea, so installed the Cursive plugin. I then:

*

*Set up a repl "runner" as shown on the Cursive site.

*Tried loading the hello world into the repl. It appears to have done
so.

Now what? I presumed after loading the contents of the editor, I could run it, but have not figured out how. Obviously, this is a very noob question.
The code in my editor follows.
(ns clojure-noob.core
  (:gen-class))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "I'm a little teapot!")
)

The repl window is divided into two panes. The upper pain shows it is connected to the local nREPL server. Then, after loading it states:
Loading src/clojure_noob/core.clj... done

In the lower pane, per comments, I tried two variations of run, both of which failed miserable as you can see below (it didn't surprise me the second failed for it was calling out run, not the function).
run -main
CompilerException java.lang.RuntimeException: Unable to resolve symbol: run in this context, compiling:(/tmp/form-init2302589649746976452.clj:1:4481)
=> #object[clojure_noob.core$_main 0x24d21d67 "clojure_noob.core$_main@24d21d67"]
run clojure-noob.core/-main
CompilerException java.lang.RuntimeException: Unable to resolve symbol: run in this context, compiling:(/tmp/form-init2302589649746976452.clj:1:4481)
=> #object[clojure_noob.core$_main 0x24d21d67 "clojure_noob.core$_main@24d21d67"]

ANSWER
Thanks to comments from @Carcigenicate, I was able to figure out what to do. The answer is:

*

*Enter (clojure-noob.core/-main) into the lower pane

*Position cursor to the right of the closing paren

*Press enter.

This resulted in the following:
(clojure-noob.core/-main)
I'm a little teapot!
=> nil

Told you it was a noob question!

A: This will be much easier in the next version of Cursive - the EAP will hopefully be out later this week or next week. You'll have the IntelliJ-standard ways of running -main functions more easily accessible:

Of course, the Clojure Way is to use the REPL as you're discovering, so continuing to explore that way of programming is definitely to be encouraged!


text:
Q: Move window by dragging background (movableByWindowBackground) I have a window that I want users to be able to move by dragging anywhere in the window content (not just the titlebar).  I know that this can be done via the NSWindow movableByWindowBackground method, however this doesn't appear to work by itself.
I gather that overriding NSView mouseDownCanMoveWindow may be necessary.  But I can't easily do that for all parent views (split views, etc).  Making it a textured window didn't help.  Unsurprisingly, subclassing NSWindow to override isMovableByWindowBackground didn't help either.
Is it really necessary to subclass all parent views in the window to make this work?

A: On OS X 10.11, setting the NSWindow's property movableByWindowBackground to YES works.
There is no longer any need to subclass for this behaviour.

A: In NSSplitView you add:
override var mouseDownCanMoveWindow: Bool {
    return true
}


text:
Q: How to pass special character in URL in windows authentication? To handle windows authentication, one way to handle such scenario is by passing credentials in URL itself as shown below
driver.get('http://username:password@abc.com')

But in my case since password contains special character, like 'password@123', so now code contains double special character '@' as shown below
driver.get('http://username:password@123@abc.com')

I tried replacing '@' with '%40' using url encoder/decoder, but it's not working. I am working with python selenium, any idea how to handle such scenario?

A: A simple raw string will do the job, note that I use triple quotes just for escaping any possible errors with ' and ".
driver.get(r'''http://username:password@123@abc.com''')

A: Can you please try out with the below syntax:
String url =  http://username:password%40123@abc.com;
driver.get(url);

In one of the application, we have more than one @ character in the password. I'm simply escaping the @ character. For example
URL: http://username:password@#@@sample.com
Encoded_URL:  http://username:password%40%23%40@sample.com

and then try to browse the encoded URL.
driver.get(Encoded_URL);

For me, it is working fine. Please let me know if it works for you.

A: If your username is 'shoaib' and your password is akhtar@123 then your .get() invocation should be:
driver.get('http://shoaib:akhtar%40123@abc.com')


text:
Q: d3.js conditional word color fill in wordcloud I created a d3.js word cloud, based on a csv.
In the csv I have three columns:

*

*word (word - unique)

*count (how many times the word came up in the text)

*index (this is the value how much the count is above average vs. how much it is below)

words.csv:
word    count   index
word1   457      239
word2   373      155
word3   76      -142
word4   345      127
word5   12      -206
word6   46      -172

I wrote the following code (with help from youtube and jason davies' world cloud package) and it works to create the word cloud, but I don't know how to change the color of the words based on the index.

I need to change this line in the code `var fill = d3.scale.category20c();`

The goal would be that all words above the average (so positive index) are green and all words below the average (negative index) are grey. If  the transparency of the color/fill could be dependent on how much above or below the average the count is that would be amazing - but not necessary.

    word    count   index   color
    word1   457      239    green
    word2   373      155    green
    word3   76      -142    grey
    word4   345      127    green
    word5   12      -206    grey
    word6   46      -172    grey

Thank you!
UPDATE:
Tried the following based on Dan's answer but with index:
    mycolor = d3.rgb("#00cc66");

var width = 1500,
    height =400;

var wordScale = d3.scale.linear().range([10,90]);
var colorScale = d3.scale.linear().range([10,90]);

// var fill = d3.scale.category20c();
d3.csv("words.csv", function(data) {
    var subjects = data
        .map(function(d) {return {text: d.word, size: +d.count, clr: d.index } })
        .sort(function(a,b) {return d3.descending (a.size, b.size); })
        .slice(0,100);

    wordScale.domain([
        d3.min(subjects, function(d) {return d.size; }),
        d3.max(subjects, function(d) {return d.size; }),
    ]);

    colorScale.domain([
        d3.min(subjects, function(d) {return d.clr; }),
        d3.max(subjects, function(d) {return d.clr; }),
    ]);

// var layout = cloud()
    d3.layout.cloud().size([width, height])
    .words(subjects)
    .padding(1)
    .rotate(function() { return ~~(Math.random() * 2) * 0; })
    .font("Impact")
    .fontSize(function(d) { return wordScale(d.size); })
    .on("end", draw)
    .start();

});

    function draw(words) {
      d3.select("#word-cloud").append("svg")
          .attr("width",width)
          .attr("height",height)
        .append("g")
          .attr("transform", "translate("+(width /2)+","+(height /2)+")")
          //where the center is
        .selectAll("text")
          .data(words)
        .enter().append("text")
          .style("fill", function(d) { return d.clr >= 50 ? mycolor : "grey";})
          .style("opacity", function(d) { return d.clr / 100 })
          .style("font-size", function(d) { return d.size + "px"; })
          .style("font-family", "Impact")
          // .style("fill", function(d, i) { return fill(i); })
          .attr("text-anchor", "middle")
          .attr("transform", function(d) {
            return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
          })
          .text(function(d) { return d.text; });
}

Unfortunately, nothing is displaying when I run it (also no error message).

A: For your code above, i.e; assuming wordScale is between 10 and 100:
In the draw function, in the .append("text") section of code,
Edit the fill function as follows. This will turn green / grey based on size being higher / lower than the mid point (55).  Feel free to use better color values than the hardcoded ones below:
.style("fill", function(d) { return d.size >= 55 ? "green" : "grey";})

To fulfil your other request, add the following style immediately below the fill. This will set the opacity relative to the size (between 0.1 and 1).  Again, you can adjust these values as required.
.style("opacity", function(d) { return d.size / 100 })

If you make these edits, you can also drop the var fill at the top of your code.
UPDATED ANSWER:
Note, I couldn't get Jason Davies' to load remotely without a script error, but no time to debug.  Scroll down after his script for the actual answer.  I also haven't added any rotation element to this.

!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b=b.d3||(b.d3={}),b=b.layout||(b.layout={}),b.cloud=a()}}(function(){var a;return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c||a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){function h(a){return a.text}function i(){return"serif"}function j(){return"normal"}function k(a){return Math.sqrt(a.value)}function l(){return 30*(~~(6*Math.random())-3)}function m(){return 1}function n(a,b,c,d){if(!b.sprite){var h=a.context,i=a.ratio;h.clearRect(0,0,(f<<5)/i,g/i);var j=0,k=0,l=0,m=c.length;for(--d;++d<m;){b=c[d],h.save(),h.font=b.style+" "+b.weight+" "+~~((b.size+1)/i)+"px "+b.font;var n=h.measureText(b.text+"m").width*i,o=b.size<<1;if(b.rotate){var p=Math.sin(b.rotate*e),q=Math.cos(b.rotate*e),r=n*q,s=n*p,t=o*q,u=o*p;n=Math.max(Math.abs(r+u),Math.abs(r-u))+31>>5<<5,o=~~Math.max(Math.abs(s+t),Math.abs(s-t))}else n=n+31>>5<<5;if(o>l&&(l=o),j+n>=f<<5&&(j=0,k+=l,l=0),k+o>=g)break;h.translate((j+(n>>1))/i,(k+(o>>1))/i),b.rotate&&h.rotate(b.rotate*e),h.fillText(b.text,0,0),b.padding&&(h.lineWidth=2*b.padding,h.strokeText(b.text,0,0)),h.restore(),b.width=n,b.height=o,b.xoff=j,b.yoff=k,b.x1=n>>1,b.y1=o>>1,b.x0=-b.x1,b.y0=-b.y1,b.hasText=!0,j+=n}for(var v=h.getImageData(0,0,(f<<5)/i,g/i).data,w=[];--d>=0;)if(b=c[d],b.hasText){for(var n=b.width,x=n>>5,o=b.y1-b.y0,y=0;y<o*x;y++)w[y]=0;if(null==(j=b.xoff))return;k=b.yoff;for(var z=0,A=-1,B=0;B<o;B++){for(var y=0;y<n;y++){var C=x*B+(y>>5),D=v[(k+B)*(f<<5)+(j+y)<<2]?1<<31-y%32:0;w[C]|=D,z|=D}z?A=B:(b.y0++,o--,B--,k++)}b.y1=b.y0+A,b.sprite=w.slice(0,(b.y1-b.y0)*x)}}}function o(a,b,c){c>>=5;for(var k,d=a.sprite,e=a.width>>5,f=a.x-(e<<4),g=127&f,h=32-g,i=a.y1-a.y0,j=(a.y+a.y0)*c+(f>>5),l=0;l<i;l++){k=0;for(var m=0;m<=e;m++)if((k<<h|(m<e?(k=d[l*e+m])>>>g:0))&b[j+m])return!0;j+=c}return!1}function p(a,b){var c=a[0],d=a[1];b.x+b.x0<c.x&&(c.x=b.x+b.x0),b.y+b.y0<c.y&&(c.y=b.y+b.y0),b.x+b.x1>d.x&&(d.x=b.x+b.x1),b.y+b.y1>d.y&&(d.y=b.y+b.y1)}function q(a,b){return a.x+a.x1>b[0].x&&a.x+a.x0b[0].y&&a.y+a.y0<b[1].y}function r(a){var b=a[0]/a[1];return function(a){return[b*(a*=.1)*Math.cos(a),a*Math.sin(a)]}}function s(a){var b=4,c=b*a[0]/a[1],d=0,e=0;return function(a){var f=a<0?-1:1;switch(Math.sqrt(1+4*f*a)-f&3){case 0:d+=c;break;case 1:e+=b;break;case 2:d-=c;break;default:e-=b}return[d,e]}}function t(a){for(var b=[],c=-1;++c>2);a.width=(f<<5)/b,a.height=g/b;var c=a.getContext("2d");return c.fillStyle=c.strokeStyle="red",c.textAlign="center",{context:c,ratio:b}}function J(b,c,d){for(var l,m,n,f=(a[0],a[1],c.x),g=c.y,h=Math.sqrt(a[0]*a[0]+a[1]*a[1]),i=A(a),j=F()<.5?1:-1,k=-j;(l=i(k+=j))&&(m=~~l[0],n=~~l[1],!(Math.min(Math.abs(m),Math.abs(n))>=h));)if(c.x=f+m,c.y=g+n,!(c.x+c.x0<0||c.y+c.y0<0||c.x+c.x1>a[0]||c.y+c.y1>a[1])&&(!d||!o(c,b,a[0]))&&(!d||q(c,d))){for(var y,p=c.sprite,r=c.width>>5,s=a[0]>>5,t=c.x-(r<<4),u=127&t,v=32-u,w=c.y1-c.y0,x=(c.y+c.y0)*s+(t>>5),z=0;z<w;z++){y=0;for(var B=0;B<=r;B++)b[x+B]|=y<<v|(B<r?(y=p[z*r+B])>>>u:0);x+=s}return delete c.sprite,!0}return!1}var a=[256,256],b=h,c=i,e=k,s=j,x=j,y=l,z=m,A=r,B=[],C=1/0,D=d("word","end"),E=null,F=Math.random,G={},H=u;return G.canvas=function(a){return arguments.length?(H=v(a),G):H},G.start=function(){function l(){for(var b=Date.now();Date.now()-b<C&&++i<h&&E;){var c=k[i];c.x=a[0]*(F()+.5)>>1,c.y=a[1]*(F()+.5)>>1,n(d,c,k,i),c.hasText&&J(f,c,g)&&(j.push(c),D.call("word",G,c),g?p(g,c):g=[{x:c.x+c.x0,y:c.y+c.y0},{x:c.x+c.x1,y:c.y+c.y1}],c.x-=a[0]>>1,c.y-=a[1]>>1)}i>=h&&(G.stop(),D.call("end",G,j,g))}var d=I(H()),f=t((a[0]>>5)*a[1]),g=null,h=B.length,i=-1,j=[],k=B.map(function(a,d){return a.text=b.call(this,a,d),a.font=c.call(this,a,d),a.style=s.call(this,a,d),a.weight=x.call(this,a,d),a.rotate=y.call(this,a,d),a.size=~~e.call(this,a,d),a.padding=z.call(this,a,d),a}).sort(function(a,b){return b.size-a.size});return E&&clearInterval(E),E=setInterval(l,0),l(),G},G.stop=function(){return E&&(clearInterval(E),E=null),G},G.timeInterval=function(a){return arguments.length?(C=null==a?1/0:a,G):C},G.words=function(a){return arguments.length?(B=a,G):B},G.size=function(b){return arguments.length?(a=[+b[0],+b[1]],G):a},G.font=function(a){return arguments.length?(c=v(a),G):c},G.fontStyle=function(a){return arguments.length?(s=v(a),G):s},G.fontWeight=function(a){return arguments.length?(x=v(a),G):x},G.rotate=function(a){return arguments.length?(y=v(a),G):y},G.text=function(a){return arguments.length?(b=v(a),G):b},G.spiral=function(a){return arguments.length?(A=w[a]||a,G):A},G.fontSize=function(a){return arguments.length?(e=v(a),G):e},G.padding=function(a){return arguments.length?(z=v(a),G):z},G.random=function(a){return arguments.length?(F=a,G):F},G.on=function(){var a=D.on.apply(D,arguments);return a===D?G:a},G};var w={archimedean:r,rectangular:s}},{"d3-dispatch":2}],2:[function(b,c,d){!function(b,e){"object"==typeof d&&void 0!==c?e(d):"function"==typeof a&&a.amd?a(["exports"],e):e(b.d3=b.d3||{})}(this,function(a){"use strict";function c(){for(var e,a=0,b=arguments.length,c={};a=0&&(c=a.slice(d+1),a=a.slice(0,d)),a&&!b.hasOwnProperty(a))throw new Error("unknown type: "+a);return{type:a,name:c}})}function f(a,b){for(var e,c=0,d=a.length;c<d;++c)if((e=a[c]).name===b)return e.value}function g(a,c,d){for(var e=0,f=a.length;e<f;++e)if(a[e].name===c){a[e]=b,a=a.slice(0,e).concat(a.slice(e+1));break}return null!=d&&a.push({name:c,value:d}),a}var b={value:function(){}};d.prototype=c.prototype={constructor:d,on:function(a,b){var h,c=this._,d=e(a+"",c),i=-1,j=d.length;{if(!(arguments.length<2)){if(null!=b&&"function"!=typeof b)throw new Error("invalid callback: "+b);for(;++i<j;)if(h=(a=d[i]).type)c[h]=g(c[h],a.name,b);else if(null==b)for(h in c)c[h]=g(c[h],a.name,null);return this}for(;++i<j;)if((h=(a=d[i]).type)&&(h=f(c[h],a.name)))return h}},copy:function(){var a={},b=this._;for(var c in b)a[c]=b[c].slice();return new d(a)},call:function(a,b){if((e=arguments.length-2)>0)for(var e,f,c=new Array(e),d=0;d<e;++d)c[d]=arguments[d+2];if(!this._.hasOwnProperty(a))throw new Error("unknown type: "+a);for(f=this._[a],d=0,e=f.length;d<e;++d)f[d].value.apply(b,c)},apply:function(a,b,c){if(!this._.hasOwnProperty(a))throw new Error("unknown type: "+a);for(var d=this._[a],e=0,f=d.length;e<f;++e)d[e].value.apply(b,c)}},a.dispatch=c,Object.defineProperty(a,"__esModule",{value:!0})})},{}]},{},[1])(1)});

/// ACTUAL START OF ANSWER ///

// fake JSON data in place of CSV file.

data = [{
    word: "word1",
    count: 457,
    index: 239
  },
  {
    word: "word2",
    count: 373,
    index: 155
  },
  {
    word: "word3",
    count: 76,
    index: -142
  },
  {
    word: "word4",
    count: 345,
    index: 127
  },
  {
    word: "word5",
    count: 12,
    index: -206
  },
  {
    word: "word6",
    count: 46,
    index: -172
  }
]

//  the script

    var width = 700, // amended to make result easier to see
        height =400;

    var wordScale = d3.scale.linear().range([10,100]);

//    d3.csv("words.csv", function(data) {  // uncomment when using CSV
        var subjects = data
            .map(function(d) {return {text: d.word, size: +d.count, in: +d.index} }) // note use of +d.index, to ensure it's held as a number when read from csv, same as +d.count
            .sort(function(a,b) {return d3.descending (a.size, b.size); })
            .slice(0,100);

        wordScale.domain([
            d3.min(subjects, function(d) {return d.size; }),
            d3.max(subjects, function(d) {return d.size; }),
        ]);

    // var layout = cloud()
        d3.layout.cloud().size([width, height])
        .words(subjects)
        .padding(1)
        .rotate(function() { return ~~(Math.random() * 2) * 0; })
        .font("Impact")
        .fontSize(function(d) { return wordScale(d.size); })
        .on("end", draw)
        .start();

 //   }); uncomment when using csv

        function draw(words) {
          d3.select("#word-cloud").append("svg")
              .attr("width",width)
              .attr("height",height)
            .append("g")
              .attr("transform", "translate("+(width /2)+","+(height /2)+")")
              //where the center is
            .selectAll("text")
              .data(words)
            .enter().append("text")
              .style("font-size", function(d) { return d.size + "px"; })
              .style("font-family", "Impact")
              .style("fill", function(d, i) { return d.in > 0 ? "#00cc66" : "grey" })
              .style("opacity", function(d) { return d.in > 0 ? d.size/100 : (50 - d.size) / 100 } ) // bit of a hack to get furthest from index to become darker
              .attr("text-anchor", "middle")
              .attr("transform", function(d) {
                return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
              })
              .text(function(d) { return d.text; });
    }


text:
Q: APEX trigger error on Account Level Only I'm new to coding and my developer friend and I have this APEX trigger to update a custom field on opportunities, based on recently created tasks.
However, we can't create a task on the account level, I keep getting an error.  I can create the task on  all other objects like Lead, Opportunity, and Contact, but not the Account.
Can you help me find out why?
trigger ActivityCreationLogger on Task (after insert, after update) {
for (Task task : Trigger.new) {
    if (task.WhatId != null) {
        Opportunity correspondingOpp = [SELECT Id, Last_Activity_Subject__c, CreatedDate FROM Opportunity WHERE Id =:task.WhatId];
        if (correspondingOpp != null){
            Task nextDueTask = [SELECT ActivityDate, Subject FROM Task WHERE WhatId =:correspondingOpp.Id AND Status != 'Completed' ORDER BY ActivityDate ASC LIMIT 1];
            if (nextDueTask != null) {
                correspondingOpp.Last_Activity_Subject__c = nextDueTask.Subject  + ': ' + nextDueTask.ActivityDate.format();
            } else {
                correspondingOpp.Last_Activity_Subject__c = null;
            }
            update correspondingOpp;
        }
    }
}

}

A: This line:
Opportunity correspondingOpp = [SELECT Id, Last_Activity_Subject__c, CreatedDate
        FROM Opportunity WHERE Id =:task.WhatId];

will produce the error "QueryException: List has no rows for assignment to SObject" if the task.WhatId relates to some other object rather than resulting in a null correspondingOpp.
One way to fix it is this (and the same sort of approach is needed for the Task query too):
Opportunity[] correspondingOpps = [SELECT Id, Last_Activity_Subject__c, CreatedDate
        FROM Opportunity WHERE Id =:task.WhatId];
if (correspondingOpps.size() > 0) {
    Opportunity correspondingOpp = correspondingOpps[0];
    ...
}

or another way (just for the Opportunity query) is:
if (task.WhatId != null && task.WhatId.getSObjectType() == Opportunity.SObjectType) {
    Opportunity correspondingOpp = [SELECT Id, Last_Activity_Subject__c, CreatedDate
            FROM Opportunity WHERE Id =:task.WhatId];
    // No null check needed

I suggest you start by making these changes and re-test with Tasks on various objects.
PS
A (untested) bulkified (see e.g. General trigger bulkification - best practices) version of what you appear to be doing is:
trigger ActivityCreationLogger on Task (after insert, after update) {
    Set<Id> oppIds = new Set<Id>();
    for (Task task : Trigger.new) {
        if (task.WhatId != null
                    && task.WhatId.getSObjectType() == Opportunity.SObjectType) {
            oppIds.add(task.WhatId);
        }
    }
    if (oppIds.size() > 0) {
        Map<Id, Task> tasks = new Map<Id, Task>();
        for (Task t : [
                SELECT ActivityDate, Subject, WhatId
                FROM Task
                WHERE WhatId in :oppIds
                AND Status != 'Completed'
                ORDER BY ActivityDate ASC
                ]) {
            // Using first only
            if (tasks.get(t.WhatId) == null) {
                tasks.put(t.WhatId, t);
            }
        }
        // No need to query before updating
        Opportunity[] opps = new Opportunity[] {};
        for (Opportunity oppId : oppIds) {
            Task t = tasks.get(oppId);
            opps.add(new Opportunity(
                    Id = oppId,
                    Last_Activity_Subject__c = t != null
                            ? t.Subject  + ': ' + t.ActivityDate.format()
                            : null
                    ));
        }
        update opps;
    }
}


text:
Q: Azure DevOps: How to stop check-ins which can break master branch? Using branch policies I have enabled Build validation on pull requests. Now whenever I create a pull request, I can see a build getting triggered and based on the status of the build, I am allowed to complete/hold the pull request. All fine up-to here.
Now consider a 2 parallel pull requests scenario
PR1: is in progress and got a green build through Build Validation. Reviewer is allowed to complete this PR.
PR2 is also in progress, which has some changes which can fail few test cases in PR1 changes. PR2 build validation build is green and this PR2 is Approved and Completed and merged into master.
Now, PR1 is Approved (as it got a green build earlier) and completed and merged into master. Once PR1 changes are merged to master, master is now a broken branch.
How to avoid this? How can we trigger a gated check-in / pre-commit build when PR changes are actually merging in master?

A: There is no gated check-in / pre-commit build when PR changes are actually merging in master but you can avoid those situations easily.
In the build validation (in the branch policies) just mark in the "Build expiration" - Immediately when master is updated:

Immediately when branch name is updated: This option sets the build policy status in a pull request to failed when the protected branch is updated. Requeue a build to refresh the build status. This setting ensures that the changes in pull requests build successfully even as the protected branch changes. This option is best for teams that have important branches with a lower volume of changes. Teams working in busy development branches may find it disruptive to wait for a build to complete every time the protected branch is updated.

A: As a workaround, you can set Approvals and checks for pipleline1, and check the status of PR2 through rest api. If the status of PR2 is not completed, pipeline1 will not start running, then the Build validation of PR1 cannot be completed, and PR1 cannot be merged until PR2 is completed.
Add an Environment in the Pipeline1, and the Environment contains the check: Invoke Rest API to check the status of the Pull Request .
Environment: Pipelines -> Environemnts-> Approvals and checks -> Invoke Rest API

For details, here is a case you can refer to.


text:
Q: What schema format supports Kafka REST v3? I revealed that tutorial schema version ref from tutorial doesn't work in kafka version3.
In additional the same result I received if I try to send the same tutorial via kafka-rest v2 from cp-kafka-rest:6.2.1 instead of cp-kafka-rest:6.1.0
An assumption which I derived that schema-registry doesn't depend on kafka-rest version - is it correct?
Tutorial:
https://docs.confluent.io/platform/current/tutorials/examples/clients/docs/rest-proxy.html#basic-producer-and-consumer
https://docs.confluent.io/platform/current/kafka-rest/api.html#post--clusters-cluster_id-topics-topic_name-records
The message:
{
  "key": {
    "subject_name_strategy": "TOPIC_NAME",
    "schema_id": 8,
    "data": 1000
  },
  "value": {
    "data": {
      "countInfo": {
        "count": 0
      }
    }
  }
}

The answer:
"Error when fetching schema version. subject = test-key, schema = [{\"type\":\"record\",\"name\":\"countInfo\",\"fields\":[{\"name\":\"count\",\"type\":\"long\"}]}]"

A: with version 7.1.0, it work
key schema :
{"type": "string"}

value schema:
{
    "type":"record",
    "name":"countInfo",
    "fields":[
        {
            "name":"count",
            "type":"long"
        }
    ]
}

import requests

data = {
    "key": {
        "data": "AAAAAA"
    },
    "value": {
        "data": {"count": 4546}
    }
}
print(data)
response = requests.post(
    f"{rest_proxy}/v3/clusters/toto/topics/tata/records",
    headers={"Content-Type": "application/json"},
    json=data)
print(response.reason)
print(response.text)

give
{'key': {'data': 'AAAAAA'}, 'value': {'data': {'count': 4546}}}
OK
{"cluster_id":"toto","topic_name":"tata","partition_id":1,"offset":32,"timestamp":"2022-06-19T23:22:05.481Z","key":{"type":"AVRO","subject":"tata-key","schema_id":1,"schema_version":1,"size":12},"value":{"type":"AVRO","subject":"tata-value","schema_id":2,"schema_version":1,"size":7}}


text:
Q: Activity finish() not working when started from PendingIntent In my application I have a foreground service that upon being pressed starts an Activity with the following PendingIntent
 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    ...
    startForeground(FOREGROUND_SERVICE_ID, getNotification());
}

private Notification getNotification(){
  Intent notificationIntent = new Intent(this, CallActivity.class);
  notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, FOREGROUND_SERVICE_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
  ...

  return notification;
}

The Activity starts and everything works fine with it, however, when I call finish() it doesn't close the Activity although it is running the finish(); statement, I made sure using the debugger.


text:
Q: How to have a consistent running head in Bookdown when using tufte-latex? It seems that bookdown running head is inconsistent when using tufte PDF.
Precisely, it is ALWAYS in lower case, as illustred below.

How can I fix this issue? I think somewhere the code is turning the title in lowercase when passing the parameter to the template.
Steps to reproduce:

*

*Checkout bookdown-demo

*Switch output to tufte