text:
Q: how to make gameobject transparent using slider in unity I am trying to make gameobject transparent using slider, but transparency could not work after writing the script. my shader setting is legacy standard/diffuse. so what changes should I make to this script? and also what setting I should make along with the script code. please help me out to work with the script.
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;

 public class TransparentObject : MonoBehaviour
{
   private GameObject objectTotransparent;
   public float alpha = 0.3f;
   //private float increaseAlpha;
   //private float decreaseAlpha;
   public Slider transparentSlider;
   //renderer attached to the object that you want to make transparent
   //public Renderer rend;
   private Material currentMat;

   /*void Awake()
  {
    transparentSlider.onValueChanged.AddListener(OnSliderChanged);
  }*/

void Start()
{
    //objectTotransparent = gameObject;
    //currentMat = objectTotransparent.GetComponent<Renderer>().material;
    AsistantControllScript = FindObjectOfType<AsistantControll>();

   currentMat = currentGameObject.GetComponent<Renderer>().material;
}

void Update()
{
    //ChangeAlpha(currentMat, alpha);
    Touch touch = Input.GetTouch(0);
    if (touch.phase == TouchPhase.Began)
    {
        Ray ray = Camera.current.ScreenPointToRay(touch.position);
        RaycastHit hitObject;
        if (Physics.Raycast(ray, out hitObject))
        {
            objectTotransparent =
             hitObject.transform.parent.transform.parent.gameObject;
            objectTotransparent.GetComponent<Recolour>().SetSelected();
        }
    }
}

void ChangeAlpha(Material mat, float alphaVal)
{
    Color oldColor = mat.color;
    Color newColor = new Color(oldColor.r, oldColor.g, oldColor.b, alphaVal);
    mat.SetColor("_Color", newColor);
}

public void ChangeAlphaOnValue(Slider slider)
{
    ChangeAlpha(currentMat, slider.value);
}

public void Deselect()
{
    objectTotransparent.GetComponent<Recolour>().SetOriginalMaterial();
    objectTotransparent = null;
    transparentSlider.value = alpha;
}
}

A: Change your material Rendering Mode into Transparent:


text:
Q: three.js - check if object is still in view of the camera When working with a 2d canvas, if you want to check if something is no longer "on screen" you simply do something like this:
if( pos.x > window.innerWidth || pos.x < 0 ||
    pos.y > window.innerHeight || pos.y < 0 ) {
    // has left the screen
}

How would I check to see if something is still "on screen" ( in view of the camera ) in a three.js scene?

A: const frustum = new THREE.Frustum()
const matrix = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
frustum.setFromProjectionMatrix(matrix)
if (!frustum.containsPoint(obj.position)) {
    console.log('Out of view')
}

Use this in a tick function so it will update you when the obj goes out of camera view.
Note: setFromMatrix() is changed to setFromProjectionMatrix() in newer versions of three.js

A: Instead of check 2d canvas, you can check a 3d point is in frustum or not.
camera.updateMatrix();
camera.updateMatrixWorld();
var frustum = new THREE.Frustum();
frustum.setFromMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));

// Your 3d point to check
var pos = new THREE.Vector3(x, y, z);
if (frustum.containsPoint(pos)) {
    // Do something with the position...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Perl and LVN_COLUMNCLICK; works fine under WinXP x86, but not under Win7 x64. Why? I have this perl subroutine that works fine under WinXP x86, sorting a column for a 32 bit application among other things, but under Win7 x64  this subroutine doesn't work at all. The others work fine(tabs switching, pressing buttons, etc). Any idea why?
sub function
{
my @searchresultswindow_handle = FindWindowLike( @_[ 0 ], undef, undef, $searchresultswindow_id );
 if( !@searchresultswindow_handle  )
  {
   die "Cannot find window handle for searchresultswindow control\n";
  }
 else
  {
   printf( "searchresultswindow handle is %x\n", $searchresultswindow_handle[ 0 ] );

            $keysList=@searchresultswindow_handle[0] ;

        my $action = pack( "l l",
        0, #ptaction.x
        0 #ptaction.y
        );

        my $action_ptr = unpack( 'L!', pack( 'P',$action));

        my $str_buf = pack( "L L L l l L L L L l",
        $keysList, #nmh.hdr.hwndFrom hwnd
        0, #nmh.hdr.idFrom

        4294967188, #LVN_COLUMNCLICK ,#nmh.hdr.code Code
        -1, #item
  13, #sub item
        0, #uNewState
        0, #uOldState
        0, #uChanged
        $action_ptr, #action
        0 #lparam
        );

          $lvitem = AllocateVirtualBuffer( $keysList, 5000 );
        WriteToVirtualBuffer( $lvitem, $str_buf );

  my $value =PostMessage( $keysList, 0x004E, 0, $lvitem->{ 'ptr' });
FreeVirtualBuffer( $lvitem );
}
}

A: The structures are packed differently on 32 and 64 bit systems.
on 32-bit:
0:000> dt tagNMHDR
notepad!tagNMHDR
   +0x000 hwndFrom         : Ptr32 HWND__
   +0x004 idFrom           : Uint4B
   +0x008 code             : Uint4B

on 64-bit:
0:000> dt tagNMHDR
kernel32!tagNMHDR
   +0x000 hwndFrom         : Ptr64 HWND__
   +0x008 idFrom           : Uint8B
   +0x010 code             : Uint4B


text:
Q: How to make reactive variables between components? Lately I've been practicing with component inputs and outputs and this has led me to this example:
In component A, I have
@Output () outputVariableA = [hi, hi2, hi3]

In component B, I have
@Input () inputVariableB [];

In component B, I define a function that modifies inputVariableB.
How do I make it reactive, between the two variables the modification of inputVariableB is reflected in outputVariableA.
app.html:

      <app-upload-refresh
                [InputVariableB] = "OutputVariableA">
      </app-upload-refresh>

app.component:
  @Output() OutputVariableA[]=[];

  constructor(

  ) { }
      if(localStorage.getItem('')){
        for( let localStorageUpdate of JSON.parse(localStorage.getItem('reefersToUpdate') )) {
            this.reefersToUpdate.push(localStorageUpdate);
        }
      }

componentb.component
@Input() InputVariableB:Observable<any>[];
onHacerSubida(){
  InputVariableB = []
}

A: if the component A and Component B are parent and child you can do the two way communication using the @input binding and @Output emitters (refer this code )
in component-A
  @Input()
   valuetoAfromB:string;
   @Output()
   valueChangeEventAtoB:EventEmitter;

and if the Component A and Component B are sibling components, the communication can be done using shared service (refer this code)

A: In order to pass the output back, you must actually emit it, so you have your EventEmitter, and your input in the child component.
@Input() data: Object;
@Output() updatedData: EventEmitter<Object> = new EventEmitter<Object>();

Then, you have a function that emits your updated variable from the child component after changes have been made.
passData() {this.updatedData.emit(this.updatedDataObject);}

In the parent component, you call one of it's functions on the data sent out where the child comonent is declared.
<child-component [data]="object" (updatedData)=updateObject($event)></child-component>

You can also use @ViewChild to access child methods from the parent component, but for my purposes, I had to use the former.


text:
Q: How can I achieve Pulumi EKS RoleMappings with C# There are Kubernetes RBAC in Amazon EKS with Pulumi instructions for TypeScript.
const vpc = new awsx.ec2.Vpc("vpc", {});
const cluster = new eks.Cluster("eks-cluster", {
  vpcId             : vpc.id,
  subnetIds         : vpc.publicSubnetIds,
  instanceType      : "t2.medium",
  nodeRootVolumeSize: 200,
  desiredCapacity   : 1,
  maxSize           : 2,
  minSize           : 1,
  deployDashboard   : false,
  vpcCniOptions     : {
    warmIpTarget    : 4,
  },
  roleMappings      : [
    // Provides full administrator cluster access to the k8s cluster
    {
      groups    : ["system:masters"],
      roleArn   : clusterAdminRole.arn,
      username  : "pulumi:admin-usr",
    },
    // Map IAM role arn "AutomationRoleArn" to the k8s user with name "automation-usr", e.g. gitlab CI
    {
      groups    : ["pulumi:automation-grp"],
      roleArn   : AutomationRole.arn,
      username  : "pulumi:automation-usr",
    },
    // Map IAM role arn "EnvProdRoleArn" to the k8s user with name "prod-usr"
    {
      groups    : ["pulumi:prod-grp"],
      roleArn   : EnvProdRole.arn,
      username  : "pulumi:prod-usr",
    },
  ],
});

Kubernetes RBAC in AWS EKS with open source Pulumi packages | Pulumi https://www.pulumi.com/blog/simplify-kubernetes-rbac-in-amazon-eks-with-open-source-pulumi-packages/

I'm looking for how to achieve this with .NET C#?
It looks like eks roleMappings extensions is only available for TypeScript, so that C# may be require to construct configmap manifest with Pulumi.Kubernetes?

https://github.com/pulumi/pulumi-aws/blob/c672e225a765b11b07ea23e7b1b411483d7f38da/sdk/dotnet/Eks/Cluster.cs
https://github.com/pulumi/pulumi-eks

A: The pulumi-eks package is currently only available in TypeScript. There is a plan to bring it to all languages later this year, but for now you basically have two options:

*

*Use TypeScript. If needed, break down your complete deployment into multiple stacks. The stack that defines the EKS package would be in TypeScript, while other stacks can be in C#.

*Refer to the pulumi-eks implementation that you linked above and transfer that code manually to C#. This is a non-trivial work, so be careful with feasibility estimation.


text:
Q: samba question: share = user
*

*I am running Ubuntu 13.04 and Windows XP.

*I am a samba newbie but was able to set this up on Ubuntu following the instructions posted here https://help.ubuntu.com/13.04/serverguide/samba-fileserver.html

*My question is that although I can copy a word document to the share from linux, when I edit it in Word on Windows I cannot save and overwrite the file. It says the file is read only.

*I have to save a copy and then do a move of the file on the Linux system.

*I tried changing the perms of the file to 777 on the linux side but this didn't fix it so I am thinking it is a perms at the user level.

*Does anyone know off the top of their head? I currently have security = user in my smb.conf file.

*When copying a file from linux to the share it has my user name on it. When creating a file from windows to the share it has  nobody nogroup on the file.

*The good news is both linux and windows see the same files and I can open all the files put on the share in windows I just can't overwrite them with edits ( word 2007 files specifically ).

*Any help on the setting to fix this is appreciated.
samba details
[share]
   comment = Ubuntu File Share
   path = /srv/samba/share
   browseable = yes
   guest ok = yes
   read only = no
   create mask = 0775

permissions of all the directories for /srv/samba/share

bjackfly@BigJackFly:~$ ls -ltr | grep srv
drwxr-xr-x   3 root root  4096 Sep 25 14:05 srv

bjackfly@BigJackFly:~$ ls -ltr /srv/ | grep samba
drwxr-xr-x 3 root root 4096 Sep 25 14:05 samba

bjackfly@BigJackFly:~$ ls -ltr /srv/samba/ | grep share
drwxrwxrwx 2 nobody nogroup 4096 Sep 25 17:25 share

A: I had to make sure that files in the share had nobody.nogroup
sudo chown nobody.nogroup  file.docx


text:
Q: jQuery basic appending I used jQuerys' $("...").append() and found out, that it is more advanced than I thought it is. For instance, the following sample

outputs

. As you can see, jQuery added the closing tag itself. In my case, I want to append just the opening tag, because I want to fill this element peu à peu.
For example
jQuery(function($) {
    $("body").append("
");
    if(...){
        $("body").append("true");
    }else{
        $("body").append("false");
    }
});

outputs

    true

instead of

true

A: How about appending to the div after it has been appended to the body?
jQuery(function($) {
    $("body").append("
");
    if(...){
        $("body div").append("true");
    }else{
        $("body div").append("false");
    }
});

A: You cannot append just an opening tag because that doesn't translate to an actual DOM element.  That's only a piece of a DOM element which isn't something that can be turned into a DOM element.
If what you're trying to create is this:

true

That isn't valid HTML.  It would have to be this to be valid:

true

You could solve your problem like this:
jQuery(function($) {
    var myDiv = $("
");    // create DOM element
    if(...){
        myDiv.html("true");    // set contents of DOM element
    }else{
        myDiv.html("false");
    }
    $(document.body).append(myDiv);   // append DOM element to the page
});

Working example: http://jsfiddle.net/jfriend00/eSncS/


text:
Q: While Loading my site on the client's web page there occurs css property clash issues When i load my Website in the client's url, there occurs a error which takes the css property from the client's css and changed in our css which affects my site.
Is there is any way to write all the property and value in my class so that it will not take from the client's css?

A: Do you have the style-loader in your css loader? Look into the rendered DOM and compare the position from the client-css and your react-css. I suspect the react css is inserted as a style tag before the client-css link tag.
Use the extract-text-plugin to generate a separat css file, which you can insert into your DOM after the client's css by hand.

A: In cases where both stylesheets style the same properties but the wrong stylesheet is winning out (e.g. you have p {border: 1px solid green; color: blue} and the client css has p {border: 1px solid red} and the tables are getting a red border):

*

*If possible, tweak your css to avoid the conflict. This may also require tweaking your markup. For example, if your css and the client's css provides styles for a class called .myclass, you could rename yours to .mynewclass.

*You may also be able to get around this by increasing the specificity of your styles. For example, if .myclass is styled in the client css, your css could style body .myclass. For more on specificity, see https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

*There's always !important (e.g. .myclass {border-color: green !important}) which may make your styles win over the client's. Keep in mind that using a lot of !important is generally considered a sign of bad CSS.

In cases where the client stylesheet is styling a property you want left at the default (e.g. you want borderless divs, but the client css specifies p {border: 1px solid red}) you'll have to add an override: p {border: 0;}.
If you can wrap all your markup in an overriding class, you can do something like

/* client's styles */
p {
  border: 1px solid blue
}
/* your styles */
.reset p {
  border: 0;
}

client (border)

you (no border)

Or maybe everything you add to the site is always inside the same element, like .main. In that case, in the above example you could style .main p.
If using a wrapper won't work, you can always add a reset class to every one of your elements. That will be a hassle, but it'll work:

/* client's styles */
p {
  border: 1px solid blue
}
/* your styles */
p.reset {
  border: 0;
}

client (border)

you (no border)

If you do a bunch of work with this client, it could be worth developing a "reset.css" with all your reset rules.


text:
Q: Delete first 5 rows of each worksheet in a workbook if they contain no values I am trying to delete all the first 5 rows of each worksheet if they do not contain any values across all columns. This program will run but only on the active worksheet. Is there something I missed?
Sub DeleteFirst5Rows()
Dim ws As Worksheet
 For Each ws In ActiveWorkbook.Worksheets
    On Error Resume Next
    Rows("1:5").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
 Next ws
End Sub

A: This is the updated code, worked perfectly. Thank you all.
Sub DeleteFirst5Rows()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
    If Application.CountA(ws.Range("1:5")) = 0 Then ws.Range("1:5").EntireRow.Delete

    Next ws
End Sub


text:
Q: Gnome-Software running in background and consuming RAM Why does this newfangled Gnome-Software have to consume 300mb of my precious RAM in the background? I remember when an previous computer of mine only had 300mb of RAM total, and now this one program is using that much on its own in the background, what can I do ?
Best regards Charles.

A: One option is to prevent the software from autostarting at login.

*

*Remove the link in ~/snap/snap-store/current/.config/autostart/
Another option is to Quit the application. (Not close the window, that doesn't Quit the application)


text:
Q: Is there an R function for displaying only a subset of legend keys? Building off of my previous question, with thanks to @AndrewGB for the code modifications (Specifying fill color independent of mapping aesthetics in boxplot (R ggplot)), I have a dataset with 24 bars (individual categories with a status high/low).
Within my categories, I have a category type, which means I need to show only a subset of the legend keys (i.e., unique colours only). In the toy data I've provided, it would be akin to "Plant Type A" (pink) and "Plant Type B" (blue) with a "Control" (grey).
My intended output is to plot only the unique legend colours and then give these keys customizable labels.
library(ggplot2)
library(data.table)

dat <- as.data.table(cbind(iris, Status = rep(c("High", "Low"), 75)))
dat <- rbind(dat, data.frame(Petal.Width = sample(iris$Petal.Width, 30, replace = T),
      Species = "Control",
      Status = "Control"), fill = T)

ggplot(dat, aes(x = Species,y = Petal.Width, fill = Status)) +
  geom_boxplot(position = position_dodge(width = 0.9)) +
  scale_fill_manual(values = c("red", "pink",
                               "red", "pink",
                               "blue", "slateblue", "grey"))

ggplot(dat, aes(x = Species, y = Petal.Width, fill = interaction(Status,Species))) +
  geom_boxplot(position = position_dodge(width = 0.9)) +
  scale_fill_manual(values = c("red", "pink",
                               "red", "pink",
                               "blue", "slateblue", "grey"))

The legends would then be:

Plant Type A: High Status (red)
Plant Type A: Low Status (pink)
Plant Type B: High Status (blue)
Plant Type B: Low Status (slateblue)
Control - no status (grey)

I've looked into the override.aes,guides and scale_fill_manual - breaks, but cannot seem to get this working without messing with the colours plotted.

A: You can use the breaks argument of scale_fill_manual to limit the number of legend entries without limiting the actual plotted colors.
However, you need to name the colors in the values argument explicitly:
library(tidyverse)
library(data.table)
#>
#> Attaching package: 'data.table'
#> The following objects are masked from 'package:dplyr':
#>
#>     between, first, last
#> The following object is masked from 'package:purrr':
#>
#>     transpose

dat <- as.data.table(cbind(iris, Status = rep(c("High", "Low"), 75)))
dat <- rbind(dat, data.frame(
  Petal.Width = sample(iris$Petal.Width, 30, replace = T),
  Species = "Control",
  Status = "Control"
), fill = T)

dat %>%
  mutate(fill = Species %>% paste0(Status)) %>%
  ggplot(aes(x = Species, y = Petal.Width, fill = fill)) +
  geom_boxplot() +
  scale_fill_manual(
    values = c(
      setosaHigh = "red", setosaLow = "pink",
      versicolorHigh = "lightgreen", versicolorLow = "darkgreen",
      virginicaHigh = "darkblue", virginicaLow = "lightblue",
      ControlControl = "purple"
    ),
    breaks = c("virginicaLow", "virginicaHigh", "ControlControl")
  )

Created on 2022-05-10 by the reprex package (v2.0.0)


text:
Q: How does `flux`/`mono`, RabbitMQ, AkkaStream work in big picture in microservies world? i try to grasp what are flux and mono for in big picture.
I get that when microservices talk to each other we can you use quee (like RabbitMQ) to make them talk asynchronously instead of synchronously.
But if i use only flux/mono using HTTP2 (to my knowledge) then my microservies already talk to each other asynchronously or not?
If not then what part of the big picture is asynchronous?
There is also Akka streams - is it something like RabbitMQ? A quee that make microservies talk asynchronously?
I would appreciate clarification - thanks.


text:
Q: Remove all commas in  tags The last person in my position was comma happy in the title tags. I need to remove all commas in the title tags of 40,000 html product pages. Is there a regex expression to find all commas in a title tag? I am hoping I can find the all the commas with a regex expression and replace them in dreamweaver. Is this possible?
The format usually follows
(opening title tag)Product, Product, 81120,
(opening title tag)Product Product, Product, 98564,
(opening title tag)Product Product, Product Product, 98564,
(opening title tag)Product, Product Product, 98564,
the number at the end is a 5 digit product #
Any help would be greatly appreciated

A: You can look for a comma after which </title> is what follows after the first < after the comma and replace them with an empty string:
,(?=[^<]*</title>)

Note that this assumes you will be doing this in an editor. Never trust regexes when it comes to unknown HTML. If you'll be using this in code, it's better to use a DOM parser to scope your replace correctly. It also assumes that either the string </title> will not appear out of context (such as in javascript code) or you can review the replacement process manually wherever this regex might get confused. (whose idea was to have 40k HTML files, again? Hopefully they don't create new title tags!).

A: Good blog describing how to do it in PHP: http://www.thatsquality.com/articles/how-to-match-and-replace-content-between-two-html-tags-using-regular-expressions
I would think to do this in dreamweaver you would want something using a back reference like:
(<Title>\S\s),+(\S\s<\/Title>)
With this in the Replace:
$1 $2
As pointed out - would need to loop this to success - was thinking this was something the IDE would support, but that is probably not the case.
Good post here: http://somerandomdude.com/2006/05/25/dreamweaver-regular-expressions/

A: You can use this
regexp: ([\,]+)


text:
Q: Not able to compile my Xamarin.Android application after upgrading to Xamarin.forms version 5.0.0.2012 Error APT2259: 'textEnd' is incompatible with attribute iconGravity (attr) flags [start=1, textStart=2] [weak]. (APT2259)
Error APT2061: failed linking file resources. (APT2061)


text:
Q: Spring boot HTTP get request return a String and a file I have a Sprint boot application using an angular 4 front page. From my front page I send a HTTP get request with an SQL query and some other parameters.
Now I want the reponse to be a String+zip file .
I know that I can send back a file like that :
return ResponseEntity.ok()
    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
    .body(file);

but I have no idea how to combine a file and a String in the ReponseEntity.
Here is my code so far (server side) :
Controller :
@GetMapping("/sql")
public ResponseEntity<String> handleSqlRequest(
    @RequestParam("sql") String sql,
    @RequestParam("source") String source,
    @RequestParam("genFile") Boolean genFile
) {
    SqlToolResponse sqlToolResponse;
    if(genFile) {
        //Create a ZIP file and execute sql
        sqlToolResponse = this.sqlToolService.executeSqlWithFiles(sql, source, "oracle.jdbc.OracleDriver");
    } else {
        //Only execute SQL
        sqlToolResponse = this.sqlToolService.executeSql(sql, source, "oracle.jdbc.OracleDriver");
    }
    Resource file = new UrlResource(("MYPATH/"+sqlToolReponse.getZipName()).toUri());
    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + sqlToolResponse.getZipName()) + "\"")
        .body(file);
    }

SqlToolResponse :
public class SqlToolResponse {

    private String result;
    private String zipName;

    public SqlToolResponse(String someResult, String zip) {
        this.result = someResult;
        this.zipName = zip;
    }

    public SqlToolResponse(String someResult) {
        this.result = someResult;
        this.zipName = null;
    }

    public String getResult() {
        return result;
    }

    public String getZipName() {
        return zipName;
    }

}

any ideas?

A: You have multiple ways to do that:

*

*return an object having 2 fields (String and File)

*return a Map<String, Object>

*set the string value in a header

A: Change your method as
MultiValueMap<String, Object> handleSqlRequest(@RequestParam("sql") String sql,
            @RequestParam("source") String source, @RequestParam("genFile") Boolean genFile) {

    // ......
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
    HttpHeaders headers1 = new HttpHeaders();
    headers1.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""
                           + sqlToolResponse.getZipName()) + "\"");
    HttpEntity<Resource> part1 = new HttpEntity<>(file, headers1);

    HttpHeaders headers2 = new HttpHeaders();
    headers2.setContentType(MediaType.TEXT_PLAIN);
    HttpEntity<String> part2 = new HttpEntity<>(sqlToolReponse.getResult(), headers2);
    body.add("file", part1);
    body.add("string", part2);
    return body;
}


text:
Q: Cannot read properties of undefined (reading 'push') react I want to navigate to a new page when clicking on a button. I used history but it not working. Using React-router-dom v6.
App.js
import React from 'react';
import './App.css';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
import ListEmployeeComponent from './components/ListEmployeeComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
import CreateEmployeeComponent from './components/CreateEmployeeComponent';

function App() {
  return (

        <Router>
              <HeaderComponent />

                    <Routes>
                          <Route path = "/" index element = {<ListEmployeeComponent/>}></Route>
                          <Route path = "/employees" element = {<ListEmployeeComponent/>}></Route>
                          <Route path = "/add-employee" element = {<CreateEmployeeComponent/>}></Route>
                    </Routes>

              <FooterComponent />
        </Router>

  );
}

export default App;

ListEmployeeComponent.js
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';

// import { createHashHistory } from 'history'
// export const history = createHashHistory()
class ListEmployeeComponent extends Component {

    constructor(props){
        super(props)
        this.state={
            employees: []
        }
        this.addEmployee = this.addEmployee.bind(this);
    }

    componentDidMount(){
        EmployeeService.getEmployees().then((res) => {
            this.setState({ employees: res.data});
        });
    }
    addEmployee(){
         this.props.history.push('/add-employee');
    }

  render() {
    return (

Employees List

                    <button className="btn btn-primary" onClick={this.addEmployee}> Add Employee</button>

                        Employee First Name
                        Employee Last Name
                        Employee Email Id
                        Actions

                    {
                        this.state.employees.map(
                            employee =>

                                {employee.firstName}
                                {employee.lastName}
                                {employee.emailId}

                        )
                    }

    )
  }
}
export default ListEmployeeComponent

CreateEmployeeComponent.js
import React, { Component } from 'react'
// import EmployeeService from '../services/EmployeeService';
// import { createHashHistory } from 'history'
// export const history = createHashHistory()

class CreateEmployeeComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            // id: this.props.match.params.id,
            firstName: '',
            lastName: '',
            emailId: ''
        }
        this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
        this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
        this.saveOrUpdateEmployee = this.saveOrUpdateEmployee.bind(this);

    }

    saveOrUpdateEmployee = (e) => {
        e.preventDefault();
        let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
        console.log('employee => ' + JSON.stringify(employee));
    }

    changeFirstNameHandler= (event) => {
        this.setState({firstName: event.target.value});
    }

    changeLastNameHandler= (event) => {
        this.setState({lastName: event.target.value});
    }

    changeEmailHandler= (event) => {
        this.setState({emailId: event.target.value});
    }

    cancel(){
        this.props.history.push('/employees');
    }
    render() {
        return (

Add Employee

                            <form>

                                 First Name:
                                            <input placeholder="First Name" name="firstName" className="form-control"
                                                value={this.state.firstName} onChange={this.changeFirstNameHandler}/>

                                             Last Name:
                                            <input placeholder="Last Name" name="lastName" className="form-control"
                                                value={this.state.lastName} onChange={this.changeLastNameHandler}/>

                                             Email Id:
                                            <input placeholder="Email Address" name="emailId" className="form-control"
                                                value={this.state.emailId} onChange={this.changeEmailHandler}/>

                                        <button className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
                                        <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
                            </form>

        )
    }
}

export default CreateEmployeeComponent

How to resolve this Type Error: Cannot read properties of undefined (reading 'push') in React Js. Please rectify. WithRouter is all not working. Hash history also not working. I am using react-router-dom v6.
Please rectify how to clear this in class component.Navigate router is not working

A: In react-router v6, you have to use "navigate" function.
Check this :https://reactrouter.com/docs/en/v6/getting-started/overview#navigation


text:
Q: Changing read only properties with reflection Is it possible? With reflection or any other way?

A: As other stated, if you need to do that, you're facing a design issue to begin with. Now, if you want to know if it's possible just for the sake of knowing, or if there's no other way on earth to do it, it's indeed possible, with the help of a very small helper library and an extension method.
Consider the following code:
class Person {

    int age;
    string name;

    public int Age { get { return age; } }
    public string Name { get { return name; } }
}

// ...

using Mono.Reflection;
using System.Reflection;

// ...

Person person = new Person (27, "jb");
PropertyInfo nameProperty = typeof (Person).GetProperty ("Name");
FieldInfo nameField = nameProperty.GetBackingField ();
nameField.SetValue (person, "jbe");

Using this code, you can get the backing field of a property with just the property, and assign a new value to the backing field. You can read more details about the implementation.
Also note that it works only for simple properties, such as:
public int Age { get { return age; } }

public string Name {
    get { return name; }
    set { name = value; }
}

public double Velocity { get; private set; }

If you have complex properties with custom code (which includes expression-bodied member like int Answer=> 42;), the backing field resolver will fail as there is no backing field in such case.

A: An alternate to Simon Mattes answer would be
Assuming you have:
public class MyClass
{
     public int MyNumber {get;}
}

You could do this if its for test purpose:
var field = typeof(MyClass).GetField("<MyNumber>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(anIstanceOfMyClass, 3);

A: As a very dirty workaround for auto generated read only properties:
class MyTestClass
{
    public string MyProperty { get; }

    public MyTestClass( string MyProperty )
    {
        this.MyProperty = MyProperty;
    }
}

You can modify the auto generated backing field in the following way:
MyTestClass MyClass = new MyTestClass( "Hello" );
FieldInfo MyWriteableField = MyClass.GetType().GetRuntimeFields().Where( a => Regex.IsMatch( a.Name, $"\\A<{nameof( MyClass.MyProperty )}>k__BackingField\\Z" ) ).FirstOrDefault();
MyWriteableField.SetValue( MyClass, "Another new value" );

PS: when you are using a .NET version < 4.6 you might have to change some of the code to work.
Enjoy!

A: it depends on the property. if it's a computed property - no, not unless you know what it's based on. if it's just an accessor to a private field, then you can try to modify the field.
in general, however, it's a very bad idea, as you likely have no knowledge of what side-effects this will cause.

A: PropertyInfo isReadOnly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance| BindingFlags.NonPublic);
//Remove the readonly property
isReadOnly.SetValue(param, false, null);

//.............put your code here.....

// Set readonly property
isReadOnly.SetValue(param, true, null);


text:
Q: How to create a custom search form and handler? I'm trying to build a search that, depending on what user chosen in admin, will either query one of several external api search methods with user input, save all the results in database and then display them or it will search the custom tables in database, it should also be fully encapsulated in a plugin. I already have the business logic that does this, I'm having trouble hooking it up to WP. What would be the best way to accomplish this?
edit: sorry, it was probably quite vague question, what I have is an app I described above built on php framework, what I want to do is move it to WP, the problem is while the logic itself will require little modification, I have no idea how to hook it up to wordpress via plugin, essentially how do I create a form with plugin and how do I take input from that form and direct it to the logic that will handle that request?

A: To change the search form, filter get_search_form. You get the form as a string here, and you can change it as you need.
add_filter( 'get_search_form', function( $form )
{
    // Replace the form, add additional fields
    return $form;
});

To change the search query to the database, filter posts_search. You get the query as a string and the current WP_Query object which provides more information. See wp-includes/query.php for context.
add_filter( 'posts_search', function( $search_query, $wp_query )
{
    // change the SQL
    return $search_query;
}, 10, 2 );

If you don't want to filter the search query, change the name attribute in the search form, example foo, and inspect the $_POST request:
if ( ! empty ( $_POST['foo'] ) )
{
    $global $wpdb;
    $results = $wpdb->get_results( /* custom sql */ );
}


text:
Q: First row of table disappears once the column headers are fixed (sticky header) I need your help,
I can't seem to figure out as to why the first row in the table (ABC-123-123456) disappears or appears to be hidden once the top columns are fixed. As my work uses IE7 still I need to be able to have a browser compliant sticky column headers.
<!DOCTYPE html>

            File Number
            Test Column
            Request Type
            Resize This
            Firstname
            Lastname
            Progress
            Vital Task

            ABC-123-123456

            100%
            Yes

            ABC-123-942471

            100%
            Yes

            ABC-123-408126

            20%
            No

            ABC-123-396225

            80%
            No

            ABC-123-385417

            ABC-123-374250

            ABC-123-408970

            ABC-123-404552

            ABC-123-403102

            100%
            Yes

            ABC-123-404555

            23%
            yes

            ABC-123-406789

            80%
            No

            Hyperlink Example

            80%
            Another

A: Remove position:absolute from #data thead tr.
jsfiddle

A: add this
#data tbody{
position: absolute;
top: 24px;
}


text:
Q: glDrawArrays on Android Smartphone has strange behaviour I am currently encountering a very strange behaviour in my android OpenGL ES 2.0 app.
This happens when I want to draw a mesh I have read from an .obj file.
It is hard to descripe therefore here is a screenshots

And here is the sourceCode I am using for loading and rendering the meshes. There should be objects in the scene: one ball and a platform a bit under the ball (later the ball should fall  and hit the box)
Loading:
public Mesh(FloatBuffer vertexData, int faceCount, int shaderProgram){
        this.faceCount = faceCount;
        System.out.println("MESH: faceCount " + faceCount);
        ByteBuffer bb = ByteBuffer.allocateDirect(8);
        bb.order(ByteOrder.nativeOrder());
        IntBuffer buffer = bb.asIntBuffer();
        GLES20.glGenBuffers(1, buffer);
        triangleBuffer = buffer.get(0);
        triangleBufferSize = vertexData.capacity();

        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, triangleBuffer);
        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, vertexData.capacity() * mBytesPerFloat, vertexData, GLES20.GL_STATIC_DRAW);

        //GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
    }

And this is how I render the mesh:
public void render(int shaderProgram){
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, triangleBuffer);
    GLES20.glVertexAttribPointer(GLES20.glGetAttribLocation(RessourceManager.getInstance().getActiveShader(), "vertex"), 3, GLES20.GL_FLOAT, false, 8*mBytesPerFloat, 0);
    GLES20.glEnableVertexAttribArray(GLES20.glGetAttribLocation(RessourceManager.getInstance().getActiveShader(), "vertex"));

    GLES20.glVertexAttribPointer(GLES20.glGetAttribLocation(RessourceManager.getInstance().getActiveShader(), "normal"), 3, GLES20.GL_FLOAT, false, 8*mBytesPerFloat, 3*mBytesPerFloat);
    GLES20.glEnableVertexAttribArray(GLES20.glGetAttribLocation(RessourceManager.getInstance().getActiveShader(), "normal"));

    GLES20.glVertexAttribPointer(GLES20.glGetAttribLocation(RessourceManager.getInstance().getActiveShader(), "texCoord"), 2, GLES20.GL_FLOAT, false, 8*mBytesPerFloat, 6*mBytesPerFloat);
    GLES20.glEnableVertexAttribArray(GLES20.glGetAttribLocation(RessourceManager.getInstance().getActiveShader(), "texCoord"));

    //GLES20.glDrawElements(GLES20.GL_TRIANGLES, faceCount, GLES20.GL_UNSIGNED_SHORT, 0);

    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, faceCount*3);

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
}

Some more information: I am using an interleaved array with "VX VY VZ NX NY NZ U V" 8 values per Vertex. faceCount contains the number of faces.
Can anyone please help me and tell me what I am doing wrong? (On my Galaxy Nexus it is working but on my HTC One X+ not, as well as on my Note 10.1)


text:
Q: PHP / Wordpress : category widget output Is there a way to modify wordpress category / archives widget html output without modifying wordpress core files? For example I have this output code:

Title

123 (1)

And what I'm trying to achieve:

Title

123 [1]

A: You have the filters widget_categories_dropdown_args and widget_categories_args to change the output for the Categories widget.
Example: https://wordpress.stackexchange.com/a/25002/12615
And for the Archives widget, widget_archives_dropdown_args and widget_archives_args.
Example: https://wordpress.stackexchange.com/q/19945/12615

A: /*
 * Add spans around category counters
*/
function _thz_filter_wp_list_categories($output, $args) {

    if($args['show_count']){
        $re = '/<\/a>(.*?)<\/li>/s';
        preg_match_all($re, $output, $matches);

        if(!empty($matches) && isset($matches[1])){
            foreach($matches[1] as $between){
                $between    = strip_tags($between);
                $output     = str_replace($between,''.$between.'',$output);
            }
        }
    }

    return $output;
}

add_filter( 'wp_list_categories', '_thz_filter_wp_list_categories',10,2 );

/*
 * Add spans around archive counters
*/
function _thz_filter_get_archives_link( $output ) {

    $re = '/<\/a>(.*?)<\/li>/s';
    preg_match_all($re, $output, $matches);

    if(!empty($matches) && isset($matches[1])){
        foreach($matches[1] as $between){
            $between = strip_tags($between);
            $output  = str_replace($between,''.$between.'',$output);
        }
    }

    return $output;
};

add_filter( 'get_archives_link', '_thz_filter_get_archives_link', 10, 6 );


text:
Q: How to make a wolf angry at a nearby player I am in 1.14 and I want to summon in wolves that are angry.  summon wolf ~ ~ ~ {Angry:1} Doesn't work, since the wolf must have a specific player to be angry at, which is stored in UUID's I believe.  This behavior is unlike Zombie Pigmen, which when set angry become agro at all players.  I thought about detecting if a player gets near a wolf, say within 10 blocks, that wolf automatically becomes hostile to that specific player.  Is there a way to do this?

A: Who a wolf is angry at is not saved in its NBT. I've created this bug report for it now: https://bugs.mojang.com/browse/MC-155036
But you can still do what you want to do, because wolves really don't like snowball fights.
Let's say the player who should be attacked has the tag "attackMe", just to have something to differentiate them. Then you can summon a snowball above the wolf and make that snowball pretend to have been thrown by that player:
execute at @e[type=wolf] run summon snowball ~ ~2 ~
execute at @e[type=wolf] run data modify entity @e[type=snowball,sort=nearest,limit=1] owner.L set from entity @p[tag=attackMe] UUIDLeast
execute at @e[type=wolf] run data modify entity @e[type=snowball,sort=nearest,limit=1] owner.M set from entity @p[tag=attackMe] UUIDMost

Of course you'll probably narrow the selector @e[type=wolf] further, currently this system makes every wolf in the loaded area angry at you.


text:
Q: Объект "влезает" в стену Есть куб, к которому привязано управление с клавиатуры, есть стена. При приближение куба к стене он в неё "влезает", а потом встаёт рядом. Как это можно починить?
using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
    public GameObject player;

    void Awake () {
        Color col = Color.green;

        GetComponent<Renderer>().material.color = col;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey("up"))
            transform.Translate(new Vector3(0, 0, 0.1f));

        if (Input.GetKey("down"))
            transform.Translate(new Vector3(0, 0, -0.1f));

        if (Input.GetKey("right"))
            transform.Translate(new Vector3(0.1f, 0, 0));

        if (Input.GetKey("left"))
            transform.Translate(new Vector3(-0.1f, 0, 0));
    }

}

вот код управления кубом.

A: Итак.
У объектов с RigidBody стоит скорее использовать как раз методы именно этого компонента. Так, например движение будет происходить за счет метода MovePosition.
Например:
public Rigidbody rb;
void Start() {
    rb = GetComponent<Rigidbody>();
}
void FixedUpdate() {
    rb.MovePosition(transform.position + transform.forward * Time.deltaTime);
}

Заметьте, метод FixedUpdate. В работают с физикой. Особенно, с классом Rigidbody.
Также, если ваш объект движется быстро, то, возможно у RigidBody уместно будет поставить CollissionDetection → `Continuous (хотя конечно 0.1f я бы не назвал быстрым).
Continuous используется для обнаружения столкновений со статической сеткой геометрии, если ваш предмет движется очень быстро.
По поводу движения, в том числе по диагонали.
Движение обычно приводится к нормализованному вектору (принимает значение от 0 до 1) и на его основе и на основе других параметров (скорость передвижения, дельта) прибавляется к позиции объекта.
В общем кривом случае это выглядит как-то так:
public Rigidbody rb;
float moveSpeed = 5.0f;

void Start() {
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate() {

    Vector3 move = new Vector3(0, 0, 0);

    if (Input.GetKey("up"))
        move.z = Vector3.forward.z;

    if (Input.GetKey("down"))
        move.z = -Vector3.forward.z;

    if (Input.GetKey("right"))
        move.x = Vector3.right.x;

    if (Input.GetKey("left"))
        move.x = -Vector3.right.x;

    rb.MovePosition(transform.position + move * moveSpeed * Time.deltaTime);
}

Небольшое замечание: По идее всякие расчеты и нажатия на клавиши надо обрабатывать в Update, а вот в применить уже относительно к RigidBody надо в FixedUpdate

В принципе, знаки движения вперед-назад-влево-вправо в Unity и можно получить за счет Input.GetAxis("Horizontal") и Input.GetAxis("Vertical"), которые принимают значение от -1 до 1, в зависимости от нажатия стрелки ← → (-1/1)  ↓ ↑ (тоже -1/1). Остается значения поместить в вектор, нормализовать его и применить к объекту.
Что-то типа такого:
public Rigidbody rb;
float moveSpeed = 5.0f;
private Vector3 inputDirection;

void Start() {
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate() {
    inputDirection = (new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"))).normalized;
    Vector3 moveDirection = transform.TransformDirection(inputDirection);
    rb.MovePosition(transform.position + moveDirection * moveSpeed * Time.deltaTime);
}


text:
Q: Get the reply of an outgoing message in the same row in SQL? I am trying to get the incoming message for an outgoing message in the same row as response? So, the data looks like below:
user_id     message             type
1           What's your name?   outgoing
1           Nitin               incoming
1           What's your age?    outgoing
1           17                  incoming
2           What's your name?   outgoing
2           Aayush              incoming
2           What's your age?    outgoing
3           What's your name?   outgoing
4           What's your name?   outgoing
4           Shubham             incoming
4           What's your age?    outgoing

The output should look like:
user_id     message             type        reply
1           What's your name?   outgoing    Nitin
1           Nitin               incoming
1           What's your age?    outgoing     17
1           17                  incoming
2           What's your name?   outgoing    Aayush
2           Aayush              incoming
2           What's your age?    outgoing    No-reply
3           What's your name?   outgoing    No-reply
4           What's your name?   outgoing    Shubham
4           Shubham             incoming
4           What's your age?    outgoing    No-reply

The reply is an incoming message for an outgoing message for a user_id & if there is no reply for an outgoing message then the reply column should be filled by 'No-reply'. I have to do this in PSQL. I am currently able to do this in python after fetching data from DB.
Below is my current python code.
df['reply'] = np.where((df['user_id'] == df['user_id'].shift(-1))
                       & (df['type'].eq('Outgoing') & df['type'].shift(-1).eq('Incoming')),
                       df['message'].shift(-1), 'No-reply')

A: Assuming that you have a column that can be used to order the records (called id), you could use lead() as follows:
select
    t.*,
    case
        when type = 'outgoing'
            and lead(type) over(partition by user_id order by id) = 'incoming'
            then lead(message) over(partition by user_id order by id)
        when type = 'outgoing' then 'no reply'
    end reply
from mytable

This query checks if the current record has type outgoing and if the next one (for the same user) is  of type incoming: if both conditions are true, then it recovers the message on the next record and displays it as reply. If type is outgoing but the next message is not incoming, then it gives no reply. In other cases, nothing is printed.


text:
Q: Simplifying a trigonometric equation for chart radius I am making a neat new charting application, yet I am stumped by this equation:
$$M=\dfrac{R}{\cos\left(\frac{θ}{2}\right)}+(\tan\left(\frac{θ}{2}\right) \cdot R)$$
I need to solve for $R$, but for some reason I am throwing a blank. Any help?
Thanks!

A: Hint: $$\dfrac{R}{\cos\left(\frac{θ}{2}\right)}+(\tan\left(\frac{θ}{2}\right) \cdot R) = R\left(\dfrac{1}{\cos\left(\frac{θ}{2}\right)}+\tan\left(\frac{θ}{2}\right)\right)$$


text:
Q: Timezones on New Year in Space Pilot 3000 During re-watching the Space Pilot 3000 I've noticed:

*

*People in various countries are counting at the same time despite that there should be several time zones.

*When the earth is shown from space USA was in daylight.

Given that the show usually breaks physics on purpose was there a reason to do it (say joke) or is it just an error/within licentia poetica?

A: If you watch the commentary for the episode, they bring up your first point. The reason they did it was that it was funny and created a nice contrast when they repeated it later in the episode. They knew it was wrong, but also that most people wouldn't think about it in the moment on first watch.

A: Since Earth basically becomes one big country wouldn't they all use the same time zone.


text:
Q: Wap push message over http I want to send a wap push message which contains a URL to my android mobile & I want to see how it popups....
This is the URL I use.
It gives this error in my linux screen.

2019-01-28 13:25:15 [31965] [9] INFO: Box connection tried from denied host <172.16.20.77>, disconnected
  2019-01-28 13:25:15 [31965] [9] ERROR: Failed to create new boxc connection.

What can I do? Any help is welcome!!!


text:
Q: Interpolation of data on non-rectangular grid I have a smooth data distribution on a 2D regular grid that is not a rectangular (it is a cross-section of a channel) and I need to find an Interpolating function f[x,y].
I have tried Interpolation[{{x1,y1},f1},{x2,y2},f2},...}] but it doesn't work.
Does Interpolation work only on rectangular grid?
Thanks
Giovanni

A: Interpolation does not only work on rectangular grids. The grid even need not to be regular.
E.g. let us produce some data (x, y,z) which are not on a regular grid on a disk with radius of 5 in the x-y plane and which have z-values between 4 and 5 with:
radius=5;
maxRandomNumber=1000;
{x,y,z}=({#1*Cos[#2]*radius,#1*Sin[#2]*radius,#3})&[
Sqrt[RandomReal[{0,1},maxRandomNumber]],
2*Pi*RandomReal[{0,1},maxRandomNumber],RandomReal[{4,5},maxRandomNumber]];
data = Transpose[{x, y, z}];

If you plot them with
 ListPlot3D[data]

You get something like

You can interpolate the data easily with
f = Interpolation[data, InterpolationOrder -> 1];

Plotting them with
Plot3D[f[x, y], {x, -6, 6}, {y, -6, 6},
RegionFunction -> Function[{x, y}, Sqrt[x^2 + y^2] < radius]]

Or
ContourPlot[f[x, y], {x, -6, 6}, {y, -6, 6},
RegionFunction -> Function[{x, y}, Sqrt[x^2 + y^2] < radius]]

give you a similar picture as the first one. So you see, interpolation still works for such data.


text:
Q: My news page in my app isn't retrieving any news and only a blank white page is being displayed instead of a newsfeed I am currently working on Android Studio 4.0, Build #AI-193.6911.18.40.6514223.
Upon entering the news page, I am being shown a blank page. It appears that the API is not retrieving the news it's supposed to. I've double checked my entire app for any typos (in case it doesn't match the API parameters). Everything appears right but the API is not retrieving the data.
I have attached below the code with respect to the problem.
newspage.java:
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.widget.Toast;

import com.example.nvirone.API.ApiClient;
import com.example.nvirone.API.ApiInterface;
import com.example.nvirone.Models.Article;
import com.example.nvirone.Models.News;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Newspage extends AppCompatActivity {
    public static final String API_KEY = "(unique API key)";
    private RecyclerView recyclerView;
    private Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private List<Article> articles = new ArrayList<>();
    private String TAG = Newspage.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newspage);
        recyclerView = findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new Adapter(articles, Newspage.this);
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setNestedScrollingEnabled(false);
        LoadJson();
    }
public void LoadJson(){
    ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
    String country = Utils.getCountry();

    Call<News> call;
    call = apiInterface.getNews(country, API_KEY);
    call.enqueue(new Callback<News>() {
        @Override
        public void onResponse(Call<News> call, Response<News> response) {
            if (response.isSuccessful() && response.body().getArticle()!=null){
                articles.clear();
                articles = response.body().getArticle();
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onFailure(Call<News> call, Throwable t) {
            Toast.makeText(Newspage.this,"NO result",Toast.LENGTH_LONG).show();
        }
    });
    }
}

Newsindetail.java:
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class NewInDetail extends AppCompatActivity {
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_in_detail);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        webView = findViewById(R.id.webView);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(url);
    }
}

Adapter:
package com.example.nvirone;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.nvirone.Models.Article;
import com.squareup.picasso.Picasso;

import java.util.List;

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
    private List<Article> articles;
    private Context context;
    private AdapterView.OnItemClickListener OnItemClickListener;
    private OnItemClickListener onItemCLickListener;

    public Adapter(List<Article> articles, Context context) {
        this.articles = articles;
        this.context = context;
    }

    public Adapter() {

    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holders, int position) {
        final MyViewHolder holder = holders;
        final Article model = articles.get(position);
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(Utils.getRandomDrawbleColor());
        requestOptions.error(Utils.getRandomDrawbleColor());
        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        requestOptions.centerCrop();

        Glide.with(context).load(model.getUrlToImage()).apply(requestOptions)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        holder.progressBar.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        holder.progressBar.setVisibility(View.GONE);
                        return false;
                    }
                })
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(holder.imageView);
        holder.title.setText(model.getTitle());
        holder.desc.setText(model.getDescription());
        holder.source.setText(model.getSource().getName());
        holder.time.setText('\u2022' + Utils.DateToTimeFormat(model.getPublishedAt()));
        holder.published.setText(Utils.DateToTimeFormat(model.getPublishedAt()));
        holder.author.setText(model.getAuthor());
        String imageURL = model.getUrlToImage();
        Picasso.get().load(imageURL).into(holder.imageView);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context,NewInDetail.class);
                intent.putExtra("url",model.getUrl());
                context.startActivity(intent);
            }
        });
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        return new MyViewHolder(view, onItemCLickListener);
    }

    @Override
    public int getItemCount() {
        return articles.size();
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemCLickListener = onItemClickListener;
    }

    public interface OnItemClickListener{
        void onItemClick(View view, int position);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView title, desc, author, published, source, time;
        ImageView imageView;
        ProgressBar progressBar;
        OnItemClickListener onItemClickListener;
        CardView cardView;
        public MyViewHolder(@NonNull View itemView, OnItemClickListener onItemClickListener) {
            super(itemView);
            itemView.setOnClickListener(this);
            title  = itemView.findViewById(R.id.title);
            desc = itemView.findViewById(R.id.desc);
            author = itemView.findViewById(R.id.author);
            published = itemView.findViewById(R.id.publishedAt);
            source = itemView.findViewById(R.id.source);
            time = itemView.findViewById(R.id.time);
            imageView = itemView.findViewById(R.id.img);
            progressBar = itemView.findViewById(R.id.progress_load_photo);
            cardView = itemView.findViewById(R.id.cardView);

            this.onItemClickListener = onItemCLickListener;
        }
        @Override
        public void onClick(View view) {
            onItemClickListener.onItemClick(view, getAdapterPosition());
        }
    }
}

ApiClient:
package com.example.nvirone.API;

import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BaseURL = "https://newsapi.org/v2/";
    public static Retrofit retrofit ;

    public static Retrofit getApiClient(){
        if(retrofit==null){
            retrofit = new Retrofit.Builder().baseUrl(BaseURL).client(getUnsafeOkHttpClient().build()).addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
    public static OkHttpClient.Builder getUnsafeOkHttpClient(){
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

ApiInterface:
package com.example.nvirone.API;

import com.example.nvirone.Models.News;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface {
    @GET("top-headlines")
    Call<News> getNews(

            @Query("country") String country,
            @Query("apiKey") String apiKey
    );
}

Utils:
package com.example.nvirone;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;

import org.ocpsoft.prettytime.PrettyTime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class Utils {

    public static ColorDrawable[] vibrantLightColorList =
            {
                    new ColorDrawable(Color.parseColor("#ffeead")),
                    new ColorDrawable(Color.parseColor("#93cfb3")),
                    new ColorDrawable(Color.parseColor("#fd7a7a")),
                    new ColorDrawable(Color.parseColor("#faca5f")),
                    new ColorDrawable(Color.parseColor("#1ba798")),
                    new ColorDrawable(Color.parseColor("#6aa9ae")),
                    new ColorDrawable(Color.parseColor("#ffbf27")),
                    new ColorDrawable(Color.parseColor("#d93947"))
            };

    public static ColorDrawable getRandomDrawbleColor() {
        int idx = new Random().nextInt(vibrantLightColorList.length);
        return vibrantLightColorList[idx];
    }

    public static String DateToTimeFormat(String oldstringDate){
        PrettyTime p = new PrettyTime(new Locale(getCountry()));
        String isTime = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
                    Locale.ENGLISH);
            Date date = sdf.parse(oldstringDate);
            isTime = p.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return isTime;
    }

    public static String DateFormat(String oldstringDate){
        String newDate;
        SimpleDateFormat dateFormat = new SimpleDateFormat("E, d MMM yyyy", new Locale(getCountry()));
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",Locale.CHINA).parse(oldstringDate);
            assert date != null;
            newDate = dateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            newDate = oldstringDate;
        }

        return newDate;
    }

    public static String getCountry(){
        Locale locale = Locale.getDefault();
        String country = locale.getCountry();
        return country.toLowerCase();
    }
}

Parameters according to the API:
NEWS:
package com.example.nvirone.Models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class News {
    @SerializedName("status")
    @Expose
    private String status;

    @SerializedName("totalResults")
    @Expose
    private int totalResult;

    @SerializedName("articles")
    @Expose
    private List<Article> article;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getTotalResult() {
        return totalResult;
    }

    public void setTotalResult(int totalResult) {
        this.totalResult = totalResult;
    }

    public List<Article> getArticle() {
        return article;
    }

    public void setArticle(List<Article> article) {
        this.article = article;
    }
}

Article :
package com.example.nvirone.Models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Article {
    @SerializedName("source")
    @Expose
    private Source source;

    @SerializedName("author")
    @Expose
    private String author;

    @SerializedName("title")
    @Expose
    private String title;

    @SerializedName("description")
    @Expose
    private String description;

    @SerializedName("url")
    @Expose
    private String url;

    @SerializedName("urlToImage")
    @Expose
    private String urlToImage;

    @SerializedName("publishedAt")
    @Expose
    private String publishedAt;

    public Source getSource() {
        return source;
    }

    public void setSource(Source source) {
        this.source = source;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }
}

Source:
package com.example.nvirone.Models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Source {
    @SerializedName("id")
    @Expose
    private String id;

    @SerializedName("name")
    @Expose
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The cardview that is supposed to display the newsfeed :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="11dp"
        android:layout_marginRight="11dp"
        android:layout_marginTop="7dp"
        android:layout_marginBottom="7dp"
        app:cardElevation="@dimen/cardview_default_elevation"
        app:cardCornerRadius="15dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:id="@+id/img"
                android:scaleType="centerCrop"
                android:transitionName="img"
                tools:ignore= "UnusedAttribute"/>
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:id="@+id/shadow_bottom"
                android:src="@drawable/bottom_shadow"
                android:layout_alignBottom="@+id/img" />
            <ProgressBar
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@android:style/Widget.ProgressBar.Small"
                android:id="@+id/progress_load_photo"
                android:layout_marginTop="70dp" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:id="@+id/author"
                android:drawablePadding="10dp"
                android:ellipsize="end"
                android:maxLines="1"
                android:textColor="@android:color/white"
                android:singleLine="true"
                android:text="Author"
                android:gravity="bottom"
                android:layout_marginRight="160dp"
                android:layout_alignLeft="@+id/title"
                android:layout_alignStart="@+id/title"
                android:layout_alignRight="@+id/layoutDate"
                android:layout_alignTop="@+id/layoutDate"
                android:layout_alignEnd="@+id/layoutDate"/>
            <FrameLayout
                android:id="@+id/layoutDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/img"
                android:background="@drawable/round_white"
                android:padding="5dp"
                android:layout_alignParentRight="true"
                android:layout_marginRight="20dp"
                android:layout_marginTop="50dp">
                <ImageView
                    android:src="@drawable/ic_date"
                    android:layout_width="18dp"
                    android:layout_height="18dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="5dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#606060"
                    android:id="@+id/publishedAt"
                    android:layout_marginLeft="27dp"
                    android:layout_marginRight="10dp"
                    android:text="01 January 2000"/>
            </FrameLayout>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:textStyle="bold"
                android:textColor="@color/colorTextTitle"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:text="Title"
                android:textSize="17sp"
                android:layout_marginTop="10dp"
                android:layout_below="@id/img"
                android:id="@+id/title"/>
            <TextView
                android:id="@+id/desc"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_marginRight="16dp"
                android:layout_below="@+id/title"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="5dp"
                android:text="Desc"/>
            <TextView
                android:id="@+id/source"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_below="@+id/desc"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:fontFamily="sans-serif-light"
                android:textStyle="bold"
                android:textColor="@color/colorTextTitle"
                android:ellipsize="end"
                android:singleLine="true"
                android:drawablePadding="10dp"
                android:maxLines="1"
                android:text="Source"/>
            <TextView
                android:id="@+id/time"
                android:layout_width="wrap_content"
                android:layout_height="20dp"
                android:layout_below="@+id/desc"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:layout_toRightOf="@+id/source"
                android:ellipsize="end"
                android:singleLine="true"
                android:drawablePadding="10dp"
                android:maxLines="1"
                android:text="Time"/>

        </RelativeLayout>

    </androidx.cardview.widget.CardView>

</FrameLayout>

EDIT :
I have added some code in the API interface as follows and the same problem has come up again after trying to use this query :
@GET("everything")
Call<News> getNewsSearch(

    @Query("q") String Keyword,
    @Query("language") String language,
    @Query("SortBy") String sortBy,
    @Query("apiKey") String apiKey

    );

A: You need to add this method in your Adapter.java:
public void addArticles(List<Article> articles) {
    this.articles.addAll(articles);
    int count = getItemCount();
    notifyItemRangeInserted(count, count + articles.size());
}

And use it this way in your NewsPage.java:
public void LoadJson() {
   ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
   String       country      = Utils.getCountry();

   Call<News> call;
   call = apiInterface.getNews(country, API_KEY);
   call.enqueue(new Callback<News>() {

      @Override
      public void onResponse(Call<News> call, Response<News> response) {
         List<Article> newArticles = response.body().getArticle();
         if (response.isSuccessful() && newArticles != null) {
            adapter.addArticles(newArticles);
         }
      }

      @Override
      public void onFailure(Call<News> call, Throwable t) {
         Toast.makeText(NewsPage.this, "NO result", Toast.LENGTH_LONG).show();
      }
   });
}


text:
Q: win server 2008r2 network share error element not found I have setup a Windows Server 2008R2 with DNS and AD.  When I define a shared folder on the Server and connect to it via \domain.lan\folder I can see the content but if I try to change something in the folder I get the error "element not found". This behaviour is always the same. It doesn't matter if I try connecting directly from the server or through a windows 7 client. BUT: IF I ACCESS THE FOLDER VIA IP ADDRESS OF THE SERVER e.g. \192.168.0.22\folder all works fine. So my guess there is a big problem with the Windows DNS Server. Pinging domain.lan results in the correct IP Address so it is resolved correctly. I don't know where the problem can be.
BTW: I could reproduce this problem exactly with Virtual Machines on my PC and different names and IP Addresses...
Does anybody have a guess?

A: What you are looking for is called Domain-based DFS namespace.
Domain-based DFS namespace allows you to use the domain name to access shared folders : \\domain.lan\folder
Then, you can grant access (or not) and setup appropriate permissions to Users/Groups on your DFS based shared folders.
Traditional shares are associated with a single server, so you will have to specify the target computer in your SMB path : \\server.domain.lan\folder
DFS is, IMHO, the most improved way to publish shared folders in Active Directory mainly because it provides more flexibily, scalability, security (review some benefits here).
Appart the fact that i would suggest you to setup Domain-based DFS namespace to solve your issue, i would also suggest some further reading :

*

*http://en.wikipedia.org/wiki/Distributed_File_System_(Microsoft)

*http://www.maxi-pedia.com/difference+between+shared+folder+and+DFS+root

*http://www.maxi-pedia.com/what+is+DFS

*http://technet.microsoft.com/en-us/library/cc732863.aspx
Hope it helps.


text:
Q: How to add a toolbar to the BOTTOM of a UITableView obj-c/ios/xcode how do I add Programmaticaly a toolbar with uitextfield at the bottom of a tableview? Like a chat or sms app.. thank you in advance..

A: Use a UIViewController subclass instead of UITableViewController subclass.
it should be something like this :
@interface ChatViewController : UIViewController
@end

#import "ChatViewController.h"

@interface ChatViewController()  <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIToolbar *toolbar;
@property (nonatomic, strong) UITextField *textField;
@end

@implementation ChatViewController

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [UITableView alloc] init];
        CGRect frame = self.view.bounds;
        frame.size.height = frame.size.height - 44;
        _tableView.frame = frame;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(UIToolbar *)toolbar
{
    if (!_toolbar) {
        _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,self.tableView.frame.size.height,self.view.frame.size.width, 44)];
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(0,0,_toolbar.frame.size.width -20)];
    self.textField.delegate = self;
    UIBarButtonItem *textFieldItem = [[UIBarButtonItem alloc] initWithCustomView:self.textField];
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                target:nil
                                                                                action:nil];
    // You'll need to add a button to send you text
    _toolbar.items = [NSArray arrayWithObjects:flexibleSpace, textFieldItem, flexibleSpace, nil];
    }
    return _toolbar;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.toolbar];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideOrShow:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideOrShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}

- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super viewDidUnload];
}

- (void)keyboardWillHideOrShow:(NSNotification *)note
{
    NSDictionary *userInfo = note.userInfo;
    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];

    CGRect keyboardFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect keyboardFrameForToolbar = [self.toolbar.superview convertRect:keyboardFrame fromView:nil];
    CGRect keyboardFrameForTableView = [self.tableView.superview convertRect:keyboardFrame fromView:nil];

    CGRect newToolbarFrame = self.toolbar.frame;
    newToolbarFrame.origin.y = keyboardFrameForToolbar.origin.y - newToolbarFrame.size.height;

    CGRect newTableViewFrame = self.tableView.frame;
    newTableViewFrame.size.height = keyboardFrameForTableView.origin.y - newToolbarFrame.size.height;

    [UIView animateWithDuration:duration
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState | curve
                     animations:^{self.toolbar.frame = newToolbarFrame;
                         self.tableView.frame =newTableViewFrame;}
                     completion:nil];
}

This would handle laying out the views and animating keyboard appearance. You'll need to handle delegate and datasource methods for the table view and the text field.

A: I just found a better trick!

*

*Make sure there is NO Navigation Bar (from your failed attempts)

*Drag and drop a "Bar Button Item" (Xcode will magically place it for you at the bottom)

*NOTE: If you Run the App now you won't see anything! (so keep reading)

*Add the following line of code under viewDidLoad:

self.navigationController.toolbarHidden = NO;

Done!

A: First create a view to hold the whole thing.
Then add a UITableview and UIToolbar programmatically set frame so that it appears under the tableview .Add the textfield to the  toolbar
    UIView *placeholderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 400, 440)];
    UITableView *tv=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 400, 400)];
    [placeholderView addSubview:tv];
    UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 400, 400, 40)];
    [placeholderView addSubview:toolBar];

A: It's not great in some ways, but I solved this by using a Container View on an additional View Controller.

The Intermediate VC to Table VC segue is "Embed"
I used this instead of the "Toolbar on Nav Controller" solution because I'm adding this to an existing app design with ~15 screens, and I wasn't sure how to configure different toolbars on different screens.


text:
Q: Android - can't read TXT files from SDcard on real machine? When I run the code bellow in the virtual android (1.5) it works well, TextSwitcher shows first 80 chars from each txt file from /sdcard/documents/ , but when I run it on my Samsung Galaxy i7500 (1.6) there are no contents in TextSwitcher, however in LogCat there are FileNames of txt files.
My Code:
      public void getTxtFiles(){
 //Scan /sdcard/documents and put .txt files in array File TxtFiles[]
    String path = Environment.getExternalStorageDirectory().toString()+"/documents/";
    String files;
    File folder = new File(path);
    if(folder.exists()==false){if (!folder.mkdirs()) {
        Log.e("TAG", "Create dir in sdcard failed");
        return;
   }}
    else{
    File listOfFiles[] = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++)
    {

     if (listOfFiles[i].isFile())
     {
     files = listOfFiles[i].getName();
         if (files.endsWith(".txt") || files.endsWith(".TXT"))
         {
            if((files.length()-1)>i){resizeArray(TxtFiles, files.length()+10);}
             TxtFiles[i]=listOfFiles[i];
             System.out.println(TxtFiles[i]);
         }
          }
       }}
    }

 private void updateCounter(int Pozicija) {
 if(Pozicija<0){Toast.makeText(getApplicationContext(), R.string.LastTxt, 5).show();
 mCounter++;}
 else if(TxtFiles[mCounter]!=null){
  TextToShow = getContents(TxtFiles[mCounter]);
  if(TextToShow.length()>80)TextToShow=TextToShow.substring(0, 80);
  mSwitcher.setText(TextToShow);
  System.out.println(Pozicija);
  }
 else mCounter--;
 }

   static public String getContents(File aFile) {
    //...checks on aFile are elided
    StringBuilder contents = new StringBuilder();

    try {
      //use buffering, reading one line at a time
      //FileReader always assumes default encoding is OK!
      BufferedReader input =  new BufferedReader(new FileReader(aFile));
      try {
        String line = null; //not declared within while loop
        /*
        * readLine is a bit quirky :
        * it returns the content of a line MINUS the newline.
        * it returns null only for the END of the stream.
        * it returns an empty String if two newlines appear in a row.
        */
        while (( line = input.readLine()) != null){
          contents.append(line);
          contents.append(System.getProperty("line.separator"));
        }
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }

    return contents.toString();
  }

And I am able to write contents of those files though LogCat!
Any ideas?

A: Problem solved: Android is based on Linux kernel and it has file permissions. I guess my app didnt have permissions over those files in /sdcard/documents/.


text:
Q: Guideline for votes is unclear First of all: this question is not about reasons for downvotes (although it implicitly refers to this).
The definition for votes on Stackoverflow is:
Good answers are voted up and rise to the top.
There is a guideline when asking a question what to consider (doing your homework, research first, choose right tags, etc..). But still this is not exactly making clear on which reason giving upvotes / downvotes.
This platform has plenty elaborated features but this one is still missing since I have seen lots of questions / answers which were down/up voted for unknown reasons, and especially lots of questions / answers with zero votes although it was a regular and certainly good contribution to this platform.
Why not giving a selection of references when to down/up vote the same way as guidelines asking / answering a question? In my opinion everybody would profit from that because things are getting more transparent.

A: Your votes are yours to cast as you see fit.
There can be many reasons for casting a vote and multiple reasons for any single vote. Choosing one from something like a drop down would be very restrictive. People being people, many would just choose the top one.
If you wish to explain your vote you can do so in a comment; that will always be much more representative of why you actually voted than some pre-configured wording in a menu.
Free, anonymous voting is, IMHO, one of the many strengths of the StackExchange sites.
Your comments would imply that your question is really about encouraging people to explain down votes. That is a topic which has been discussed many times, there is no need to rehash it here.


text:
Q: How to import a jar file which is in a package? I have a jar file named stdlib-package, the .class files in this jar file are all in a edu.princeton.cs.introcs package
For example, I want to use one class named StdDraw from that jar file in my own codes
Say E:\code is my current working directory. like other conditions, I create a subdirectory bin\edu\princeton\cs\introcs to put stdlib-package in
Here is my codes:
package com.david.test;
import edu.princeton.cs.introcs.stdlib-package.*; // any problems here ?

public class DrawTest
{
    public static void main(String[] args)
    {
        StdDraw.line(0.5, 0.5, 1, 0.5);
    }
}

Then I put DrawTest.java in the src\com\david\test
To compile the DrawTest.java, I type the commands in command line:
javac -d bin -cp bin\edu\princeton\cs\introcs\stdlib-package.jar src\com\david\test\DrawTest.java

But it failed : package edu.princeton.cs.introcs.stdlib_package doesn't exist...
I searched for a lot of time, but haven't found the answer
Thanks for your help
EDIT===
@EJP's comment solves my question too.

A: This should be all you need in code:
import edu.princeton.cs.introcs.*

Then you only need to make sure the jar is on your class path; it doesn't matter what the name of the jar is, or where it is.  If it is on your classpath, Java will load it, and use the location of the files within it.
Move the jar into a lib directory in your current directory, and do something like
javac -cp lib\stdlib-package.jar src\com\david\test\DrawTest.javac

A: Your import is wrong. There's no such package in that .jar file.
import edu.princeton.cs.introcs.*;

In general, however, that's a bad practice and you should really only import what you need:
import edu.princeton.cs.introcs.StdDraw;

A: I understand that there is no package with 'stdlib-package' name.
If the fully qualified name of the class you are using is edu.princeton.cs.introcs.StdDraw, you can just import 'edu.princeton.cs.introcs.StdDraw'
     import edu.princeton.cs.introcs.StdDraw

If you want to load all the classes in that package
     import edu.princeton.cs.introcs.*


text:
Q: I am trying to make an inventory management system using React. I am using axios to get and post to an API but request is failing with status code 429 import axios from "axios";
import React, { useEffect, useState } from "react";

function Create() {
  const [name, setName] = useState("");
  const [category, setCategory] = useState("");
  const [price, setPrice] = useState("");

  console.log(name);
  console.log(category);
  console.log(price);

  const sendData = () => {
    axios.post("https://63609f7caf66cc87dc1754b9.mockapi.io/IVMS", {
      name,
      category,
      price
    });
  };

  return (

      <form>

          Product name
          <input
            type="text"
            class="form-control"
            id="exampleInputEmail1"
            aria-describedby="emailHelp"
            placeholder="Product name"
            onChange={(e) => setName(e.target.value)}
          />

          Category
          <input
            type="text"
            class="form-control"
            id="exampleInputPassword1"
            placeholder="Category"
            onChange={(e) => setCategory(e.target.value)}
          />

          Price
          <input
            type="text"
            class="form-control"
            id="exampleInputPassword1"
            placeholder="Price"
            onChange={(e) => setPrice(e.target.value)}
          />

        <button type="submit" class="btn btn-primary" onClick={sendData}>
          Submit
        </button>
      </form>

  );
}

export default Create;

This is the file that is posting data to the API. Even when I'm not sending any requests, it says too "too many requests".
I tried to make the user input values in the form and display them in a table underneath the form. It's working but it fails saying too many requests(429).

A: try  const sendData = () => {} to function sendData(){}


text:
Q: JS Making a multiplication table without console.log() I want to build a multiplication table without the use of console.log() in the function. I am currently experiencing difficulty splitting the values. The whole function must be in pure JS. Not intended for use on the DOM. I want the output printed on the terminal.
function multiplicationTable (maxValue){

 var array = []

 for (var i = 1; i <= maxValue; i++)
 {
  for (var j = 1; j <= maxValue; j++)
 {
   if (j >= 1 && i >= 1)
   {
     array.push(j*i)
   }
 }

}
var m = array.join()
return m;

}
console.log(multiplicationTable(3));

Current Output: 1,2,3,2,4,6,3,6,9
Required Output:
1 2 3
2 4 6
3 6 9

I feel I have to use .split() or .splice(). I just can't pinpoint where to add the values.

A: Here is your multiplication table. It is supported in browser dev console, but not as a code snippet here. Copy and paste it inside browser console.

let a = 0;
let b = 0;
const len = 4;
let output = [];
for(a=0;a<len;a++){
  output.push([]);
  for(b=0;b<len;b++){
    output[a].push(`${a} x ${b} = ${a*b}`);
  }
}
console.table(output);

A: Instead of joining in the array, I would build and return a multidimensional array. Then you can use forEach to join and log when calling. Like,

function multiplicationTable(maxValue) {
  var array = []
  for (var i = 1; i <= maxValue; i++) {
    var t = []
    for (var j = 1; j <= maxValue; j++) {
      t.push(j * i)
    }
    array.push(t)
  }
  return array
}

multiplicationTable(3).forEach(x => console.log(x.join(" ")));

A: Return an object and then with the function forEach build the desired output.

function multiplicationTable(maxValue) {
  var result = {}

  for (var i = 0; i < maxValue; i++) {
    for (var j = 0; j < maxValue; j++) {
      result[`${j + 1} ${i + 1}`] = (j + 1) * (i + 1);
    }
  }

  return result;
}

var maxValue = 3;
var arr = multiplicationTable(maxValue)
Object.keys(arr).forEach((k) => {
  console.log(k, arr[k]);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Consider creating a new array for every loop of i, then storing them in the original array.
for (var i = 0; i < maxValue; i++) {
  array[i] = [];
  for (var j = 0; j < maxValue; j++) {
    array[i].push((j+1)*(i+1))
  }
}

The return type will then be an array of arrays, which you will have to loop over to console log.
var multTable = multiplicationTable(3);
for (i = 0; i < multTable.length; i++) {
  console.log(multTable[i].join(" ");
}

A:

function multiplicationTable(maxValue) {
  var array = []
  for (var i = 1; i <= maxValue; i++) {
    var t = []
    for (var j = 1; j <= maxValue; j++) {
      t.push(j * i)
    }
    array.push(t)
  }
  return array
}

multiplicationTable(3).forEach(x => console.log(x.join(" ")));


text:
Q: Custom DataBase in Apache Pulsar Manager I've Apache Pulsar configured on IBM Cloud Kubernetes Cluster. It includes Pulsar Manager too. I want to customize the database to use PostgreSQL for Pulsar Manager. I've replaced the database properties in application.properties file to use PostgreSQL. Ref
But When I see Pulsar manager UI, it still shows me old topics/namespaces etc. It seems it is not connecting to my standalone PostgreSQL. Looking for some help on the same.
Please see the logs from Pulsar Manager pod:
2021-10-21 09:22:10.333 UTC [25] LOG: listening on IPv4 address "127.0.0.1", port 5432
2021-10-21 09:22:10.338 UTC [25] LOG: listening on Unix socket "/run/postgresql/.s.PGSQL.5432"
2021-10-21 09:22:10.342 UTC [25] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"
2021-10-21 09:22:10.361 UTC [26] LOG: database system was shut down at 2021-10-21 09:22:10 UTC
2021-10-21 09:22:10.366 UTC [25] LOG: database system is ready to accept connections

Please help me on the same. Many Thanks!
I've done changes in application.properties file as below:
env: - name: PULSAR_CLUSTER value: pulsar - name: USERNAME valueFrom: secretKeyRef: name: pulsar-pulsar-manager-secret key: PULSAR_MANAGER_ADMIN_USER - name: PASSWORD valueFrom: secretKeyRef: name: pulsar-pulsar-manager-secret key: PULSAR_MANAGER_ADMIN_PASSWORD - name: SPRING_DATASOURCE_DRIVER-CLASS-NAME valueFrom: configMapKeyRef: name: pulsar-pg-config key: SPRING_DATASOURCE_DRIVER-CLASS-NAME - name: SPRING_DATASOURCE_URL valueFrom: configMapKeyRef: name: pulsar-pg-config key: SPRING_DATASOURCE_URL - name: SPRING_DATASOURCE_USERNAME valueFrom: configMapKeyRef: name: pulsar-pg-config key: SPRING_DATASOURCE_USERNAME - name: SPRING_DATASOURCE_PASSWORD valueFrom: configMapKeyRef: name: pulsar-pg-config key: SPRING_DATASOURCE_PASSWORD
I've used these values in Pulsar Manager's deployment file as below:
name: SPRING_DATASOURCE_DRIVER-CLASS-NAME

valueFrom:
configMapKeyRef:
name: pulsar-pg-config
key: SPRING_DATASOURCE_DRIVER-CLASS-NAME

*

*name: SPRING_DATASOURCE_URL
valueFrom:
configMapKeyRef:
name: pulsar-pg-config
key: SPRING_DATASOURCE_URL