text:
Q: How to solve error: "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result"? I install Xampp on Windows 7, and try to select data from a database table. For this I create code like this:
<?php
$con=mysqli_connect("localhost","test1","2jan1991","test1");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM Persons");

while($row = mysqli_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br>";
  }

mysqli_close($con);
?>

But when I try to run code it has error like:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\t2\1.php on line 11

How to resolve this?

A: $result = mysqli_query($con, "SELECT * FROM Persons") or die("Error: " . mysqli_error($con));

Can tell you the reason.


text:
Q: Creating a new array with elements from input array I have an array like below
[{
    "IM_Id":1,
    "IM_Name":"Hello",
    "ItemNumber":2001,
    "FE_Id":2,
    "FE_Name":"Wall",
    "FE_Code":"XYZ",
    "FC_Id":[2,3],
    "FC_Name":["ABC","PQR"],
    "FC_Value":[9,7],
    "OC_Id":6,
    "OC_Name":"Rai",
    "OC_Price":"$30",
    "CH_Id":4,
    "CH_Name":"Sen",
    "CH_Code":"LMN",
    "CO_Id":[5,9],
    "CO_Name":["xyz","pqr"],
    "CO_Value":["qqq","LMN"]
},
 {
     "IM_Id":2,
     "IM_Name":"World",
     "ItemNumber":2002,
     "FE_Id":3,
     "FE_Name":"WallMart",
     "FE_Code":"009F",
     "FC_Id":[4,5],
     "FC_Name":["ABCD","PQRS"],
     "FC_Value":[4,2],
     "OC_Id":7,
     "OC_Name":"Raj",
     "OC_Price":"$60",
     "CH_Id":7,
     "CH_Name":"Ken",
     "CH_Code":"IJK"
 }]

You can see FC_Id,FC_Name,FC_Value have 2 elements and these 3 parameters are actually related.
Similarly all parameters prepended with CO have same pattern.
I want my resulting array should consider every element of array one by one.
So for the first element of array, it should consider one by one  elements of FC_Id,FC_Name,FC_Value,CO_Id,CO_Name and CO_Value.
It should actually consider all the elements of subarrays and main array both.
And hence my result should be something as below
    [{
    "IM_Id":1,
    "IM_Name":"Hello",
    "ItemNumber":2001,
    "FE_Id":2,
    "FE_Name":"Wall",
    "FE_Code":"XYZ",
    "FC_Id":2, //Here it took the first element
    "FC_Name":"ABC", // //Here it took the first element
    "FC_Value":9, ////Here it took the first element
    "OC_Id":6,
    "OC_Name":"Rai",
    "OC_Price":"$30",
    "CH_Id":4,
    "CH_Name":"Sen",
    "CH_Code":"LMN",
    "CO_Id":5,
    "CO_Name":"xyz",
    "CO_Value":"qqq"
},
{
    "IM_Id":1,
    "IM_Name":"Hello",
    "ItemNumber":2001,
    "FE_Id":2,
    "FE_Name":"Wall",
    "FE_Code":"XYZ",
    "FC_Id":3, //Here it took the second element
    "FC_Name":"PQR", //Here it took the second element
    "FC_Value":7,//Here it took the second element
    "OC_Id":6,
    "OC_Name":"Rai",
    "OC_Price":"$30",
    "CH_Id":4,
    "CH_Name":"Sen",
    "CH_Code":"LMN",
    "CO_Id":9,
    "CO_Name":"pqr",
    "CO_Value":"LMN"
},
 {
     "IM_Id":2,
     "IM_Name":"World",
     "ItemNumber":2002,
     "FE_Id":3,
     "FE_Name":"WallMart",
     "FE_Code":"009F",
     "FC_Id":4,
     "FC_Name":"ABCD",
     "FC_Value":4,
     "OC_Id":7,
     "OC_Name":"Raj",
     "OC_Price":"$60",
     "CH_Id":7,
     "CH_Name":"Ken",
     "CH_Code":"IJK",
     "CO_Id":"-",
    "CO_Name":"-",
    "CO_Value":"-"
 },
 {
     "IM_Id":2,
     "IM_Name":"World",
     "ItemNumber":2002,
     "FE_Id":3,
     "FE_Name":"WallMart",
     "FE_Code":"009F",
     "FC_Id":5,
     "FC_Name":"PQRS",
     "FC_Value":2,
     "OC_Id":7,
     "OC_Name":"Raj",
     "OC_Price":"$60",
     "CH_Id":7,
     "CH_Name":"Ken",
     "CH_Code":"IJK",
     "CO_Id":"-", // as there's no element here we are inputting a '-'
    "CO_Name":"-",
    "CO_Value":"-"
 }
 ]

Also, note that as there are no CO_ values for Item Number 2002 am putting a "-".
There will be more more other parameters in the array too I need some dynamic logic to create the resulting array

A: Something like this:

*

*For each element of the data

*
*

*Find at least one list of IDs between FC and CO (or construct a one-element list if no such list is found)

*
*

*Iterate its length, and replace the relevant entries with subentries

*Flatten the result

let data = [{"IM_Id":1,"IM_Name":"Hello","ItemNumber":2001,"FE_Id":2,"FE_Name":"Wall","FE_Code":"XYZ","FC_Id":[2,3],"FC_Name":["ABC","PQR"],"FC_Value":[9,7],"OC_Id":6,"OC_Name":"Rai","OC_Price":"$30","CH_Id":4,"CH_Name":"Sen","CH_Code":"LMN","CO_Id":[5,9],"CO_Name":["xyz","pqr"],"CO_Value":["qqq","LMN"]},{"IM_Id":2,"IM_Name":"World","ItemNumber":2002,"FE_Id":3,"FE_Name":"WallMart","FE_Code":"009F","FC_Id":[4,5],"FC_Name":["ABCD","PQRS"],"FC_Value":[4,2],"OC_Id":7,"OC_Name":"Raj","OC_Price":"$60","CH_Id":7,"CH_Name":"Ken","CH_Code":"IJK"}];

let result = [].concat(...data.map(r =>
  (Array.isArray(r.FC_Id) ? r.FC_Id :
    Array.isArray(r.CO_Id) ? r.CO_Id :
    [0]
  ).map((_, i) =>
    Object.assign({}, r, {
      FC_Id: r.FC_Id ? r.FC_Id[i] : "-",
      FC_Name: r.FC_Name ? r.FC_Name[i] : "-",
      FC_Value: r.FC_Value ? r.FC_Value[i] : "-",
      CO_Id: r.CO_Id ? r.CO_Id[i] : "-",
      CO_Name: r.CO_Name ? r.CO_Name[i] : "-",
      CO_Value: r.CO_Value ? r.CO_Value[i] : "-",
    })
  )
));

console.log(result);

A: Here is a snippet to achieve this. If you need to handle more properties with values as arrays, simple add them to props array :
let props = ["FC_Id", "FC_Name", "FC_Value", "CO_Id", "CO_Name", "CO_Value"]
Sample snippet

let arr = [{
    "IM_Id": 1,
    "IM_Name": "Hello",
    "ItemNumber": 2001,
    "FE_Id": 2,
    "FE_Name": "Wall",
    "FE_Code": "XYZ",
    "FC_Id": [2, 3],
    "FC_Name": ["ABC", "PQR"],
    "FC_Value": [9, 7],
    "OC_Id": 6,
    "OC_Name": "Rai",
    "OC_Price": "$30",
    "CH_Id": 4,
    "CH_Name": "Sen",
    "CH_Code": "LMN",
    "CO_Id": [5, 9],
    "CO_Name": ["xyz", "pqr"],
    "CO_Value": ["qqq", "LMN"]
  },
  {
    "IM_Id": 2,
    "IM_Name": "World",
    "ItemNumber": 2002,
    "FE_Id": 3,
    "FE_Name": "WallMart",
    "FE_Code": "009F",
    "FC_Id": [4, 5],
    "FC_Name": ["ABCD", "PQRS"],
    "FC_Value": [4, 2],
    "OC_Id": 7,
    "OC_Name": "Raj",
    "OC_Price": "$60",
    "CH_Id": 7,
    "CH_Name": "Ken",
    "CH_Code": "IJK"
  }
]

function convertArray() {
  let result = [];
  let props = ["FC_Id", "FC_Name", "FC_Value", "CO_Id", "CO_Name", "CO_Value"]

  arr.forEach(function(obj) {
    // Assume `FC_Id` array length is the reference array length
    obj["FC_Id"].forEach(function(id, $index) {
      // Create a clone of original object, so that we only have to override `props` defined above
      let objClone = JSON.parse(JSON.stringify(obj));

      // Override each prop value
      props.forEach(function(prop) {
        // Ensure original object property is an array with enough elements
        if (obj[prop] instanceof Array && obj[prop].length > $index) {
          objClone[prop] = obj[prop][$index];
        }
        else {
          // else simply use an hyphen as value
          objClone[prop] = "-";
        }
      });

      // Push clone to result
      result.push(objClone);
    });
  });

  return result;
}

let newArray = convertArray();

console.log(JSON.stringify(newArray, null, 2));

A: From where are you creating this array . If you create this array in JavaScript or from webservice class. Then we could tell you the generic class for it. And a small method to convert the class element in your desire output array.
Let me answer in JavaScript code.
// I am creating a array object manual you could get it from source or from server json.
var Arr=[];

var obj={};
Obj.Name="fc_name";
obj.Value="12";
Arr.push(obj);

var obj={};
Obj.Name="fc_value";
obj.Value="dieje";

Arr.push(obj);

Similarly push all the elements in the array.
Then you will have a array of object with name value.
Arr=[
{"Name":"fc_value",
"Value":""dieje"
},
...
});

Now use below function to convert this array of object into your desire array.
function Convert(arr)
{
var array=[];
var obj={};
Arr.forEach(value)
{
obj[value.Name]=value.Value;
}

array.push(obj);//this is for single object you could apply loop to get the multiple value in array.
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Removing file in haskell I am trying to delete a text file in haskell while working in winhugs with help of removeFile function.But it is giving an error that
Program error: price.txt: Directory.removeFile: permission denied

What can be the reason?

A: According to the Hackage Docs for removeFile, the operation may fail with:

isPermissionError / PermissionDenied The process has insufficient privileges to perform the operation. [EROFS, EACCES, EPERM]

Also, according to the source code there, removeFile is just a thin wrapper around deleteFile in the Win32 API:
removeFile :: FilePath -> IO ()
removeFile path =
#if mingw32_HOST_OS
  Win32.deleteFile path
#else
  Posix.removeLink path
#endif

Update
After digging around the source code for winhugs, it seems the Windows API function unlink is actually being used to delete a file in Hugs:
primFun(primRemoveFile) { /* remove a file     */
  int rc;
  String s = evalName(IOArg(1));

  if (!s) {
    IOFail(mkIOError(NULL,
             nameIllegal,
             "Directory.removeFile",
             "illegal file name",
             &IOArg(1)));
  }

   rc = unlink(s);

  if (rc != 0)
    throwErrno("Directory.removeFile", TRUE, NO_HANDLE, &IOArg(1));
  IOReturn(nameUnit);
}

In any case, the previous answer is going to hold up in the sense that any permissions constraint is not introduced by Haskell. Rather, any permissions error would be due to the underlying OS environment (user accounts, open files, permissions, etc).


text:
Q: User Instance uses Path for database name when attached in SSMS When I attached my database to SQL Server Express, my database name got changed to my database address. Can someone help me to figure this out?
Here is a screenshot:


text:
Q: How to keep Appendix (as is) in TOC but have heading capitalized in report I am using report and I need to have chapter headings be in all caps (including the Appendix) but not in the TOC.  E.g. instead of "Appendix A", it should appear as "APPENDIX A" inside the paper and "Appendix A" in the TOC.  I seem to have fixed the regular chapters but cannot seem to figure out how to fix the Appendix.
I can just change \appendixname to APPENDIX, but then it will appear as all caps in the TOC (which I would prefer not be the case).  Changing the definition of \appendix for report class seems to have the same effect (I believe because it's basically just redefining \@chapapp):
\renewcommand{\appendix}{\par
   \setcounter{chapter}{0}%
   \setcounter{section}{0}%
   \gdef\@chapapp{APPENDIX}% modified from \appendixname
   \gdef\thechapter{\@Alph\c@chapter}}

I was able to fix the regular chapter issue by keeping \chaptername as is and hard coding CHAPTER rather than using \@chapapp in the following (which was part of the original template--I did not create this so I don't fully understand what all this is doing):
\def\@chapter[#1]#2{
    \ifnum \c@secnumdepth >\m@ne
        \refstepcounter{chapter}%
        \typeout{CHAPTER\space\thechapter.} % originally used \@chapapp
        \addcontentsline{toc}{chapter}%
        {\@chapapp\space {\thechapter}: {#1}}
    \else
         \addcontentsline{toc}{chapter}{#1}%
    \fi
    \chaptermark{#1}%
    \addtocontents{lof}{\protect\addvspace{10\p@}}%
    \addtocontents{lot}{\protect\addvspace{10\p@}}%
    \if@twocolumn
        \@topnewpage[\@makechapterhead{#2}]%
    \else
        \@makechapterhead{#2}%
        \@afterheading
    \fi
}

Honestly, I don't understand why \uppercase doesn't work in the following but it doesn't capitalize "Chapter" from \@chapapp (this was from the original template as well) and still appears in the style file after the above (the chapter titles have always appeared in CAPS, just not the "Chapter x:" prefix).
\def\@makechapterhead#1{%
    \vspace*{-20\p@}%
    {\parindent \z@ \raggedright \normalfont
    \interlinepenalty\@M
    \ifnum \c@secnumdepth >\m@ne
        \centering  \large\bfseries
        \uppercase{\@chapapp\space \thechapter: #1}
    \fi
    \vskip 20\p@
    }
}

A: A solution without hardcoding or editing the .cls file directly:
The O.P. was right in his assumption about \@makechapterhead:
\def\@makechapterhead#1{%
  \vspace*{50\p@}%
  {\parindent \z@ \raggedright \normalfont
    \ifnum \c@secnumdepth >\m@ne
        \huge\bfseries \@chapapp\space \thechapter
        \par\nobreak
        \vskip 20\p@
    \fi
    \interlinepenalty\@M
    \Huge \bfseries #1\par\nobreak
    \vskip 40\p@
  }}

The line with \@chapapp does indeed print Chapter (or Appendix), followed by the chapter number.
To get this uppercase, it's necessary to use \MakeUppercase{\@chapapp}, not \uppercase.
Instead of editing the report.cls code, it's better to use \xpatchcmd, looking for the line \huge\bfseries\@chapapp.. and replacing this with the relevant code using \MakeUppercase.
However, this should be done only after \appendix, so append this patch to \appendix using \xapptocmd{\appendix}{...} (see the code please)
\documentclass{report}

\usepackage{xpatch}

\makeatletter

\xapptocmd{\appendix}{%
\xpatchcmd{\@makechapterhead}{%
  \huge\bfseries \@chapapp\space \thechapter
}{%
  \huge\bfseries \MakeUppercase{\@chapapp}\space \thechapter
}{\typeout{Patching \@makechapterhead succeeded}}{\typeout{Patching failed}}% Patching ends
}{\typeout{Appending succeeded}}{\typeout{Appending failed}}
\makeatother

\begin{document}

\chapter{First}

\appendix

\chapter{Appendix 1}

\end{document}

Please note that my code does not work for \chapter* like - appendices.


text:
Q: How to encode a URL that I want to pass as a query string I'm trying to send a URL as paramter of a query string like this example:
http://localhost.com/myapp.jsp?pathToFileURL=http://192.168.0.1/my_file.pdf
What I did is I used encode URL to encode the path before sending it to the server, problem is im getting a "400 Invalid URI: noSlash" because of this.
From what I read the problem is the tomcat security and that I should add a parameter to the tomcat startup
-Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
But I can't modify the parameters of the tomcat, so is it possible to do it other way?
Thanks

A: Complete stab in the dark but you could try escaping the slashes with backslashes or you could try replacing them with %2F which is the URL encoded version of forward slash.
Hope this helps.

A: You can do URLSafebase64 encoding at the client side and URLSafebase64 decoding at the server side.
Check URLEncoder class for more details:
http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html
You can test manually before coding using any of the online URL Encoder/Decoder. Just google for "URL Encoder/Decoder"

A: Base64 the URL then on the receiving end base64 decode to get the original URL without any alteration


text:
Q: How to hide header and search component in other component using navigation? Current Code:
I have two components (app-header,app-search), both components integrated in app.component.html like below.
<app-header></app-header><app-search></app-search>

and I am using navigation to go to other component like user:app-user.
Problem:
Issue is i tried to hide the header and search components like using below code
in user.component.ts:
show: boolean = false;

and user.component.html code written given below

<app-header></app-header><app-search></app-search>

But header and search components showing, Kindly help me to hide the search and header components when using navigation to user?

A: You can achieve solution this way.
Create service, which has a BehaviorSubject<boolean> property with initial value as true, BehaviorSubject is choosen because it emits the default value when the BehaviorSubject is subscribed for the first time.
@Injectable()
export class HeaderService {
 private showOrHideHeader = new BehaviorSubject<boolean>(true); // First
 subscription value will be true.
 // This method returns a BehaviorSubject that you can subscribe to, or emit new value from.
 getHeaderFlag() {
  return this.showOrHideHeader;
 }
}

Inject HeaderService in AppComponent. and subscribe to showOrHideHeader BehaviorSubject in ngOnInit. You can get the showOrHideHeader by calling this.headerService.getHeaderFlag()
@Component({
 selector: 'my-app',
 template:`<div *ngIf="show"> <app-header></app-header> <app-search> </app-search></div>,`
providers: [HeaderService]
})
export class AppComponent implements OnInit {
 private show: boolean = true;
 constructor(private headerService : HeaderService ) { }

 ngOnInit(): void {
   this.headerService.getHeaderFlag().subscribe((flag)=>{
   this.show = flag;
 });
}
}

In UserComponent, Inject the HeaderService and do .next(false) on the showOrHideHeader BehaviorSubject which is returned from the headerService.getHeaderFlag() method.
@Component({
selector: 'app-user',
template: `<div> User </div>`,
providers: [HeaderService]
})
export class UserComponent implements OnInit {
 constructor(private headerService : HeaderService ) { }

 ngOnInit(): void {
  let headerFlagSubj = this.headerService.getHeaderFlag();
  headerFlagSubj.next(false);
 }
}

You can provide HeaderService in AppModule so you dont have to provide HeaderService in these two components.

A: Problem is app-header and app-search are in app-component.html.
You are not specifying condition in AppComponent to whether or not to show app-header and app-search in app-component.html.
One thing you can do is, use a flag in app-component.html, like below.

<app-header></app-header><app-search></app-search>

You can set this show flag using any of the following methods.

*

*You can use @Output event bindings to emit false when the UserComponent is loaded. You can do emit on ngOnInit() method of UserComponent. Then use this emitted value in AppComponent to set the show flag.

*You can use the Router in AppComponent.ts. when the page navigates to "UserComponent", you can set show to false (In AppComponent.ts).

*You can use a service to do it. Create a service. Inject in AppComponent and in UserComponent.
create Subject in the service
let $showOrHideAppHEader = new Subject<boolean>().
In AppComponent, Subscribe to $showOrHideAppHEader Subject in in constructor or in ngOnInit.
this.$showOrHideAppHEader.subscribe((flag) => {
this.show = flag;
});
And when the UserComponent is loaded do $showOrHideAppHEader.next(false).


text:
Q: Responsive design for display:none Any help with this would be greatly appreciated, I cant work it out.
I have a list of information contained within seperate div
On page load only the title of each div is showing.

Title

#

Tel: #

#

copy: ipsum blah

Blah Blah

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}

onclick toggles the visibility of the content. So far so good.
Say now I start to add some simple responsive design. If on small screen I want one column of div, no problem. If slightly wider I make a media query to adjust the width of the div accordingly.
Say I have 2 columns. If I onclick to toggle visibility it of course still shows the content in the 4 column responsive layout. But I want the unhidden content to now revert to full width (might be lot of content, and looks strange to extend down only half a column).  So essentially I need the onclick toggle visibility div to always be full screen width.
Can I do this in css? I've tried styling the 'revealed' div but no joy.
Any pointers would be most welcome???!!!! Im sure its easy but Ive tried everything and Im still learning all this!

A: I recommend avoiding using JavaScript to change style directly whenever possible.  Classes are better for this, and they let you do things like customize the styling via media queries, as well as animating content changes.
First, change your HTML to use a class rather than a hard style:

Next, change your JS to toggle the class, rather than change the style directly:
function toggle_visibility(id) {
   var e = document.getElementById(id);
  // Note: classList is IE10+, so you might have to do more work
  // to support older browsers
   e.classList.toggle('visible');
}

Finally, use CSS to handle the magic:
.listing-item {
    display: none;
}
.listing-item.visible {
    display: block;
}

@media (...) {
    .listing-item.visible {
        ...
    }
}

If you want to get fancy, try some CSS3 styling:
.listing-item {
    overflow: hidden;
    max-height: 0;
    transition: all 0.2s ease-in-out;
}
.listing-item.visible {
    // pick something reasonable here, to make sure your
    // content is visible.  Too high, and the animation will be off.
    max-height: 999px;
    overflow: visible;
}


text:
Q: Deserializing an existential data type I need to write a Serialize instance for the following data type:
data AnyNode = forall n . (Typeable n, Serialize n) => AnyNode n

Serializing this is no problem, but I can't implement deserialization, since the compiler has no way to resolve the specific instance of Serialize n, since the n is isolated from the outer scope.
There's been a related discussion in 2006. I am now wondering whether any sort of solution or a workaround has arrived today.

A: You just tag the type when you serialize, and use a dictionary to untag the type when you deserialize. Here's some pseudocode omitting error checking etc:
serialAnyNode (AnyNode x) = serialize (typeOf n, serialize x)

deserialAnyNode s = case deserialize s of
          (typ,bs) -> case typ of
                         "String" -> AnyNode (deserialize bs :: String)
                         "Int" -> AnyNode (deserialize bs :: Int)
                         ....

Note that you can only deserialize a closed universe of types with your function. With some extra work, you can also deserialize derived types like tuples, maybes and eithers.
But if I were to declare an entirely new type "Gotcha" deriving Typeable and Serialize, deserialAnyNode of course couldn't deal with it without extension.

A: You need to have some kind of centralised "registry" of deserialization functions so you can dispatch on the actual type (extracted from the Typeable information).  If all types you want to deserialize are in the same module this is pretty easy to set up.  If they are in multiple modules you need to have one module that has the mapping.
If your collection of types is more dynamic and not easily available at compile time, you can perhaps use the dynamic linking to gain access to the deserializers.  For each type that you want to deserialize you export a C callable function with a name derived from the Typeable information (you could use TH to generate these).  Then at runtime, when you want to deserialize a type, generate the same name and the use the dynamic linker to get hold of the address of the function and then an FFI wrapper to get a Haskell callable function.  This is a rather involved process, but it can be wrapped up in a library.  No, sorry, I don't have such a library.

A: It's hard to tell what you're asking here, exactly. You can certainly pick a particular type T, deserialize a ByteString to it, and store it in an AnyNode. That doesn't do the user of an AnyNode much good, though -- you still picked T, after all. If it wasn't for the Typeable constraint, the user wouldn't even be able to tell what the type is (so let's get rid of the Typeable constraint because it makes things messier). Maybe what you want is a universal instead of an existential.
Let's split Serialize up into two classes -- call them Read and Show -- and simplify them a bit (so e.g. read can't fail).
So we have
class Show a where show :: a -> String
class Read a where read :: String -> a

We can make an existential container for a Show-able value:
data ShowEx where
  ShowEx :: forall a. Show a => a -> ShowEx
-- non-GADT: data ShowEx = forall a. Show a => ShowEx a

But of course ShowEx is isomorphic to String, so there isn't a whole lot point to this. But note that an existential for Read is has even less point:
data ReadEx where
  ReadEx :: forall a. Read a => a -> ReadEx
-- non-GADT: data ReadEx = forall a. Read a => ReadEx a

When I give you a ReadEx -- i.e. ∃a. Read a *> a -- it means that you have a value of some type, and you don't know what the type is, but you can a String into another value of the same type. But you can't do anything with it! read only produces as, but that doesn't do you any good when you don't know what a is.
What you might want with Read would be a type that lets the caller choose -- i.e., a universal. Something like
newtype ReadUn where
  ReadUn :: (forall a. Read a => a) -> ReadUn
-- non-GADT: newtype ReadUn = ReadUn (forall a. Read a => a)

(Like ReadEx, you could make ShowUn -- i.e. ∀a. Show a => a -- and it would be just as useless.)
Note that ShowEx is essentially the argument to show -- i.e. show :: (∃a. Show a *> a) -> String -- and ReadUn is essentially the return value of read -- i.e. read :: String -> (∀a. Read a => a).
So what are you asking for, an existential or a universal? You can certainly make something like ∀a. (Show a, Read a) => a or ∃a. (Show a, Read a) *> a, but neither does you much good here. The real issue is the quantifier.
(I asked a question a while ago where I talked about some of this in another context.)


text:
Q: Set Selected Value on Dropdown Based on Model Property i have a simple dropdown like :
<%= collection_select("user_cities", "city_id", current_user.cities, :id, :name ) %>

current_user.cities is an array of the user cities. Each city has a field named "is_primary" and only one city has it set as true.
My question is, how can i make the above collection_select(or transform it if needed), so that it picks the selected option, based on City.is_primary ?

A: From the docs:

By default, post.person_id [in your case user_cities.city_id] is the selected option. Specify :selected => value to use a different selection or :selected => nil to leave all options unselected.

Armed with that knowledge we can pass the appropriate option to collection_select:
<%= collection_select "user_cities", "city_id", current_user.cities, :id, :name,
      :selected => current_user.cities.detect(&:is_primary).id
%>

A: collection_select("user_cities", "city_id", current_user.cities, :id, :name,{:selected => current_user.cities.where(:is_primary => 1)})

A: I would start by defining a method called primary_city in your User model.
def primary_city
  cities.where(:is_primary => true).first
end

Then,
<%= collection_select("user_cities", "city_id", current_user.cities, :id, :name, { :selected=> current_user.primary_city.id } ) %>


text:
Q: replace character '@' in java android i want to replace character '@' and '.' to '_' from my string . I can replace char '.' to '_' but cant replace char '@' .
public String getemailparsing(String email){
        String result="";
        char keong = 64;
        for(int i=0; i<email.length();i++){
            if(email.charAt(i) == '@' ){
                result = email.replace('@', '_'); //this is NOT working
            }else if(email.charAt(i) == '.'){
                result = email.replace('.', '_'); //this one is working
            }
        }
        return result;
    }

any idea to replace char '@' ...

A: public String getEmailParsing(String email){
    return email.replaceAll("[@.]+","_");
}

A: Apply the little change as shown in below code. And you will get your desired output.
public String getemailparsing(String email) {
        String result = email;

        if (email.contains("@")) {
            result = result.replace('@', '_');
        }
        if (email.contains(".")) {
            result = result.replace('.', '_');
        }
        return result;
    }


text:
Q: How override input CSS styles for ng2-date-picker I am trying to style the Angular2 ng2-date-picker (link) component and would appreciate any guidance.
I cannot find any documents regarding the styling of this component online, and there is only one similar question on stackoverflow, which does not help me much.
I would like to style the actual `<input >` element inline with the below CSS:

.af-input {
    font-size: 20px;
    font-weight: normal;
    font-stretch: normal;
    font-style: normal;
    letter-spacing: normal;
    border-radius: 15px;
    border: solid 1px $af-brownish-grey;
    background-color: transparent;
    color: $af-brownish-grey;
  }

This is my setup in my HTML/View:

    <dp-date-picker theme="dp-material" [(ngModel)]="selectedDate" mode='daytime' [config]='config'></dp-date-picker>

These are the CSS attributes I see when inspecting the element in the browser:
dp-date-picker.dp-material .dp-picker-input {
    box-sizing: border-box;
    height: 30px;
    width: 213px;
    font-size: 13px;
    outline: 0;
}

button, input {
    overflow: visible;
}
button, input, optgroup, select, textarea {
    margin: 0;
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
}

This is the HTML code when inspecting the ng-date-picker element:

    <dp-date-picker _ngcontent-oyd-c55="" theme="dp-material" mode="daytime" ng-reflect-theme="dp-material"
        ng-reflect-mode="daytime" ng-reflect-config="[object Object]" class="dp-material ng-valid ng-dirty ng-touched"
        ng-reflect-model="Fri Jun 19 2020 13:50:18 GMT+0">

<input type="text" class="dp-picker-input ng-pristine ng-valid ng-touched"
                    ng-reflect-is-disabled="false" ng-reflect-model="2020-06-19" placeholder="">

    </dp-date-picker>

Thank you in advance!

A: It doesn't seem like this component allows configurations styling-wise.
You'll need to manually override existing styling with css. Just inspect the element and find the required selectors you want to override.
As this is an external component, make sure to wrap your styles with ::ng-deep { ... }, so that your styles get placed at the top of the DOM tree and can override initial styling.

A: As per Berk Kurkcuoglu's answer, I solved my styling challenge using ::ng-deep { ... }.
This is my specific implementation to style the <input >:
.date-picker {
    ::ng-deep {
        input {
            &:last-child {
                font-family: $af-default-font;
                font-size: 20px;
                font-weight: normal;
                font-stretch: normal;
                font-style: normal;
                letter-spacing: normal;
                border-radius: 15px;
                border: solid 1px $af-brownish-grey;
                background-color: transparent;
                color: $af-brownish-grey;
            }
        }
    }
}

*See also this answer for more details.
I hope this helps someone else!


text:
Q: how to incorporate a set of standard utility directives into an angular module Let's say we have a few dozen "general purpose" utilities in the form of angular directives, like this one for ignoring typed characters other than 0-9.
How do we set up a file containing those directives so that it would be easy to include them in any angular module, and how do we include them?
Do we just create a  module Foo to hold these directives
     var FOO = angular.module('Foo', []);
     FOO.directive('stripExcessWhiteSpace', function() {
        return {
           <snip>
         }
     });

and then include that module in our current app?  Does the name of that file have to be Foo.js and does the file have to be in the same folder the file for our current app is found in?
     var app = angular.Module('Customers', ['Foo']);

or is there more to it?

A: Yes, you create a module for it. And you place the code of the directives in a JS file that will have to be included in the HTML file of the application like any other JS file. The JS file name doesn't have any importance. What matters is the name of the module.
Since this module is supposed to be reusable, you should choose a name that has a very low chance of conflicting with a module that an app might have already chosen (like 'controllers' or 'services'). Prefixing the module name with a string that identifies yourself or your company is a good idea:
angular.module('myCompany.utils')


text:
Q: WPF - Vertical scroll bar of list view does not let scroll through individual items I have a listview inside a stackpanel. There is a vertical scroll bar in it. It is visible too. The issue is that when it is scrolled , it does not scroll through the individual items of the listview. Scrolling through set of items by set of items is possible.
       <stackpanel>

             <ListView  ScrollViewer.VerticalScrollBarVisibility="Visible"
                       ScrollViewer.CanContentScroll="True">

                   <GridView>

                       ..................
                   </GridView>

             </ListView>

       </stackpanel>

I found some answer somewhere and it said this happens since the listview is there inside a stackpanel. Is there a solution to this ? If it can be done, without removing the stackpanel then that would be great.

A: I set the property ScrollViewer.CanContentScroll to False and it worked.
       ScrollViewer.CanContentScroll="False"


text:
Q: How to right-align widgets in panel in Kubuntu 11.10? First, please take a look at this screenshot:

The problem is...

*

*It all happened before I realized what I did. So, I don't know how I messed it up. :(

*Do you see the panel at the bottom? The 'Time', 'System Tray', and 'Show the Desktop' widgets which are supposed to be aligned right in the panel, are aligned left. Selecting "Panel Tool Box > More Settings >  Panel Alignment > Right" changes nothing.

*Also, the application switcher in the panel (that allows me to switch between various open apps in a workspace - - like in Windows) is missing.

There should probably be a way to reset it all. I would like to know that, and... I would also like to know how I can manually rearrange things back to default, so that I know how it actually works.

A: KDE Plasma desktop
The KDE panel and the widgets are plasmoids or plasma widgets. More of the KDE plasma: http://userbase.kde.org/Plasma .
How to manage the KDE plasma panel: http://userbase.kde.org/Plasma/Panels .
Probably
Probably you have removed the "Task Manager". More : http://userbase.kde.org/Plasma/Tasks

You could add it back (KDE userbase):

To place a widget in the panel first open the Panel Toolbox and from
  there open the Widget Explorer (click Add Widgets), locate the widget
  you wish to add and drag it to the desired position in the Panel.

You could move plasmoids: Open the Panel Toolbox and move mouse cursor over the widget. The cursor should change to the "compas rose". Move the widget to the right place.
Same from the KDE userbase:

The panel can then be configured by clicking on the toolbox located on
  the right for horizontal or bottom for vertical panel. At that point,
  the panel will be in configuration mode. Panel configuration may also
  be accessed via the context (right click) menu in the panel.
Widgets in the panel can be sorted by dragging them when in
  configuration mode.

New default panel (KDE userbase):

To add a new panel either click on the desktop toolbox button and
  select Add Panel or open the context (right click) menu on the desktop
  and select Add Panel from the menu.
If more than one kind of Panel is installed, you will be able to
  select between them to choose what sort of Panel you would prefer. By
  default, two Panel types are available: Default Panel, which creates a
  Panel containing all of the default widgets (launcher, pager, tasks,
  system tray, clock, etc.), and Blank Panel, which adds an empty Panel
  without any pre-configured widgets in it.


text:
Q: I've written a simple JS program for Age Calculator If in the JavaScript, we write program today = new Date("2022 03 01") and we put input "2022 02 28" in the input column, the result comes out as 4 days instead of 1 day. Can someone help me with this one particular case?

function calculateAge() {
  let bdate = document.querySelector("#Isdate").value
  let bmonth = document.querySelector("#Ismonth").value
  let byear = document.querySelector("#Isyear").value

  let validate = validateInput(bdate, bmonth, byear)

  if (validate) {
    let today = new Date()
    let tdate = today.getDate()
    let tmonth = today.getMonth() + 1
    let tyear = today.getFullYear()

    // console.log(tyear)
    // let tdate = 01
    // let tmonth = 03
    // let tyear = 2022

    let BirthYear = tyear - byear
    let BirthMonth
    let BirthDate

    if (tmonth >= bmonth) {
      BirthMonth = tmonth - bmonth
    } else {
      BirthMonth = 12 - (bmonth - tmonth)
      BirthYear--
    }

    if (tdate >= bdate) {
      BirthDate = tdate - bdate
    } else {
      BirthMonth--
      BirthDate = 31 - (bdate - tdate)

      // case where a BirthMonth can go negative
      if (BirthMonth < 0) {
        BirthYear--
        BirthMonth = 11
      }
    }

    if (BirthYear < 0) {
      document.querySelector("#output-result").innerHTML = "Date of birth needs to be earlier than Current date"
    } else {
      document.querySelector("#output-result").innerHTML = `Your Age Is ${BirthYear} Years, ${BirthMonth} Months & ${BirthDate} Days`
    }
  }
}

function validateInput(bdate, bmonth, byear) {

  if (!bdate) {
    document.querySelector("#output-result").innerHTML = "Please provide a date"
    return false;
  }
  if (!bmonth) {
    document.querySelector("#output-result").innerHTML = "Please provide a Month"
    return false;
  }
  if (!byear) {
    document.querySelector("#output-result").innerHTML = "Please provide a Year"
    return false;
  }

  if (parseInt(bmonth) > 12) {
    document.querySelector("#output-result").innerHTML = "Please provide Month value in the range from 1 to 12"
    return false;
  }

  if (byear.length < 4) {
    document.querySelector("#output-result").innerHTML = "Provide year in format YYYY"
    return false;
  }

  if (parseInt(bdate) <= 0) {
    document.querySelector("#output-result").innerHTML = "Date cannot be 0 or less than 0"
    return false;
  }
  if (parseInt(bmonth) <= 0) {
    document.querySelector("#output-result").innerHTML = "Month cannot be 0 or less than 0"
    return false;
  }
  if (parseInt(byear) <= 0) {
    document.querySelector("#output-result").innerHTML = "Year cannot be 0 or less than 0"
    return false;
  }

  if (isNaN(bdate)) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date"
    return false;
  }
  if (isNaN(bmonth)) {
    document.querySelector("#output-result").innerHTML = "Please provide valid month"
    return false;
  }
  if (isNaN(byear)) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Year"
    return false;
  }

  if (parseInt(bdate) > 31 && parseInt(bmonth) == 1) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 28 && parseInt(bmonth) == 2) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 3) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 4) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 5) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 6) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 7) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 8) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 9) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 10) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 30 && parseInt(bmonth) == 11) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }
  if (parseInt(bdate) > 31 && parseInt(bmonth) == 12) {
    document.querySelector("#output-result").innerHTML = "Please provide valid Date with respect to Month"
    return false;
  }

  return true;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  background: linear-gradient(103.71deg, rgba(97, 192, 191, 0.28) 5.64%, rgba(255, 182, 185, 0.46) 45.19%, #FAE3D9 86.43%);
  height: 100vh;
  width: 100%;
  padding-top: 5rem;
}

.container .heading>h1 {
  font-family: 'Sen', sans-serif;
  font-weight: 400;
  font-size: 96px;
  line-height: 115.5px;
  text-align: center;
  text-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
  text-transform: capitalize;
}

span {
  font-family: 'Sen', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 36px;
  line-height: 43px;
  text-align: center;
  text-transform: capitalize;
}

input {
  width: 180px;
  height: 43px;
  border: none;
  outline: none;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.25);
  padding: 20px;
  font-size: 20px;
}

.input-info {
  display: flex;
  gap: 125px;
  justify-content: center;
  margin-top: 7rem;
}

.date,
.month,
.year {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 3rem;
}

.submit {
  text-align: center;
  margin-top: 6rem;
}

.submit button {
  width: 275px;
  height: 56px;
  background: rgba(60, 160, 255, 0.84);
  font-family: 'Sen';
  font-style: normal;
  font-weight: 400;
  font-size: 40px;
  color: #FFFFFF;
  border: none;
  outline: none;
  letter-spacing: 0.09em;
  text-transform: capitalize;
  cursor: pointer;
}

.output {
  text-align: center;
  margin-top: 6rem;
  font-family: 'Sen';
  font-style: normal;
  font-weight: 400;
  font-size: 32px;
  color: #20B2AA;
  line-height: 29px;
  text-transform: capitalize;
  letter-spacing: 0.09em;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sen:wght@400;700;800&display=swap" rel="stylesheet">

age calculator

      Date(DD)
      <input type="text" id="Isdate">

      Month(MM)
      <input type="text" id="Ismonth" name="" id="">

      Year (YYYY)
      <input type="text" id="Isyear" name="" id="">

    <button type="submit" onclick="calculateAge()">Submit</button>

I want you to check whether the code that I've written is correct or wrong. My senior told me that this part can be written differently:
if (tdate >= bdate) {
            BirthDate = tdate - bdate
        } else{
            BirthMonth--
            BirthDate = 31 - (bdate - tdate)

A: The javascript date object contains everything you need without you  having to account for months with different days and leap years. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
At the heart of every date object is a numerical value representing the number of milliseconds since January 1, 1970, UTC (and agreed datum).
When you create a data object with a date string, the underlying epoch time string is referenced using the getTime() method of the date object:

today = new Date("2022 03 01");
console.log(today.getTime());

The sure and simple way to calculate the number of days between two date strings is to construct theirDate objects, subtract their underlying epoch times from each other, and divide the resulting milliseconds value by the number of milliseconds in a day:

const today = new Date("2022 03 01");
const birthDate = new Date("2022 02 28");
const milliSecPerDay= 1000*60*60*24;

let elapsedDays = (today-birthDate)/milliSecPerDay;

console.log(`elapsed days = ${elapsedDays}`);

A: There are several ways to write a routine to calculate age.  Some are more elegant than others.  I wrote a javascript that I use anytime I need to display an age broken down by years, months, days.
The basic logic is to use math to determine the number of years and months... this is achieved by knowing how many milliseconds (ms) are in a year and month.  The code you see here accounts for leap year where each year = 365.25 days
The craziness occurs whenever trying to determine the days because of the different amount of days in each month including leap year has an extra day in february.  The idea here is to create a date to substract from and let the javascript determine if there was a leap year and how many days in the month, etc..

calcAge = (nMonth, nDay, nYear) =>{
  let dtBirth = new Date(nYear, nMonth - 1, nDay);
  let dtNow = new Date();

  if(dtBirth > dtNow) return "Only a terminator can be born in the future";

  let msYear = 31557600000; // milliseconds in a year (365.25 days)
  let msMonth = msYear / 12; // milliseconds in a month
  let msDay = 86400000; // milliseconds in a day

  let nYears = Math.floor((dtNow - dtBirth) / msYear);
  let msRemain = (dtNow - dtBirth) % msYear;
  let nMonths = Math.floor(msRemain / msMonth);

  // determine if needing to adjust month and/or year
  if(dtBirth.getDate() > dtNow.getDate()){
    if(dtNow.getMonth() == 0){
      dtNow.setMonth(11);
      dtNow.setFullYear(dtNow.getFullYear() - 1);
    }
    else
        dtNow.setMonth(dtNow.getMonth() - 1);
  }
  dtNow.setDate(dtBirth.getDate());

  let nDays = Math.floor((new Date() - dtNow) / msDay);

  return `You are ${nYears} ${nYears == 1 ? 'year' : 'years'}, ${nMonths} ${nMonths == 1 ? 'month' : 'months'}, and ${nDays} ${nDays == 1 ? 'day' : 'days'} old`
}

console.log(calcAge(01,08,2011));


text:
Q: How to map user permissions with view in PHP,HTML? I am stuck in a situation while I was designing a CRM in php. I need to design various user groups with various permissions. Now consider a situation;
I have two user groups group1 and group2.
Now users under group1 can see a button called button1 in a html page but users under group2 can't.
Groups will be created by end user and each group permission can be modified later as needed. I mean if end user wants to give permission to group2 users to be able to see the button1 that can be done anytime later.
How can I accommodate this functionality in my existing code in a plugin basis. I mean I don't want to change my existing code much.
For your information I am using the REST API concept that means I am not using any PHP base template engine while rendering view.
Do I need to create a different view for each group?


text:
Q: What goes into the context parameter of YouTubeStandalonePlayer.createVideoIntent (*context*, YTapiKey, videoID)? I'm writing an app, and want the app to play a YouTube video using the YouTube API. What do I put in the context parameter of YouTubeStandalonePlayer.createVideoIntent (context, YTapiKey, videoID)?
The documentation says that the context should be an activity. I've tried MainActivity, and activity_main, and findViewById<>(R.layout.activity_main). None of them works.
the MainActivity.kt file:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intent = YouTubeStandalonePlayer.createVideoIntent(context, YTapiKey, videoID)
        startActivity(intent)
    }
}

the activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context="com.vcsw.explicacao.MainActivity">

    <com.google.android.youtube.player.YouTubePlayerView
            android:id="@+id/youtubePlayerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

I expected that simply placing the name of the activity in the context parameter of the intent YouTubeStandalonePlayer.createVideoIntent(context, YTapiKey, videoID) would work, but it doesn't.

A: Your code is in an activity. To refer to the activity instance, use this keyword for an activity context.


text:
Q: AngularJS bootstrap popover custom directive I have created a directive using bootstrap custom popover. That works taking an input from a user for a group name and it has two buttons for apply that value to model and show that value on tooltip and a button to close the popover.
I am using popover java script events , Problem is that single popover works perfectly but when I open another one this popover not closing itself. Need help in closing other popovers while one is open.
Here is the plnk showing the directive.
Here is the code
var app = angular.module('myApp',[]);
app.directive('customEditPopover', function () {
        return {
            restrict: 'A',
            template: '',
            scope: {
                'myModel': '=',
            },
            link: function (scope, el, attrs) {
                scope.label = attrs.popoverLabel;
                var btnsave = '#' + attrs.popoverSave;
                var btncancel = '#' + attrs.popoverCancel;
                var index = attrs.index;
                $(el).tooltip({
                    title: '' + (scope.myModel == undefined) ? "" : scope.myModel,
                    container: 'body',
                    placement: 'top'
                });
                $(el).popover({
                    trigger: 'click',
                    html: true,
                    content: attrs.popoverHtml,
                    placement: attrs.popoverPlacement,
                    container: 'body'
                })
                .on('inserted.bs.popover', function (e) {
                    bindevents();
                    $('#popovertext' + index).val(scope.myModel);
                }).on('hidden.bs.popover', function () {
                    Unbindevents();
                });
                function bindevents() {
                    $(btnsave).bind('click', function () {
                        var text = $('#popovertext' + index).val();
                        scope.myModel = text;
                        $(el).tooltip('hide')
                       .attr('data-original-title', text)
                       .tooltip('fixTitle')
                        toggle();
                    });
                    $(btncancel).bind('click', function () {
                        toggle();
                    });
                }
                function Unbindevents() {
                    $(btnsave).unbind('click');
                    $(btncancel).unbind('click');
                }
                function toggle() {
                    $(el).popover('hide');
                    $(el).click();
                }

            }
        };
    });
app.controller('MyController',['$scope',function($scope){
  $scope.list=[
    {
      name:'ABC'
    },
     {
      name:'DEF'
    },
     {
      name:'GHI'
    },
     {
      name:'KLM'
    }
    ];

}]);

Need help closing other popover while opening next one.

A: You can close the other popovers when show.bs.popover is triggered as shown below : Updated Plunkr
$(el).popover({
                trigger: 'click',
                html: true,
                content: attrs.popoverHtml,
                placement: attrs.popoverPlacement,
                container: 'body'
            })
             .on('show.bs.popover', function () {
              var siblings = $(el).parent().parent().siblings();
              siblings.each(function (each){
                $(siblings[each]).find('span').popover('hide');
              });
            });

A: IMO, the most modular way would be to use a service to track all opened PopUps.
This gives multiple benefits.

*

*You can extend the service to track different types of popups, allowing you to close all or open all or do whatever you need

*It removes the logic from the controls and directives on keeping track of popups. Thus they can focus on 1 specific thing. You can also run multiple controllers and popups on a page allowing each controller/popup to be a discrete unit of work and not needing to worry about other controllers/popups stomping on their items.
The cons of doing this

*

*As I commented earlier you can use the  angular bootstrap directives  for this. Making your code "cleaner", because all this is done for you. What is not done for you is closing all active popups. You can take the same service approach I have used and just plug it into the ng-bootstrap directives.

*Binding/Unbinding the JQUERY events seems to become unresponsive when you click 8+ times. I do not have an answer for why that is, but the overall idea of using a service to keep track is still a valid one.

You shoudl be able  to cut and paste this code into the plnkr or your dev box and it will work.
// Code goes here
var app = angular.module('myApp',[]);

app.factory('popUpService', function() {
  var activePopups = [];
  // factory function body that constructs shinyNewServiceInstance

  return {
  AddPopup : function(el)
  {
  activePopups.push(el);
  },
  CloseAllPopups : function(closeFunction){
  for (var i = 0; i < activePopups.length; i++)
  {
           closeFunction(activePopups[i])

  }
  }
  }

});
app.directive('customEditPopover',['popUpService', function (popUpService) {
        return {
            restrict: 'A',
            template: '',
            scope: {
                'myModel': '=',
            },
            link: function (scope, el, attrs) {
                scope.label = attrs.popoverLabel;
                var btnsave = '#' + attrs.popoverSave;
                var btncancel = '#' + attrs.popoverCancel;
                var index = attrs.index;
                $(el).tooltip({
                    title: '' + (scope.myModel == undefined) ? "" : scope.myModel,
                    container: 'body',
                    placement: 'top'
                });
                $(el).popover({
                    trigger: 'click',
                    html: true,
                    content: attrs.popoverHtml,
                    placement: attrs.popoverPlacement,
                    container: 'body'
                })
                .on('inserted.bs.popover', function (e) {
                    bindevents();
                    $('#popovertext' + index).val(scope.myModel);
                }).on('hidden.bs.popover', function () {
                    Unbindevents();
                });
                function bindevents() {

                CloseAll();

                popUpService.AddPopup($(el));

                    $(btnsave).bind('click', function () {
                        var text = $('#popovertext' + index).val();
                        scope.myModel = text;
                        $(el).tooltip('hide')
                       .attr('data-original-title', text)
                       .tooltip('fixTitle')
                    closeCurrent();
                    });
                    $(btncancel).bind('click', function () {
                    closeCurrent();
                    });
                }
                function Unbindevents() {
                    $(btnsave).unbind('click');
                    $(btncancel).unbind('click');
                }
                function closeCurrent(){
                   $(el).popover('hide');
                 //   $(el).click();
                }
                function CloseAll() {

                popUpService.CloseAllPopups(function(popup){

                   popup.popover('hide');
                //    popup.click();
              });

            }
        }
        }
    }]);
app.controller('MyController',['$scope',function($scope){
  $scope.list=[
    {
      name:'ABC'
    },
     {
      name:'DEF'
    },
     {
      name:'GHI'
    },
     {
      name:'KLM'
    }
    ];

}]);


text:
Q: React | render html tag in jsx How do render string along with html tag in react. I just want to add redirecting in 10 seconds to next line but I'm getting [object object] instead.
tip={"Please wait!" +
+"Redirecing in 10 seconds..."}

DEMO:
CodeSandbox Link

A: According to the Doc :
Tip should be a string , use \n for line breaks and add whiteSpace: "break-spaces to the style of the Spin:
<Spin tip={"Please wait! \n Redirecing in 10 seconds..."} style={{ whiteSpace: "break-spaces"}}>

ReactDOM.render(
  <antd.Spin tip={"Please wait! \n Redirecing in 10 seconds..."} style={{ whiteSpace: "break-spaces"}}>
    <antd.Alert
      message="Alert message title"
      description="Further details about the context of this alert."
      type="info"
    />
  </antd.Spin>,
  document.getElementById("container")
);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/antd/4.0.2/antd.min.css" />

A: you can try like this:
<Spin tip={
"Loading..."}>

A: You can try add "\n" into the string

A: You should put everything inside a jsx tag without quotes and concatenation, like this:
tip={Please wait!
Redirecing in 10 seconds...}

A: It might be something like <Spin tip={[
, "Loading..."]}>.

A: You can not send HTML tags inside Spin component of ant design spin prop.
It will always consider it a string and will not render the HTML.
I think this helps to prevent unnecessary code into our app.


text:
Q: Password Protect Sqlite in UWP I am using sqlite in my UWP project and I have referenced two dll from NuGet to perform DDL, DML operation on the sqlite tables.

SQLite for Universal App Platform
SQLite.Net-PCL

However, I want to password protect my sqlite file. Any clue on how to protect the sqlilte file with password?
Thanks!

A: Unfortunately there's no password protection available for SQLite in UWP.
One thing you can do is to encrypt the data you store in your DB. There's a good article on MSDN which talks about Data protection. The article also shows how you can encrypt and decrypt your data.
You could maybe write a wrapper around your data access layer which helps to deal with your data encryption needs. This way you could continue to use the SQLite as you are using it right now and let the data access layer to deal with protecting your data.
I've seen some solutions where not all data in SQLite is encrypted, just the sensitive columns. In these cases the columns were marked with some postfix (for example ("_PROTECT"). The data access layers was then coded to check the column names and to protect the data if postfix was found.
There's also an another interesting article on MSDN which talks about securing your UWP apps: Intro to secure Windows app development

A: You have to purchase the source code of Sqlite SEE (SQLite Encryption Extension) and build a SEE-enabled Sqlite library by yourself.
With a SEE-enabled Sqlite, you can encrypted your sqlite db file with a key (password).
The cost of a perpetual source code license for SEE is US $2000. http://www.hwaci.com/sw/sqlite/see.html
Where to download SEE source code. (You need to login before download.)
http://www.sqlite.org/see
How build SEE for UAP 10.0 -
https://www.sqlite.org/see/doc/trunk/www/uap10.wiki


text:
Q: How to force rsyslog ommysql use utf8? I'm using ommysql in rsyslog for transfering data into mysql
$ModLoad ommysql
local6.*        :ommysql:localhost,Syslog,rsyslog,1

but cyrilic data goes like "·Ð¾Ð²Ð°Ð½Ð¸Ðµ иÑ�точнÐ" in database.
I think It's because ommysql doesn't set utf8 encoding and starts inserting at once it's connected: http://s017.radikal.ru/i441/1606/e0/050cf30c495f.png
Is it any way to say «set names utf8;» before inserting?

A: That should have said something like ование, correct?
When trying to use utf8/utf8mb4, if you see Mojibake, check the following.
This discussion applies to Double Encoding, which is not necessarily visible.

*

*The bytes to be stored need to be utf8-encoded.

*The connection when INSERTing and SELECTing text needs to specify utf8 or utf8mb4.

*The column needs to be declared CHARACTER SET utf8 (or utf8mb4).

*HTML should start with <meta charset=UTF-8>.


text:
Q: AngularJs, $http Interceptor and $interval I think I am using Interceptors incorrectly in AngularJS. I want to use them to change a specific value in the response to a $interval so that it increments in the UI.
The idea was to use an Interceptor to hijack the response and insert the $interval into the response before it reached the template. Nice idea but it doesn't work.
First issue is that I get errors when trying to reassign a property in the response.
The second is that the Interceptor seems to be called for all requests, this isn't ideal as its only specific responses I need to change. This leads me to believe that Interceptors are for authentication and things that are needed for all requests.
Bearing all this in mind I now know that Interceptors are not the way to go.
How else should I solve this issue of needing to add in an $interval for certain values in a response? There a few places that this needs to be done so I want to avoid having insert the $interval each time.
EDIT
The two answers so far are great, now I have this which works and the values are right now they are reassigned, but the $interval is not working. There are no errors, but my live value is not increasing each second. Any more help would be great.
I am not entirely sure that this is the right place for the the forEach either when iterating over response.data. Could that be causing me issues with my $interval?
var shepServices = angular.module('shepServices', ['ngResource']);

shepServices.factory('SiloInterceptor', function($q, $interval) {
    return {
        'response': function(response) {
            if(response.config.url.endsWith('/silos')) {
                angular.forEach(response.data, function (value, key) {
                    $interval(function () {
                      response.data[key].live = response.data[key].live * 2;
                    }, 1000);
                });
            }

            return response;
        }
    };
});

EDIT 2
My data looks like this in response.data
0:
     quantity: 767.5
1:
     quantity: 77.5
2:
     quantity: 80

I want to add a new element to this array which is an $interval, so it ends up like so;
0:
     quantity: 767.5
     live: //increment $interval value here
1:
     quantity: 77.5
     live: //increment $interval value here
2:
     quantity: 80
     live: //increment $interval value here

The $interval is firing as I can see output from console.log, but its not registering in the response and incrementing he value shown in the UI. The response array is bound to the $scope as asilos. So I want to do this in my template and have the silo.live value increment every second.

{{silo.live | number}}

EDIT 3
This is how I am injecting the Interceptor, its not using the classic $http object, but is via a $resource in a Service.
shepServices.factory('Silo', ['$resource', 'SiloInterceptor',
    function($resource, SiloInterceptor) {
        return $resource("/silos", {word: "@word"}, {
            'query': {
                url:        "/silos",
                isArray:    true
            },
            'forLocation': {
                interceptor: SiloInterceptor,
                url:        "/silos",
                params:     {location: "@location_id"},
                isArray:    true
            },
        })
    }]);

A: Filter out the requests you want in the response handler the way it is done in response function of responseInterceptor.
module.factory('myInterceptor', ['$q', 'someAsyncService', function($q, someAsyncService) {
    var responseInterceptor = {
        response: function(response) {
            if(response.config.url.startsWith('/api/')) {
              //Do your custom processing here
           }
            var deferred = $q.defer();
            someAsyncService.doAsyncOperation().then(function() {
                // Asynchronous operation succeeded, modify response accordingly
                ...
                deferred.resolve(response);
            }, function() {
                // Asynchronous operation failed, modify response accordingly
                ...
                deferred.resolve(response);
            });
            return deferred.promise;
        }
    };

    return responseInterceptor;
}]);

A: You can fully modify the response in the interceptor. In this fiddle, I intercept the response of a user API to inject your name. Unless you post code, we can't tell you what's wrong in your interceptor.
Code of the interceptor:
app.factory('myHttpInterceptor', function () {
   return {
    'response': function(response) {
      response.data[0].name = 'Jake N (modified by interceptor)';
      return response;
    }
   }
});

Regarding the second issue, you could use the config object so as to modify the response only if it match a url pattern (or using a different condition). Here I modify the http response only if the url contains 'users':
app.factory('myHttpInterceptor', function () {
   return {
    'response': function(response) {
      if (response.config.url.indexOf('users') > -1) {
          response.data[0].name = 'Jake N (modified by interceptor)';
      }
      return response;
    }
   }
});

See updated fiddle


text:
Q: How to set first table column as bold (CSS) I am a little rusty on CSS.
Problem 1: I'm trying to make the example table below. I want only the first column to always be in bold. Can anyone help me to get the td first-child argument to work?
Status: Solved... I had rows and columns mixed... pretty stupid error that passed my attention. - Thanks Ovokuro
Problem2: I have corrected the code  (in the snippet) but it doesn't seem to work on IE or Chrome. Can anyone tell why? Looks good to me and works on the online sim, but not when I save it in an html doc. First column doesnt show as Bold; and column width is off..
PS.: Can't add the styles in tags along the document as the rows will be created progamatically.
Please let's try to keep the code simple.

table {
  font-size: 16px;
  font-family: Optimum, Helvetica, sans-serif;
  border-collapse:collapse
}
tr {
    border-bottom: 1px solid #A9A9A9;
}
td {
  padding: 4px;
  margin: 3px;
  padding-left: 20px;
  width: 75%;
  text-align: justify;
}

th {
  background-color: #A9A9A9;
  color: #FFF;
  font-weight: bold;
  font-size: 28px;
  text-align: center;
}

td:first-child {
  font-weight: bold;
  width: 25%;
  text-align: left;
}

      Sample

Line 1	Text

Line 2	Text

A: Just add first-child next to td so it looks like this:
td:first-child {
  font-weight: bold;
}

Also if you want to add a table class before (just for namespacing):
.table1 td:first-child{
  font-weight:bold;
}

A: Target td:first-child instead of tr:first-child
Also, CSS declarations are terminated with ;. The
 element is used in HTML to produce a line break in text.
Also note that td will always be a child of tr, so you don't need to declare tr td:first-child in this case. Similarly, tr is a child of table so you don't need table either.

table {
  font-size: 12px;
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
}

td {
  padding: 4px;
  margin: 3px;
  border: 1px solid #CCC;
}

th {
  background-color: #104E8B;
  color: #FFF;
  font-weight: bold;
}

td:first-child {
  font-weight: bold
}

      Sample Table

      1st Column
      Text

A: Simple. Exist many ways to do that. One way is Applying direct styles in the tag. I mean open a style="" property in the  tag. will looks like:

A: Problem with Brownser Compatibility perhaps. It is working fine on Chrome.


text:
Q: Prevent Visual Studio Code from replacing tabs with spaces on save My problem is not present while editing a file, like here: Spaces to tabs in Visual Studio Code
VSC converts all tabs to spaces when I save the file. How could I stop that stupid behavior?
This are my actual user settings:
{
    "editor.insertSpaces": false,
    "editor.detectIndentation": false
}

Further informations:
 "editor.formatOnSave": false

A: Wish I understood more about what's happening here, but in my case, what finally worked (for now) was unchecking "Editor: Insert Spaces" in my user prefs. Without this, disabling Save on Format didn't seem to help. ¯\_(ツ)_/¯

A: I had an extension which overrides the default behaviour:
https://marketplace.visualstudio.com/items?itemName=lonefy.vscode-JS-CSS-HTML-formatter


text:
Q: problem current value not showing slider range html/javascript Why is my value not showing when I slide HTML JS? I want the value of the slider to show in the h3 class number.

function rangeSlider(value) {
  document.getElementsByClassName("agenumber").innerText = value;
}

Select your age

<input type="range" min="6" max="60" step="1" value="50" class="slider" onmousemove="rangeSlider(this.value)" onchange="rangeSlider(this.value)">


text:
Q: TypeError: Cannot read property 'trim' of undefined in ReactJS code returns a error TypeError: Cannot read property 'trim' of undefined,
const [category, setCategory] = useState();

const classes = useStyles();
const [fields, setFields] = useState([''
]);

const onChangeHandler = (e, i) => {
    const { name , value } = e.target
    const currentFields = [...fields];
    currentFields[i] = value;
    setFields(currentFields)
}

//Validators

const [errors, setErrors] = useState ('');

const onSubmit = (e) => {
    e.preventDefault()
    let errors = {};
    if (!category.trim()){
        errors.category="Select Type of Category is Required"
    }
    if (!fields.trim()){
        errors.fields="Field is Required/Remove empty Fields"
    }
    setErrors(errors)
    if (Object.keys(errors).length === 0){
        formSubmit()
    }
}

A: From what I can see, your category state initial value is undefined.
const [category, setCategory] = useState();

You should provide a valid string value for it.
const [category, setCategory] = useState("");

The alternative is to use null-checks
if (category && !category.trim()){
  errors.category="Select Type of Category is Required"
}

Or Optional Chaining
if (!category?.trim()){
  errors.category="Select Type of Category is Required"
}

Note: Any other time you are updating the category state you should also ensure the state invariant is maintained, i.e. it should likely always be a string, or apply the same alternative checks when accessing that state.


text:
Q: Call a specific button onClick event when the enter key is pressed C# I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.
The other factor to be taken into account is that the button is within a asp:Login control template.
I've no idea how to do this, suggestions on a postcard please.

A: You could look at the DefaultButton property of the panel control.

A: You could set the DefaultButton property on the form. Either as an attribute of the form tag in your markup DefaultButton = "btnSubmit" or using something like this in your code-behind:
Page.Form.DefaultButton = "btnSubmit"

A: Its HtmlForm.DefaultButton

A: You need to do it with javascript. It's really easy with jQuery.
You can do something like (off the top of my head, not tested):
$('#myTextBox').keypress(function(e){
    if(e.which == 13)
        $('#myBtn').click();
});

Edit: Be aware that although jQuery works exceptionally cross browser, there are some quirks with keypress described here.
Whoops i didnt see you said the "enter key" i thought you said "any key", yeah in that case use DefaultButton on asp:panel


text:
Q: Unexpected multithreaded result and timing I wrote a simple server. When do I run this server and then immediately open 3 tabs in browser with uri localhost:7777 I expect thread by request, in my case it is 3
simultaneously threads (every thread starts at same time and die at about the same time).
But I see in console output that first thread started at 0(local minutes):11(local seconds) then second thread started at 0:11 but stopped(why? it's not independent thread?) at reading loop block
and resumed execution only after awaking(0:16) of first thread
and third thread runs only when the second thread dies(0:21).
I expecting following timing:

Connected with Thread-1 0:11
Connected with Thread-2 0:11
Connected with Thread-3 0:11
Disconnect with Thread-1 0:16
Disconnect with Thread-2 0:16
Disconnect with Thread-3 0:16

What I missed?  Why second thread waits awaking of first thread and third thread starts only after death of second thread?
public class Starter {

    public static void main(String args[]){

    int port = 7777;
        try {

            final ServerSocket socket = new ServerSocket(port);
            new Thread(new ThreadPool(socket)).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class ThreadPool implements Runnable{

protected ServerSocket socket;

public ThreadPool(ServerSocket socket){
    this.socket = socket;
}

@Override
public void run() {

    final ExecutorService executors = Executors.newCachedThreadPool();

    while(true){
        try {
            final Socket acceptedSocket = this.socket.accept();
            //executors.execute(new ThreadWork(acceptedSocket));
            new Thread(new ThreadWork(acceptedSocket)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
}

public class ThreadWork implements Runnable {

protected final Socket clientSocket;

public ThreadWork(Socket clientSocket){
    this.clientSocket = clientSocket;
}

@Override
public void run() {
    try {
        System.out.println("Connected with " + java.lang.Thread.currentThread().getName() + " " + ((System.currentTimeMillis() / 1000*60) % 60) + ":" + ((System.currentTimeMillis() / 1000) % 60));
        System.out.println("   " + clientSocket.toString());

        InputStream sin = clientSocket.getInputStream();
        OutputStream sout = clientSocket.getOutputStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(sin));
        OutputStreamWriter out = new OutputStreamWriter(sout);

        String line =
                "HTTP/1.1 200 OK\n"  +
                        "Date: Thu, 19 Feb 2009 12:27:04 GMT\n"       +
                        "Server: Apache/2.2.3\n"                         +
                        "Last-Modified: Wed, 18 Jun 2003 16:05:58 GMT\n"       +
                        "Content-Type: text/html\n"             +
                        "Content-Length: 115\n"      +
                        "Accept-Ranges: bytes\n"      +
                        "Connection: close\n"  +
                        "\r\n" +
                        "<title>Hello</title>It Works!\n";

        String requestLine;

        System.out.println("      Before reading " + java.lang.Thread.currentThread().getName() + " " + ((System.currentTimeMillis() / 1000*60) % 60) + ":" + ((System.currentTimeMillis() / 1000) % 60));
        while((requestLine = in.readLine()) != null) {
            if(requestLine.isEmpty()){
                break;
            }
        }
        System.out.println("         Asleep " + java.lang.Thread.currentThread().getName());
        java.lang.Thread.sleep(5000);
        System.out.println("         Awake " + java.lang.Thread.currentThread().getName());
        out.write(line);
        out.flush();
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        System.out.println("Disconnect with " + java.lang.Thread.currentThread().getName() + " " + ((System.currentTimeMillis() / 1000*60) % 60) + ":" + ((System.currentTimeMillis() / 1000) % 60));
    }
}
}

Program output

Connected with Thread-1 0:11
   Socket[addr=/0:0:0:0:0:0:0:1,port=45416,localport=7777]
      Before reading Thread-1 0:11
         Asleep Thread-1
Connected with Thread-2 0:11
   Socket[addr=/0:0:0:0:0:0:0:1,port=45419,localport=7777]
      Before reading Thread-2 0:11
         Awake Thread-1
Disconnect with Thread-1 0:16
         Asleep Thread-2
         Awake Thread-2
Disconnect with Thread-2 0:21
Connected with Thread-3 0:21
   Socket[addr=/0:0:0:0:0:0:0:1,port=45424,localport=7777]
      Before reading Thread-3 0:21
         Asleep Thread-3
         Awake Thread-3
Disconnect with Thread-3 0:26

A: As far as I can see, there's nothing wrong with your code. The same thing happens for me, however, so I tried running it myself while monitoring the network traffic with tcpdump, and it seems it's simply the browser playing tricks, not your code.
I'm using Chromium, and it simply doesn't send the second request until the first one is complete, nor does it even connect the third time until then. I'm guessing it's trying to be kind to the server by not overloading it, or something.


text:
Q: jquery 1.5 problem with $.getJSON request to Vimeo I'm trying to make an ajax-request to vimeo to get data from an vimeo video needed for our webapplication.
var vimeoDataUrl = "http://vimeo.com/api/oembed.json?url=http://vimeo.com/" + vimeoId; //+ "&callback=?";
console.log(vimeoDataUrl); //http://vimeo.com/api/oembed.json?url=http://vimeo.com/16630327

$.getJSON(vimeoDataUrl, function (json, textStatus) {
    if (json != null) {
        var title = json.title;
        var videoWidth = json.width;
        var videoHeight = json.height;
        if (title != null && videoWidth != null && videoHeight != null) {

            var vimeoImageUrl = json.thumbnail_url;
            $('#largeImageUrl').val(vimeoImageUrl);
            $('#videoName').val(title);
            $('#videoWidth').val(videoWidth);
            $('#videoHeight').val(videoHeight);
            hasValidVideoUrl = true;
        }
    }
    else
    {
        //an message is shown
    }
    $('#videoName, #placeVideo').removeAttr('disabled');
    $('img#loading').remove();
 });

When I enter the vimeoDataUrl in an browser like IE i'm getting the json result as expected, but as soon as i'm looking at the request in firebug i'm getting an empty response with an 200-status. Can someone help me out here? Is the problem located at vimeo or am I doing something wrong?

A: You cannot make json request to different domains ( JS docs and wikipedia).
You need to use jsonp
If you  un-comment the final part in your url, the &callback=? it works just fine .. because jquery will use jsonp if it finds it in the url.
so use
var vimeoDataUrl = "http://vimeo.com/api/oembed.json?url=http://vimeo.com/" + vimeoId + "&callback=?";

from the getJsondocs

JSONP
If the URL includes the string
  "callback=?" (or similar, as defined
  by the server-side API), the request
  is treated as JSONP instead. See the
  discussion of the jsonp data type in
  $.ajax() for more details.
Additional Notes:

*

*Due to browser security restrictions, most "Ajax" requests are
  subject to the same origin policy; the
  request can not successfully retrieve
  data from a different domain,
  subdomain, or protocol.

*Script and JSONP requests are not subject to the same origin policy
  restrictions.

Demo at http://www.jsfiddle.net/gaby/gQaXD/


text:
Q: TinyMCE editor is stripping my html code in joomla 2.5 I have a problem in my TinyMCE editor in joomla. Every time i make any changes from the editor my html code gets messed up.
I tried using a different editor like (JCE Editor), but the result is the same.
I am new to joomla so if anyone suggest me how to go about in fixing this problem
Thanks

A: I have got a solution for this.
Instead of using TinyMCE editor i switched to JCE Editor and followed these steps
Change the defualt setting of JCE Editor

Once inside the JCE Administration area, click on Default editor profile

Inside the Default editor profile, click on the Editor Parameters tab, and then click on the Advanced tab. Depending on which type of code you d like to save in your articles, you can choose to allow JavaScript, PHP, CSS, and XHTML. Please note that these are disallowed by default because they can be potentially dangerous to your site. It s always best to create a backup of your site before adding code like this. Don t forget to save your work after you make these changes.

Next, go to the Plugin Parameters tab, and then click on the Media Support tab. As illustrated in the screenshot below, you may also choose to display some additional elements. You can click on "Save & Close" in the toolbar when you re done. That s all the configuration that you should have to do through the JCE Editor.

You can test your changes by embedding a YouTube video into an article or Custom HTML module.

A: Under global configuration go to text filtering and set public to no filtering

A: TinyMCE (and most other Editor-Plugins) try to output/save the best possible HTML-code, thats why your HTML gets changed.
Go to "Site" => "Global Configuration" => "Text Filters" and set the appropriate filters. You might want to use a custom Blacklist by editing the 'Filter Tags'- & 'Filter Attributes'-fields. :)
answer for Joomla pre-2.0:
You can find the 'Clean code on save'-option in the settings (go to "Extensions" => "Plugins" => "Editor - TinyMCE" and go through the options on the right side).
Greetings


text:
Q: How do I add logic to a view controller inside of a tab bar controller I have setup a tab bar application with four tabs on the bottom (as set inside IB) Three of them are UIViews and one of them is a UITableView, and the empty shell of an app switches between tabs fine.
Now, being that I have no experience with tab bars, I am not sure where my logic for the view controllers goes. I am used to setting up a ViewController for each view, is that the case in a tab bar? Does each tab need a separately programmed viewcontroller? If not, how can I link my logic to the correct tab's view?
Please help. Thanks!

A: A UITabBarController manages an array of UIViewController objects. These in turn manage the UIViews that are visible to the user.
So yes, you need to create a separate UIViewController for each view that you want the UITabBarController to manage.


text:
Q: Are random numbers generated using a quantum integer as its seed considered pseudo-random or truly random? I always hear that random numbers produced by quantum computers are considered "truly random" while random numbers generated from a classical computer are considered "pseudo-random".
If one were to  generate random numbers using a quantum integer as the seed, would the numbers generated from that seed be considered "pseudo-random" or truly random? Cannot find this clarification anywhere, any explanation welcome.
import random
random.seed(get_my_quantum_number()) #Some quantum integer generated from an API.
random.random() #Is this "pseudo-random" or "truly random" ?

A: random.random() uses a pseudorandom number generator (PRNG), which uses a deterministic algorithm by definition and mathematically expands its input. Thus, the numbers it generates are pseudorandom, even if it was seeded by the output of a quantum random number generator or some other nondeterministic source.
A seed is a value that initializes the PRNG, and the number of possible sequences a PRNG can generate depends on the PRNG's state size and the size of the seed. For example, if the seed or the state is only 32 bits long, at most 232 different pseudorandom number sequences are possible with that PRNG, regardless of where the seed came from.
See also these questions:

*

*Is Random function (in any programming language) biased?

*How to get truly random data, not random data fed into a PRNG seed like CSRNG's do?

In any case, the distinction between "pseudorandom" and "truly random" numbers is not what applications care about (and you didn't really specify what kind of application you have in mind). Instead, in general:

*

*Security applications care whether the numbers are hard to guess; in this case, only a cryptographic RNG can achieve this requirement (even one that relies on a pseudorandom number generator). A Python example is the secrets module or random.SystemRandom.

*Scientific simulations care whether the numbers behave like independent uniform random numbers, and often care whether the numbers are reproducible at a later time. A Python example is numpy.random.Generator.

For example, the pseudorandom number generator used by random.random(), Mersenne Twister, is not suitable for cryptography or information security; the numbers it produces are not designed to be hard to guess, and this is the case no matter how that generator was seeded (whether by a quantum random number generator or otherwise).
By contrast, pseudorandom generators designed for information security often involve cryptographic hash functions, block ciphers, or stream ciphers — especially because one goal is to make future pseudorandom numbers hard to guess, even if the generator's outputs are known.


text:
Q: Using Web Service to authenticate on LDAP Since it' apparently not possible to authenticate with LDAP on my BlackBerry App, I'm trying to use a kind of workaround. Instead of authenticate directly on the LDAP Server, I want to use a Web Service in between. So it looks like this
App --calls--> Web Service --calls--> LDAP Server

So the Web Service should take the username and password given from the Application and send it to the LDAP Server. If its possible to sign in, the Web Service gets a TRUE as response and forward it to the App.
That's how it should work. But at the moment, when I call the Web Service from the App, I get following error:

SoapFault - faultcode: 'S:Server' faultstring:
  'java.lang.NullPointerException' faultactor: 'null' detail:
  org.kxml2.kdom.Node@21e05a11

Seems like a Server problem but I don't know where :(
Well, that's the Web Service I'm using:
import javax.ejb.Stateless;
import javax.jws.WebService;

import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPException;

@Stateless
@WebService()
public class ldapServiceBean implements ldapService {

    @Override
    public String error() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean ldapLogin(String username, String password) {
         int ldapPort = LDAPConnection.DEFAULT_PORT;
         int ldapVersion = LDAPConnection.LDAP_V3;
         String ldapHost = "dc1.somehost ";
         String loginDN =
         "CN="+username+",OU=employee,OU=user,DC=somehost";

         byte[] passwordBytes = password.getBytes();
         LDAPConnection lc = new LDAPConnection();

         try {
             // connect to the server
             lc.connect( ldapHost, ldapPort );

             // authenticate to the server
             lc.bind( ldapVersion, loginDN, passwordBytes );
             System.out.println("Bind successful");

             return true;
         }
         catch( LDAPException e ) {
             if ( e.getResultCode() == LDAPException.NO_SUCH_OBJECT ) {
                 System.err.println( "Error: No such entry" );
             } else if ( e.getResultCode() ==
                 LDAPException.NO_SUCH_ATTRIBUTE ) {
                 System.err.println( "Error: No such attribute" );
             } else {
                 System.err.println( "Error: " + e.toString() );
             }
         }
        return false;
    }

And that's the method calling the Web Service
private static final String SOAP_ACTION = "";
    private static final String METHOD_NAME = "ldapLogin";
    private static final String NAMESPACE = "http://ldapproxy.somehost/";
    private static final String URL = "http://myIP:8080/LDAPProxy/ldapServiceBeanService";

...

public boolean login(String username, String password) {

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //SoapObject
        request.addProperty("username", username);
        request.addProperty("password", password);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        //envelope.dotNet = true;
        //envelope.bodyOut = request;
        envelope.setOutputSoapObject(request);

        HttpTransport httpTransport = new HttpTransport(URL);
        try
        {

            httpTransport.call(SOAP_ACTION, envelope);

            System.out.println("request: " + httpTransport.requestDump);
            resultsRequestSOAP = (SoapObject) envelope.getResponse();

            return true;

        }catch(SoapFault sF){
            String error = sF.toString();
            Dialog.alert(error);
        }
        catch (Exception aE)
        {
            Dialog.alert("Connection failed");
            aE.printStackTrace ();
        }
        return false;

    }

What I found out so far:
It seems that the webservice don't receives the username and password property. As I print them I get:
`CN=null, OU=employee, OU=...`

Like I've read at this post Web service recieves null parameters from application using ksoap method it seems ksoap have a problem with colons. I changed my NAMESPACE but without any success. Maybe I need to change my URL too. But how would I do this while I still need to use localhost ?

A: As always when doing LDAP bind testing this way, recall that the standard requires that a bind of a username, no password, is a successful Anonymous bind, so therefore you MUST validate for this case (empty password) on login attempts.


text:
Q: Angle Between 2 Vectors Restrictions When finding the angle between 2 vectors, why does the angle have to be greater than or equal to 0 and less than or equal to pi(180 degrees)?

A: A vector has only two properties

*

*Magnitude

*Direction

Although directions can be expressed as angles in relation to a standard direction, a direction is not the same thing as an angle.
An angle may have any size and may have positive or negative sign. This is essential when measuring, for example, a rotation.
But the angle between two vectors is defined as the minimum non-negative angle separating their directions. That angle cannot exceed a value of $\pi$ radians or $180^\circ$.


text:
Q: How does backwards write in Jetpack Compose work? We have the official docs showcasing an example of backwards write in Compose:
@Composable
fun BadComposable() {
   var count by remember { mutableStateOf(0) }

   // Causes recomposition on click
    Button(onClick = { count++ }, Modifier.wrapContentSize()) {
        Text("Recompose")
   }
   Text("$count")
   count++ // Backwards write, writing to state after it has been read
}

It's clear to me that updating State object inside a composable like that causes a backwards write.
The stated effect of this backwards write is that we end up with an infinite cycle of recompositions.
However, what's interesting is that the count++ increment action at the bottom of the composable doesn't trigger an infinite cycle of recompositions. Basically, on the first composition of BadComposable, everything seems fine as there are no extra recompositions even though we've updated count at the end of the body of BadComposable.
If, however, you then press on the Button, the count++ increment action inside the onClick callback triggers an infinite cycle of recompositions.
Why do we have to press on the Button to trigger an infinite cycle of recompositions?
I was expecting that it's enough to read a value and update it in the body of the composable to get such an effect.
Jorge Castillo (thank you for your help) has hinted that it may be because the first update of the count state object happens before the initial recomposition scope of BadComposable is registered.
Source for this idea.


text:
Q: Boolean object is not working properly in condition I´m really confused. Maybe anyone can help me?
The problem is the following:
var isSignInside = new Boolean(someCondition);

if (!isSignInside) {
    //doStuff
}
else {
    //doOtherStuff
}

Now, if isSignInside is false (the debugger told me), the script still jumps to //doOtherStuff. How can this be?
The rest of the snippet isn´t of relevance, but I can share it if asked.
Surely there is an easy explanation i don´t see. Thanks in advance.
Edit:
The someCondition really is a custom method "forced" to return a bool instead of (otherwise) a string.
Edit: Just used the function directly in the if. Needed some tricky paranthesis, but works now. Thanks for the hint that a (boolean) object can never be === to a static boolean primitive. Hell this forum is fast.

A: When you create a Boolean object, it's an object. A reference to it, regardless of the boolean primitive value it represents, will always test as truthy just like any other non-null object reference.
There's generally no point in constructing a Boolean instance like that:
var isSignInside = !!someCondition;

That'll give you a boolean primitive that reflects the truthy/falsy state of your condition.

A: if(new Boolean(false)) alert("hehe");

Actually, isSignedInside is not a boolean, but a boolean object (thanks to the new). You may want to get its primitive value for comparison:
if( (new Boolean(false)).valueOf() ) alert("hehe");

Or even easier, take the value directly.

A: Well that's not how that's done. You want to use a boolean primitive. What you're trying to do is done this way:
var isSignInside = (someCondition);
if (isSignInside === false) {
   //doStuff
}
else {
    //doOtherStuff
}

https://jsfiddle.net/catbadger/pxrteq59/


text:
Q: Selecting a metric in training models using caret package in R As far as I know, caret has accuracy and kappa as metrics we can select. How can we train a model using F-1 Score? Let's say we are training a CART model. Any example would be appreciated
I also have imbalanced data (binary class where one class is 10% in the data). I am trying to balance between precision and recall as models tend to predict the other class. Should I consider F-1 score or Kappa or ROC? I thought F-1 score might be a better option...

A: Caret allows you to implement your own performance measures, so you could do it that way. An alternative would be to use the mlr package, which does implement F1 (and many more measures). For example, to find the best values for minsplit and minbucket by F1 score you'd do something like the following.
library(mlr)

ps = makeParamSet(
  makeDiscreteParam("minsplit", values = 1:20),
  makeDiscreteParam("minbucket", values = 1:10)
)
ctrl = makeTuneControlRandom(maxit = 10)
rdesc = makeResampleDesc("CV", iters = 10)
res = tuneParams("classif.rpart", measures = f1, task = sonar.task,
                 resampling = rdesc, par.set = ps, control = ctrl)
print(res$x)
print(res$y)

The mlr tutorial has a whole section on imbalanced classification problems.

A: You are much better off using the ROC curve so that you don't have to worry about the event threshold. For imbalanced data, many metrics that use the default 50% cutoff result in artificially skewed results. In caret, you  can use the twoClassSummary function


text: Q: What are the differences between gRPC AsyncIO and RabbitMQ and when to use them? I want to implement event-driven communication in my microservices architecture. For example, if event A happens, services X and Y would carry out certain things while service Z would do nothing. I am new at gRPC AsyncIO and RabbitMQ, and my research suggests that they could be both suitable for my need. What could be the pros and cons of using gRPC AsyncIO and RabbitMQ? What are the differences and when should I use them?


text:
Q: How can i know my windows 7 product key? I have a Dell inspiron N-4050 laptop. And i am running windows 10 pro on it. I have a product key for it and there was windows 7 genuine with the product key from the manufacturer. But now sticker with the product key on the back faded and no product key is there. I also change the Hard drive long ago. Is there any way i can find my product key for windows-7? Or I can give windows 10 pro product key in exchange with windows 7 pro of ultimate or any. Thank you.

A: In your situation, based on the comments, if you don't have the paperwork, there isn't a way to retrieve the product key.
If the machine had been upgraded, it would be possible to revert to Windows 7, then use a program such as Produkey to get the Licence Key from the system.