text:
Q: What would be some particular benefits to using GhostDocs with C# The whole point of GhostDocs is obviously to document your code. It asks you to name your methods well to do so. With well named methods however, theoritically shouldn't they be useful enough to be considered documentation?
I just want to hear some pros/cons of current users as I don't want to download it and clutter up my code with unnecessary and duplicating documentation.

A: While self-documenting code helps, if it were all you needed nobody would ever consult MSDN (which is, by the way, an expanded, language-merged HTML form of the XML documentation in the .NET libraries themselves).
XML-doc comments allow you to describe classes, methods, parameters, and other members more verbosely than you'd ever want to do with an identifier. You can recommend best practices, discourage incorrect or "hack-y" uses of your code, detail what could go wrong and why, etc etc. This information is available when your source code isn't (if you compile it properly), and is invaluable when your code isn't quite as self-documenting as you think (many things you might think obvious are because you think a certain way, and not everybody will think the same way).


text:
Q: Can you add a specific link to IOS homescreen? I have a vbulletin forum I frequent in which I'd like to place a link to the "new posts" search on my homescreen.  Anyone familiar with vbulletin knows this is a url with search.php?do=getnew , once you access that URL it redirects you to a search ID which is cached for easy access later.  Thing is, you can't add that to your home screen as it wil just pull up the old search results rather than returning the newest posts.  I'd like to add a link to the new posts link on my homescreen but it seems there is no way to edit the homescreen links.

A: Short answer: yes!
I faced the same issue and basically tricked my iPad, you simply turn on airplane mode, you don't hit the redirect, you store the "server not found" page on the home screen and you are done :-)
Hope you can now resolve your 4 year old question.

A: Yes - this works just fine for many web sites.
For example, these two links work very well when saved to the home screen on iOS.

*

*http://apple.stackexchange.com/questions?sort=active

*http://apple.stackexchange.com/questions?sort=newest
Each will reuse an existing window and refresh the content to be sorted as specified (active versus newest) and they also work if you don't already have a "tab" open to this site on Mobile Safari.
Not all websites will allow you to embed these codes, so you might have to shoot off an email to the webmaster asking if they have an URL that will set the proper cookies or yield the desired results. This is the sort of technical thing most web sites will provide for users with the smarts to take advantage of - even if they decide to hide that URL from most of the users that are browsing the site normally.

A: Short answer: No!
There's only one possibility to add a website to homescreen: Tell the user to add it. It's also not possible to change the link for this.
So the user needs to navigate to your search.php and add this page to the homescreen.
Maybe you could write a webapp with dashcode which creates a page for new posts..?

A: I was also wondering how I could create a Safari icon on the home screen of my iPhone with the http://vbulletin-forum/thread-name-new-posts.html URL, which will take me to the latest page in a forum thread.  The problem is when you go to that URL in Safari, it will redirect you to a URL for a specific page in the thread (e.g. http://vbulletin-forum/thread-name-page-number.html).  If you try to add that to your home screen, you are adding the URL for that specific page, not the "new posts" URL.  There is no way to edit the URL for an icon already on the home screen.
But I found a free app called App Icons that lets you create a Safari icon with a URL and put it on your home screen.  After installing the app, do the following:

*

*Touch "Create Icon"

*Under "Common Tasks", touch "Go to Link"

*In the "TYPE URL" field, paste or type in your desired URL

*In the "Go to Link" field, type in a name for the icon

*Touch "Install" and touch "Install" again

*Touch the square icon with the up arrow

*Touch "Add to Home Screen"

*Touch "Add" and a Safari icon with your desired URL will be on your home screen

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exchange mailbox: Send via "Send as" but with use of own name We have the following mailbox:
mail: customerservice@ourcompany.com
Label: Cutomer Service
Two staff members have "Send as" authorization.
When they send an email it appears as "Customer Service
customerservice@ourcompany.com" in our customers mailbox.
We want the follwing:
"Bob Smith customerservice@ourcompany.com" if Bob Smith sends an Email
"Nico Pearson customerservice@ourcompany.com" if Nico Pearson sends an Email
We don't want to use the "Bob Smith on behalf of Customer Service" option.
Is this feasible and how?

A: As I know, it is impossible to achieve that. I found a similar thread, in which @Rubén♦ provided a workaround: delegated account could be added to the delegate mailbox as another email address or alias. Maybe you could check if it could be useful to you.


text:
Q: How to validate a filename in JAVA to resolve CWE ID 73(External Control of File Name or Path) using ESAPI? I am facing this security flaw in my project at multiple places. I don't have any white-list to do a check at every occurrence of this flaw. I want to use ESAPI call to perform a basic blacklist check on the file name. I have read that we can use SafeFile object of ESAPI but cannot figure out how and where.
Below are a few options I came up with, Please let me know which one will work out?
ESAPI.validator().getValidInput() or  ESAPI.validator().getValidFileName()

A: Blacklists are a no-win scenario.  This can only protect you against known threats.  Any code scanning tool you use here will continue to report the vulnerability... because a blacklist is a vulnerability.  See this note from OWASP:

This strategy, also known as "negative" or "blacklist" validation is a
  weak alternative to positive validation. Essentially, if you don't
  expect to see characters such as %3f or JavaScript or similar, reject
  strings containing them. This is a dangerous strategy, because the set
  of possible bad data is potentially infinite. Adopting this strategy
  means that you will have to maintain the list of "known bad"
  characters and patterns forever, and you will by definition have
  incomplete protection.

Also, character encoding and OS makes this a problem too.  Let's say we accept an upload of a *.docx file.  Here's the different corner-cases to consider, and this would be for every application in your portfolio.

*

*Is the accepting application running on a linux platform or an NT platform?  (File separators are \ in Windows and / in linux.)
a.  spaces are also treated differently in file/directory paths across systems.

*Does the application already account for URL-encoding?

*Is the file being sent stored in a database or on the system itself?

*Is the file you're receiving executable or not?  For example, if I rename netcat.exe to foo.docx does your application actually check to see if the file being uploaded contains the magic numbers for an exe file?

*I can go on.  But I won't.  I could write an encyclopedia.

If this is across multiple applications against your company's portfolio it is your ethical duty to state this clearly, and then your company needs to come up with an app/by/app whitelist.
As far as ESAPI is concerned, you would use Validator.getValidInput() with a regex that was an OR of all the files you wanted to reject, ie. in validation.properties you'd do something like: Validator.blackListsAreABadIdea=regex1|regex2|regex3|regex4
Note that the parsing penalty for blacklists is higher too... every input string will have to be run against EVERY regex in your blacklist, which as OWASP points out, can be infinite.
So again, the correct solution is to have every application team in your portfolio construct a whitelist for their application.  If this is really impossible (and I doubt that) then you need to make sure that you've stated the risks cited here clearly to management and you refuse to proceed with the blacklist approach until you have written documentation that the company chooses to accept the risk.  This will protect you from legal liability when the blacklist fails and you're taken to court.
[EDIT]
The method you're looking for was called HTTPUtilites.safeFileUpload() listed here as acceptance criteria but this was most likely never implemented due to the difficulties I posted above.  Blacklists are extremely custom to the application.  The best you'll get is a method HTTPUtilities.getFileUploads() which uses a list defined in ESAPI.properties under the key HttpUtilities.ApprovedUploadExtensions
However, the default version needs to be customized as I doubt you want your users uploading .class files and dll to your system.
Also note:  This solution is a whitelist and NOT a blacklist.

A: The following code snippet works to get past the issue CWE ID 73, if the directory path is static and just the filename is externally controlled :
//'DIRECTORY_PATH' is the directory of the file
//'filename' variable holds the name of the file
//'myFile' variable holds reference to the file object

File dir = new File(DIRECTORY_PATH);
FileFilter fileFilter = new WildcardFileFilter(filename);
File[] files = dir.listFiles(fileFilter);
File myFile = null ;
if(files.length == 1 )
   myFile = files[0];


text:
Q: How to create a databricks job with parameters I'm creating a new job in databricks using the databricks-cli:
databricks jobs create --json-file ./deploy/databricks/config/job.config.json

With the following json:
{
    "name": "Job Name",
    "new_cluster": {
        "spark_version": "4.1.x-scala2.11",
        "node_type_id": "Standard_D3_v2",
        "num_workers": 3,
        "spark_env_vars": {
            "PYSPARK_PYTHON": "/databricks/python3/bin/python3"
        }
    },
    "libraries": [
        {
            "maven": {
                "coordinates": "com.microsoft.sqlserver:mssql-jdbc:6.5.3.jre8-preview"
            }
        }
    ],
    "timeout_seconds": 3600,
    "max_retries": 3,
    "schedule": {
        "quartz_cron_expression": "0 0 22 ? * *",
        "timezone_id": "Israel"
    },
    "notebook_task": {
        "notebook_path": "/notebooks/python_notebook"
    }
}

And I want to add parameters that will be accessible in the notebook via:
dbutils.widgets.text("argument1", "<default value>")
dbutils.widgets.get("argument1")

A: Found the answer after a bit of tweaking, you can simply expand the notebook_task property to include base_parameters as follows:
{
    "notebook_task": {
        "notebook_path": "/social/04_batch_trends",
        "base_parameters": {
            "argument1": "value 1",
            "argument2": "value 2"
        }
    }
}

This is documented in the Create method of the Jobs API. It lists the notebook_task parameter, which can be of the type NotebookTask.


text:
Q: Winform dialog with WPF window as Parent I have a WinForm dialog and I want to set its Parent property to a WPF window.
How can I do this?

A: Consider passing parameter to ShowDialog method instead of using Parent property.
You can write helper class
class Wpf32Window : IWin32Window
{
  public IntPtr Handle { get; private set; }

  public Wpf32Window(Window wpfWindow)
  {
    Handle = new WindowInteropHelper(wpfWindow).Handle;
  }
}

public static class WindowExtensions
{
  public static IWin32Window GetWin32Window (this Window parent)
  {
    return new Wpf32Window(parent);
  }
}

After that you can just write
winFormsWindow.Show(yourWpfWindow.GetWin32Window());


text:
Q: Asp.net paging crashing on chrome I have a timer control on my page and an image handler which is set on every timer refresh. After about two minutes of running my page the page crashes on chrome with the "Aw Snap message". Can anybody help me out ??
JS Code.
    var t
    function set_coordinates_up(event) {
        //Get final co-ordinates
        var pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("divCar").offsetLeft;
        var pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("divCar").offsetTop;
        var hdf = document.getElementById('HiddenField1')

        //Store event information in hidden feild
        if (hdf != null) hdf.value = t + " " + pos_x + " " + pos_y;

    }
    function set_coordinates_down(event) {
        //Get initial co-ordinates
        var pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("divCar").offsetLeft;
        var pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("divCar").offsetTop;
        t = pos_x + " " + pos_y
    }

A: check if your tab is leaking memory for some reason by opening up Chromes Task manager... probable reasons would be an infinite loop somewhere.
Chrome pages usually crash (Snap!) when there is low memory on the system. I would worry about that too.. Make sure you dont have many other processes running either.
Keep us updated.


text:
Q: Cannot execute this binary file appreciate any assistance, I'm a Mac Noob
Im trying to upgrade MySQL in MAMP to 5.6 according to the these instructions
When I try to run the .command script as per #2 I get the following output:
Sandies-MacBook:~ sandie$ /Users/sandie/Downloads/Install_MySQL_5.6.25.command ; exit;
-bash: /Users/sandie/Downloads/Install_MySQL_5.6.25.command: cannot execute binary file

I have found this post, but I still get the "Cannot Execute" error.  I checked the file type as per the instructions, and the result is:
Zip archive data, at least v2.0 to extract
The instructions suggest I need to unzip it but I have no idea how?
Any help appreciated :)

A: *

*Remote/delete the downloaded file

*Download it again, it should get a .zip extension

*Double-click the downloaded file to unpack it

*In Terminal, run
cd ~/Downloads
chmod +x Install_MySQL_5.6.25.command
./Install_MySQL_5.6.25.command


text:
Q: Windows 10 equivalent to OSX's ⌘+D to navigate to my desktop, ⌘+Shift+H for Home, ⌘+shift+A for apps etc In finder on OSX there are shortcuts to special folders like the user's Desktop, the user's Home directory and the Applications directory (from memory it's ⌘D for ~/Desktop, ⌘shiftH for ~/ and ⌘shiftA for /Applications, but it's been a while since I moved to the dark side, so please feel free to edit).
One thing that's always bugged me is that there is no equivalent for Windows. To navigate to my home folder is particularly annoying, I have to go My PC>C:>Users>stib> which is way too many clicks. So is there an addon or hack that mimics the OSX behaviour? Ideally it would work in open file dialogs as well as in Explorer.
EDIT
Here's what I tried with AutoHotKey
;-- ctrl win d opens the documents dir
^#d::
send {Ctrl down}l{Ctrl up}
send Documents{Enter}
Return

That works in some dialogs, but not all. For example the dialog that opens with notepad++ looks like this,

and neither the ctrll nor altd shortcuts would move focus to the address box. So that script would send the word "Documents" to the name box, resulting in it creating or opening a file called Documents in whatever folder it happened to be open in. The workaround is to send the absolute path to the Documents folder, but it's still a bit brittle. If focus is moved away from the dialog for any reason (eg a notification window from another ap opening) the script will send keystrokes to random elements. Not optimal.

A: The structure of file system one Windows is different from the Mac, so sometimes there is no strict equivalent.
You can use the shortcut ⊞ Win+D to minimize all open windows and see the desktop. Use it again to restore those open windows.
In File Explorer, This PC is technically your home folder. For example, let's say you have a folder named Test on the Desktop. If you go to This PC > Desktop > Test, now check the address bar and you will see C:\Users\stib\Desktop\Test. In Folder Options, you can change what File Explorer opens to. You can choose This PC, or Quick access.
But more accurately, your home folder is actually your name in File Explorer and it is displayed at the same level along with Quick access and This PC.
You can customize Quick access and add all the folders that you use more often. This way you can reach them much faster. Right-click on any folder and select Pin to Quick access. Those folders not only show up in File Explorer in Quick access, but also when you have a File Explorer window open and right-click on its button in the Task Bar, those folders show up pinned to the context menu and clicking on one of them opens a new File Explorer window to that folder.


text:
Q: ShowDialog Compiled for x86 Displays Behind Main Form on x64 I've got an application that has to be compiled to x86 because of some old COM controllers to very old 3rd party software drivers.
I have noticed that anytime I call a Form's Modal Dialog Box while some other application has focus (like the Visual Studio code that I am stepping through), that Dialog Box is brought up behind the parent window.
private string Locate(string filename) {
  if (!File.Exists(filename)) {
    using (OpenFileDialog dlg = new OpenFileDialog()) {
      dlg.FileName = filename;
      if (dlg.ShowDialog(this) == DialogResult.OK) {
        return dlg.FileName;
      }
    }
  }
  return filename;
}

I can compile the application as x64, but loading the COM drivers will fail, causing the application to never start.
Has anyone else noticed this behavior from (Visual Studio, the .NET Framework, or Windows 7)? If not, then I must have something screwy going on in my code elsewhere.
Is there a way to "fix" it?

A: VS2010 defaults to x86 so your configuration is quite common which would suggest you do have something screwy going on with your code.
Are you sure that this as in dlg.ShowDialog(this) is actually the parent and is visible etc?
Is Locate being called from a non-UI thread?  If not, did you try using dlg.ShowDialog().


text:
Q: Assign value to line layer attributes from another layer by lines start / end coordinates I have two layers (Lines and Points). Points are the break points of lines and correspond to start and end of the lines. Lines start_point_id and end_point_id columns should get Point_ID values.
I was thinking to create a field calculator expression by taking Point_id from points layer by lines start and end coordinates. I've managed to get begin and end point ids' as an array, but I need them in separate columns.
overlay_intersects('Points', id)
Result: [25, 52]

How can I do it using field calculator?

A: For the start point use this expression.
array_filter(
    overlay_intersects(
        'Points',
        array(id, $geometry)
    ),
    intersects(
        @element[1],
        start_point($geometry)
    )
)[0][0]

and for end point
array_filter(
    overlay_intersects(
        'Points',
        array(id, $geometry)
    ),
    intersects(
        @element[1],
        end_point($geometry)
    )
)[0][0]


text:
Q: de Sitter and anti de Sitter metric Is the following correct for the distance $d$ from the origin $(0,0)$ to point $(t,x)$ in the 2-dimensional
de-Sitter and anti de-Sitter spaces? Here, $t$ is time and the distance may be called the interval if you prefer.
1) de-Sitter:
$\sinh{d}=\frac{\sqrt{t^2-x^2}}{\sqrt{1-(t^2-x^2)}}$
2) anti de-Sitter:
$\sin{d}=\frac{\sqrt{t^2-x^2}}{\sqrt{1+(t^2-x^2)}}$
If the above is correct, it implies that the de-Sitter space is akin to the hyperbolic space in terms of the distance measure, whereas anti de-Sitter space is more like the elliptic space. So, then the de-Sitter space has negative curvature, whereas it is positive for the anti de-Sitter space.
EDIT:
I derived (1) and (2) from a formula for $\Psi_{pq}$ given on page 439 of "Perspectives on projective geometry" by Jurgen Richter-Gebert, taking p=(0,0,1),
q=(x,t,1) and A=B=diag(1,-1,+1) for the de-Sitter space and A=B=diag(1,-1,-1) for anti de-Sitter space. I've just checked my derivation and with the final amendments the formulas are correct as written. What I want to know is whether my identifications of the spaces is correct. Perhaps, my (1) should be for anti de-Sitter space and (2) for de-Sitter. However, I read somewhere that de-Sitter space has hyperbolic distance measure (in Beltrami-Klein model I'm using) in accord with my choice. Oh, and I haven't linked those wikipedia pages. I think it's confusing and unnecessary to view de-Sitter and anti de-Sitter spaces as sub-manifolds of a higher-dimensional Minkowski space.


text:
Q: Automount lookup failed. How to determine what is trying to access the file? Is there a way to find out what is trying to mount this file?

Jul 13 14:27:24 myhost automount[13527]: lookup(file): lookup for
  tmp_dir failed

Something is looking for "tmp_dir", and I've grepped a bunch of places but cannot find what script, program, etc... is looking for the file/dir and is causing automount to try and mount it up.
I see there are entries in /proc/mounts for tmp_dir, but looks like I cannot remove them since /proc/mounts is read-only (probably for good reason).  Thoughts?
For a little background, we recently took down a file share that was called tmp_dir, and I think a programmer still has something pointing to tmp_dir, but he claims he cleaned everything up.  I'm thinking maybe we did not umount tmp_dir properly before taking down the share, and autofs is still attempting to load it.  The OS is SLES 11 SP1.

A: Here are a couple of ways to monitor accesses to particular files. I'm not completely sure how they'll interact with an automounter, but they probably will work.

*

*Put a LoggedFS filesystem on the automount directory (/amnt or whatever), and configure it to look out for /amnt/tmp_dir. Start from the provided configuration file example and tweak the include/exclude rules according to this guide.

*Get the Linux audit subsystem utilities (on any recent distribution, this should just be a matter of installing a package), and make the kernel look out for this file:
auditctl -a exit,always -w /amnt/tmp_dir

See also Determine which process is creating a file; my answer there has more explanations on LoggedFS and auditd.


text:
Q: Cannot resolve file 'img.jpg'. intellij idea don't see the image. How can fix error?
enter image description here
Cannot resolve file 'img.jpg'.
This inspection checks unresolved file references in HTML

A: for inline css you used attribute style in open t
used this code:
<body style="background:url(img.jpg)">

A: If you are defining the background image with inline styles, it would be written like this:
<body style="background: url(img.jpg);">

Or more specifically, if you only want to change the background image and not unset all other background properties:
<body style="background-image: url(img.jpg);">


text:
Q: Use config.json file's parameters in app We are using google map api and we have a key. We have codede this key in one of our module file. We want to use this key in config.json file so that it should be secure and when we push our changes to git, it should not be available as we dont push our config.json file on git. I don't have any idea about this.
mobile-content.module.ts
@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      apiKey: 'GOOGLE-API KEY',
      libraries: ['places']
    }),

hip-config.json
googleMapsApiKey: "GOOGLE-API KEY" <--- want to use here ONLY

I want to use this key in hip-config.json file only and want to remove it from mobile-content.module.ts file.
Is there any way to impliment such thing?

A: Import hip-config.json into your module file
import config from "../config/hip-config.json";
Replace the hard-coded key in the module
```
@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      apiKey: 'config.GOOGLE-API KEY',
      libraries: ['places']
    }),

```
Make sure that hip-config.json has been added to .gitignore so it doesn't accidentally get pushed.


text:
Q: $K$ is not endowed with any algebraic structure. How can pointwise sum and convolution product be defined on $K^{(S)}$ I'm doing Exercise 6 in textbook Algebra by Saunders MacLane and Garrett Birkhoff.

If $S$ is an additive monoid, the support of a function $f: S \rightarrow K$ is the set of all those $s \in S$ with $f(s) \neq 0$. Show that the set of all functions $f$ with finite support constitute a ring $K^{(S)}$ under pointwise sum and convolution product, with a suitable unit, and construct a monomorphism $K \rightarrow K^{(S)}$ of rings. (Hint: If $S$ is the additive monoid ${N}$, then $K^{(S)}$ is the ring $K[x]$), The ring $K^{(S)}$ is called the "monoid ring" for S over $K$.

The authors do not endow $K$ with any algebraic structure. How can pointwise sum and convolution product be defined on $K^{(S)}$?
Thank you very much for your clarification!

Update: @ Angina Seng verified my observation in a comment. Here is my attempt.
For $p,q \in K^{(S)}$, we define addition and multiplication by, for all $x \in S$, $$\begin{aligned} (p + q) (x) &= p(x) + q(x) \\ (p q) (x) &= \sum_{\substack{y+z=x\\p(y) q(z) \neq 0}} p(y) q(z)\end{aligned}$$
Because $p,q$ have finite support, the set $\{(y,z) \in S^2 \mid y+z=x \text{ and } p(y) q(z) \neq 0\}$ is finite and thus the sum is well-defined. Then it's straightforward to verify that $K^{(S)}$ is actually a ring. The additive identity $\mathbf{0}$ is the function whose values are $0$ everywhere. The multiplicative identity $\mathbf{1}$ is the function such that $\mathbf{1}(x) = 1$ if $x = 0$ and $\mathbf{1}(x) = 0$ otherwise.
Consider $\sigma: K \to K^{(S)}$ that maps $r \in K$ to $p \in K^{(S)}$ such that $p(x) = r$ if $x = 0$ and $p(x) = 0$ otherwise. Then $\sigma$ is the required monomorphism.


text:
Q: bash printf duplicate line I expect to print
$ pwd: /home/me/actual_folder size: 5.3M

with:
$ cat test.sh
printf 'pwd: %s size:%s\n' `pwd` `du -sh .`
$

But I get:
$ sh test.sh
pwd: /tmp/actual_folder size:5.3M
pwd: . size:
$

How to avoid the last pwd: . size: line ?

A: Remove the dot from the output of du:
printf 'pwd: %s size: %s\n' `pwd` `du -sh . | cut -f1`

Otherwise, the second command substitution outputs two words, so printf sees 3 arguments, so it repeats the template for the second pair (dot and nothing).
You can also use pwd as the argument of du directly, but you need to revert the order of the output:
printf 'pwd: %s size: %s\n' $(du -sh $(pwd) | awk '{print $2, $1}')

A: You can use:
printf "pwd: %s size:%s\n" "$(pwd)" "$(du -sh)"

But if you don't want the "." in the end you can cut it with:
 printf "pwd: %s size:%s\n" "$(pwd)" "$(du -sh | cut -d '.' -f1)"


text:
Q: How to decode URL parameter using AngularJS or JavaScript? I have a value that I pass on to URL parameter the original value looks like this:
1436641259169/nDfmDmVa

when it gets passed on it converts it to this:
1436641259169%252FnDfmDmVa

So, how to do I convert it back when I pull it down?

A: This may help you: decodeURIComponent
decodeURIComponent(string);

Example:
decodeURIComponent(decodeURIComponent("1436641259169%252FnDfmDmVa"))
> "1436641259169/nDfmDmVa"

A: I think this will help you to decode the url :
  decode(content: string){
    return decodeURIComponent(content);
  }


text:
Q: Lost Hover Styling in Chrome for Mac Can be replicated by scrolling past the header, then trying to hover over a menu item.
Here's a link to the website: http://fire.wakeyyc.com
And since I can't post pictures, here is a link to a picture to outline the problem:
http://fire.wakeyyc.com/images/glitch.png
Thanks for your help everyone! :)

A: Well, I've found the solution myself. It turns out that there is a glitch in Chrome that when you add a JS Google Map while having a fixed item on your page, you'll run into z-indexing problems.
The problem is caused by a style of -webkit-transform: translateZ(0); applied by google to their JS Maps.
The source for my answer is found here although my answer is slightly modified.
Add a transform: translateZ(0); along with all the different vendor extensions to the ul element and call it a day.

A: it is working in chrome.
below is the attached screenshot.

my suggestion clear the catche or update the chrome version and TRY.


text:
Q: Índices em consultas no MySQL Utilizar índices em consultas mysql realmente faz o resultado vir rapidamente para algumas consultas ou tabelas grandes.
Por exemplo na consulta abaixo:
SELECT * FROM table WHERE status = 1;

Para uma tabela com 1 milhão registros se eu der o comando abaixo:
DELETE FROM table WHERE status = 1;

Essa consulta demora muito. Então crie o índice para a coluna status e consegui remover 700 mil linhas rapidamente (coisa de 0.8s)
No select do exemplo eu não coloquei o use index xyz mas o banco de dados foi inteligente em usar o índice que crie para a coluna.
Mas e para consultas com vários  WHERE? Algo como
SELECT * FROM table WHERE status = 1 AND account = 12 AND data > '2014-09-09 00:00:00';

Se eu criar um índice com as colunas status, account e data o MYSQL vai usar na consulta acima de forma automática ou vou ter que colocar de forma explícita o use index xpto?
UPDATE
Depois de implementar somente um índice em uma tabela que tinha uma query complicada. Olha só o que resultou no uso de CPU no meu RDS na Amazon.

Vou até poder diminuir o tipo de instância :D
Exemplo de criação de índice para o exemplo da query acima:
ALTER TABLE `table` ADD INDEX `status_idx` (`status`);

A: Para esta query específica vai utilizar o índice se existir um índice apropriado para ela. Este índice deverá incluir as colunas status, account e data. De preferência nesta ordem. Não há porque o MySQL não usar o índice automaticamente. De qualquer forma para ter certeza crie e veja o que acontece. Nem sempre o que deduzimos está correto.
Assim o índice classificará o status crescentemente, então ele poderá achar rápido as linhas com possuem o valor 1. Em seguida ele poderá achar rápido as linhas que possuem o valor 12 para account, dentre as linhas já selecionadas que satisfaça a condição anterior. E finalmente selecionará todas as datas acima do valor indicado na query, novamente entre as linhas já selecionadas anteriormente nas condições anteriores. Obviamente que esta seleção não considerará outras faixas de dados que não contém os valores anteriores.
Note que precisa haver uma faixa única de seleção para aproveitar o índice por completo na query. Por isto a ordem pode ser importante para determinar se dá ou não para usar o índice. Por isso eu disse que nesta query específica o índice com a composição indicada seria usado. Uma outra query pode não conseguir usar o índice ou pode usar parcialmente para selecionar uma faixa através dele e o resto da seleção ter que ser varrendo o banco de dados linha por linha entre as linhas já selecionadas no índice.
Normalmente o segredo é ter índices que atendem as principais queries e evitar queries que não possam se beneficiar dos índices.
Os índices funcionam bem quando você consegue montar sub-faixas com eles. Em uma query muito complexa, que dificulte pegar estas sub-faixas não há índice que resolva. Aí o ideal é tentar pelo menos reduzir bastante as linhas que foram obtidas através do índice e deixar pouco para a seleção final.
Para tentar facilitar o entendimento, pense em como funciona esta busca. Quando você tem algo ordenado de acordo com o que você quer buscar fica fácil achar através de uma busca binária que tem uma complexidade logarítmica O(log n), ou seja, ela divide e conquista. Mesmo com bilhões de linhas, em pouco mais de 30 passos ele acha o que você quer. Quando não tem ordem alguma, o jeito é olhar um por um, complexidade linear O(n). Se a query olha para várias colunas ela vai tentar usar o primeiro método e fazer uma seleção bem rápida. Quando não for mais possível, apenas entre as linhas que já conseguiu selecionar rápido ele vai aplicar a condição determinada individualmente linha por linha. Para entender um pouco mais sobre Big O leia essa resposta.
Quando o otimizador não usa um índice existente é porque ele não conseguiu montar uma forma de "entender" sua query apropriadamente para o índice. Isto pode ser culpa da forma como o índice está montado ou pode ser porque o otimizador não é tão bom. Quase sempre o otimizador faz bem o seu serviço.
Na verdade pode ser que o índice não seja usado mesmo que tenha uma chave adequada. Há volumes de dados pequenos que a busca direta nos dados tenha um custo menor. O otimizador pode identificar que mesmo que ele possa selecionar sub-faixas, a análise subsequente pode ser tão custosa que eliminando a consulta ao índice pode trazer um resultado melhor. Mas nestes casos o otimizador renunciou seu uso de forma "consciente" para o seu benefício. Não dá para achar ruim. Apesar que há casos que ele erra.
Mas cuidado para não criar índices demais. As atualizações a eles podem tornar o software bem lento.
O que o AP fez na edição da pergunta é exatamente o que precisa ser feito. Tentar e ver o que realmente acontece. Com uma chave simples utilizando apenas a coluna mais relevante ele conseguiu um ganho enorme. Ele utilizou a coluna status. Não sei se ele tentou, mas poderia experimentar só com a coluna account, só com a coluna data, e fazer as combinações possíveis entre as três colunas e ver como fica cada resultado. Como o ganho parece ser fundamental, vale o pequeno esforço.
Coloquei no GitHub para referência futura.


text:
Q: What is this weird process I see in WSL called "plan9?" I'm using WSL2 with Ubuntu on Windows 11 and there is a weird process called plan9 I see with htop.
Here is a picture of it.

ps ax output:
4 ?        Sl     0:00 plan9 --control-socket 5 --log-level 4 --server-fd 6 --log-truncate

Can anyone explain what that is? I found nothing on the internet about that.

A: It's a really good question -- I hadn't noticed this yet, but I hadn't upgraded WSL in a few days.  This is a very recent change (last week) in the latest WSL releases.
As mentioned in the comments, WSL uses the 9P protocol to share files between Windows and WSL.  However, this process only appears starting in WSL 0.70.4.  Although there is nothing mentioned about it in the 0.70.4 release notes, the 0.70.5 notes mention  fixing a race condition in (what is likely) this component.
It's definitely injected by WSL itself, so nothing to worry about, but it would be nice to know what the purpose is, since it is new.  Several theories that I can think of:

*

*This is related to the recent Systemd changes in WSL.

*This change fixed a WSL issue -- Although I don't see any 9P issues that were recently closed in the WSL GitHub repo.

*This change might be designed to give the WSL team more control over changes to the 9P component, where previous releases might have been tied to Windows components/functionality.

*This change (hopefully!) will allow the WSL team to improve the performance of 9P when accessing Windows files through WSL2.  The extremely poor performance has been one of the few reasons to use WSL1 over WSL2 (when that feature is needed).  I tested this under 0.70.5, and this change definitely doesn't improve performance, but maybe it sets the stage for a future update where that will happen.

But, until someone from Microsoft tells us more, these are just theories.


text:
Q: Rails 4: Create object only in a factory method? Going to simplify a bit here, but assume an app that has Users and UserRecords. A User must have one or more UserRecords. I want to limit the creation of UserRecords to a method in User, namely #create_new_user_record.
In other words, I don't want to allow UserRecord.new or UserRecords.create anywhere else in the application. I need to control the creation of these records, and perform some logic around them (for example, setting the new one current and any others to not current), and I don't want any orphaned UserRecords in the database.
I tried the after_initialize callback and checking if the object is new and raising an error there, but of course I do need to call UserRecord.new in User#create_new_user_record. If I could somehow flag in #create_new_user_record that I am calling new from that method, and pick that up in after_intialize, that would work, but how?
I might be over thinking it. I can certainly create a that method on User, and just 'know' to always call it. But others will eventually work on this app, and I will go away and come back to it as some point.
I suppose I could raise the error and just rescue from it in #create_new_user_record. Then at least, if another develop tries it elsewhere they will find out why I did it when they pursue the error.
Anyway, wondering what the Rails gurus here had to say about it.

A: super method is what you are looking for. Though you'll need some workaround (maybe simple check for value of option only you know about) to fit your needs
    class User < ActiveRecord:Base
   def .new(attributes = nil, options = {})
     do_your_fancy_stuff
     if option[:my_secret_new_method]
       super # call AR's .new method and automatically pass all the arguments
   end

 end

A: Ok, here's what I did. Feel free to tell me if this is bad idea or, if it's an ok idea, if there's a better way. For what it's worth, this does accomplish my goal.
In the factory method in the User model, I send a custom parameter in the optional options hash defined on the new method in the API. Then I in the UserRecord#new override, I check for this parameter. If it's true, I create and return the object, otherwise I raise in custom error.
In my way of thinking, creating a UserRecord object any other way is an error. And a developer who innocently attempts it would be lead to explanatory comments in the two methods.
One thing that's not clear to me is why I need to leave off the options hash when I call super. Calling super with it causes the ArgumentError I posted in my earlier comment. Calling super without it seems to work fine.
class User < ActiveRecord::Base
  ...
  def create_new_user_record
    # do fancy stuff here
    user_record = UserRecord.new( { owner_id: self.id, is_current: true }, called_from_factory: true )
    user_record.save
  end
  ...
end

class UserRecord < ActiveRecord::Base
  ...
  def UserRecord.new(attributes = nil, options = {})
    if options[:called_from_factory] == true
      super(attributes)
    else
      raise UseFactoryError, "You must use factory method (User#create_new_user_record) to create UserRecords"
    end
  end
  ...
end


text:
Q: mysql group_concat group by on multiple fields I have a Table member with member_id, member_name, club_name, region, zone, email as fields.
I am using the MySQL group_concat function like
SELECT group_concat(distinct m.email
SEPARATOR ', ' ) from member m group by m.club_name

This is working fine. But I would like to be able to group_concat on other fields without creating additional queries.
Is it possible to supply the other fields as parameter?
member_id   member_name club_name   region  zone    email
1           member1           A        1    1   email1@example.com
2           member2           A        1    1   email2@example.com
3           member3           B        1    1   email3@example.com
4           member4           C        1    2   email4@example.com
5           member5           D        2    1   email5@example.com

**group by club**
email1@example.com,email2@example.com
email3@example.com
email4@example.com
email5@example.com

**group by region**
email1@example.com, email2@example.com, email3@example.com, email4@example.com
email5@example.com

**group by zone**
email1@example.com, email2@example.com, email3@example.com
email5@example.com

Say every Region has 3 Zones, every zone has more than one club. Now how can I get emails which can be grouped or related to Region, Zone or Club for that matter?

A: It's hard to understand what are you after exactly from your question but you can try
SELECT club_name,
       GROUP_CONCAT(DISTINCT email SEPARATOR ', ' ) emails,
       GROUP_CONCAT(DISTINCT member_name SEPARATOR ', ' ) members
       ...
 FROM member
GROUP BY club_name

Sample output:

| CLUB_NAME |                                EMAILS |          MEMBERS |
------------------------------------------------------------------------
|     Club1 | m1@mail.com, m2@mail.com, m3@mail.com | Jhon, Mark, Beth |
|     Club2 |              m4@mail.com, m5@mail.com |    Helen, Thomas |

Here is SQLFiddle demo
On a side note: providing sample data and desired output in a question like this usually improves your changes of getting your answer faster and that best fits your needs.
UPDATE: You can deeply pack information using GROUP_CONCAT() using different separators if it's what you want
SELECT 'club' group_type, GROUP_CONCAT(details SEPARATOR '|') details
  FROM
(
  SELECT CONCAT(club_name, ';', GROUP_CONCAT(DISTINCT email)) details
    FROM member
   GROUP BY club_name
) a
UNION ALL
SELECT 'region' group_type, GROUP_CONCAT(details SEPARATOR '|') details
  FROM
(
  SELECT CONCAT(region, ';', GROUP_CONCAT(DISTINCT email)) details
    FROM member
   GROUP BY region
) a
UNION ALL
SELECT 'zone' group_type, GROUP_CONCAT(details SEPARATOR '|') details
  FROM
(
  SELECT CONCAT(zone, ';', GROUP_CONCAT(DISTINCT email)) details
    FROM member
   GROUP BY zone
) a

Sample output:

| GROUP_TYPE |                                                                                DETAILS |
-----------------------------------------------------------------------------------------------------------------------
|       club | A;email1@example.com,email2@example.com|B;email3@example.com|C;email4@example.com|D;email5@example.com |
|     region |     1;email1@example.com,email2@example.com,email3@example.com,email4@example.com|2;email5@example.com |
|       zone |     1;email1@example.com,email2@example.com,email3@example.com,email5@example.com|2;email4@example.com |

Here is SQLFiddle demo
If you're using php on the client side you can then easily enough unwind details column into separate records using explode() while you're iterating over the resultset.


text:
Q: Conversor de divisas en Batch Script Estoy tratando de crear en batch script un conversor de divisas.
El codigo fuente que tengo es este:
@echo off
setlocal enabledelayedexpansion
title Conversor multidivisas de los paises que tienen el euro:
rem Indicando las cantidades de las divisas convertidas:
set a[0]=6.55957
set a[1]=166.386
set a[2]=13.7603
set a[3]=1.95583
set a[4]=40.3399
set a[5]=110.265
set a[6]=0.585274
set a[7]=1.95583
set a[8]=15.6466
set a[9]=166.386
set a[10]=5.94573
set a[11]=6.55957
set a[12]=340.75
set a[13]=0.787564
set a[14]=1936.27
set a[15]=491.96775
set a[16]=3.4528
set a[17]=40.3399
set a[18]=0.702804
set a[19]=6.55957
set a[20]=1.95583
set a[21]=0.4293
set a[22]=2.20371
set a[23]=200.482
set a[24]=239.64
set a[25]=30.126
set a[26]=1936.27
set a[27]=1936.27
set a[28]=655.957
set a[29]=655.957
set a[30]=119.3317
rem Indicando el nombre de las divisas convertidas:
set b[0]=Franco Andorrano
set b[1]=Peseta Andorrana
set b[2]=Chelin Austriaco
set b[3]=Marco Bosnio-Herzegovino
set b[4]=Franco Belga
set b[5]=Escudo Caboverdiano
set b[6]=Libra Chipriota
set b[7]=Marco Aleman
set b[8]=Corona Estonia
set b[9]=Peseta Espanyola
set b[10]=Marco Finlandes
set b[11]=Franco Frances
set b[12]=Dracma Griega
set b[13]=Libra Irlandesa
set b[14]=Lira Italiana
set b[15]=Franco Comorense
set b[16]=Litas Lituana
set b[17]=Franco Luxemburgues
set b[18]=Lats Leton
set b[19]=Franco Monegasco
set b[20]=Denar Macedonio
set b[21]=Lira Maltesa
set b[22]=Florin Neerlandes
set b[23]=Escudo Portugues
set b[24]=Tolar Esloveno
set b[25]=Corona Eslovaca
set b[26]=Lira Sanmarinense
set b[27]=Lira Vaticana
set b[28]=Franco CFA de Africa Central
set b[29]=Franco CFA de Africa Occidental
set b[30]=Franco CFP Polinesia Francesa
rem Mostrando el nombre de las divisas:
for /l %%n in (0,1,30) do (
echo !b[%%n]!
)
rem Introduciendo la cantidad a convertir:
set /p "cantidad=Cuanta cantidad quieres convertir? "
rem El nombre de la divisa original:
set /p "divisainicial=Como se llama la divisa inicial? "
rem El nombre de la divisa final:
set /p "divisafinal=Como se llama la divisa final? "
rem Guardando en una variable el numero del array de la divisa inicial:
for /l %%n in (0,1,30) do (
if "!b[%%n]!"=="%divisainicial%" (
    set /a "contadorinicial=%%n"
)
)
rem Guardando en una variable el numero del array de la divisa final:
for /l %%n in (0,1,30) do (
if "!b[%%n]!"=="%divisafinal%" (
    set /a "contadorinicial=%%n"
)
)
rem Convirtiendolo al euro:
set /a "euros=%cantidad%/!a[%contadorinicial%]!"
rem Convirtiendolo a la nueva divisa:
set /a "nuevadivisa=%euros%*!a[%contadorfinal%]!"
echo %cantidad% %divisainicial% equivale a %nuevadivisa% %divisafinal%
pause
exit

El problema lo he llegado a ver con dos mensajes que me aparecen que son estos mas el mensaje final, en el que me aparece casi todo el mensaje:
Falta el operador.
Falta un operando.
200 Peseta Espanyola equivale a  Franco Frances (en este caso, no me muestra la cantidad convertida)
Una indicacion con el codigo fuente. La parte de donde tengo las divisas, lo tengo puesto con decimales (por lo general, sabemos que los decimales en programacion se indican con puntos)


text:
Q: "Pyaudio" pip install fails for every package even after upgrading pip I downloaded the package  PyAudio-0.2.11-cp39-cp39-win_amd64 and copied it in the script file in python 3.9 directory, but when i tried to install the pack pip throws me errors
ERROR: No matching distribution found for PyAudio-0.2.11-cp39-cp39-win_amd64

I tried to upgrade pip as a solution that i found it here in Stack :
pip install --upgrade pip

then:
pip install PyAudio-0.2.11-cp39-cp39-win_amd64
but pip keeps failing with an this Error :
ERROR: Could not find a version that satisfies the requirement PyAudio-0.2.11-cp39-cp39-win_amd64
`ERROR: No matching distribution found for PyAudio-0.2.11-cp39-cp39-win_amd64`

I also tried
pip install pipwin
pipwin install pyaudio

is there any other  solutions please ?

A: Maximum officially supported version of python for pyaudio is 3.6; quoting from the Installation page:

Microsoft Windows
Install using pip:
python -m pip install pyaudio

Notes:
If pip is not already bundled with your installation of Python, get it
here. pip will fetch and install PyAudio wheels (prepackaged
binaries). Currently, there are wheels compatible with the official
distributions of Python 2.7, 3.4, 3.5, and 3.6. For those versions,
both 32-bit and 64-bit wheels are available.

You could read about installing different versions of the python on your machine and use it with 3.6 version of python without any errors


text:
Q: SQL Combine Join Having trouble combining tables in a SQL join.  I would like to combine both table A column of NationalAvg and table B column SchoolAvg in table C however none of my queries are correct.
Table A - Where I can get NationalAvg
 Select Round(Cast(AVG(me.members_exams_score)as float), 2) as NationalAvg, e.exams_description
from members_exams as me
left join exams as e on e.exams_id = me.exams_id
join schools as s on s.schools_id = me.schools_id
where me.members_exams_score is not null
group by e.exams_description

Results
+--------------------+-------------------+
|NationalAvg         | exams_description |
+--------------------+-------------------+
| .78                | Medical Asst.Exam |
| .90                | Health Exam       |
| .79                | EKG Exam          |
| .81                | Phlebotomy        |
+--------------------+-------------------+

Table B - Where I can get SchoolAvg
select Round(Cast(AVG(me.members_exams_score)as float), 2) as SchoolAvg, e.exams_description, s.schools_name
from members_exams as me
left join exams as e on e.exams_id = me.exams_id
join schools as s on s.schools_id = me.schools_id
where me.members_exams_score is not null
group by e.exams_description, s.schools_name
order by s.schools_name

Results
+--------------------+-------------------+--------------+
|SchoolAvg           | exams_description |  School      |
+--------------------+-------------------+---------------
| .90                | Medical Asst.Exam | School A     |
| .88                | Health Exam       | School A     |
| .65                | EKG Exam          | School A     |
| .76                | Phlebotomy        | School A     |
| .93                | Medical Asst.Exam | School B     |
| .79                | Health Exam       | School B     |
| .82                | EKG Exam          | School B     |
| .76                | Phlebotomy        | School B     |
+--------------------+-------------------+--------------+

Incorrect Combine Table - Wanting Both SchoolAvg & NationalAvg.  The NationalAvg column is not showing up.
select Round(Cast(AVG(me.members_exams_score)as float), 2)  as SchoolAvg, e.exams_description, s.schools_name
from members_exams as me
left join exams as e on e.exams_id = me.exams_id
join schools as s on s.schools_id = me.schools_id
join
        ( select Round(Cast(AVG(me.members_exams_score)as float), 2) as NationalAvg
        from members_exams as me
        left join exams as e on e.exams_id = me.exams_id
        join schools as s on s.schools_id = me.schools_id
        group by e.exams_description) nAvg on e.exams_id = nAvg.NationalAvg
where me.members_exams_score is not null
group by  s.schools_name, e.exams_description

Results - are bring back the same table as B.
Intended Results -
+------------------+--------------------+-------------------+--------------+
|  School Avg      |NationalAvg         | exams_description |  School      |
+------------------+--------------------+-------------------+--------------|
| .90              | .78                | Medical Asst.Exam | School A     |
| .88              | .90                | Health Exam       | School A     |
| .65              | .79                | EKG Exam          | School A     |
| .76              | .81                | Phlebotomy        | School A     |
| .93              | .78                | Medical Asst.Exam | School B     |
| .79              | .90                | Health Exam       | School B     |
| .82              | .79                | EKG Exam          | School B     |
| .76              | .81                | Phlebotomy        | School B     |
+------------------+--------------------+-------------------+--------------+

Thanks,

A: Try adding your logic to CTEs and joining that way.
With CTE1 as(
  Select Round(Cast(AVG(me.members_exams_score)as float), 2) as NationalAvg, e.exams_description
  from members_exams as me
  left join exams as e on e.exams_id = me.exams_id
  join schools as s on s.schools_id = me.schools_id
  where me.members_exams_score is not null
  group by e.exams_description
),CTE2 as (
  select Round(Cast(AVG(me.members_exams_score)as float), 2) as SchoolAvg, e.exams_description, s.schools_name
  from members_exams as me
  left join exams as e on e.exams_id = me.exams_id
  join schools as s on s.schools_id = me.schools_id
  where me.members_exams_score is not null
  group by e.exams_description, s.schools_name
)
select A.exams_description, A.NationalAvg, B.schools_name, B.SchoolAvg
from CTE A
left Join CTE1 B ON A.exams_description = B.exams_description

A: By looking into your input-output examples, you want to join the two tables on the column exams_description.
Since you already have two subqueries written yourself, you can do a join on the result of the two subqueries.
with T1 as(
  select Round(Cast(AVG(me.members_exams_score)as float), 2) as NationalAvg, e.exams_description
  from members_exams as me
  left join exams as e on e.exams_id = me.exams_id
  join schools as s on s.schools_id = me.schools_id
  where me.members_exams_score is not null
  group by e.exams_description
),T2 as (
  select Round(Cast(AVG(me.members_exams_score)as float), 2) as SchoolAvg, e.exams_description, s.schools_name
  from members_exams as me
  left join exams as e on e.exams_id = me.exams_id
  join schools as s on s.schools_id = me.schools_id
  where me.members_exams_score is not null
  group by e.exams_description, s.schools_name
)
select T2.SchoolAvg, T1.NationalAvg, T2.exams_description, T1.exams_description
from T1 Join T2
where T1.examples_description = T2.examples_description;


text:
Q: locking current appscreen of my application i need to lock my applications current screen when a specific push message send to phone, i try to make it as a transparent view but i cant get it please help me

A: It definitely seems like tounder.com would be your best option. They take care of most set up, they let you send a notifications based on user names.
After setting up the Android SDK
All you have to do for log in is:
    public class MainActivity extends Activity {
...

Tounder mTounder;

int REQUEST_CODE = 1;

Button logInBtn;

...

@Override

protected void onCreate(Bundle savedInstanceState) {

    ...

    mTounder = new Tounder(this);

    ...

    if(alreadyLoggedIn()) {

        Intent fetchDeviceInfo = new Intent(this, FetchDeviceInfoActivity.class);

        fetchDeviceInfo.putExtra(TounderConstants.EXTRA_USER, mTounder.getUserId());

        startActivityForResult(fetchDeviceInfo, REQUEST_CODE);

    }else {

        logInBtn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Intent fetchDeviceInfo = new Intent(this, FetchDeviceInfoActivity.class);

                fetchDeviceInfo.putExtra(TounderConstants.EXTRA_USER, userName);

                startActivityForResult(fetchDeviceInfo, REQUEST_CODE);

            }

        });

    }

    ...

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data){

    super.onActivityResult(requestCode, resultCode, data);

    String result = data.getStringExtra(TounderConstants.EXTRA_STATUS);

    if(result.contains("Verified") || result.contains("Success")){

        Intent openNextWindow = new Intent(this, SendActivity.class);

        openNextWindow.putExtra("user", username)

        startActivity(openNextWindow);

    }else{

        mTounder.eraseUserId();

        mTounder.eraseRegId();

    }

}

}

Then to send a notification from device a to b would be:
(in oncreate in the btn click)
mTounder = new Tounder(this);
mTounder.sendNormalNotification("deviceb-username", "message");

Here is a video setting up the Android sdk : Youtube Video
I've worked with it before so if you have any questions just comment or post a new question with the tag tounder.com


text:
Q: Using conversion operator to initialize a map What is preventing this initialization to work?
#include <map>
using std::map; using std::pair; using std::make_pair;
struct P {
    char a_, b_;
    P(char a, char b) : a_{a}, b_{b} {}
    operator pair<char,char>() { return make_pair(a_, b_); }
};
int main() {
    map<char,char> qmap { P( 'a','b' ) };
}

It looks like the conversion operator in P can not be applied implicitly inside a braced-initialisier-list? Or is it something else?

A: Note that the key part of a std::map is const, so the type of element of std::map<char, char> is std::pair<const char, char>; the type doesn't match here. The returned std::pair<char, char> with braces cant't be used to construct a std::initializer_list<std::pair<const char, char>>, (and then construct a std::map<char, char> further).
If you change it to
operator pair<const char,char>() { return make_pair(a_, b_); }

or
operator std::map<char, char>::value_type () { return make_pair(a_, b_); }

the code would work fine.

A: It can, but you forgot the key point: map's value_type is actually pair<const Key, Value>, so in your example you'd need two conversions (P ⟶ pair<char, char> ⟶ pair<char const, char>) to meet your qmap's value_type. This is one more conversion that the rules allow.
If you change your conversion operator to
operator pair<char const,char>() { return make_pair(a_, b_); }

your code compiles.


text:
Q: Auto Complete jquery adding search icon I am using jquery autocomplete, and want to add Search icon in auto search input box, and when they start searching want to display search jpg. Can you anyone throw their suggestions on this.

A: You can observe a keyup event of your textbox. Try this:
    $( "#tags" ).autocomplete({
        source: availableTags
    }).keyup(function () {
        if (this.value !== '') {
            $(this).addClass('close');
        } else {
            $(this).removeClass('close');
        }
    });

Demo: http://jsfiddle.net/codef0rmer/5AASU/


text:
Q: SQL: Create table with term names (String containing years) I would like to create a table (two columns, first is auto incremental) which contains the term names, e.g. "SS 2000" and "WS 2000/2001" (for summer and winter term).
I tried the following:
CREATE PROCEDURE create_terms()
BEGIN
Declare @YearEnd integer;
SET @YearEnd = 2014;
Declare @YearFrom integer = @YearEnd - 100;
Declare @Term varchar = '';
while @YearFrom < @YearEnd Begin
    @Term = concat('SS ', @YearFrom);
  Insert into terms (term) VALUES @Term;
  Set @YearFrom = @YearFrom + 1;
End
END

but I already get an error in line 3: SQL query:
CREATE PROCEDURE create_terms()
BEGIN
    Declare @YearEnd integer;
MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@YearEnd integer' at line 3
After reading the comments from Abishek and Stuart, I tried the following:
DELIMITER $$
DROP PROCEDURE IF EXISTS create_terms$$
CREATE PROCEDURE create_terms()
BEGIN
  DECLARE YearEnd INT;
  Declare YearFrom INT;
  Declare Term varchar(10);

  SET YearEnd = 2014;
  SET YearFrom = YearEnd - 100;
  SET Term= '';

WHILE (YearFrom < YearEnd) DO
  SET Term = concat('SS ', YearFrom);
  Insert into terms (term) VALUES (Term);
  Set YearFrom = YearFrom + 1;
 END WHILE;
END;

DELIMITER ;

This results in just the DROP PROCEDURE command being successfully processed. Even when removing this line and changing the first lines to:
 DELIMITER $$
 CREATE PROCEDURE create_terms()$$
 BEGIN

it doesn't work, the SQl console just writes "ERROR" and that's it....    :(

A: All variable staring @ are user variables and need not to be declared, procedures has their local variables not prefix with @, try like this:
DELIMITER $$
DROP PROCEDURE IF EXISTS create_terms$$
CREATE PROCEDURE create_terms()
BEGIN
Declare YearEnd integer;
SET YearEnd = 2014;
Declare YearFrom integer = YearEnd - 100;
Declare Term varchar = '';
while YearFrom < YearEnd Begin
    Term = concat('SS ', YearFrom);
  Insert into terms (term) VALUES YearFrom;
  Set YearFrom = YearFrom + 1;
End;
END;
DELIMITER ;

Here is help

A: There are quite a bunch of errors here

*

*You should use procedure variables

*The Syntax for insert is INSERT INTO Table(columns) VALUES(values);

*You probably also want to insert the term, not the year end

*Your syntax for while is wrong

CREATE PROCEDURE create_terms()
BEGIN
  DECLARE YearEnd INT;
  Declare YearFrom INT;
  Declare Term varchar(10);

  SET YearEnd = 2014;
  SET YearFrom = YearEnd - 100;
  SET Term= '';

  WHILE (YearFrom < YearEnd) DO
      SET Term = concat('SS ', YearFrom);
      Insert into terms (term) VALUES (Term);
      Set YearFrom = YearFrom + 1;
  END WHILE;
END

Fiddle here


text:
Q: Convergence of QR method How does the number of iterations for QR-method for eigenvalues to converge depend on the matrix size $n$?
I ran a MATLAB code for $n$ from 10 to 400 and the number of iterations before convergence does increase, but I can't seem to find any analytical approximations of such growth rate.

A: For a Hermitian or symmetric matrix, the time to compute the eigenvalues is dominated by time to reduce the matrix to tridiagonal form: approximately $4n^3/3$ floating point operations.
Since the convergence of shifted QR is at least quadratic (and usually cubic), each eigenvalue can be computed to machine precision in a number of iterations of the QR decomposition independent of $n.$  So the number of iterations is $O(n)$ (a constant number times the number of eigenvalues). This answers your question for the Hermitian case.
Since a QR decomposition of a tridiagonal matrix can be computed in $O(n)$ floating point operations, the total time for computing eigenvalues after reducing to tridiagonal form is $O(n^2)$ floating point operations.
See "Numerical Linear Algebra" by Trefethen and Bau for details.
For a non-symmetric matrix, Francis's double-shift algorithm is used on a reduction of the matrix to upper Hessenberg form.    The convergence rate of the double-shift algorithm is usually quadratic, so the number of iterations will still be a constant times the number of eigenvalues (in other words, $O(n)$).  However, since the QR decomposition of an upper Hessenberg matrix takes approximately $6n^2$ operations, more time will be spent on the iterative part of the algorithm than on the reduction to Hessenberg form.  See David S. Watkins's paper on Francis's algorithm for details.


text:
Q: steinmetz package comma problem MWE
\documentclass{article}
\usepackage{steinmetz}
\begin{document}
$220\phase{0^{\circ}}$
$220\phase{0{,}5^{\circ}}$
$220\phase{0\phantom{{,}}\!\!^{\circ}}$   %<-- My solve
\end{document}

output

There are difference 0 and 0,5 horizontal line, added comma. Is there a automatic/macro solution?

A: The position of the angle depends on the material to be typeset inside it.
If you want that all \phase command produce the angle as if a comma is in the number, you can patch it as follows
\documentclass{article}
\usepackage{steinmetz}
\usepackage{xpatch}

\xpatchcmd{\phase}{#2}{\vphantom{,}#2}{}{}

\begin{document}

$220\phase{0^{\circ}}$
$220\phase{0{,}5^{\circ}}$

\end{document}

Otherwise, for the occasional fix when two of those \phase command appear next to each other, add a \vphantom yourself
\phase{\vphantom{,}0^{\circ}}


text:
Q: What is wrong f-string in Python?
*

*below code is my valid requirement.

import numpy as np
a =np.array([1, 3, 0, 2], int)
b =np.array([5, 2, 1, 2], int)
print(f'{a > b = }')

*

*result is ok

a > b = array([False,  True, False, False])

*

*I wanna make inner function which have f-string style.

import numpy as np
a =np.array([1, 3, 0, 2], int)
b =np.array([5, 2, 1, 2], int)

def myprn(text):
    print(f'{text = }')

myprn(a > b)

*

*result is not my requirement

*I wanna print 'a > b' instead of 'text'

text = array([False,  True, False, False])
#^^^ how to fix this requirement?

A: You can't, = in f-string is self-documenting sign which just prints expression before it as is. Doc reference

A: Thanks to @Tomerikoo.

*

*His reply gave me a hint. I was able to learn the movements I wanted according to his comments

@Tomerikoo's comment

The only way I can think to make something similar to this work is
print(f'{text} = {eval(text)}') and then passing the function strings
with the expression, i.e. myprn('a > b')


text:
Q: How to use a while loop instead of switch case statement to allow for variable number of questions I am currently working on developing a "quiz" program in C# and I want to make the number of questions it asks variable so it can be easily changed in the future. Previously, I used a switch case statement to run a series of 20 questions, and the code in each statement is virtually same except for the parameters for which values I pull from MySQL. However, when I try to do the same thing in a while loop, the quiz window does not pop up. This is built on Visual Studio 2019 using the Web Quiz .NET template. Please take a look at the screenshots and let me know if you see any errors that could be causing the quiz to not show up in the while loop but does show up in the switch case. Screenshot Also, here is What pops up when I use the switch case but doesnt with the while loop. My code:
 private void askQuestion(int qnum)
    {
        int numOfRows = 20;
        int questionNum = qnum;
        while (questionNum <= numOfRows)
        {
            string num = "'" + qnum.ToString() + "'";
            lblQuestion.Text = getValue("question", "quizquestions", "questionid", num, "questionid", num);
            //lblQuestion.Text = "An alarm may be canceled by calling the monitoring station and giving them the correct passcode and / or password.";

            button1.Text = getValue("answertext", "answertable", "answerid", "'1'", "questionid", num);
            button2.Text = getValue("answertext", "answertable", "answerid", "'2'", "questionid", num);
            button3.Text = getValue("answertext", "answertable", "answerid", "'3'", "questionid", num); ;
            button4.Text = getValue("answertext", "answertable", "answerid", "'4'", "questionid", num); ;

            scoreBox.Text = "Current Score: " + score + "/20";
            currentQ.Text = "Current Question: " + questionNumber;

            correctAnswer = Int32.Parse(getValue("correctid", "quizanswers", "questionid", num, "questionid", num));

            questionNum++;
        }
    }

    /*private void askQuestion(int qnum)
    {

        switch (qnum)
        {
            case 1:
                //pictureBox1.Image = Properties.Resources.questions;

                lblQuestion.Text = getValue("question", "quizquestions", "questionid", "'1'", "questionid", "1");
                //lblQuestion.Text = "An alarm may be canceled by calling the monitoring station and giving them the correct passcode and / or password.";

                button1.Text = getValue("answertext", "answertable", "answerid", "'1'", "questionid", "'1'");
                button2.Text = getValue("answertext", "answertable", "answerid", "'2'", "questionid", "'1'");
                button3.Visible = false;
                button3.Text = "";
                button4.Visible = false;
                button4.Text = "";

                scoreBox.Text = "Current Score: " + score +"/20";
                currentQ.Text = "Current Question: " + questionNumber;

                correctAnswer = Int32.Parse(getValue("correctid", "quizanswers", "questionid", "'1'", "questionid", "'1'"));

                break;
            case 2:...

A: public string getValue(string columnName, string tableName, string refName, string refValue, string ref2Name, string ref2Value)
    {
        string serverIp = "localhost";
        string username = "root";
        string password = "Shared1203";
        string databaseName = "faquiz";

        string value = "";

        string dbConnectionString = string.Format("server={0};uid={1};pwd={2};database={3};", serverIp, username, password, databaseName);
        string query = "SELECT " + columnName + " FROM " + tableName + " WHERE " + refName + " = " + refValue + " AND " + ref2Name + " = " + ref2Value;

        var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString);
        conn.Open();

        var cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn);
        var reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            var someValue = reader[columnName];

            value = someValue.ToString();
        }

        return value;
    }

No errors received


text:
Q: How to detect which object in array has changed property value? I have an array of objects. User can change value of some property in that array of objects. What i want to detect which object has changed. I musing iterableDiffer but i dont know how to display only those that are changed. Any suggestion ?
   let changes = this.iterableDiffer.diff(this.workorders);
        if (changes) {

       }


text:
Q: Customize New Experience SharePoint List with InfoPath? Is this possible?
I have created a new style list because the MS Flow works 100000000 times better than workflows.
But now that I have switched to this experience, I cannot find anything related to InfoPath.

A: No. SharePoint online modern experience does not support InfoPath customizations.
If you want to use InfoPath, you have to switch back to classic experience.
Modern options:

*

*Show or hide columns in a list or library form

*Configure the list form - using JSON

*Customize a SharePoint list or library form by using Power Apps

A: As a supplement, from the SharePoint Designer feature deprecation article, Microsoft said that:
Users who have previously leveraged SharePoint Designer to create custom Forms are instead able to utilize PowerApps for this purpose.
PowerApps is an easy and powerful tool that allows users operating in the SharePoint Online Modern experience to create and edit custom Forms for SharePoint lists and document libraries right from a browser window. PowerApps does not require traditional coding knowledge or any additional app downloads such as InfoPath.
Similar issue for your reference:
https://docs.microsoft.com/en-us/answers/questions/349538/deprecation-of-sharepoint-designer-custom-forms.html


text:
Q: php array comparison using diff and intersect seems not giving the result i need I have 2 arrays
$a = array("1", "2", "3", "4", "5");
$b = array("3", "4", "5", "6", "7");

I want the final result be ("6", "7")
It seems that array_diff() and array_intersect() can't give the result that I need.

A: Yes, use array_diff, what's your problem?
$arrayA = array("1", "2", "3", "4", "5");
$arrayB = array("3", "4", "5", "6", "7");
$result = array_diff($arrayB, $arrayA);

Docs:

Return Values
Returns an array containing all the entries from array1 that are not present in any of the other arrays.

(codepad example)


text:
Q: can we change the main method of java? Main method in Java have the String[] as input parameter to the main method, but i want to pass object as a parameter. Java and all command line parametrized languages accept only String array of arguments which make sense as our ability to call using command line gives us the ability to enter text that could be represented by String object in Java
This is how we used to have a method like:
public static void main (String[] args) {

for (String text: args) {
System.out.println(text);
}
}

If we need to pass integer value, we need to use parsing
 method to obtain the numeric value from it.
 try {
 Arg = Integer.parseInt(args[0]);
 } catch (NumberFormatException e) {
 System.err.println("Number format mismatch");
 }

What if we need to pass a whole object as an argument to the class?
Regards

A: No.  You can't change it.  This is because the command line is only really a block of text.  It makes no sense for a command line to try figure out what data type the text is.
That would mean the command line would need to have prior knowledge about the data types available in whatever is about to be run and somehow create (in the case of Java) the correct Objects and cast to them.

A: There is no way to pass anything but string, because in command line you in fact can type only strings.

A: To my knowledge, you can only pass to the main knowledge in String format. This is because things passed to the main method come from System.in, either through random user input or things like piping, whereby you pass Strings from one Java program to another.
That being said, what you could do is that you create a method in your object class to parse a String form of that object to recreate the original version of that object.
For example:
public class myRectangle
{
     private int length;
     private int width;

     public myRectangle(int inLength, int inWidth)
     {
         this.length = inLength;
         this.width = inWidth;
     }

     // the rest of your class
     public String toString()
     {
          return "[" + length + ", " + width + "]";
     }

     public static Rectangle parseString(String input)
     {
          int firstBracketIndex;
          int commaIndex;
          int lastBracketIndex;

          firstBracketIndex = 0;
          commaIndex = input.indexOf(",");
          lastBracketIndex = input.length() - 1;

          String aWidth = input.substring(firstBracketIndex, (commaIndex - 1));
          String aLength = input.substring((commaIndex + 2), lastBracketIndex);

          return new Rectangle(Integer.parseInt(aWidth), Integer.parseInt(aLength));
      }

 }

Something like this could solve your problem. (There may be some off by one errors in my code and I wrote it out really long so it would be clear, but you get the idea!)
The point is, that you create a parsing method that is the inverse of your toString method, so that you can take copies of your class off the command line.

A: This is not possible. However, as a workaround you can move the logic from main to a separate function accepting the object or whatever you need. Then main would only parse its string argument and call your new function, which also could be called directly.

A: You can only pass a String into main. However nothing stops that String being a chunk of XML/JSon/whatever that you then parse into an object.
For example in JAXB:
 // Needs xml annotations etc
 class T {
 }

 public static void main(String[] args) {
       T t=null;
            JAXBContext jc = JAXBContext.newInstance(T.class);
            try ( StringReader sr = new StringReader(args[0])) {
                t = (T)jc.createUnmarshaller().unmarshal(sr);
            } catch (JAXBException ex) {
                // handle failure
            }
  }


text:
Q: Replace \n with '' by using str_replace() in PHP I have the following code
$s = '\n test@gmail.com \n ';
$s = str_replace('\n', '', $s);

echo $s;

I want to replace the '\n' char with '' but it's not working with the above code. I have found that as \n is the new line char with ascii value 10 by echo ord(substr($s, 0, 1)); it is not working. It's not clear to me what is the exact reason behind not working the above code. please help.

A: You have to use double quotes. \n is not interpreted as newline with single quotes.

A: You need to place the \n in double quotes.
Inside single quotes it is treated as 2 characters '\' followed by 'n'
Try below code:
$s = "\n test@gmail.com \n";
$s = str_replace("\n", '', $s);

echo $s;


text:
Q: Overriding isEqual: so that different objects can equal the same object (sort of) So I have a situation where im using a class as a kind of struct. now i want to override the isEqual: method so if this type of object is inside an array, i can use [objects indexOfObject:obj]
but, now say obj contains objects called duck, and chicken, i would like to go [objects indexOfObject:duck] and it will actually give me the index of obj
so i tried something like this:
- (BOOL)isEqual:(id)anObject {

    if([anObject isKindOfClass:[Duck class]]){

        return [anObject isEqual:_duck];
    }
    else if([anObject isKindOfClass:[Chicken class]]){

        return [anObject isEqual:_chicken];
    }

    return [anObject isEqual:self];
}

which doesnt work and isnt even getting called... think that has to do with overriding hash, which i tried by just returning self.hash (effectively obj.hash) but that didnt work.
Do you think something like this is possible? or should i just use for loops to search through all my obj's to find which duck is contained in which obj and return the index of it (which i can do, just wanted to try be cool and neat at the same time)

A: It sounds using -isEqual: is a bad idea here.
You can't have a DuckAndChicken that compares equal to its Duck and its Chicken, (and vice versa) because in order to stay consistent, all ducks and chickens would then have to compare equal.
Example:

*

*duck1 + chicken1 compares equal to duck1

*chicken1 compares equal to duck1 + chicken1

*duck2 + chicken1 compares equal to chicken1

*duck2 compares equal to duck1

*Universe explodes

The good news is that you don't have to use -indexObject: to retrieve from the array. NSArray has a handy -indexOfObjectPassingTest: method that should do what you want.
        [ducksAndChickens indexOfObjectPassingTest:^BOOL(DuckAndChicken *obj, NSUInteger idx, BOOL *stop) {
            if ([obj.duck isEqual:myDuck]) {
                // woop woop...
            }
        }];

A: Yes, it sounds like a hash issue.
I would avoid trying to do this by overriding isEqual: because you're liable to break things that you don't think you'd break.
Instead add a custom method that you can call to determine your version of equivalence. Then have a helper method or a category on NSArray which adds my_indexOfObject: and does the iteration.

A: Its hard to tell what you really want to do from your example but could you perhaps have two dictionaries one where ducks are the key and one where chickens are the key and the object value is either the actual parent object or a NSNumber with the index in the array. This would make lookup much quicker though would take up more memory, and could make synchronisation between the three data structs.


text:
Q: ActionScript3: Inheriting constructor arguments from parents I'm making a game in action script 3. In it, I have an actor class from which player and enemy classes will be derived. I'm doing this so that unless I need to provide specific AI or fancy behavior (such as for bosses), I can just make a new clip in the library for each enemy without making an actionscript file.
However, I've run into a problem.
Whenever I try to pass arguments to the construction of an enemy (make it spawn with more health), I get error 1136 (Incorrect number of arguments.)
This is because the constructor created automatically at runtime doesn't have the same arguments as it's parent class. Is there any way to get around this without making a class file where I copy and paste the parent constructor function for each of my hundreds of enemies?

A: Edit
actually rereading your question I think you may be looking for super();
Example
public class Actor{
 private var myHelth:uint;
     public function Actor(helth:uint = 100){
         myHelth = helth; //this will be set to 100 if nothing it passed in or the value passed
    }
}

Class that extends Actor:
public class Boss extends Actor{
     public function Boss(){
          super(200); //passes 200 to Actor;
     }
}

If you're trying to pass data into a classes constructor you need to make sure it's accepting arguments.
public class Actor{
     private var myHelth:uint;
     public function Actor(helth:uint = 100){
         myHelth = helth; //this will be set to 100 if nothing it passed in or the value passed
     }
}

Then to use
 var a:Actor = new Actor(200); //setting health to 200

 var b:Actor = new Actor(); //using the default of 100

A: Make sure your symbols in Flash Pro have appropriate AS linkage, then use pass constructor arguments in super statements:
Actor - base class
package
{

    public class Actor
    {
        public function Actor(name:String, role:String)
        {
        }
    }
}

Player - inherits from Actor defining its own constructor parameters:
package
{

    public final class Player extends Actor
    {
        public function Player(... params:Array)
        {
            // pass desired inherited constructor parameters
            super("name", "role");
        }
    }
}

Enemy - inherits from Actor defining its own constructor parameters:
package
{

    public final class Enemy extends Actor
    {
        public function Enemy(... params:Array)
        {
            // pass desired inherited constructor parameters
            super("name", "role");
        }
    }
}


text:
Q: Dynamic HTML table with rowspan in R? For example, suppose I have a data.frame:
df <- data.frame(gene = 'RHO', ref = 123456, totalHits = 13,
                 diseases = c('Multiple Myeloma\nMultiple Myeloma\nMultiple Myeloma\nMultiple Myeloma'),
                 relations = c(' depend\neffect\nexamine\nincrease'),
                 entrez = 1233)

I want to dynamically create an HTML table that appears like the following. However, after looking through the DT and htmlTable packages, I cannot find clear documentaion on how to handle this rowspan behavior. It appears DT cannot handle this, and I can only find examples of colspan-like behavior for htmlTable package. Keep in mind, my intention is to create the table dynamically. This is going to be with in a Shiny app, so I might have more than a single row, like I have in this example, in which the "Gene" would be the same, but the "Reference" would be different. Or, more than 4 entries under the "Diseases" column, which should match up horizontally with those entries in the "Relations" column. Any suggestions?

<!DOCTYPE html>

      geneSymbol
      reference
      totalHits
      diseases
      relations
      entrez

      RHO
      123456
      16
      Multiple Myeloma
      depend
      1233

      Multiple Myeloma
      effect

      Multiple Myeloma
      examine

      Multiple Myeloma
      increase


text:
Q: Signing a unique number to a row in postgresql based on another row I am trying to uniquely identify users within an anonymous comment section. I have decided to have 256 unique identifiers. So I want to return a value of 0-255 for the post they made. I have this table for example:
create table post (
  reply_to int,         //post number they are replying to
  opUUID varchar(36),
  imageuuid varchar(36),
  contents varchar(1516),
  timestamp timestamp
)

create table identity (
   reply_to int,
   opUUID varchar(36),
   <unique value from 0-255> int,
)

Where this is a many post to one identity relation for the context of the comment section.
I was looking into using postgresql identities and passing in a function to it but I am unable to find a way to do this. When its the first opUUID (user) to comment on a post (reply_to) I would like to look at all other unique values assigned to other opUUIDs and assign a unique value not used yet to this new opUUID.


text:
Q: Magento cannot override Mage_Payment_Model_Method_Cc.php file I am trying to override Payment/Model/Method/Cc.php file but it's not able rewrite. can you please any one check my script.
config.xml:
<?xml version="1.0"?>
<config>
   <modules>
      <Naveed_Abbas>
        <version>0.1.0</version>
      </Naveed_Abbas>
   </modules>
<global>
    <models>
       <payment>
            <rewrite>
                <method_cc>Naveed_Abbas_Model_Payment_Method_Cc</method_cc>
            </rewrite>
       </payment>
    </models>
  </global>
</config>

Naveed/Abbas/Model/Payment/Method/Cc.php :
<?php
  class Naveed_Abbas_Model_Payment_Method_Cc extends Mage_Payment_Model_Method_Cc {

    public function isAvailable($quote = null) {
         Mage::log("Canel Order",null,'isAvailable-test-1.log');
        return $this->getConfigData('cctypes', ($quote ? $quote->getStoreId() : null))
        && parent::isAvailable($quote);
    }
  }

A: Explanation is easy here.
There is a class Mage_Payment_Model_Method_Cc which has a lot of methods. The other class Mage_Payment_Model_Method_Ccsave is extended from it. It has few protected properties. All methods it takes from it's parent.
When magento is looking for some method from Mage_Payment_Model_Method_Ccsave and didn't find it there - it goes to it's parent method.
As result you see in xdebug that you are referring to Mage_Payment_Model_Method_Cc. But if you look which class is inside $this - you will see Mage_Payment_Model_Method_Ccsave.

A: I tried lot of ways finally i got the solution.
config.xml
<?xml version="1.0"?>
<config>
   <modules>
      <Naveed_Abbas>
          <version>0.1.0</version>
      </Naveed_Abbas>
   </modules>
   <global>
     <models>
        <payment>
          <rewrite>
            <method_ccsave>Naveed_Abbas_Model_Payment_Method_Cc</method_ccsave>
           </rewrite>
        </payment>
     </models>
   </global>
 </config>

Naveed/Abbas/Model/Payment/Method/Cc.php :
<?php

   class Naveed_Abbas_Model_Payment_Method_Cc extends Mage_Payment_Model_Method_Ccsave{

      public function isAvailable($quote = null) {
         echo "Test"; //sssssssexit;
         Mage::log("Canel Order",null,'isAvailable-test-1.log'); exit;
         return $this->getConfigData('cctypes', ($quote ? $quote->getStoreId() : null))
        && parent::isAvailable($quote);
     }
  }

A: You can try with below way using <payment_method_cc> in config.xml file,
<?xml version="1.0"?>
<config>
   <modules>
      <Naveed_Abbas>
        <version>0.1.0</version>
      </Naveed_Abbas>
   </modules>
<global>
    <models>
       <naveed_abbas>
            <class>Naveed_Abbas_Model</class>
       </naveed_abbas>
       <payment>
            <rewrite>
                <payment_method_cc>Naveed_Abbas_Model_Payment_Method_Cc</payment_method_cc>
            </rewrite>
       </payment>
    </models>
  </global>
</config>


text:
Q: Regular Expression to exclude substring I'm trying to parse through a string with regular expressions (.NET) and find all custom tokens starting with [[ and ending with ]]. My first attempt was to use \[\[(.*)\]\]. This seemed to work when there was only one token in a string. But if there were multiple, it just return one result from the first [[ to the very last ]].
My thought is to exclude ]] from matching characters, but I've yet to find a way to get that working. I've tried using exclusion sets (?! \]\]) and played around with different syntax, but can't find anything that actually works.
Anyone know an easy way to do this?

A: Regular expressions are greedy by default, i.e. they consume as many characters as possible. To avoid this put a "?" after the ".*", i.e. try \[\[(.*?)\]\].

A: It's even simpler than that, try using .*? (the last ? means it is an ungreedy match, meaning it will grab the bare minimum when catching the information).
For reference, please check out this site on regex. It will give you more details on greedy vs. ungreedy.

A: .* is a "greedy" match, and goes to the last match of your brackets.
*? specifies the first match that consumes as few repeats as possible (equivalent to lazy *)


text:
Q: Printing using PDFrenderer to print pdf files I am trying to print a pdf file using the pdfrenderer library. For that, it is required to convert the actual pdf file to bytebuffer and pass it to create a PDFFile object. But when i am attempting to do that i am facing illegalArgumentException:
public static void printpdf2(String filename) throws IOException, PrinterException{

    // Create a PDFFile from a File reference
    File f = new File(filename);
    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();
    ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    PDFFile pdfFile = new PDFFile(bb);//Create PDF Print Page,exception here
    PDFPrintPage pages = new PDFPrintPage(pdfFile);

    // Create Print Job
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    pjob.setJobName(f.getName());
    Book book = new Book();
    book.append(pages, pf, pdfFile.getNumPages());
    pjob.setPageable(book);

    // Send print job to default printer
    pjob.print();
}

and this is the exception i receive:
java.lang.IllegalArgumentException
at java.nio.Buffer.position(Unknown Source)
at com.sun.pdfview.PDFFile.parseFile(PDFFile.java:1430)
at com.sun.pdfview.PDFFile.<init>(PDFFile.java:132)
at com.sun.pdfview.PDFFile.<init>(PDFFile.java:108)
at com.amin.PrintRepeatPDF.JPrintFile.printpdf2(JPrintFile.java:77)
at com.amin.PrintRepeatPDF.PrintFile.addTitlePage(PrintFile.java:136)
at com.amin.PrintRepeatPDF.PrintFile.print(PrintFile.java:65)
at com.amin.PrintRepeatPDF.ThreadedAction.run(ThreadedAction.java:79)
at java.lang.Thread.run(Unknown Source)

the method printpdf2 is called from JPrintFile.java line 77. before that its just called from couple of other classes in the hierarchy.
Can someone tell me what am i doing wrong here?


text:
Q: How to specify multiple ids for one record I have records table with booking records info (8 columns). And I want to add to a record information about extra services that a client booked. I created extra_services table, but how can I specify multiple extra services to one record in records table?
If I add 9th column with just one id of extra service then there will be redundancy problem.

A: It depends a little on what is the content of the extra_services table. If it does contain a set of extra services that can be booked you need a table to cross reference the bookings with the extra_services.
If on the other hand you are storing the booked extra services belonging to the record you can just use a ForeignKey field to the index of the records table in the extra_services table, that way you can track which records in extra_services belong the booking record.


text:
Q: Azure Devops - How to access a variable group variable within another variable The following Patch variable works perfectly when setup using the variables functionality within a Pipeline:

*

*Major = 1

*crmRelease = 91

*Minor = 0

*Patch = $[counter(format('{0}.{1}.{2}', variables['major'], variables['crmRelease'], variables['minor']), 030)

Result (on first run) = 1.91.0.30
However, when moving this to a Variable Group, whilst the Major, CrmRelase, and Minor variables are ok, the Patch variable isn't valid and fails. Must you reference Variable Group variables in a different way?

A:
Must you reference Variable Group variables in a different way?

The issue for Patch does not been parsed is not relevant with the reference way to variable which stored at variable group. It just because the function parse does not supported in Variable group.
For further analysis, here let's do 2 tests(the first one is failed to get Patch value, but the second one can succeed).
One is put all of them into Variable group.
The another is putting Major, crmRelease, Minor into Variable group, but **  ** make Patch in Variables.

Here are their initial logs:
Putting all of them into Variable group:

Only store Patch into Variables, but make others still in Variable group:

You can see, only store Patch in Variables, the function of it can be parsed at compile time. For the one which store at Variable group, our system treat it as a normal value. We does not support the function parse process when it is from Variable group.

To make it not interrupt your build, please make sure the variable which contains the functions in it are located at Variables instead of Variable group.


text:
Q: how to return custom data with response in Customer API I am calling Magento2 API /V1/customers/me I want to add custom data in response of this API that is stored in my custom table how can I implement this ?
Thanks !!

A: You should add this custom data via extension attributes. The approach for this is well documented, links below:

*

*https://developer.adobe.com/commerce/php/development/components/add-attributes/
You'll want to set these extension attributes on \Magento\Customer\Api\Data\CustomerInterface for your use case.

A: To implement custom data in response, you need to create a custom API, i.e., with a custom module first, so you code your custom API.
You need to extend the functionality of your model like Vendor -> Module -> Model. And add your code in the getData() function call the other module dependencies if you want.
Just like this:
class GetCustomer implements GetCustomerInterface
{

 /**
 * {@inheritdoc}
 */

public function getData()
{

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();

    $tableName = $resource->getTableName('your_table_name');

    $select = $connection->select()
    ->from(
   ['p' => $tableName]);

   $data = $connection->fetchAll($select);

   return $data;

}

}

If you didn't understand anything or need further justification, feel free to ask.


text:
Q: Apply "active" class on active url in Laravel dynamically, what is the clean and reusable way? For the following URLs:

*

*http://localhost/admin/users

*http://localhost/admin/users/create

*http://localhost/admin/users/profile/1
I want to apply class "active" to users navigation dynamically in Laravel as follows:

Users

Pages

What is the clean and reusable way to do this without using third party plugins?

A: Method 1: Single line shortcut solution

Use {{ request()->is('users') ? 'active' : '' }} as described in this answer as follows:

is('*users*') ? 'active' : '' }}">Users

is('*pages*') ? 'active' : '' }}">Pages

Method 2: Clean and reusable solution
You can create and use a custom helper named "active" by following these steps:

*

*Add {{ active('partial-url') }} in your class attribute

Users

Pages

*Create a file named "helpers.php" in your app directory and add this helper function

<?php
function active($partialUrl){
      return request()->is("*".$partialUrl."*") ? 'active' : '';
}

*Add the helpers.php file to autoload by adding the following line in your composer.json file

    ...
     "autoload": {
          ...
          "files": [
              ...
              "app/helpers.php",
          ],
          ...
    },
   ...

"..." in above code snipet means that there may or may not be some other lines of code

*Dump the auto-loader by running the following command

composer dump-autoload


text: Q: Does it slow down to initializing an objects for all usres I was wondering in php if i initialize a new object for each user that logs into my system and add all the users that are logged in a collection then access their methods and properties whenever needed will that slow down my system in the future if i start having more logins. i need to know what is the best method, is it to list all the users from the database using a static method or it is better off to initialize the object and assign their values to the right property then call those properties whenever i need them while using the system.


text:
Q: Cannot save ggplot2 graph with ggsave on Mac After successfully creating a graph with this code:
qplot(ethcat3, Percent, data=g_02_1b_pov, geom="bar", stat="identity")

I would like to save the graph as a png, pdf, or jpeg file. I used the following code:
ggsave(file="test.png")

Instead of outputting the graph, I receive the following (error) message:
Saving 7.82 x 3.75 in image
Error in eval(expr, envir, enclos) : attempt to apply non-function

and no file is saved. (Instead of png, I also tried the extensions pdf, and jpeg).
I found in a forum that I should use the command: dev_mode() and has_devel()
the output of dev_mode is:
> dev_mode()
Dev mode: OFF

and
> has_devel()
/Library/Frameworks/R.framework/Resources/bin/R --vanilla CMD SHLIB foo.c

sh: make: command not found
Error: Command failed (1)

However, I don't know what to do with this feedback?
Can anyone help me with this problem? I think I used the same approach in the past on a PC and it worked without a problem. I'm wondering if it is connected to my installation on a mac?
Thanks a lot!
Addition: @DWin asked for the sessionInfo() output:
d> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] C/en_US.UTF-8/C/C/C/C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] devtools_0.8    reshape2_1.2.1  plyr_1.7.1      ggplot2_0.9.2.1

loaded via a namespace (and not attached):
 [1] MASS_7.3-18        RColorBrewer_1.0-5 RCurl_1.95-3       colorspace_1.2-0
 [5] dichromat_1.2-4    digest_0.5.2       evaluate_0.4.2     grid_2.15.1
 [9] gtable_0.1.1       httr_0.2           labeling_0.1       memoise_0.1
[13] munsell_0.4        parallel_2.15.1    proto_0.3-9.2      scales_0.2.2
[17] stringr_0.6.1      tools_2.15.1       whisker_0.1


text:
Q: How can I keep an environment all on one page? In other words, how can I forbid pagination between \myenv and \endmyenv?  I thought at first to make the whole thing a box; if I'm not mistaken---this would prevent TeX from breaking it up---but I don't know how to do that in an environment...environment.
I have a not-MWE, but I feel like this question is sufficiently general that it doesn't need one; it may even be a duplicate that I failed to find.


text:
Q: Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression I have a ternary operator dir === 'next' ? ++$currentSlide : --$currentSlide; in my JS used to increment of decrement an integer. when I run my script in grunt JSHint hightlights this line as Expected an assignment or function call and instead saw an expression.
Can anyone advise where I'm going wrong with this? Should I set my condition up differently etc?

A: In general, for disabling the 'Expected an assignment or function call and instead saw an expression.' warning, you can do /* jshint expr: true */

A: Does it pass if you write it like this?
$currentSlide = (dir === 'next' ? $currentSlide + 1 : $currentSlide - 1);

Linters and hinters usually don't like in/decrements because they're sensitive to bugs.

A: You are misusing the conditional operator as an if statement, that's why you are getting that note. The real work in the code is done as a side effect of the expression, and the result of the expression is ignored.
As a real if statement, it would be:
if (dir === 'next') {
  ++$currentSlide;
} else {
  --$currentSlide;
}

You can use the conditional operator if you use it as an actual expression:
$currentSlide += dir === 'next' ? 1 : -1;

A: Try this syntax:
$currentSlide = (dir === 'next' ? $currentSlide+1 : $currentSlide-1);

A: make ternary operator in to if else condition
Before:
(pbook.id === book.id ? book.shelf = pbook.shelf : "none");

After:
                     if(pbook.id === book.id){
                        return book.shelf = pbook.shelf
                      } else {
                        return "none"
                      };


text:
Q: Mysterious color showing up on tab hover In my site's design, I am using jQuery UI tabs, and I would like to change a dark green color that shows up when I hover over the tabs. However, I cannot find this color anywhere in the CSS or override it, and the Chrome developer tools do not show any such color matched to the tabs. Here is the jsfiddle: http://jsfiddle.net/Uy4Jz/1/
I feel like this CSS should be able to override it but that doesn't seem to be the case:
#tabs .ui-tabs-nav .ui-state-active {
    background: transparent url(images/uiTabsArrow.png) no-repeat bottom center;
    border: none;
    color: #000;
}

How should I go about changing this color or overriding it with a different color?

A: It comes from this declaration in your CSS:
.ui-state-hover a,
.ui-state-hover a:hover,
.ui-state-hover a:link,
.ui-state-hover a:visited {
    color: #205225;
    text-decoration: none;
}

Probably best to update all instances of
color: #205225;

To the appropriate hex color you're after.

A: Overwrite this in your CSS with your desired color
.ui-state-hover a,
.ui-state-hover a:hover,
.ui-state-hover a:link,
.ui-state-hover a:visited{
    color: #205225; /*change this*/
}

A: If you are talking about "Blog", "About Me" and "Projects", target the a within the li list and style its hover psuedo element
#tabs ul li a:hover {
    color: blue;
}