text:
Q: reading .bmp file header I'm trying to read a .bmp file. I succesfully read the initial B and M characters, but after that i get only 0, if wrote into an integer or blanks, if wrote into a char.
According to https://en.wikipedia.org/wiki/BMP_file_format there should be the size of the file, some reserved Bytes and the Offset of my file.
int main(){
    std::ifstream file("bmp.bmp");
    char token;
    int num;
    file >> token;
    if(token != 'B')
        std::cerr << "file is not a .bmp";
    file >> token;
    if(token != 'M')
        std::cerr << "file is not a .bmp";
    for(int i = 0; i < 3; i++){
        file >> num;
        std::cout << num << "\n;
    }
    file.close
}

All this Code will print on the consol is:
0
0
0
Why am i not getting the expected Output?

A: You need to do binary reads (not text like you are doing now)
std::ifstream file("bmp.bmp", std::ios_base::binary);

file.read((char*)&num, sizeof num);

where num is declared at the correct size (int32_t or int16_t).
In addition you may need to correct the numbers for endianess.
I recommend doing some reading on binary I/O in C++ before going any further.


text:
Q: How to use react-responsive as a const I'm new in react.js and I'm trying to add some responsive features to my first app using https://github.com/contra/react-responsive
So, it cool that I can use it as a wrapper to my content like
<MediaQuery maxDeviceWidth={767}>
   this will shown only on mobile
</MediaQuery>

But can I do some magic to use this feature like some constant?
const isMobile = MediaQuery < 768;
return <div className={isMobile ? "mobile" : "desktop"}

Thanks for help!

A: No, but I suppose you could just use the window width instead:
const isMobile = window.innerWidth < 768;
return

;

If you want to update this on window resize then there's a bit more to it.
You would need to keep the isMobile value in the component state and then update the state when the window resizes, which will cause the component to re-render.
You would need something like this:
class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isMobile: window.innerWidth < 768
        };
    }

    updateIsMobile() {
        this.setState({
            isMobile: window.innerWidth < 768
        });
    }

    componentDidMount() {
        window.addEventListener('resize', this.updateIsMobile);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.updateIsMobile);
    }

    render() {
        return

    }

}

However, if it's just to set a CSS class though then you would probably be best just using CSS media queries.

A: Looking into the documentation, you can do this:
return (
    <MediaQuery maxDeviceWidth={767}>
        {isMobile => (

        )}
    </MediaQuery>
);

If the children are a function, the function is used to generate the real children.

redpajama_set_name: RedPajamaStackExchange


text:
Q: On the sum of all elements of inverted correlation matrix Assume I have a correlation matrix,$A$
 \begin{equation}
A_{i,j} =
\begin{cases}
1,& \text{if}\ i=j\\
\rho_{i,j},& \text{otherwise}  \\
\end{cases}
\end{equation}
Where $ 0\leq \rho_{i,j} \leq 1 $  and $A$ is positive definite.
Now define a correlation matrix $\bar{A}$ as follows:
\begin{equation}
\overline{A} =
\begin{cases}
1,& \text{if}\ i=j\\
\overline{\rho},& \text{otherwise} \\
\end{cases}
\end{equation}
Where $\overline{\rho}=\frac{\sum_{i \neq j} \rho_{i,j}}{n^{2}-n}$
I want to prove that the sum of elements in the inverse matrix $\overline{A}^{-1}$ is less than the the sum of elements in the inverse matrix ${A}^{-1}$. Any ideas?
I wrote a program that makes random matrices of this sort and it was true for all matrices in many different dimensions so it can't be just by chance. I just don't know how to prove it.
Thanks

A: This is true because with respect to the partial ordering of positive semidefinite matrices, matrix inverse is convex on the set of all positive definite matrices.
More specifically, if $X,Y\succ0$ and $t\in[0,1]$, then $(1-t)X^{-1}+tY^{-1}\succeq\left[(1-t)X+tY\right]^{-1}$, because positive definite matrices are simultaneously diagonalisable by congruence and the inverse function on positive reals is convex.
Now observe that $\bar{A}=\frac1{n!}\sum_PP^TAP$, where the summation runs through all permutation matrices $P$. By assumption, $A$ is positive definite. Therefore $\bar{A}$ is positive definite too and its inverse exists. So, by convexity of matrix inverse of positive definite matrix,
\begin{aligned}
\frac1{n!}\sum_PP^TA^{-1}P
=\frac1{n!}\sum_P(P^TAP)^{-1}
\succeq\left(\frac1{n!}\sum_PP^TAP\right)^{-1}
=\bar{A}^{-1}.
\end{aligned}
Consequently,
$$
e^TA^{-1}e
=\frac1{n!}\sum_Pe^TP^TA^{-1}Pe
\ge e^T\bar{A}^{-1}e.
$$


text:
Q: Using SSL over TCP to establish safe connection between two servers with NodeJS I am trying to send a package from one server to another but i need to be sure that the sender is the "real" one and the package cannot be intercepted, How can i do this using SSL with NodeJS or some other way.
This is what I've done:
Server code:
server = tls.createServer(function(c) {
console.log('server connected',

c.authorized ? 'authorized' : 'unauthorized');
});

Client code:
var tls = require('tls');
var fs = require('fs');

var options = {
key  : fs.readFileSync('server.key'),
cert : fs.readFileSync('server.crt')
};

var client = tls.connect(9838, options, function () {

console.log(client.authorized ? 'Authorized' : 'Not authorized');

});

and this errors out:
Error: 101057795:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv handshake failure:openssl\ssl\s23_clnt.c:769:

A: To ensure that the sender (the client) is the "real" one, you might try using TLS client auth (or mutual authentication).  This means you'll need a client certificate (and key), a server certificate (and key), the CA certificate which issued/signed the server certificate, and the CA certificate which issued/signed the client certificate.
First, your TLS server will need to provide its certificate to any connecting TLS clients; this means you'll need to configure its certificate and key.  You'll also want the TLS server to request that the client send its certificate to the server, as part of the handshake:
var tlsOptions = {
  cert: fs.readFileSync('server-cert.pem'),
  key: fs.readFileSync('server-key.pem'),
  ca: [ fs.readFileSync('client-ca-cert.pem'),
  requestCert: true,
  rejectUnauthorized: true
};

var server = tls.createServer(tlsOptions, function () {

Then, for the client, you configure it with its certificate and key, and the CA certificate which issued/signed the server certificate (so that the client can verify that the receiver is the "real" one):
var tlsOptions = {
  host: 'server.example.com',
  port: 9838,
  cert: fs.readFileSync('client-cert.pem'),
  key: fs.readFileSync('client-key.pem'),
  ca: [ fs.readFileSync('server-ca-cert.pem')
};

var client = tls.connect(tlsOptions, function () {

Hope this helps!


text:
Q: onVideoSelect vs onVideoSelected in my react app, I have the following code in the component
<VideoList
      onVideoSelect={(selectedVideo) => this.setState({ selectedVideo })}
      videos={this.state.videos}
/>

The above code works, NO PROBLEM, but as soon as I change the onVideoSelect to onVideoSelected, I get an error that onVideoSelected is not a defined function.
My question is that is onVideoSelected a function defined in ReactJS or ES6?
FYI:
class VideoList extends Component {
    render() {
        const VideoItems = this.props.videos.map((video) => {
            return (
                <VideoListItem
                    onVideoSelect={this.props.onVideoSelect}
                    key={video.etag}
                    video={video} />
            )
        });
        return (

                    {VideoItems}

        );
    }
};

Other code:
const VideoListItem = ({ video, onVideoSelect }) => {
    const imageUrl = video.snippet.thumbnails.default.url;

    return (

 onVideoSelect(video)} className="list-group-item">

                        {video.snippet.title}

)
};

A: If you want to change onVideoSelect to onVideoSelected you need to pass to as onVideoSelected to VideoListItem component Like
    <VideoListItem
                onVideoSelected={this.props.onVideoSelect}
                key={video.etag}
                video={video} />

Now in VideoListItem onVideoSelected will work
     const VideoListItem = ({ video, onVideoSelected }) => {
     const imageUrl = video.snippet.thumbnails.default.url;

        return (

 onVideoSelected(video)} className="list-group-item">

                           {video.snippet.title}

)
  }

Keep in mind that when you are accessing a function which is passed from parent. You need to access as it is the way you passed as prop


text:
Q: What is the best directory to install a Bash Script? I have developed my own Bash Script (to undo the last APT commands), and now I'm looking for the best directory to install it.
Is the /usr/bin always the best choice?
Just for information this is my script:
https://gitlab.com/fabio.dellaria/apt-rollback
and this is a little demo:

A: For the case you're asking about, I agree with Liso's answer saying /usr/local/bin (or perhaps /usr/local/sbin), because your script kind of needs to act on the entire system.
But for completeness I want to add that if you would like to install a script under your own account without root access (which can be a good alternative for programs that are not related to system administration), I would suggest putting it in $HOME/.local/bin. As noted in an answer on Unix & Linux SE, this directory is specified by the systemd file-hierarchy spec as the equivalent of /usr/bin or /usr/local/bin for individual users' programs. It seems to be catching on for Linux systems that don't use systemd as well.

A: If you intend to make it available to all users, you should place it to /usr/local/bin, excerpt from below answer.

/usr/local/bin is for normal user programs not managed by the distribution package manager, e.g. locally compiled packages. You should not install them into /usr/bin because future distribution upgrades may modify or delete them without warning.

Taken from usr-bin-vs-usr-local-bin-on-linux


text:
Q: NSP module not recognized I am trying to install nsp module globally using npm package management. I have used the command
npm install -g nsp

The installation process gets completed successfully and I see that nsp module folder gets created globally.
Now, if I try to fire the command,
nsp check

from my project directory, it does not recognize the command.
Just for the record, I am initiating the complete process using my administrator.
Thanks in advance.


text:
Q: How do I flatten many-to-many relationships within a Redux state using Normalizr? Scenario
We have a database that maps the following relationship:

*

*A tag has many campaigns

*A campaign has many tags

*The relationship between campaigns and tags is represented by an associative entity called a campaign_tag

*The campaign_tag entity has a priority attribute

Question
How can we implement normalizr (or any similar library) to generate a flattened app state that accounts for our associative entities, when our associative entities do not have unique IDs / values?
Notes / Misc Thoughts
Other examples I've seen only had the original entities mapped out and seem better suited for one-to-many or one-to-one relationships. They usually produced state tree such as this:
{
  entities: {
    campaigns: {
      '1': { id: 1, name: 'Ace', tags: [1, 2, 3] },
      ...
    },
    tags: {
      '1': { id: 1, name: 'Example Tag', campaigns: [1, 2, 3] },
      ...
    }
  },
  ...
}

Would our associative entities go in that entities group? Should we just add unique IDs?  That seems counter-productive.  Is it even appropriate to flatten such relationships?
Any help is appreciated, thanks.

A: Scenarios:

*

*You control the API: I'll send objects like this:
campaigns: [{
  id: <id>,
  name: <name>,
}],
tags: [{ id: <id>, name: <name> }],
campaign_tags: [{campaign_id, tag_id, priority}]

So this will be easy to manage and avoid duplication of information. When you mount your component using redux connect, you can create a selector to fill your campaign tags to add to your component's properties.

*You don't control the API. In this case I'll need to know what type of response are you getting from the server in order to recommend something.


text:
Q: Run Eclipse in verbose mode Is there any way to run Eclipse CDT in verbose mode?
When I want to open a project it takes forever to finish (the activity scroll bar keeps scrolling with no end). I am hoping to get some insight into the issue by looking at the logs that may be generated in verbose mode.
is there any log file in Eclipse that may help figuring out these kind of problems?
EDIT: one more data point is I recently started to use Accurev version control and since then I experience these kind of issues with Eclipse.

A: The problem is likely that there's a lot of CPU being chewed up by the workspace being rebuilt and other startup activities (maven re-indexing, workspace re-indexing, other tools trying to run faster later by making you wait longer now).  Try limiting the number of open projects in the workspace by closing projects not in use or by factoring set of inter-related projects into separate workspaces.
I don't think you can have any impact on the time it takes to initialize the tools on workspace open, unless you can reduce or disable any tools you don't need or you reduce the number of projects those tools act against.

A: I'd also suggest making sure you are using the latest plugin for Eclipse for AccuRev, if you believe it is part of the problem. You can also contact AccuRev support as they may have additional tools for investigating problems like this.


text:
Q: Turbulent flow and Separated flow My knowledge in aerodynamics is very limited as I am doing just an introduction to the subject, and so I may not understand very complex explanations.
I know that at some point laminar flow becomes turbulent flow, but why is this, and why does this occur in less distance if the surface is rougher?
And why does turbulent flow "stick" to the surface longer?
I know for this reason, this actually decreases pressure (form) drag due to the fact that causing turbulent flow causes the separation flow to occur further, for example a smooth ball and a golf ball.
Also, it would be very much appreciated if one explains from the very basic definitions, starting from definitions of laminar flow, turbulent flow and viscosity to illustrate their explanation, so I can notice the flaws in my thinking.
Thank you.

A: Not exactly the logic for the whole answer, but a beautiful fact to get going.
A dimensionless constant $K$, called Reynold's Number is used as a measure to tell if the flow is streamlined or turbulent.
The value of this constant is determined experimentally.
For Streamlined flow,$K<2000$
For Turbulent flow, $K>2000$.
Bit more mathematical than actual reality, but hope that helps in understanding the type of flow.

A: Let's first look at laminar and turbulent flow. When an object moves through air, the air molecules directly at the surface of the object will get carried along courtesy of viscosity. Viscosity causes adjacent molecules to assume the same speed, so there will be a layer of air surrounding the object in which the speed transitions from the object's speed (right next to the surface) to the speed of the outer flow. This is the boundary layer.  Initially, the layers of air within the boundary layer show no cross movement of molecules. Compare it with a multi-lane road with bumper-to-bumper traffic where no car changes lanes. Since all molecules move along their layer of air, this is called laminar flow (lat. lamina = layer). Drivers who stay in their lane are like air molecules in a laminar flow. They follow a straight path and interact with their neighbors to the left and right mainly through shear, which will change their speed only slowly.
How does roughness cause a turbulent boundary layer?
Roughness lets air molecules bump into peaks or get sucked into troughs which adds a perpendicular speed component. Normally, the motion of the flow is expressed relative to the object. This will make the molecules close to the surface the slow ones. Now you have faster molecules from more distant layers moving closer to the surface and kicking the slow ones there ahead, and slower ones from close to the surface moving away, slowing down the more distant layers. So air molecules in turbulent flow wiggle around all the time and bump into slower molecules, or get bumped by faster ones. This makes all of them assume the same speed, more or less. Only at the surface you find a strong speed gradient, maybe like at an onramp on a highway. The slow cars entering the highway speed up really fast when others will cut into their lane frequently.
What does the boundary layer look like?
Below you see two typical speed profiles, where the speed $u(y)$ increases as you move away from the surface (at $y = 0$). Left is laminar flow and right the turbulent variety.

Speed profiles of laminar (left) and turbulent (right) boundary layers. Image source.
In still air every boundary layer starts laminar. Inside the laminar boundary layer, small disturbances become less and less damped, and at some point some frequencies become unstable (see Tollmien-Schlichting waves) and will eventually create so much cross movement that the boundary layer becomes turbulent, even without roughness. How soon it transitions to a turbulent boundary layer depends on (besides roughness):

*

*the length and speed of the flow, mostly expressed as the local Reynolds number,

*the pressure gradient,

*wing sweep and

*disturbances like bugs, rivet heads or turbulators.

If the flow is accelerated, all speeds in flow direction increase while cross flow will not be affected, so a laminar boundary layer in accelerating flow is stabilized. On the other hand, a pressure rise in flow direction corresponds to a deceleration in flow direction, so any movements perpendicular to the flow direction will grow relative to the flow speed, and as a consequence the turbulent transition occurs rather quickly.
Why does turbulent flow "stick" to the surface longer?
Flow around a three-dimensional object will accelerate in the forward region and decelerate where the object's cross-section contracts again. Since the energy transfer across the stratified flow in the laminar boundary layer is reduced to shear, the molecules close to the surface will lose speed quickly once this deceleration starts. Soon the flow close to the surface comes to a rest relative to the surface and starts to flow backwards. This allows the outer layers of the flow to move away from the surface of the object because the space between them and the surface is now filled with slow-moving air. That is called flow separation.
The much higher energy transfer in a turbulent boundary layer will delay separation because the slow molecules close to the surface will get kicked along. Now the flow is able to follow the contracting contour of the object for much longer and separation is delayed.
Note that the golfball effect only occurs in a small range of speed and size combinations, because with bigger objects or at higher speeds the laminar-turbulent transition will have occurred already before the deceleration starts.


text:
Q: PC14 and PC15 on STM32F401 not working as inputs I'm trying to use PC14 and PC15 on Nucleo F401RE board, as inputs using this simple code:
  RCC_LSEConfig(RCC_LSE_OFF);

  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);

  // initialize ID pins as inputs
  GPIO_InitTypeDef gpio_init_struct;
  GPIO_StructInit(&gpio_init_struct);
  gpio_init_struct.GPIO_Mode = GPIO_Mode_IN;
  gpio_init_struct.GPIO_PuPd = GPIO_PuPd_UP;
  gpio_init_struct.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
  GPIO_Init(GPIOC, &gpio_init_struct);

  // read ID pins
  uint8_t inputs_state = 0;
  inputs_state |= GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_13);
  inputs_state |= GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_14) << 1;
  inputs_state |= GPIO_ReadInputDataBit(GPIOC, GPIO_Pin_15) << 2;

Unfortunately, while PC13 works as expected, PC14 and PC15 always stay high in case of pull-up configuration or low in case of pull-down.
The reference on page 155 states:

The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as
  general-purpose PC14 and PC15 I/Os, respectively, when the LSE
  oscillator is off. The PC14 and PC15 I/Os are only configured as LSE
  oscillator pins OSC32_IN and OSC32_OUT when the LSE oscillator is ON.
  This is done by setting the LSEON bit in the RCC_BDCR register. The
  LSE has priority over the GPIO function.

So I'm setting LSE off, but still no result. What am I missing?

A: One of the issue I find is the jumper settings
By default, both jumpers SB48 and SB49 are open.

Reference: Schematics of Nucleo F401RE
Second way is to later measure the resistance from the resistors highlighted and
connector CN7 pin numbers 25 and 27.

If the hardware settings is fine, you should read zero ohms approximately.


text:
Q: Why i got error when i write the coding, df = pd.read_csv('C:\Users\COE-DRONE01\posing.csv') File "C:\Users\COE-DR~1\AppData\Local\Temp/ipykernel_7600/1138649954.py", line 1
df = pd.read_csv('C:\Users\COE-DRONE01\Desktop\codeAi')
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

A: The error log say SyntaxError: unicodeescape can't be decoded, change the "_" to something else, or remove it!


text:
Q: How to make matched text bold with jquery chosen? I am wondering how to make the matched part of the autocomplete suggestions bold when using jquery chosen plugin?
Anyone knows how to do that?
http://harvesthq.github.com/chosen/

A: On their example page this is the css selector they use:
.chzn-container .chzn-results li em {
  font-weight: bold;
}

The matched text is wrapped in an <em /> so you might need to set `font-style: normal;' as well.

A: Yes Just in your php page search the result with the passed string and then change it using bold tag.Like
$result='Tom Cruise';//retreived frmo database
$passed_string='Tom';//passed string from which db is searched
then
$result=str_replace($passed_string,'<b>'.$passed_string.'</b>',$result);

A: Or this following CSS property as the name has changed
.chosen-container .chosen-results li em {
  font-style: normal;
  font-weight: bold;
}


text:
Q: VS Code Salesforce import picklist value [isActive Tag missing] When importing a picklist, VS Code offers only the Active picklist value, and the tag isActive does not come in the xml import file, how can we make sure we get all active and inactive picklist values
here is what I get and I want to have the tag isActive as well
        <value>
            <fullName>Commercial</fullName>
            <default>false</default>
            <label>Commercial</label>
        </value>

A: What are you retrieving, a "normal" custom picklist or a global value set? Docs say

isActive  boolean
Indicates whether this value is currently active or
inactive. The default value is true. Users can select only active
values from a picklist. An API retrieve operation for global picklist
values returns all active and inactive values in the picklist.
(Meanwhile, retrieving the values of a non-global, unrestricted
picklist returns only the active values.)


text:
Q: Create a webpart with typescript / sass I created a webpart for a footer and I have to insert an image in the footer and I can't get it to display. I am using typescript and sass. It is my first webpart!

INTRANET | Tritec Intervento

y en sass:
  .subTitle {
    margin-right: 10px;
    @include ms-fontColor-white;
  }

A: If you want to reference a local image, Please take a reference of below snippet:
const logo: any = require('./assets/logo.png');

export default class HelloWorldWebPart extends BaseClientSideWebPart<IHelloWorldWebPartProps> {
  public render(): void {
    this.domElement.innerHTML = `

`;
  }

For more details please refer to:

*

*https://blog.mastykarz.nl/correctly-reference-images-sharepoint-framework-solutions/
BR


text:
Q: Show that a linear map is well-defined Let $V,W$ be vector spaces over field $F$ and $f:V\rightarrow W$ be a linear mapping such that $U \subseteq \ker(f)$. Show that the mapping $\overline{f}:V/U \rightarrow W$ given by $\overline{f}(v+U)=f(v)$ is a well-defined linear mapping. Show that $\ker(\overline{f})$=can$(\ker(f))$ where can$(\ker(f))=\{$can$(x) \mid x \in \ker(f)\}$
It looks like I need to apply first isomorphism theorem but I have no idea how to do that.

A: For your first question: if $v+U = w+U$, then $v-w\in U\subseteq \mathrm{ker}(f)$ and so $f(v) = f(w)$. Hence $\bar{f}(v+U) = f(v) = f(w) = \bar{f}(w+U)$. Thus, $\bar{f}$ is well-defined.


text:
Q: Can the handle be same on two windows? Suppose if a window with handle 123456 is closed and another window is opened. Can Windows assign handle 123456 to the new window in the rarest possibility?

A: There's no guarantee anywhere that Windows won't immediately re-use a handle. In practice, all extant implementations take steps to try to avoid re-using handles.


text:
Q: how to delete a android notification? I want to push a notification to the user every X minutes.
However if there already exist an unread notification,
I want to delete it and replace it with a new one. How can I delete?
How can I check how many unread notification my app has already pushed?

A: To replace an existing notification with a new one you should simply post a notification with the same id, this behavior is mentioned in the documentation of NotificationManager's notify() method. If you want to just remove a notification, call cancel() providing the id you used to start it.
Regarding counting the number of notifications your app has sent, I think the best solution would be to just store a counter and increment it once a notification has been sent.


text:
Q: Fully functional drawing outside component bounds? setClip() usage and other I have designed simple JPanel extension which I was expecting will able to draw outside it's bounds:
public class JGlassPanel extends JPanel {

@Override
protected void paintBorder(Graphics g) {
}

@Override
protected void paintComponent(Graphics g) {
    if( getParent() != null ) {
        g.setClip(-getX(), -getY(), getX() + getWidth(), getY() + getHeight());
    }
    super.paintComponent(g);
}
}

The test of this class showed it works only partially (code below). For example, the button is drawn outside a panel, while background felt inside bounds and button visual effects also felt inside bounds.
Is it possible to extend all visual features to arbitrary area?
UPDATE
I found that overriding contains made button also function outside a panel (react on clicks). Meanwhile, visual effects and background are still inside component bounds.
USAGE CODE
public class Tester_JGlassPanel_01 {

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {

            JButton button = new JButton("my button");
            button.setBounds(-50, -20, 100, 40);

            JGlassPanel panel = new JGlassPanel();
            //JPanel panel = new JPanel();
            panel.setLayout(null);
            panel.setBackground(Color.RED);
            panel.setBounds(100, 100, 100, 100);
            panel.add(button);

            JFrameEx frame = new JFrameEx();
            frame.setLayout(null);

            frame.add(panel);
            frame.setSize(0.5);
            frame.center();

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.setVisible(true);

        }

    });

}
}

A: I think setClip is intended only as an optimization, i.e. to make the drawing area smaller, but not larger. Swing is full of optimizations, and there are other optimizations as well in addition to setClip: the background is obviously drawn only within the bounds of a component.
So I wouldn't rely on setClip - even if you can find a tricky way to use it like this, it will break at some point.


text:
Q: Unable to send file value to controller in asp.net mvc with js I have a little problem here. I am unable to send the content of a file input to the controller via js, I'm using 'croppie' plugin to re-scale the picture size before submission. Before using this  js plugin at all, I could submit the file and save it but not anymore but now, I get all values in my model submitted but not the file. I'm not good with js, please help me.
Here is the input and submit codes

      <input type="file" name="ImageUpload" id="ImageUpload" value="Select an image" />

      <input type="hidden" id="productImage" name="productImage">

            Add Product

Here is the croppie plugin code

I have this post action in my controller
 public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
 {
     //.... some codes here
 }

A: if you using submit then you will need to put from body in your controller..
public ActionResult AddProduct([FromBody]ProductVM model, HttpPostedFileBase file)
 {
     //.... some codes here
 }


text:
Q: What is the meaning of AWESOME_SERVICE_API_TOKEN in pm2 pm2 json app declaration has an env entry as below
"env": {
    "NODE_ENV": "production",
    "AWESOME_SERVICE_API_TOKEN": "xxx"
  }

What does AWESOME_SERVICE_API_TOKEN means here?

A: The AWESOME_SERVICE_API_TOKEN is just an example. You can define any parameters that you need in your application, see here.
In your app you can access the NODE_ENV or AWESOME_SERVICE_API_TOKEN values to do whatever you want.


text:
Q: UIImageView changed in all UITableViewCell I want to change a specific UIImageView inside a UITableViewCell with this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self updateTableView];
    //get and show the image at selected cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UYLCellIdentifier forIndexPath:indexPath];
    UYLTextCell *textCell = (UYLTextCell *)cell;
    textCell.testImage.image = [UIImage imageNamed:@"image280280.jpg"];

}

but what happened is some cell had their image View changed and it also takes time.
this is where I declared the UIImageView in the UITableViewCell class:
@interface UYLTextCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *lineLabel;
@property (strong, nonatomic) IBOutlet UIImageView *testImage;

@end

A: The problem is that you're changing the information in an essentially-random cell instead of changing the information in your data source. You need logic within your cellForRowAtIndexPath method that knows that this cell was selected, and then set the image in that method (or specifically reset the image if it should not be selected). Keep a BOOL value in your data source and set it when it is selected and then reload that cell.
Example:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self updateTableView];
    //get and show the image at selected cell
    dataSourceObjectForIndexPath.cellShouldBeSelected = YES;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UYLTextCell *textCell = (UYLTextCell *)[tableView dequeueReusableCellWithIdentifier:@"whatever" forIndexPath:indexPath];

    // set up your cell however it needs to be

    if(dataSourceObjectForIndexPath.cellShouldBeSelected)
    {
        textCell.testImage.image = [UIImage imageNamed:@"image280280.jpg"];
    }
    else
    {
        textCell.testImage.image = //whatever the default state is
    }

    return textCell;
}

A: This code is nonsense:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UYLCellIdentifier forIndexPath:indexPath];

This cell is not the cell that was just selected, so who knows what cell it is, if any?
So what cell was just selected? It's this one:
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];


text:
Q: Magento - Create Customer Account form is missing On a Magento 1.11.1 site (Pro).
When I go to the URL [site]/customer/account/create I should get the form for creating a customer from the file /frontend/base/default/template/persistent/customer/form/register.phtml in block Mage_Customer_Block_Form_Register.  Instead there is no such block included (show hints and show blocks enabled).
The customer login form works [site]/customer/account/login by displaying the form from file /frontend/base/default/template/persistent/customer/form/login.phtml in block Mage_Customer_Block_Form_Login. This works fine.
I'm using basically the modern theme with modifications (in a separate directory).
Also, customers are still able to create an account via the checkout process.
Is there an configuration parameter that might be set that could disable the standalone 'create customer account' functionality?
Could I have some issue with the templating that is getting in the way of displaying this register block?
So far I have not found the program logic that controls whether the register block is included or removed or anything?  I've checked on file permissions and everything else I could think of, but there is obviously something I am overlooking or not aware of.
Any pointers on discovering the source of the problem would be appreciated.


text:
Q: Python KafkaConsumer not printing output I am using following script to read data from kafka -
from kafka import KafkaConsumer
from json import loads
import json

consumer = KafkaConsumer('topicname',bootstrap_servers=['brokerip'],enable_auto_commit=True)

 for message in consumer:
     message = message.value
     print(message)

When i first ran the code it was working, but now it's not printing anything. Nothing is changed in code. Any reason for why its happening?

A:
When i first ran the code it was working

You've committed the messages for your consumer group (enable_auto_commit=True), and there are no messages actively being produced.
If you want to repeat the messages, you need to reset the consumer group or use a new one


text:
Q: How to write an X11 app that follows the cursor I'd like to write a Linux screen magnifier that's customized to my liking. Ideally, the magnified window would be a square about 150 pixels wide that follows the mouse cursor wherever it goes.
Is it possible to do this in X11? Would it be easier to have an application window that follows the mouse around, or would it be better (or possible) to forget about the window altogether and just make the mouse pointer a 150x150 square that magnifies whatever's underneath?

A: Look at the source to xeyes?

A: This actually already exists, it's called Xmag (do a Google search for additional info). You might want to check out the source code for it if you want to know how it works.
EDIT: looks like I misread your question a little bit... if you want a magnified square to follow the mouse pointer around, I suppose it should be possible, but I don't know the technical details of how you'd do it. Regardless, the place to start is probably by looking at Xmag as a starting point.

A: I am unsure if this can run as its own app or would have to be integrated into your window manager.  Either way, you would need libx11 (might have a different name from distro to distro).  Also, I would suggest taking a look at swarp.  I know this is not even close to what you are talking about, but the source code is only 35 lines and it shows what can be done with libx11.

A: I would personally make that a frameless window that always stays atop with a 1px hole in the middle. The events that the user makes (Mouse clicks, keypresses, whatever) is passed to the window below.
And when the user moves it's cursor it is ought to be visible to your window and you just move it over a bit. For the magnifying part, well - that is left as an exercise to the reader (Because I do not know how to do that as of yet ;-).

A: Texworks comes with such a feature to inspect the pdf resulting from typesetting a latex source. You can also choose between a square or a circular magnifier. See https://www.tug.org/texworks/ for access to the code which can serve a launchpad.


text:
Q: How to get Prisma client to generate relationship types I am trying to create a one-to-many relationship between a user and posts. I can create the database schema and can write / query all ok but it appears the prisma client that is being generated doesn't have the relationships on the type.
For example, my schema looks like this:
model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int
}

I then run npx prisma generate which creates a client with the following types
/**
 * Model User
 *
 */
export type User = {
  id: number
}

/**
 * Model Post
 *
 */
export type Post = {
  id: number
  authorId: number
}

I would expect the user type to look like this:
export type User = {
  id: number;
  posts: Post[];
}

Have I defined my Prisma schema correctly? What do I need to do to get the type to include the relation?

A: By default, a Prisma type will not include relational fields in the base "type". If you want to get the type of your User which includes related Posts, the Prisma client will include that based on the structure of your query.
https://www.prisma.io/docs/concepts/components/prisma-client/select-fields
You can use the include attribute on any Prisma CRUD operation to have the Prisma client return specific relational fields, AND those related fields are included in the emitted type. Prisma will take care of this typing for you!
const usersWithPosts = await prisma.user.findMany({
  include: {
    posts: true
  }
});

// usersWithPosts has a type like this:
// Array<User & { posts: Array<Post> }>

========
EDIT: If you want to compute the type in advance without wanting to write a query, you can use Prisma.UserGetPayload (or some other form of GetPayload, as the prefix will change based on the model.)
type UserWithPosts = Prisma.UserGetPayload<{
  include: {
    posts: true;
  };
}>;

This emits the following type:
type UserWithPosts = User & {
    posts: Post[];
}


text:
Q: Three.TextureLoader is not loading images files So I've been messing around with THREE and Node for a while, and up until now, I have been loading textures using the TextureLoader class as follows:
var loader = new THREE.TextureLoader;
loader.crossOrigin = '';

function createSphere ( radius , segments , rings ) {

  var geometry = new THREE.SphereGeometry(radius , segments , rings);

  var material = new THREE.MeshPhongMaterial({

        map: loader.load('./images/...'),
        bumpMap: loader.load('./images/...'),
        ect...

  });

  return new THREE.Mesh ( geometry, material )
}

It was working fine, and then I decided that instead of loading the textures when I created the material that I would like to pre-load all my textures, so I made a a small utility to do just that:
var loader = new THREE.TextureLoader;
loader.crossOrigin = '';

var textureMap = {

earthTex : {file : 'earth_no_ice_clouds.jpg', message : 'Loading Global Land Masses'},
earthBumpTex : {file : 'earth_bump.jpg', message : 'Loading Global Depth'},
earthSpecTex : {file : 'earth_specular.png', message : 'Loading Water'},
earthCloudTex : {file : 'earth_clouds.png', message : 'Loading Clouds'},
earthCultureTex : {file : 'earth_cultural.png', message :'Loading Country Borders'},
earthLookUpTex : {file : 'earth_lookup.jpg', message :'Loading Country Projections'},
moonTex : {file : 'moon.jpg', message :'Loading Lunar Surface'},
moonBumpTex : {file : 'moon_bump.jpg', message : 'Loading Lunar Depth'},
skyDomeTex : {file : 'galaxy_3.png', message : 'Loading Galaxy'}

};

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
}

function loadTextures(  ) {

    var path = "./images/";
    var size = Object.size(textureMap);
    var count = 0;

    for(var key in textureMap) {
        var textureItem = textureMap[key];
        var texture = loader.load(path + textureItem.file);
        console.log(texture);
    }
}

loadTextures();

Whenever I run this in my browser (Chrome) with the developer tools open, the THREE.texture object that ends up being logged has its image property set to 'undefined' and its src property set to " ". I do not understand why this is happening, and I have not changed any of the paths for my .png or .jpg files nor the location of the file in which I am using my the TextureLoader.
When I try to run the first snippet of code up top, the error also occurs and now I cannot seem to load any textures into my application.
Any help in understanding why this has happened all of a sudden would be greatly appreciated.
EDIT
I edited the first code block in an attempt to make my issue more clear. I wasn't using promises or callbacks or anything of the sort before. I was just calling my 'createSphere' function and similar functions from my scene initialization function. It used to work fine, and I had no problems loading textures.
Now, using the same program structure from before, the first code block doesn't work.

A: You're not calling it correctly. TextureLoader.load() returns immediately (with an empty, still to be populated THREE.Texture object ... it populates only when the request completes), and it doesn't wait for the image to be loaded.
Instead, as you can read in its documentation here you can feed it with callback methods which will be called when loading is complete, finished, or in progress.
Taking the example from the documentation:
// instantiate a loader
var loader = new THREE.TextureLoader();

// load a resource
loader.load(
    // resource URL
    'textures/land_ocean_ice_cloud_2048.jpg',
    // Function when resource is loaded
    function ( texture ) {
        // do something with the texture
        var material = new THREE.MeshBasicMaterial( {
            map: texture
         } );
    },
    // Function called when download progresses
    function ( xhr ) {
        console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
    },
    // Function called when download errors
    function ( xhr ) {
        console.log( 'An error happened' );
    }
);

If you want to wait for all the textures to be loaded, that's going to get more complicated. One way is to use Promises, here is an answer to a very similar question I've given before: Is there a way to wait for THREE.TextureLoader.load() to finish?

A: I fixed it by first importing the image
import image from './myimg.jpg'

this import is the url of the image, and using that url in the textureloader fixes it
const texture = new THREE.TextureLoader().load(img)


text:
Q: Display icon for mime type in MCV3 razor page Is there a quick way to determine (and display) the icon in use for a particular user, and display it on an MVC3 page?
e.g.
All my users will be on Win (XP/Vista/7) and I will restrict mime types for uploaded files to: "text/plain" (for csv), "application/pdf", "application/msword" and "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
However, it would be "nice" if the icon displayed to the user matched the application they use to view the files.
Is this possible?

A: This relies on what would be a security hole: The ability for javascript to identify installed software on a persons computer. That said, it may be possible to new ActiveXObject and identify whether some apps are installed by identifying if assemblies are registered in this way. Otherwise you're best bet is to go with chances: If they're using windows display excel, if mac display it's icon, if android display whatever, etc
I would really just go with a best guess, you'll be right the vast majority of the time I'd wager. It's just a major loss in ROI to get any more accurate than basing it off of their detected OS considering the amount of work anything beyond that would take.


text:
Q: Python: Printing nested classes What's the best way to print the contents of a nested class? For example:
class Library():
    def __init__(self):
        self.shelves = []
        self.shelf = self.Shelf()

    class Shelf():
        def __init__(self):
            self.books = []

x = Library()

I know vars(x) works if the class is not nested. But if it is, I get something like:
{'shelf': <__main__.Shelf instance at 0x7f4bae723560>, 'shelves': []}

as the output. How do I get python to print it out as:
{'shelf': {'books': []}, 'shelves': []}

A: You are aiming to have a string version of your objects.  Python knows two methods for this: __repr__() and __str__().  The first is meant to be a string which, if interpreted as Python source, would re-generate the thing it represents.  If you just call vars(x) you receive a dict of all fields in the given x.  Most means to output this dict (and probably also yours) make it call the __repr__() function of each of its contents.  That's why you see that ugly string <__main__.Shelf instance at 0x7f4bae723560> because that's the __repr__() of your Shelf object.
I propose to implement it and thus override the standard implementation.  You will have to do that in Shelf:
class Library():
    def __init__(self):
        self.shelves = []
        self.shelf = self.Shelf()

    class Shelf():
        def __init__(self):
            self.books = []
        def __repr__(self):
            return repr(vars(self))

x = Library()

And while you're at it, you could do the same in your Library as well; then typing x alone (i. e. instead of vars(x)) would also give the nice output:
class Library():
    def __init__(self):
        self.shelves = []
        self.shelf = self.Shelf()
    def __repr__(self):
        return repr(vars(self))

    class Shelf():
        def __init__(self):
            self.books = []
        def __repr__(self):
            return repr(vars(self))

x = Library()

And of course you can refactor that out and put that aspect into a base class:
class Representer(object):
    def __repr__(self):
        return repr(vars(self))

class Library(Representer):
    def __init__(self):
        self.shelves = []
        self.shelf = self.Shelf()

    class Shelf(Representer):
        def __init__(self):
            self.books = []

x = Library()

A: First, I would recommend that you not nest classes. There isn't really any reason to do so.
Second, you're seeing exactly what you're supposed to: the value for the shelf variable is a Shelf object, and you haven't defined any special appearance (or "reproduction") for it. Since vars is not recursive, you see the default appearance with a memory location.
If you want to see the contents of a vars() call on a Shelf object when printing the Shelf object, you can define a __repr__ method for Shelf that calls vars() on itself:
class Library():
    def __init__(self):
        self.shelves = []
        self.shelf = self.Shelf()
    class Shelf():
        def __init__(self):
            self.books = []
        def __repr__(self):
            return str(vars(self))

>>> x = Library()
>>> vars(x)
{'shelf': {'books': []}, 'shelves': []}


text:
Q: Fatal error: Cannot redeclare PHPUnit\Framework\assertArrayHasKey() I need help with this error when try to run phpunit tests in VS code terminal at address: D:\xampp\htdocs\coscProj>
Fatal error: Cannot redeclare PHPUnit\Framework\assertArrayHasKey() (previously declared in phar://D:/xampp/php/phpunit.phar/phpunit/Framework/Assert/Functions.php:80) in D:\xampp\htdocs\coscProj\vendor\phpunit\phpunit\src\Framework\Assert\Functions.php on line 79

As I tried to install phpunit with multiple ways, I am not sure is that the cause of this error or not.

A: This error tells you that your function is already defined. This usually happens when a file is included/required several times, or the function with the same name is declared in several times. You can wrap function_exists around your function definition, like
if (!function_exists("somefunction")) {
    function somefunction() {}
}

But that might be a naive approach. You will first need to make sure that you do not require the same thing several times. If only a single function is duplicated, then you can add the logic above. require_once and include_once are keywords that spring to mind when this kind of issue happens.


text:
Q: Output of Gen.choose() and .oneOf() When running the below test, Gen() gets printed out for both println statements.
Based on the ScalaCheck docs, I would've expected the output to be:

(number, number)
"Hello" or "World"

class TestScalaCheck extends FlatSpec {

    @author first test - https://github.com/rickynils/scalacheck/wiki/User-Guide
    "a test" should "print out Gen.choose(1, 100)" in {
        val myGen = for {
          n <- Gen.choose(10,20)
          m <- Gen.choose(2*n, 500)
        } yield (n,m)

        println(myGen)

        val c = Gen.oneOf("Hello", "World")
        println(c)
    }
}

A: Gen[T] is a generator of values (of type T), and this is the type of both myGen and c above. If you want to print out example values of what the generators can produce (wrapped as an Option), try println(myGen.sample) and println(c.sample).


text:
Q: How are number theory and C*-algebras connected? I came across this research profile where under Research Overview, it states that

These days C*-algebra theory is a very active area of mathematical research in its own right, and enjoys deep connections with other areas of mathematics such as symbolic dynamics, ergodic theory, group theory and even number theory.

My question is how C*-algebras and number theory are connected and if this is an active area of research?

A: *

*$C^∗$-algebras
associated with the $ax+b$-semigroup over $\mathbb{N}$ (2006)

*Ring $C^*$-algebras (2009)

*$K$-theory for ring $C^*$-algebras (2012)

*$C^*$-algebras from actions of congruence monoids on rings of algebraic integers (2019)

*On $K$-theoretic invariants of semigroup $C^*$-algebras from actions of congruence monoids (2019)
These papers associate C*-algebras to rings and study the inner structure of these ring C*-algebras.  The
generators of the corresponding $K$-theory turn out to be determined
by prime numbers. Several connections to algebraic number theory are worked out in section 6 of the 2009 paper.

A: I think the most prominent example of this is Connes' work on the Riemann hypothesis from a C*-algebra perspective.


text:
Q: Format JodaTime LocalDate in SpringMvc JSON using formatter I have a problem with my Spring application.
How can I format a LocalDate in a JSON...
The problem is that when I send the JSON I have to send a number, but when Spring generate the JSON I have:
"data": {
    "weekyear": 1970,
    "weekOfWeekyear": 1,
    "chronology": {
        "zone": {
            "fixed": true,
            "id": "UTC"
        }
    },
    "monthOfYear": 1,
    "yearOfEra": 1970,
    ...and a lot more

I have my field with the annotation DateTimeFormat like:
@DateTimeFormat(pattern="dd/MM/yyyy")
private LocalDate data;

And also configurated the format service in my servlet-context.xml:
<beans:bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
 </beans:bean>

But this alone doesn't work, what I miss to configure?


text:
Q: GeoSpatial ArcGIS loading map in multiple iframes. ERR: Cors Using: ArcGIS4.1x Java script on my local network and my server has not access to internet.
Background: This is a preexisting project which has a basic structure with a Main Pane and Detail pane as iframes.
When the page loads for the first time a Basemap is loaded with few markers and every marker is linked with a onClick popup to display the details on the marker. (Works fine)
When the user clicks on the popup there is a details pane which opens and the Lat,Long point associated with the marker should load in the new map.
It is basically using the same code as main pane to load the marker, the only difference is it loads detail pane with only one marker(detail pane) instead of 20+ markers ((Main pane)
but when the detail pane is loaded there is an error, the basemap loads but with no marker.
Err:: Access to fetch at 'http://scripts/ArcGIS4.1x/esri/t9n/common.json' from origin 'http://localhost:56145' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Not sure why it is looking at 'http://scripts/...' when the .js files are on the local network.
On loading of the main pane there is no refence to 'http://scripts/...'
Any suggestions?


text:
Q: Is there news about the podcast? It's been two months, should we be expecting a new podcast? Is there somewhere on Stack Exchange to go for this information?

A: As far as I know, the Stack Exchange blog (and the podcasts category in particular) is the only source of up-to-date information on the podcast. As you say, it's been over six to eight weeks since the last podcast, whose blog entry enthusiastically states

That's it for Podcast #30, which is it for podcasts in 2011. See you next year!

So I guess the only thing we know for sure is: sometime this year (2012).
Update (2012/02/06)
Now that Jeff Atwood is leaving Stack Exchange, it's somewhat unclear when the next podcast will be.
Update (2012/03/02)
Podcast #31 just went up yesterday.

A: SE Podcast #33 – It's Back!

It's Back! Welcome to episode #33 of the Stack Exchange podcast.
We've got a brand new co-host (Jay Hanlon, our new VP of Community
Growth) plus our guest this week is David Fullerton, VP of Engineering
at Stack Exchange.


text:
Q: Hierarchical clustering methods using a similarity metric for which d(x, x) != 0, and possibly assymmetric I want to cluster files based on an information distance, which is obtained by comparing the compressed length of two files separately and the concatenation of the two files, using a real-world compressor like zlib. (In words: given files $x$ and $y$, how easy can you express $x$ in terms of $y$?)
This "metric" does not satisfy $d(x,x) \ne0$, and it does not always satisfy $d(x,y)=d(y,x)$, depending on the compressor used. (But I'm willing to throw away one half of the distance matrix and pretend it's triangular.)
I'm told I cannot use hclust in R, because it always expects $d(x,x)=0$.
See my other question regarding my troubles with R (I'm only a beginner.)
What hierarchical clustering method would be suitable, preferably one that is implemented in R/Python? I only want to cluster up to 30 items right now, so scale is not an issue.

A: Hierarchical agglomerative clustering should never attempt to use $d(x,x)$ anyway. It's not a possible "merge" of two clusters.
Symmetry is a different thing. Have you considered "fixing" your similarity?
$$
d^\prime(x,y):=\begin{cases}
\min\{d(x,y), d(y,x)\} & \text{if }x\neq y \\
0 & \text{if }x = y
\end{cases}
$$
As long as your distance matrix fits into main memory this should be easy to do, and then you should be able to run many clustering algorithms (except k-means and Mclust).


text:
Q: Sending Huge Collection of DTOs back to Client I have prepared a DTO with 10 string properties. I need to pass a collection of 500 objects of these DTOs to client from WCF service.
//DTO with object info
[DataContract()]
public class RTVPIDObj
{
    public RTVPIDObj()
    {
    }
    [DataMember()]
    public string OBID { get; set; }

    [DataMember()]
    public string UID { get; set; }

    [DataMember()]
    public string NAME { get; set; }

    [DataMember()]
    public string DESCRIPTION { get; set; }
    .
    .
    .
    .
}

Whenever user requested, I need to pass properties of one selected object, which typically comprised of 500 string properties from WCF service.
//DTO with properties info
[DataContract()]
public class RTVPIDProp
{
    public RTVPIDProp()
    {
    }

    [DataMember()]
    public List<Tuple<string, string>> Properties { get; set; }
}

I can pass this properties DTO when ever requested, but preparing that properties DTO at server side on the fly is taking long time.
So I am thinking to pass collection of object DTO where each object contains properties DTO also,  all at a time.
//DTO with object info and properties info
[DataContract()]
public class RTVPIDObj
{
    public RTVPIDObj()
    {
    }
    [DataMember()]
    public string OBID { get; set; }

    [DataMember()]
    public string UID { get; set; }

    [DataMember()]
    public string NAME { get; set; }

    [DataMember()]
    public string DESCRIPTION { get; set; }
    .
    .
    .
    .
    [DataMember()]
    public List<Tuple<string, string>> Properties { get; set; }
}

With the help of some background process, I can prepare this collection with properties also easily. Then, no need to do multiple client-server calls whenever object selected at client side.
Is this way of passing a huge size DTO (500 objects where each object comprised of 500 string collecion properties) to client is a bad approach?
And is sending this kind of huge size DTO itself takes long time??? Any other way in achieving this?


text: Q: More than two arrows on SplieJS I can't find the answer anywhere, even in the official Splide documentation. Is there any possibility to have two functional splide_arrows? For example: one on the top of the div and second on the bottom? I tried to implement two custom splide_arrows at the top of splide section but it doesn't work...


text:
Q: SQL Server : matching records from 2 tables with sorting Let's assume I have two tables, A and B, both with an ID column and a foreign key (value).
I want to do a select based query that returns only the matching records, not including those that don't meet the condition of having the same data (ID and Value columns), also sorted by Value column of table B.
Table A
SELECT *
FROM (VALUES
(15, 1),
(16, 2),
(17, 3)
) as t(idMetadata, [Value])

Table B
SELECT *
FROM (VALUES
(185442, 22008, 16, 6 ,2),
(187778, 22269, 16, 6 ,2),
(211260, 24925, 16, 6 ,2),
(251476, 29431, 15, 4 ,1),
(251477, 29431, 16, 5 ,2),
(251478, 29431, 17, 6 ,3)
) as t(idDet, idEnc, idMetadata, OrderValue, [Value])

The expected result is

Can this be achieved by a single query? Or do I have to create a CTE or subqueries ?
EDIT: Sorry, I forgot to mention another condition for the query: in Table B, the records should have the same  idEnc and the OrderValue column should be consecutive, That's why the expected result also have same idEnc and the OrderValue is 4, 5 & 6.

A: You can use CTE notation
;with cte as(
SELECT B.*,row_number() over(partition by b.idmetadata order by b.value,b.iddet desc) rn
FROM (VALUES
(185442, 22008, 16, 6 ,2),
(187778, 22269, 16, 6 ,2),
(211260, 24925, 16, 6 ,2),
(251476, 29431, 15, 4 ,1),
(251477, 29431, 16, 5 ,2),
(251478, 29431, 17, 6 ,3)
) as B(idDet, idEnc, idMetadata, OrderValue, [Value])
inner join
(VALUES
(15, 1),
(16, 2),
(17, 3)
) as A(idMetadata, [Value]) on A.idMetadata=B.idMetadata
)
select * from cte
where rn=1

or without CTE:
select * from (
SELECT B.*,row_number() over(partition by b.idmetadata order by b.value,b.iddet desc) rn
FROM (VALUES
(185442, 22008, 16, 6 ,2),
(187778, 22269, 16, 6 ,2),
(211260, 24925, 16, 6 ,2),
(251476, 29431, 15, 4 ,1),
(251477, 29431, 16, 5 ,2),
(251478, 29431, 17, 6 ,3)
) as B(idDet, idEnc, idMetadata, OrderValue, [Value])
inner join
(VALUES
(15, 1),
(16, 2),
(17, 3)
) as A(idMetadata, [Value]) on A.idMetadata=B.idMetadata
) t
where rn=1

A: I believe you can do this with a fairly simple INNER JOIN:
SELECT
    b.idDet, b.idEnc, b.IDMetadata, b.OrderValue, b.Value
FROM
    TableB b
INNER JOIN
    TableA a ON b.IDMetadata = a.idMetadata
             AND b.Value = a.Value

A: That will give you desired result:
SELECT  idDet,
        idEnc,
        idMetadata,
        OrderValue,
        [Value]
FROM (
    SELECT  b.idDet,
            b.idEnc,
            b.idMetadata,
            b.OrderValue,
            b.[Value],
            ROW_NUMBER() OVER (PARTITION BY b.idEnc ORDER BY b.OrderValue) as rn,
            DENSE_RANK() OVER (ORDER BY a.[Value]) as dr
    FROM TableB b
    INNER JOIN TableA a
        ON b.idMetadata = a.idMetadata AND b.[Value] = a.[Value]
) as t
WHERE rn = dr


text:
Q: How to label a row of plots with the labels close to the plots? I am running this code:
Plot3D[#, {x, -5, 5}, {y, -5, 5}, PlotRange -> {-5, 10}] & /@ {x, y,
   Abs[x], Abs[y], Abs[x + y], Abs[x] + Abs[y]} //
 GraphicsGrid[{#, {"x", "y",
     "\[LeftBracketingBar]x\[RightBracketingBar]",
     "\[LeftBracketingBar]y\[RightBracketingBar]",
     "\[LeftBracketingBar]x+y\[RightBracketingBar]",
     "\[LeftBracketingBar]x\[RightBracketingBar]+\[LeftBracketingBar]\
y\[RightBracketingBar]"}}] &

to produce this result:

which is great. But I would like the labels to be rendered closer to the plots.  Is there some way to do that with GraphicsGrid?
(I don't really want to be using a GraphicsGrid – I actually want to be using a GraphicsRow, with labels below the plots.  But I can't figure out how to do that.  This is the best hack I have come up with.)

A: You can use PlotLabel if you don't mind having the labels above the plots:
GraphicsRow[
    Map[
        Plot3D[#,{x,-5,5},{y,-5,5},PlotRange->{-5,10},PlotLabel->#]&,
        {x,y,Abs[x],Abs[y],Abs[x+y],Abs[x]+Abs[y]}
    ],
    ImageSize->800
]

For labels below the plot you can use Labeled (as in the comments) or PlotLegends:
GraphicsRow[
    Map[
        Plot3D[#,{x,-5,5},{y,-5,5},PlotRange->{-5,10},PlotLegends->Placed[#,Below]]&,
        {x,y,Abs[x],Abs[y],Abs[x+y],Abs[x]+Abs[y]}
    ],
    ImageSize->800
]


text:
Q: what is divergence of $\text{div} (nu)$? Let $n$ be the density of the fluid and $u\in \mathbb R^3$ its velocity field.
My Question is: what is $\text{div} (nu)$?
Motivation: I'm trying to understand  the equation: $\partial_t n + \text{div} (nu)=0, x \in \mathbb T^3, t>0$ (Navier-stack equation on 3 dimensional torus).

A: In Euclidian coordinates, we have that
$$\operatorname{div}(nu)=\partial_i (nu_i)=(\partial_i n)u_i+n \partial_iu_i=\operatorname{grad}(n)\cdot u+ n \operatorname{div}(u)$$


text:
Q: How to change multiple populated checkbox input field values? I was looking for solution, how to change multiple populated checkbox - input field values with JavaScript help. How to change values yes to no and no to yes if checkbox checked. Here is the part of code I use:
html form:
<form method="post" action="" autocomplete="off" id="form">

Select place

                <select data-skip-name="true" name="pl[]">
                    <option value="">select place</option>
                    <option value="Berlin">Berlin</option>
                    <option value="London">London</option>
                    <option value="Barcelona">Barcelona</option>
                </select>
                Date: <input type="date" name="pl[]" value="iesndat">
                Yes/No: <input type="checkbox" name="pl[]" id="trick" value="no">
                <button type="button" name="add3" id="add3" class="btn btn-success">+</button>

</form>

javascript:

this part is working perfectly:
$('.dothetrick input[type="checkbox"]').change(function() {
                if ($(this).is(":checked")) {
                    document.getElementById("trick").value = "yes";
                } else
                    document.getElementById("trick").value = "no";
                });

but how to make to work this part of js code which makes populated checkbox values change value from no to yes and yes to no:
var i = 1;
                $('#add3').click(function(){
                    i++;
                    $('#df3').append('
<select data-skip-name="true" name="pl[]"><option value="">select place</option><option value="Berlin">Berlin</option><option value="London">London</option><option value="Barcelona">Barcelona</option></select> Date: <input type="date" name="pl[]" value="iesndat"> Yes/No: <input type="checkbox" name="pl[]" id="trick'+i+'" value="no"> <button name="remove" id="'+i+'" class="btn btn-danger btn_remove3">-</button>');
                });

The idea is something like this:
var i = 1;
$('#row'+i).change(function() {
            if ($(this).is(":checked")) {
                i++;
                document.getElementById("trick"+i).value = "yes";

            } else
            i++;
                document.getElementById("trick"+i).value = "no";

});

checkbox checked not changing no to yes value in new populated rows:

Can't find answers by myself. I hope the idea is clear and someone can help me with this!

A: You can use other way with set .trick class to checkbox
Then use $(document).on('change', '.trick' , function() { ... })
In fact your issue is the other checkbox are not part of the DOM and will be added to DOM with click event of #add3

$(document).ready(function() {

    $(document).on('change', '.trick' , function() {

        if ( $(this).is(":checked") ) {

            $(this).attr('value','yes');

        } else
        {
            $(this).attr('value','no');
        }
        console.log( $(this).attr('value') )
    });

    var i = 1;
    $('#add3').click(function() {
      i++;
      $('#df3').append('
<select data-skip-name="true" name="pl[]"><option value="">select place</option><option value="Berlin">Berlin</option><option value="London">London</option><option value="Barcelona">Barcelona</option></select> Date: <input type="date" name="pl[]" value="iesndat"> Yes/No: <input type="checkbox" name="pl[]" class="trick" value="no"> <button name="remove" id="' + i + '" class="btn btn-danger btn_remove3">-</button>');
    });

    $(document).on('click', '.btn_remove3', function() {
      var button_id = $(this).attr("id");
      $("#row" + button_id + "").remove();
    });

});

<form method="post" action="" autocomplete="off" id="form">

Select place

        <select data-skip-name="true" name="pl[]">
            <option value="">select place</option>
            <option value="Berlin">Berlin</option>
            <option value="London">London</option>
            <option value="Barcelona">Barcelona</option>
        </select>
        Date: <input type="date" name="pl[]" value="iesndat">
        Yes/No: <input type="checkbox" name="pl[]" class="trick" value="no">
        <button type="button" name="add3" id="add3" class="btn btn-success">+</button>

</form>


text:
Q: Sorting array by count of subarray I have an array looking like this:
Array(
   ['some_first_category'] => Array(
            ['some_first_name'] => Array(
                           [0]=>'first@email.com',
                           [1]=>'second@email.com',
                           [2]=>'third@email.com',
                           [3]=>'fourth@email.com' )
             ['some_second_name'] => Array (
                           [1]=>'first@email.com',
                           [2]=>'second@email.com')
             ['some_third_name'] => Array(
                           [1]=>'first@email.com',
                           [2]=>'second@email.com',
                           [3]=>'third@email.com',
                           [4]=>'fourth@email.com' )
   ['some_second_category'] => Array(
            ['some_first_name'] => Array(
                           [0]=>'first@email.com' )
             ['some_second_name'] => Array(
                           [1]=>'first@email.com',
                           [2]=>'second@email.com',
                           [3]=>'third@email.com',
                           [4]=>'fourth@email.com')
             ['some_third_name'] => Array(
                           [1]=>'first@email.com',
                           [2]=>'second@email.com'))

And I want to sort the array by the number of values of that has the names, In my case I want to become this array:
Array(
   ['some_first_category'] => Array(
             ['some_third_name'] => Array(
                           [1]=>'first@email.com',
                           [2]=>'second@email.com',
                           [3]=>'third@email.com',
                           [4]=>'fourth@email.com' )
            ['some_first_name'] => Array(
                           [0]=>'first@email.com',
                           [1]=>'second@email.com',
                           [2]=>'third@email.com',
                           [3]=>'fourth@email.com' )
             ['some_second_name'] => Array (
                           [1]=>'first@email.com',
                           [2]=>'second@email.com')

   ['some_second_category'] => Array(
             ['some_second_name'] => Array(
                           [1]=>'first@email.com',
                           [2]=>'second@email.com',
                           [3]=>'third@email.com',
                           [4]=>'fourth@email.com')
             ['some_third_name'] => Array(
                           [1]=>'first@email.com',
                           [2]=>'second@email.com')
            ['some_first_name'] => Array(
                           [0]=>'first@email.com' ))

This means sorting categories by name by the number(count) of values of the names. Someone can help me?
Thanks in advance,
Aäron

A: Using uksort:
uksort($yourArray, function($a, $b) { return count($b) - count($a); });

Using array_multisort:
array_multisort(array_map('count', $yourArray), SORT_DESC, $yourArray);

and you can see uasort as well
best of luck :)

A: All you need is  uasort
uasort($list, function ($a, $b) {
    $a = count($a);
    $b = count($b);
    return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
});

Full Example
$list = Array(
   'some_first_category' => Array(
            'some_first_name' => Array(
                           0=>'first@email.com',
                           1=>'second@email.com',
                           2=>'third@email.com',
                           3=>'fourth@email.com' ),
             'some_second_name' => Array (
                           1=>'first@email.com',
                           2=>'second@email.com'),
             'some_third_name' => Array(
                           1=>'first@email.com',
                           2=>'second@email.com',
                           3=>'third@email.com',
                           4=>'fourth@email.com' )
        ),
   'some_second_category' => Array(
            'some_first_name' => Array(
                           0=>'first@email.com' ),
             'some_second_name' => Array(
                           1=>'first@email.com',
                           2=>'second@email.com',
                           3=>'third@email.com',
                           4=>'fourth@email.com'),
             'some_third_name' => Array(
                           1=>'first@email.com',
                           2=>'second@email.com'))

    );

$list = array_map(function ($v) {
    uasort($v, function ($a, $b) {
        $a = count($a);
        $b = count($b);
        return ($a == $b) ? 0 : (($a < $b) ? 1 : - 1);
    });
    return $v;
}, $list);

print_r($list);

Output
Array
(
    [some_first_category] => Array
        (
            [some_first_name] => Array
                (
                    [0] => first@email.com
                    [1] => second@email.com
                    [2] => third@email.com
                    [3] => fourth@email.com
                )

            [some_third_name] => Array
                (
                    [1] => first@email.com
                    [2] => second@email.com
                    [3] => third@email.com
                    [4] => fourth@email.com
                )

            [some_second_name] => Array
                (
                    [1] => first@email.com
                    [2] => second@email.com
                )

        )

    [some_second_category] => Array
        (
            [some_second_name] => Array
                (
                    [1] => first@email.com
                    [2] => second@email.com
                    [3] => third@email.com
                    [4] => fourth@email.com
                )

            [some_third_name] => Array
                (
                    [1] => first@email.com
                    [2] => second@email.com
                )

            [some_first_name] => Array
                (
                    [0] => first@email.com
                )

        )

)

A: You should use usort function. Refer here.
function sort_sub($a,$b)
{
$res= count($b)-count($a);
return $res;
}

usort($array_name,'sort_sub')


text:
Q: Flutter : How to automatically change the page after passing a certain time? Thank you for reading my question and taking your time. I am trying to add a function that makes you go back to the home screen after a certain time passes in Flutter. I have struggled with this problem for 3 weeks so I came here.
There are 4 pages.

*

*HomeScreen()

*SecondRoute()

*ThirdRoute()

*ForthRoute()

When you go to the next page or SecondRoute(), a timer starts. If you go to the next page or ThirdRoute(), the timer restarts.  I succeeded in adding this timer function, but the page transition never happened after reaching 0.

1. My codes

Here are my codes below.
mian.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:question/fourth_route.dart';
import 'package:question/second_route.dart';
import 'package:question/third_route.dart';
import 'package:question/timer_store.dart';

import 'home_screen.dart';

void main() {
  runApp(ChangeNotifierProvider(
    create: (context) => TimerStore(),
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Question',
      theme: ThemeData.dark(),
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/second_route': (context) => SecondRoute(),
        '/third_route': (context) => ThirdRoute(),
        '/fourth_route': (context) => FourthRoute(),
      },
    );
  }
}

time_store.dart
import 'dart:async';
import 'package:flutter/material.dart';

import 'home_screen.dart';

class TimerStore with ChangeNotifier {
  static const COUNTER_VALUE = 10; // TODO: ユーザーが設定できるように
  var count = COUNTER_VALUE;
  static const sec = const Duration(seconds: 1);
  static const ms = const Duration(milliseconds: 1);
  Timer _timer;

  startTimer() {
    if (_timer != null) {
      _timer.cancel();
    }

    count = COUNTER_VALUE;
    _timer = Timer.periodic(sec, (timer) {
      updateCounter();
    });
  }

  void updateCounter() {
    if (count > 0) {
      count--;
      print(count);
    } else {
      _timer.cancel();
      updateCounter2();
      updateCounter4;
    }
    notifyListeners();
  }

//追加
  void updateCounter2() {
    print('page trangition');
  }

  void updateCounter3(BuildContext context) {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => HomeScreen(),
    ));
  }

  void updateCounter4(BuildContext context){
    Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => HomeScreen()));
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

//追加 ---
  void stopTimer() {
    _timer.cancel();
  }

  void restartTimer() {
    startTimer();
  }
}

2. Problems

In order to see if the function is working, I used "print" and checked the output in the console. I could see the count down and "page transition" word of updateCounter2().
enter image description here
  void updateCounter() {
    if (count > 0) {
      count--;
      print(count);
    } else {
      _timer.cancel();
      updateCounter2();
      updateCounter4;
    }
    notifyListeners();
  }

//追加
  void updateCounter2() {
    print('page trangition');
  }

However, updateCounter4 did not work. I know this looks strange because it should have () like updateCounter4(). But if I do that I got an error saying,

1 positional argument(s) expected, but 0 found.  Try adding the missing arguments.

enter image description here
I know updateCounter4 needs arguments which is context. But I am not sure what exactly should be added in the() of updateCounter4...
I put "updateCounter4(context)" but it did not work...

Hope you understand my question and provide me advice. If it is not clear enough, happy to explain the details.

Thank you so much.

A: you can use Timer for that
 @override
void initState() {
 Timer(Duration(seconds: 3), (){
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>
 HomeScreen()));
});
 super.initState();
}

this will route you to your home screen after 3 seconds
and make sure to import dart:async at the top of your file
import 'dart:async';


text:
Q: How to open an appication using VBScript within an HTA file I am having trouble with getting the HTML Application (MeowcatSoftware Launcher Demo.HTA on GitHub) to open a target application, for example, MultiToolv0.2.exe. Is there a way to open the target applications such as the MultiTool using VBScript besides using Wscript.shell objects, which has been causing most of my problems?
I have tried the following, which didn't work:
Sub RunProgram
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run "notepad.exe c:\script\test.txt"
End Sub

(From 'Hey, Scripting Guy" Blog Post)
I played around a little with it but couldn't figure out how to achieve my goal. The blog post also mentioned using a Windows Shell object instead of Wscript.shell, but it looks like from the example that the Windows Shell object method was for opening a file using another program, and I just want it to simply open the target application. How do I open a program using VBScript within an HTA Application?

A: In vbscript this should work : You should using quote (") not like you posted in your question (") and (")
Call RunProgram()

Sub RunProgram
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run "notepad.exe c:\script\test.txt"
End Sub


text:
Q: BATCH - Better way to copy single folder from multiple directories I have built a batch backup program for work. It also has the capability to restore the data to computer.
Originally I had robocopy exclude appdata and just grab outlook files seperately. Recently I have found I want to grab all the appdata but put it into a seperate folder.
My challenge is I want to grab Appdata from all users on the computer, not just the current user.
I know I can just discover all folders in C:\Users and then copy appdata folders in a for loop, but I feel like there has to be a better, cleaner way to do it.
Currently I would be doing something like this:
(This is not working code, its just the idea I want to make cleaner)
For /f %%a in ('dir C:\Users /B /A D') do (
   robocopy "C:\Users\%%a" "BACKUP DIR\AppData"
)

I would love for a solution more like the exclusion method
robocopy "C:\Users" "BACKUP DIR\AppData" /only folders named appdata

A: This will check if the user has an appdata dir and copy it.
for /f %%a in ('dir /b /a:d "C:\Users"') do (
  if exist C:\Users\%%a\Appdata robocopy c:\Users\%%a\Appdata\ D:\BACKUP\
)

You probably need to also do if not exist backup mkdir backup if each user will have his/her own backup dir.


text:
Q: window.history.back() scrolls to lastscroll position rather than next page I am using window.history.back(-1) to attempt to go back to the last url, however it will work until i goto another page scroll and enter another page url through click.
Then when i go back to the previous page it scrolls to last position, But when I click the Back button again it just goes back to the scroll position and not the previous page. Even though there was a previous page.
How do I fix this. Thank you.
`

<button class="btn" onclick="window.history.back(-1)" >Go Back</button>

I have tried using the following but get only the same results.
window.history.go(-1)
I am not sure how else to approach this problem.


text:
Q: Provide Access to User With Insufficient Privilege - Attachment? I have a scenario where a specific Custom profile users , they can see the notes and attachment section in the Order object. However when they click on the Attachment it shows them Insufficient privilege.
How can I provide them access?
I tried to find it by editing the profile but could not find.


text:
Q: Combining count and linked tables I have a table Clients (ID, name), a table Items1 (ID, clientID, item1Name) and a table Items2 (ID, ClientID, item2Name)
Clients:
1, John
2, Miriam
3, Peter
4, Trude

Items1:
1,1,exam1
2,1,exam2
3,2,exam3

Items2:
1,1,test1
2,2,test2
3,4,test3

What I would like to accomplish is a query that sums up the items1.ID and the items2.ID together into one number, where the clientID = n
Query result
clientID, total Items
=====================
1,3
2,2
3,0
4,1

Is this possible?

A: Hope this also works
SELECT c.id,
       Count(item.itemname) AS TotalItem
FROM   clients c
       LEFT JOIN (SELECT id,
                         clientid,
                         item1name AS itemName
                  FROM   item1
                  UNION ALL
                  SELECT id,
                         clientid,
                         item2name AS itemName
                  FROM   item2) item
              ON c.id = item.clientid
GROUP  BY c.id

A: Try this
Select c.id, count(a.*) + count(b.*)
From clients a
Left join items1 a on c.id = a.clientid
Left join items2 b on c.id = b.clientid
Group by c.id

A: SQL-Server 2005 +
SELECT c.ID, i1.Cnt, i2.Cnt, i1.Cnt + i2.Cnt TotalCount
FROM Clients c
    CROSS APPLY (SELECT COUNT(*) Cnt FROM Items1 WHERE ClientID = c.ID) i1
    CROSS APPLY (SELECT COUNT(*) Cnt FROM Items2 WHERE ClientID = c.ID) i2

A: This code may help too:
;with CTE as
(select ClientID,count(*) as ItemsCount
 from Items1
 group by ClientID
 union all
 select ClientID,count(*)
 from Items2
 group by ClientID)
select c.ID,isnull(sum(CTE.ItemsCount),0)
from Clients c
left join CTE on c.ID=CTE.ClientID
group by c.ID


text:
Q: Add icon to border button I would like help to represent this image with css.
I do not know how to put that little orange ball on the left edge of the button.

.btn-typesTitleCreator {
    box-shadow: 0 2px 21px 0 rgba(255,114,1,0.51) !important;
    border: 1px solid #FF7201;
    height: 70px;
    border-radius: 12px;
}
<button type="button" class="btn-typesTitleCreator" id="createSmartTitle_button">Criar título inteligente</button>

IMG Example

A: Use a pseudo element (::before) with a border in the color that you want, and border-radius: 50% to make it round:

.btn-typesTitleCreator {
  position: relative;
  box-shadow: 0 2px 21px 0 rgba(255, 114, 1, 0.51);
  border: 1px solid #FF7201;
  height: 70px;
  border-radius: 12px;
  padding: 0 1em;
  margin: 1em;
}

.btn-typesTitleCreator::before {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 0;
  top: 50%;
  height: 10px;
  width: 10px;
  border: 5px solid #FF7201;
  border-radius: 50%;
  background: white;
  content: '';
}
<button type="button" class="btn-typesTitleCreator" id="createSmartTitle_button">
    Criar título inteligente
  </button>

A: Unicode Characters
Try using a unicode font character, I found 3 suitable ones by searching with keyword circle: here.. For each font there are several protocols to use a font character but there 2 we will concern ourselves with:

CSS
Use the CSS pattern as the content value in a pseudo-element as per Ori Drori's answer:

 button.css::before {  // ::before` is a pseudo-element

    content: '\1f787'; //  content` is the CSS unicode
        ....
   }

HTML
Using HTML entities is far easier to use, but it depends on placing unicode in markup which done on a large scale would be tedious and hard to maintain.

button.html b {
   ...
  }
  <button>🞇</button>

Demo

html,
body {
  font: 400 16px/1.5 Cosolas
}

#display {
  width: 95%;
  border-collapse: collapse;
  padding: 15px;
}

th,
td {
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.4);
}

button.btn {
  box-shadow: 0 2px 21px 0 rgba(255, 114, 1, 0.51) !important;
  border: 1px solid #FF7201;
  height: 70px;
  width: 200px;
  line-height: 2;
  border-radius: 12px;
  display: table;
  margin: 10px;
  font: 700 16px/2 Verdana;
  position: relative;
}

button.css::before {
  content: '\1f787';
  font-size: 2rem;
  display: inline-table;
  position: absolute;
  left: -8%;
  top: 8%;
  color: rgba(255, 144, 0, 1);
}

button.html b {
  font-size: 2rem;
  display: inline-table;
  position: absolute;
  left: -8%;
  top: 8%;
  color: rgba(255, 144, 0, 1);
}

      Raw

      ⭕

      ⦾

      HTML
      &#11093;
      &#128903;
      &#10686;

      CSS
      \2b55
      \1f787
      \29be

<button class='btn css' type='button'>CSS Button</button>

<button class='btn html' type='button'>
🞇 HTML Button</button>


text:
Q: How to create a struct model from a complex JSON response I am trying to consume data from an api in swift, json data has successfully been delivered back to the app but the json response from my backend is very complex hence forming struct for my model is very difficult. I'm able to only retrieve the simple strings but if I add the objects and arrays everything stops working
[
    {
        "type": "movie",
        "id": "ffff-ddd968-4cf0-a939-8skeu",
        "title": "Sorority Row",
        "description": "When five laldkdk",
        "categories": [],
        "genres": [
            "Mystery",
            "Horror"
        ],
        "links": {
            "amazonPrime": [
                {
                    "link": "somelink",
                    "format": "native_ios"
                },
                {
                    "link": "somelink",
                    "format": "native_ios"
                }
            ],
            "appleTvPlus": [],
            "disneyPlus": []
            "iTunes": [
                {
                    "link": "www.somelink",
                    "format": "webview_computer"
                }
            ],
            "netflix": [],
            "youTubePremium": []
        },
        "promoted": false,
        "certification": "18",
        "releaseDate": "2009-09-09",
        "runTime": 101,
        "userRating": null,
        "inUserList": false,
        "packShot": {
            "thumbnail": "imageurl"
        },
        "backdrop": {
            "thumbnail": "imageurl"
        }
    }
   ]

    struct Responder: Codable {
    let type: String
    let id: String
    let description: String
    let title: String
    let promoted: Bool
    let certification: String
    let firstAirDate: String
    let lastAirDate: String
    let numberEpisodes: Int
    let numberSeasons: Int
    let userRating: Int?
    let inUserList: Bool
    let thumbnail: PackShotObj
    let amazonPrime: linksObj
}

struct PackShotObj: Codable {
    let packShot: [String]
}

struct linksObj: Codable {
    let link: String
    let format: String
}

struct genres: Codable {
    let empty: String
}

A: Here is the code that works, decoding your json data. Note the differences between my struct models and yours. You will need to consult the docs of the server to determine which fields are optionals and adjust the code for that:
struct ContentView: View {
    @State var responders: [Responder] = []

    var body: some View {
        List(responders) { responder in
            Text(responder.title)
            Text(responder.description)
            Text(responder.releaseDate)
        }
        .onAppear {
            let json = """
[
    {
        "type": "movie",
        "id": "ffff-ddd968-4cf0-a939-8skeu",
        "title": "Sorority Row",
        "description": "When five laldkdk",
        "categories": [],
        "genres": [
            "Mystery",
            "Horror"
        ],
        "links": {
            "amazonPrime": [
                {
                    "link": "somelink",
                    "format": "native_ios"
                },
                {
                    "link": "somelink",
                    "format": "native_ios"
                }
            ],
            "appleTvPlus": [],
            "disneyPlus": [],
            "iTunes": [
                {
                    "link": "www.somelink",
                    "format": "webview_computer"
                }
            ],
            "netflix": [],
            "youTubePremium": []
        },
        "promoted": false,
        "certification": "18",
        "releaseDate": "2009-09-09",
        "runTime": 101,
        "userRating": null,
        "inUserList": false,
        "packShot": {
            "thumbnail": "imageurl"
        },
        "backdrop": {
            "thumbnail": "imageurl"
        }
    }
   ]
"""
            // simulated API data
            let data = json.data(using: .utf8)!
            do {
                self.responders = try JSONDecoder().decode([Responder].self, from: data)
                print("\n---> responders: \n \(responders)\n")
            } catch {
                print("\n---> decoding error: \n \(error)\n")
            }
        }
    }
}

// MARK: - Responder
struct Responder: Identifiable, Codable {
    let type, id, title, description: String
    let categories: [String]
    let genres: [String]
    let links: Links
    let promoted: Bool
    let certification, releaseDate: String
    let runTime: Int
    let userRating: Int?
    let inUserList: Bool
    let packShot, backdrop: Backdrop
}

// MARK: - Backdrop
struct Backdrop: Codable {
    let thumbnail: String
}

// MARK: - Links
struct Links: Codable {
    let amazonPrime: [Provider]
    let appleTvPlus: [Provider]
    let disneyPlus: [Provider]
    let iTunes: [Provider]
    let netflix: [Provider]
    let youTubePremium: [Provider]
}

struct Provider: Codable {
    let link, format: String
}

A: Just copy and paste this model to file and you are good to go.
struct Responder: Codable {
    let type, id, title, welcomeDescription: String
    let categories: [String]
    let genres: [String]
    let links: Links
    let promoted: Bool
    let certification, releaseDate: String
    let runTime: Int
    let userRating: Any?
    let inUserList: Bool
    let packShot, backdrop: Backdrop

    enum CodingKeys: String, CodingKey {
        case type, id, title
        case welcomeDescription = "description"
        case categories, genres, links, promoted, certification, releaseDate, runTime, userRating, inUserList, packShot, backdrop
    }
}

// MARK: - Backdrop
struct Backdrop: Codable {
    let thumbnail: String
}

// MARK: - Links
struct Links: Codable {
    let amazonPrime: [AmazonPrime]
    let appleTvPlus, disneyPlus: [String]
    let iTunes: [AmazonPrime]
    let netflix, youTubePremium: [String]
}

// MARK: - AmazonPrime
struct AmazonPrime: Codable {
    let link, format: String
}


text:
Q: Heroku / Python - script stops with error i have a python script which i want to run on the heroku plattform - everything seems fine and scheduled - but at the end i allways get an error when running on heroku (i see this in the papertrail logs)
When i run the script locally on my machine it works fine.
The error occurs when i want to read data using the yfinance module:
(obviously in the last line)
tday = datetime.today()
startDay = tday - timedelta(days=2200)
print(f"Read stock price data for {stock}...")
hist_price_stock = yf.download(stock,start=startDay,end=tday)

This is the error message which i get from heroku / papertrail:
(on the first look it didn´t help me much)
Sep 04 03:13:12 scoresupdatetickers app/worker.1 Read stock price data for AAPL...
Sep 04 03:13:12 scoresupdatetickers app/worker.1 Exception in thread Thread-1:
Sep 04 03:13:12 scoresupdatetickers app/worker.1 Traceback (most recent call last):
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/threading.py", line 954, in _bootstrap_inner
Sep 04 03:13:12 scoresupdatetickers app/worker.1     self.run()
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/threading.py", line 892, in run
Sep 04 03:13:12 scoresupdatetickers app/worker.1     self._target(*self._args, **self._kwargs)
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/site-packages/multitasking/__init__.py", line 102, in _run_via_pool
Sep 04 03:13:12 scoresupdatetickers app/worker.1     return callee(*args, **kwargs)
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/site-packages/yfinance/multi.py", line 167, in _download_one_threaded
Sep 04 03:13:12 scoresupdatetickers app/worker.1     data = _download_one(ticker, start, end, auto_adjust, back_adjust,
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/site-packages/yfinance/multi.py", line 179, in _download_one
Sep 04 03:13:12 scoresupdatetickers app/worker.1     return Ticker(ticker).history(period=period, interval=interval,
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/site-packages/yfinance/base.py", line 157, in history
Sep 04 03:13:12 scoresupdatetickers app/worker.1     data = data.json()
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/site-packages/requests/models.py", line 900, in json
Sep 04 03:13:12 scoresupdatetickers app/worker.1     return complexjson.loads(self.text, **kwargs)
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/json/__init__.py", line 346, in loads
Sep 04 03:13:12 scoresupdatetickers app/worker.1     return _default_decoder.decode(s)
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/json/decoder.py", line 337, in decode
Sep 04 03:13:12 scoresupdatetickers app/worker.1     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
Sep 04 03:13:12 scoresupdatetickers app/worker.1   File "/app/.heroku/python/lib/python3.9/json/decoder.py", line 355, in raw_decode
Sep 04 03:13:12 scoresupdatetickers app/worker.1     raise JSONDecodeError("Expecting value", s, err.value) from None
Sep 04 03:13:12 scoresupdatetickers app/worker.1 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Sep 04 07:09:47 scoresupdatetickers heroku/scheduler.7291 Cycling
Sep 04 07:09:47 scoresupdatetickers heroku/scheduler.7291 State changed from up to complete
Sep 04 07:09:48 scoresupdatetickers heroku/scheduler.7291 Stopping all processes with SIGTERM
Sep 04 07:09:48 scoresupdatetickers heroku/scheduler.7291 Process exited with status 143

Any idea why this is only running locally and not when hosted on heroku?

A: yfinance is a python package.
You have to update it's version to the latest one in your requirements.txt file and then push those changes to Heroku.
Heroku will then install the updated version and then your app will be using the latest version of yfinance.


text:
Q: Perspective based ranking? I have a program where each peer has their own ranking system of other peers, what is the best way to implement this is NetLogo?
Normally, I would solve this with a 2D list:
[[turtle 1, score], [turtle 2, score], ...]
But this seems very troubling in NetLogo. This is my code for creating and modifying a 2D list:
to test
  clear-all
  crt 10
  ;Create a list of turtles
  let agents-list [self] of turtles
  ;Create empty list, which will be the top level of the TwoD list
  let TwoD-list []

  ;Populate the TwoD-list: [[turtle 0, 0], [turtle 1, 0], ...]
  foreach agents-list [
    set TwoD-list (lput (list ? 0) TwoD-list)
  ]
  show TwoD-list

  repeat 5 [
    ;Change a value in the TwoD-list
    let rand-index random (length TwoD-list) ;select a random index
    ;The next line is what makes it a huge headache, basically you have to select a list at the top level to replace, and then select the list at the lower level to replace it.
    ;This entire line of code is just adding one to an element
    set TwoD-list (replace-item rand-index TwoD-list (replace-item 1 (item rand-index TwoD-list) (item 1 (item rand-index TwoD-list) + 1)))
    show TwoD-list
  ]
end

What else can I do? Or is there a better way to implement this method?

A: If you want to model relations between agents, NetLogo has the perfect thing for that: links!
Having each turtle assign a score to all other turtles can be quite naturally expressed as:
directed-link-breed [ rankings ranking ]
rankings-own [ score ]
to setup
  clear-all
  create-turtles 10
  ask turtles [ create-rankings-to other turtles ]
  ; increment 5 random rankings by one:
  ask n-of 5 rankings [ set score score + 1 ]
  ; display the rankings of each turtle:
  ask turtles [ show [ (word end2 " " score) ] of my-out-rankings ]
end

If you don't want the links to show up in the view, you can hide them with:
ask links [ set hidden? true ]


text:
Q: Silverlight. Cannot set base style from other xaml resources I need to create resource with name OkButtonStyle based on RedButtonStyle.
But i have resource with key not found exception. What i am doing wrong?
I have two resouce dictionaries. One baseStyles.xaml where RedButtonStyle located and styles.xaml where i need to locate my okbuttonstyle but all my efforts results nothing.
App.xaml
     <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="baseStyles.xaml" />
            <ResourceDictionary x:Name="currentTheme" Source="styles.xaml" />

        </ResourceDictionary.MergedDictionaries>

styles.xaml

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="baseStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="OkButtonStyle"
       BasedOn="RedButtonStyle"
       TargetType="Button">
</Style>

baseStyles.xaml
<Style x:Key="RedButtonStyle"
           TargetType="Button">
...properties...
    </Style>

A: Instead of using the syntax:
<Style BasedOn="RedButtonStyle" ...

use the syntax:
<Style BasedOn="{StaticResource RedButtonStyle}" ...

The Style.BasedOn property is not the name of the other style it is based on, it is the style it is based on.