text:
Q: IOException: The process cannot access the file 'file path' because it is being used by another process I have some code and when it executes, it throws a IOException, saying that

The process cannot access the file 'filename' because it is being used by
  another process

What does this mean, and what can I do about it?

A: Using FileShare fixed my issue of opening file even if it is opened by another process.
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}

A: As other answers in this thread have pointed out, to resolve this error you need to carefully inspect the code, to understand where the file is getting locked.
In my case, I was sending out the file as an email attachment before performing the move operation.
So the file got locked for couple of seconds until SMTP client finished sending the email.
The solution I adopted was to move the file first, and then send the email. This solved the problem for me.
Another possible solution, as pointed out earlier by Hudson, would've been to dispose the object after use.
public static SendEmail()
{
           MailMessage mMailMessage = new MailMessage();
           //setup other email stuff

            if (File.Exists(attachmentPath))
            {
                Attachment attachment = new Attachment(attachmentPath);
                mMailMessage.Attachments.Add(attachment);
                attachment.Dispose(); //disposing the Attachment object
            }
}

A: I got this error because I was doing File.Move to a file path without a file name, need to specify the full path in the destination.

A: What is the cause?
The error message is pretty clear: you're trying to access a file, and it's not accessible because another process (or even the same process) is doing something with it (and it didn't allow any sharing).
Debugging
It may be pretty easy to solve (or pretty hard to understand), depending on your specific scenario. Let's see some.
Your process is the only one to access that file
You're sure the other process is your own process. If you know you open that file in another part of your program, then first of all you have to check that you properly close the file handle after each use. Here is an example of code with this bug:
var stream = new FileStream(path, FileAccess.Read);
var reader = new StreamReader(stream);
// Read data from this file, when I'm done I don't need it any more
File.Delete(path); // IOException: file is in use

Fortunately FileStream implements IDisposable, so it's easy to wrap all your code inside a using statement:
using (var stream = File.Open("myfile.txt", FileMode.Open)) {
    // Use stream
}

// Here stream is not accessible and it has been closed (also if
// an exception is thrown and stack unrolled

This pattern will also ensure that the file won't be left open in case of exceptions (it may be the reason the file is in use: something went wrong, and no one closed it; see this post for an example).
If everything seems fine (you're sure you always close every file you open, even in case of exceptions) and you have multiple working threads, then you have two options: rework your code to serialize file access (not always doable and not always wanted) or apply a retry pattern. It's a pretty common pattern for I/O operations: you try to do something and in case of error you wait and try again (did you ask yourself why, for example, Windows Shell takes some time to inform you that a file is in use and cannot be deleted?). In C# it's pretty easy to implement (see also better examples about disk I/O, networking and database access).
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

for (int i=1; i <= NumberOfRetries; ++i) {
    try {
        // Do stuff with file
        break; // When done we can break loop
    }
    catch (IOException e) when (i <= NumberOfRetries) {
        // You may check error code to filter some exceptions, not every error
        // can be recovered.
        Thread.Sleep(DelayOnRetry);
    }
}

Please note a common error we see very often on StackOverflow:
var stream = File.Open(path, FileOpen.Read);
var content = File.ReadAllText(path);

In this case ReadAllText() will fail because the file is in use (File.Open() in the line before). To open the file beforehand is not only unnecessary but also wrong. The same applies to all File functions that don't return a handle to the file you're working with: File.ReadAllText(), File.WriteAllText(), File.ReadAllLines(), File.WriteAllLines() and others  (like File.AppendAllXyz() functions) will all open and close the file by themselves.
Your process is not the only one to access that file
If your process is not the only one to access that file, then interaction can be harder. A retry pattern will help (if the file shouldn't be open by anyone else but it is, then you need a utility like Process Explorer to check who is doing what).
Ways to avoid
When applicable, always use using statements to open files. As said in previous paragraph, it'll actively help you to avoid many common errors (see this post for an example on how not to use it).
If possible, try to decide who owns access to a specific file and centralize access through a few well-known methods. If, for example, you have a data file where your program reads and writes, then you should box all I/O code inside a single class. It'll make debug easier (because you can always put a breakpoint there and see who is doing what) and also it'll be a synchronization point (if required) for multiple access.
Don't forget I/O operations can always fail, a common example is this:
if (File.Exists(path))
    File.Delete(path);

If someone deletes the file after File.Exists() but before File.Delete(), then it'll throw an IOException in a place where you may wrongly feel safe.
Whenever it's possible, apply a retry pattern, and if you're using FileSystemWatcher, consider postponing action (because you'll get notified, but an application may still be working exclusively with that file).
Advanced scenarios
It's not always so easy, so you may need to share access with someone else. If, for example, you're reading from the beginning and writing to the end, you have at least two options.
1) share the same FileStream with proper synchronization functions (because it is not thread-safe). See this and this posts for an example.
2) use FileShare enumeration to instruct OS to allow other processes (or other parts of your own process) to access same file concurrently.
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
}

In this example I showed how to open a file for writing and share for reading; please note that when reading and writing overlaps, it results in undefined or invalid data. It's a situation that must be handled when reading. Also note that this doesn't make access to the stream thread-safe, so this object can't be shared with multiple threads unless access is synchronized somehow (see previous links). Other sharing options are available, and they open up more complex scenarios. Please refer to MSDN for more details.
In general N processes can read from same file all together but only one should write, in a controlled scenario you may even enable concurrent writings but this can't be generalized in few text paragraphs inside this answer.
Is it possible to unlock a file used by another process? It's not always safe and not so easy but yes, it's possible.

A: The error indicates another process is trying to access the file.  Maybe you or someone else has it open while you are attempting to write to it.  "Read" or "Copy" usually doesn't cause this, but writing to it or calling delete on it would.
There are some basic things to avoid this, as other answers have mentioned:

*

*In FileStream operations, place it in a using block with a FileShare.ReadWrite mode of access.
For example:
using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}

Note that FileAccess.ReadWrite is not possible if you use FileMode.Append.

*I ran across this issue when I was using an input stream to do a File.SaveAs when the file was in use.  In my case I found, I didn't actually need to save it back to the file system at all, so I ended up just removing that, but I probably could've tried creating a FileStream in a using statement with FileAccess.ReadWrite, much like the code above.

*Saving your data as a different file and going back to delete the old one when it is found to be no longer in use, then renaming the one that saved successfully to the name of the original one is an option.  How you test for the file being in use is accomplished through the
List<Process> lstProcs = ProcessHandler.WhoIsLocking(file);

line in my code below, and could be done in a Windows service, on a loop, if you have a particular file you want to watch and delete regularly when you want to replace it.  If you don't always have the same file, a text file or database table could be updated that the service always checks for file names, and then performs that check for processes & subsequently performs the process kills and deletion on it, as I describe in the next option.  Note that you'll need an account user name and password that has Admin privileges on the given computer, of course, to perform the deletion and ending of processes.

*When you don't know if a file will be in use when you are trying to save it, you can close all processes that could be using it, like Word, if it's a Word document, ahead of the save.
If it is local, you can do this:
ProcessHandler.localProcessKill("winword.exe");

If it is remote, you can do this:
ProcessHandler.remoteProcessKill(computerName, txtUserName, txtPassword, "winword.exe");

where txtUserName is in the form of DOMAIN\user.

*Let's say you don't know the process name that is locking the file. Then, you can do this:
List<Process> lstProcs = new List<Process>();
lstProcs = ProcessHandler.WhoIsLocking(file);

foreach (Process p in lstProcs)
{
    if (p.MachineName == ".")
        ProcessHandler.localProcessKill(p.ProcessName);
    else
        ProcessHandler.remoteProcessKill(p.MachineName, txtUserName, txtPassword, p.ProcessName);
}

Note that file must be the UNC path:  \\computer\share\yourdoc.docx in order for the Process to figure out what computer it's on and p.MachineName to be valid.
Below is the class these functions use, which requires adding a reference to System.Management. The code was originally written by Eric J.:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Management;

namespace MyProject
{
    public static class ProcessHandler
    {
        [StructLayout(LayoutKind.Sequential)]
        struct RM_UNIQUE_PROCESS
        {
            public int dwProcessId;
            public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
        }

        const int RmRebootReasonNone = 0;
        const int CCH_RM_MAX_APP_NAME = 255;
        const int CCH_RM_MAX_SVC_NAME = 63;

        enum RM_APP_TYPE
        {
            RmUnknownApp = 0,
            RmMainWindow = 1,
            RmOtherWindow = 2,
            RmService = 3,
            RmExplorer = 4,
            RmConsole = 5,
            RmCritical = 1000
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        struct RM_PROCESS_INFO
        {
            public RM_UNIQUE_PROCESS Process;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
            public string strAppName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
            public string strServiceShortName;

            public RM_APP_TYPE ApplicationType;
            public uint AppStatus;
            public uint TSSessionId;
            [MarshalAs(UnmanagedType.Bool)]
            public bool bRestartable;
        }

        [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
        static extern int RmRegisterResources(uint pSessionHandle,
                                            UInt32 nFiles,
                                            string[] rgsFilenames,
                                            UInt32 nApplications,
                                            [In] RM_UNIQUE_PROCESS[] rgApplications,
                                            UInt32 nServices,
                                            string[] rgsServiceNames);

        [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
        static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

        [DllImport("rstrtmgr.dll")]
        static extern int RmEndSession(uint pSessionHandle);

        [DllImport("rstrtmgr.dll")]
        static extern int RmGetList(uint dwSessionHandle,
                                    out uint pnProcInfoNeeded,
                                    ref uint pnProcInfo,
                                    [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                    ref uint lpdwRebootReasons);

        /// <summary>
        /// Find out what process(es) have a lock on the specified file.
        /// </summary>
        /// <param name="path">Path of the file.</param>
        /// <returns>Processes locking the file</returns>
        /// <remarks>See also:
        /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
        /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
        ///
        /// </remarks>
        static public List<Process> WhoIsLocking(string path)
        {
            uint handle;
            string key = Guid.NewGuid().ToString();
            List<Process> processes = new List<Process>();

            int res = RmStartSession(out handle, 0, key);
            if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");

            try
            {
                const int ERROR_MORE_DATA = 234;
                uint pnProcInfoNeeded = 0,
                    pnProcInfo = 0,
                    lpdwRebootReasons = RmRebootReasonNone;

                string[] resources = new string[] { path }; // Just checking on one resource.

                res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

                if (res != 0) throw new Exception("Could not register resource.");

                //Note: there's a race condition here -- the first call to RmGetList() returns
                //      the total number of process. However, when we call RmGetList() again to get
                //      the actual processes this number may have increased.
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

                if (res == ERROR_MORE_DATA)
                {
                    // Create an array to store the process results
                    RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                    pnProcInfo = pnProcInfoNeeded;

                    // Get the list
                    res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                    if (res == 0)
                    {
                        processes = new List<Process>((int)pnProcInfo);

                        // Enumerate all of the results and add them to the
                        // list to be returned
                        for (int i = 0; i < pnProcInfo; i++)
                        {
                            try
                            {
                                processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                            }
                            // catch the error -- in case the process is no longer running
                            catch (ArgumentException) { }
                        }
                    }
                    else throw new Exception("Could not list processes locking resource.");
                }
                else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
            }
            finally
            {
                RmEndSession(handle);
            }

            return processes;
        }

        public static void remoteProcessKill(string computerName, string userName, string pword, string processName)
        {
            var connectoptions = new ConnectionOptions();
            connectoptions.Username = userName;
            connectoptions.Password = pword;

            ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2", connectoptions);

            // WMI query
            var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");

            using (var searcher = new ManagementObjectSearcher(scope, query))
            {
                foreach (ManagementObject process in searcher.Get())
                {
                    process.InvokeMethod("Terminate", null);
                    process.Dispose();
                }
            }
        }

        public static void localProcessKill(string processName)
        {
            foreach (Process p in Process.GetProcessesByName(processName))
            {
                p.Kill();
            }
        }

        [DllImport("kernel32.dll")]
        public static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);

        public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;

    }
}

A: I had this problem and it was solved by following the code below
var _path=MyFile.FileName;
using (var stream = new FileStream
    (_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
    // Your Code! ;
  }

A: I had a very specific situation where I was getting an "IOException: The process cannot access the file 'file path'" on the line
File.Delete(fileName);

Inside an NUnit test that looked like:
Assert.Throws<IOException>(() =>
{
    using (var sr = File.OpenText(fileName) {
        var line = sr.ReadLine();
    }
});
File.Delete(fileName);

It turns out NUnit 3 uses something they call "isolated context" for exception assertions. This probably runs on a separate thread.
My fix was to put the File.Delete in the same context.
Assert.Throws<IOException>(() =>
{
    try
    {
        using (var sr = File.OpenText(fileName) {
            var line = sr.ReadLine();
        }
    }
    catch
    {
        File.Delete(fileName);
        throw;
    }
});

A: Problem
one is tying to open file System.IO.File.Open(path, FileMode) with this method and want a shared access on file but
if u read documentation of System.IO.File.Open(path, FileMode) it is explicitly saying its does not allow sharing

Solution
use you have to use other override with FileShare

using FileStream fs = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

with  FileShare.Read

A: Had an issue while uploading an image and couldn't delete it and found a solution. gl hf
//C# .NET
var image = Image.FromFile(filePath);

image.Dispose(); // this removes all resources

//later...

File.Delete(filePath); //now works

A: I had the following scenario that was causing the same error:

*

*Upload files to the server

*Then get rid of the old files after they have been uploaded

Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.
It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":
using (var wc = new WebClient())
{
   var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
   tskResult.Wait();
}

A: In my case this problem was solved by Opening the file for Shared writing/reading. Following are the sample codes for shared reading and writing:-
Stream Writer
using(FileStream fs = new FileStream("D:\\test.txt",
FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (StreamWriter sw = new StreamWriter(fs))
{
    sw.WriteLine("any thing which you want to write");
}

Stream Reader
using (FileStream fs = new FileStream("D:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader rr=new StreamReader(fs))
{
    rr.ReadLine())
}

A: My below code solve this issue, but i suggest
First of all you need to understand what causing this issue and try the solution which you can find by changing code
I can give another way to solve this issue but better solution is to check your coding structure and try to analyse what makes this happen,if you do not find any solution then you can go with this code below
try{
Start:
///Put your file access code here

}catch (Exception ex)
 {
//by anyway you need to handle this error with below code
   if (ex.Message.StartsWith("The process cannot access the file"))
    {
         //Wait for 5 seconds to free that file and then start execution again
         Thread.Sleep(5000);
         goto Start;
    }
 }


text:
Q: HTML Radio button in body tag, Once selected get all the values for that row and call RPGLE program I have HTML web page and i am using Table layout to show all the values from database. Now once user select any row using radio button, i want all the values in that row passed on to Iseries/AS400 program.
Webpage image
How to get all the values from row.. please advise ...
is there any method of passing those values. In Iseries i am using CGI libraries. In html i am using POST method which i calling backend program.

A: if each record is a html table row and each cell html table cell, all embedded inside a true html table element, then do the following javascript at the very bottom of the html document just above the  end tag:

        ...cell 1
        ...cell 2
        ...cell 3
        ...etc...

A: Yes, that's a very basic requirement.
You don't mention which CGI library you are using, but of of them should have documentation, examples and possibly tutorials that will show you what needs to be done to accomplish your request.
Edit
Check out the http://cgidev2.easy400.net/ site...
But basically, you'll probably want to wrap your other RPG program with a CGI RPG program that can convert the query parms or post data into the parameter's needed by the program you want called.  Then it's simply a matter of redirecting the user to the new CGI program.
However
Judging from your screen shot, you've got basically a WRKSPLF screen with View, Download and Delete button's I assume you are trying to get to function...
Delete is easy, as there's no real UI for it..
View & Download are a whole other story... you can't simply "call another program" and expect the user to be able to view or download the spool data.  Well you could, assuming you've built a program that will convert a spool file to HTML/TXT/PDF that a browser can display or download.
Such a program would normally store the converted stream file in the IFS; in which case it's a simple matter of calling the DspStmf() or DnlStmf() subprocedure included in CGIDEV2.
Honestly CGIDEV2 was a good option 15 years ago, but you'll have to handle a lot yourself.  There's much better options now-a-days.
I suggest taking a look at the Tools and Solutions for Modernizing Your IBM i Applications Redpaper by IBM.   It's a good start for some of the possibilities.  However, even though it was updated in 2017, it doesn't go into some of the opensource options such as PHP, Python or node.js all of which are supported on today's IBM i and offer lot's of possibilities for new development.
Since stackoverflow isn't the place for asking for tool recommendations, consider joining the Midrange.com WEB400 mailing list.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set seekbar unmovable using kotlin? How to set seekbar widget unmovable using kotlin language in android studio?

A: //kotlin
mySeekBar.enabled = false;

//java
mySeekBar.setEnabled(false);

This will block it from moving and it will be frozen


text:
Q: Rails: Modeling a list that can contain both items and lists I can't wrap my head around modeling a particular sort of list in Rails.
Basically, I'd like to model a list whose members contain other lists or individual items.
Let's say I have a table of car parts
Table Part
name
cost
color

Let's say that some lists of parts are very common so I want to define some lists of parts and reuse those lists.  For instance:
Table PartList
name

Table PartListItem
part_id
partList_id
position

Now, if I want show the items needed for a particular car, I'd like a list whose members may be items particular to a given car and members that are a list of commonly bundled items that can be found in many cars.
Might look like this:
Parts List For Modest car:
 - List of parts for engine
 - List of parts for body
 - front bumper
 - back bumper
 - tail pipe
 - List of parts for safety compliance
Parts List For Fancy car:
 - List of parts for engine
 - List of parts for body
 - Shiny front bumper
 - Shiny back bumper
 - Wizbang tail pipe
 - List of parts for safety compliance
If I were to modify the list of parts for 'engine' a view into either car part list would reflect the change. Regardless of the hierarchical level of the list, the list may contain more lists or individual items.
Once all lists are 'expanded' their contents are all 'Parts'
I may be wrong, but this is not exactly recursion, not exactly a tree, and not exactly nested sets.  Feels a little like a menuing system to me, but each member of the 'menu' may have many attributes.
Is there a DRY solution for this sort of problem?  I'd be happy to accept some, uh... lack of DRYness if it facilitated a solution I could understand.

A: Seems to me STI and HABTM could solve your problem.
You'd like to design something like the following:

A Car can have many parts and a Part can be a single PartItem or a PartList. And a PartList can have many PartItem.
In rails it would be something like:
# migrations
class CreateCars < ActiveRecord::Migration
  def change
    create_table :cars do |t|
      t.string :model
    end
  end
end

class CreateParts < ActiveRecord::Migration
  def change
    create_table :parts do |t|
      t.string :type # STI
      t.string :name
    end
  end
end

class CreateCarsParts < ActiveRecord::Migration
  def change
    create_table :cars_parts do |t|
      t.integer :car_id
      t.integer :part_id
    end
  end
end

class CreatePartListsPartItems < ActiveRecord::Migration
  def change
    create_table :part_lists_part_items do |t|
      t.integer :part_list_id
      t.integer :part_item_id
    end
  end
end

# models
class Car < ActiveRecord::Base
  has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
  has_and_belongs_to_many :cars
end

class PartItem < Part
  has_and_belongs_to_many :part_lists,
                          join_table: :part_lists_part_items
end

class PartList < Part
  has_and_belongs_to_many :part_items,
                          join_table: :part_lists_part_items
end

Hope that helps.


text:
Q: Magento 2 | Add submenu to System->Configuration I want to add a new submenu to this.
How can I do that and add more submenus to the new submenu?

A: app/code/Vendor/Module/etc/adminhtml/system.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="generalmen" translate="label" sortOrder="900">
            New menu
        </tab>

            <class>separator-top admin-newmenu</class>
            Section1
            <tab>generalmen</tab>
            <resource>Vendor_Module::general_config</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                Group1
                <field id="field1" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                    Field1
                </field>
            </group>

    </system>
</config>

This will add :


text:
Q: Golang struct inheritance not working as intended? Check out this sandbox
When declaring a struct that inherits from a different struct:
type Base struct {
    a string
    b string
}

type Something struct {
    Base
    c string
}

Then calling functions specifying values for the inherited values gives a compilation error:
f(Something{
    a: "letter a",
    c: "letter c",
})

The error message is: unknown Something field 'a' in struct literal.
This seems highly weird to me. Is this really the intended functionality?
Thanks for the help!

A: You have to actually instantiate the embedded struct as well. Just so you know this isn't inheritance technically, no such feature exists in Go. It's called embedding. It just hoists fields and methods from the embedded type to the embeddors scope. So anyway, the composite literal instantiation you're trying to do would look like this;
f(Something{
    Base: Base{a: "a", b: "b"},
    c:    "c",
})

A: Golang doesn't provide the typical notion of inheritance. What you are accomplishing here is embedding.
It does not give the outer struct the fields of the inner struct but instead allows the outer struct to access the fields of the inner struct.
In order to create the outer struct Something you need to give its fields which include the inner struct Base
In your case:
Something{Base: Base{a: "letter a"}, c: "letter c"}

A: You need to explicitly create Base field like that
f(Something{
    Base: Base{a: "letter a"},
    c:    "letter c",
})

Go has no inheritance, it is just composition.


text:
Q: scanf() not returning the correct number of arguments I am trying to write a simple program that will take input about people in this format:
 name,age,gender,info

Here is the code so far:
 #include <stdio.h>

 int main() {
    char name[10];
    int age;
    char gender[2];
    char info[50];

    while(scanf("%9s,%i,%1s,%49[^\n]", name, &age, gender, info) == 4)
    puts("Success");

    return 0;
 }

So at the terminal I enter something like: bob,10,M,likes cheese but it does not print out the success message, so I guess the condition at the while loop failed.
So add this code to check the number of arguments:
int i = scanf("%9s,%i,%1s,%49[^\n]", name, &age, gender, info);
printf("%i", i);

and when I enter bob,10,M,likes cheese again, it prints out 1.
Can anyone help please?

A: %9s will consume input until it finds white-space, reaches the specified length (9) or the end of the string, which, in this case, will consume bob,10,M, instead of just bob.
Test.
Try %9[^,],%i,%1s,%49[^\n] instead.
Test.
Also, since gender is 1 character, you may as well make it a char and use %c instead of %1s (unless it's optional).
Test.


text:
Q: How do I DRY query logic between IEnumerable and IQueryable? Given two entities EntityOne and EntityTwo:
public class EntityOne
{
    public string Title { get; set; }
    public bool IsSomething { get; set; }
}

public class EntityTwo
{
    ...

    public virtual IEnumerable<EntityOne> EntityOnes { get; set; }
}

and an EntityOneFilter object like:
public class EntityOneFilter
{
    public EntityOneFilter(string? query, bool? isSomething, ...)
    {
        ...
    }

    public string? Query { get; }
    public bool? IsSomething { get; }
}

I'd like to reuse the query logic that can be applied to both IEnumerable<EntityOne> and IQueryable<EntityOne>:
(filter.Query == null || EF.Functions.Like(entity.Title, $"%{filter.Query}%"))
    && (!filter.IsSomething.HasValue || entity.IsSomething == filter.IsSomething.Value)
    && ...

So that it can be applied to both IQueryables coming from a DbContext:
dbContext.EntityOnes.Where(<something with filter>).FirstAsync();

and also to IEnumerable<EntityOne> that appear as a one to many collection to EntityTwo:
dbContext.EntityTwos
    .Where(e2 => e2.EntityOnes.Where(<something with filter>).Any())
    .FirstAsync();

How can I accomplish this?

A: As suggested in the comments by, I just had to use:
dbContext.EntityTwos
    .Where(e2 => e2.EntityOnes
        .AsQueryable()
        .Where(expression).Any())
    .FirstAsync();

where expression is an Expression<Func<EntityOne, bool>>.


text:
Q: Save in the join table of a ternary relation using hibernate and struts2 is inserting long string in the FK column instead of the IDs Using hibernate - oracle DB, struts2, I am trying to insert in the join table of a ternary relation, but the result is: can not violate FK constraints, so after I removed the FK constraints from DB, I got: ORA-12899: value too large for column, when I looked into the DB, it's inserting too large text instead of the IDs.
I am taking the user info for jsp and the Group and application as checkboxes in the screen.
Tables I have: Users, Groups, Applications and the join table: user_group_application.
the classes are as following:
//-- Users Class --//
public class User implements Serializable{

    private static final long serialVersionUID = 9148926206758390091L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "ID")
    public Long id;
    @Email
    @Column(name="email", unique = true, nullable = false)
    public String email;
    @Column(name="fullName")
    public String fullName;
    @Column(name="password")
    public String password;
    @Column(name="type")
    public String type;
    @Column(name="location")
    public String location;
    @Column(name="status")
    public String status;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.user", cascade = CascadeType.ALL)
    public Set<UserGroupApplication> getUsergroupapplications() {
        return usergroupapplications;
    }
    public void setUsergroupapplications(
            Set<UserGroupApplication> usergroupapplications) {
        this.usergroupapplications = usergroupapplications;
    }

// -- setters and getters
}

the Application and the Groups class are on the same way ..
//-- the join classID --//
 @Embeddable
    public class UserGroupApplicationId implements java.io.Serializable{
        private static final long serialVersionUID = -6790693372846798580L;

        private User user;
        private Group group;
        private Application application;

    @ManyToOne(cascade={CascadeType.ALL})
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

    @ManyToOne(cascade={CascadeType.ALL})
    public Group getGroup() {
        return group;
    }
    public void setGroup(Group group) {
        this.group = group;
    }

    @ManyToOne(cascade={CascadeType.ALL})
    public Application getApplication() {
        return application;
    }
    public void setApplication(Application application) {
        this.application = application;
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserGroupApplicationId that = (UserGroupApplicationId) o;

        if (user != null ? !user.equals(that.user) : that.user != null) return false;
        if (group != null ? !group.equals(that.group) : that.group != null) return false;
        if (application != null ? !application.equals(that.application) : that.application != null) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = (user != null ? user.hashCode() : 0);
        result = 31 * result + (group != null ? group.hashCode() : 0);
        result = 31 * result + (application != null ? application.hashCode() : 0);
        return result;
    }

}

//-- the join class is --//
@Entity
@Table(appliesTo = "RESOURCE_GROUP_APPLICATION")
@AssociationOverrides({
    @AssociationOverride(name = "pk.user", joinColumns = @JoinColumn(name = "resourceid", nullable=false,updatable=false, insertable=false)),
    @AssociationOverride(name = "pk.group", joinColumns = @JoinColumn(name = "groupid", nullable=false,updatable=false, insertable=false)),
    @AssociationOverride(name = "pk.application", joinColumns = @JoinColumn(name = "applicationid", nullable=false,updatable=false, insertable=false))})

public class UserGroupApplication implements Serializable{
    private static final long serialVersionUID = 1949826260753890091L;
    private UserGroupApplicationId pk = new UserGroupApplicationId();
    public UserGroupApplication() {
        // TODO Auto-generated constructor stub
    }

    @EmbeddedId
    public UserGroupApplicationId getPk() {
        return pk;
    }
    public void setPk(UserGroupApplicationId pk) {
        this.pk = pk;
    }

    @Transient
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name = "RESOURCEID")
    public User getUser() {
        return getPk().getUser();
    }
    public void setUser(User user) {
        getPk().setUser(user);
    }

    @Transient
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name = "GROUPID")
    public Group getGroup() {
        return getPk().getGroup();
    }
    public void setGroup(Group group) {
        getPk().setGroup(group);
    }

    @Transient
    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name = "APPLICATIONID")
    public Application getApplication(){
        return getPk().getApplication();
    }
    public void setApplication(Application application) {
        getPk().setApplication(application);
    }

    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        UserGroupApplication that = (UserGroupApplication) o;

        if (getPk() != null ? !getPk().equals(that.getPk())
                : that.getPk() != null)
            return false;

        return true;
    }

    public int hashCode() {
        return (getPk() != null ? getPk().hashCode() : 0);
    }

}

//-- the Action class is --//
public class UserAction extends ActionSupport {
public String addUser() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        this.user = user;
        // save or update the user
        session.saveOrUpdate(user);
        User us = (User) session.get(User.class, user.getId());
    Long gid;
    Group gr;
    usrgrpsapps = new HashSet<UserGroupApplication>(0);
    userGroupApplication = new UserGroupApplication();
    userGroupApplication.setUser(us);
    Long uid = userGroupApplication.getUser().getId();

    this.groupschecked = groupschecked;
    for (int i = 0; i < groupschecked.size(); i++) {
        gid = Long.parseLong(groupschecked.get(i));
        gr = (Group) session.get(Group.class, gid);
        userGroupApplication.setGroup(gr);

        Long appid;
        Application app;
        this.appschecked = appschecked;
        for (int j = 0; j < appschecked.size(); j++) {
            appid = Long.parseLong(appschecked.get(j));
            app = (Application) session.get(Application.class, appid);
            userGroupApplication.setApplication(app);
            usrgrpsapps.add(userGroupApplication);
            us.getUsergroupapplications().add(userGroupApplication);
            app.getUserGroupApplication().add(userGroupApplication);
            gr.getUserGroupApplication().add(userGroupApplication);
            session.saveOrUpdate(us);
            session.saveOrUpdate(gr);
            session.saveOrUpdate(app);
            session.save(userGroupApplication);
            //session.save(usrgrpsapps);
        }
    }
    tx.commit();

    return SUCCESS;
}


text:
Q: asp.net check image resolution and save in DB asp.net core MVC - framework net6.0
I have a page in which i upload an image and save it to the db.
the file i'm getting from the view is IFormFile.
I want to be able to check the resolution (width and height) of the photo before saving in DB.
Can it be done with IFormFile?
here is the controller that handles the file :
public JsonResult Submit(IFormFile PhotoFile)
        {
            int success = 0;
            string excep = "";
            try
            {
                if (PhotoFile.Length > 0)
                {
                    using (var ms = new MemoryStream())
                    {
                        PhotoFile.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                    }
                }
                ApplicationUser appUser =
                     _unitOfWork.ApplicationUser.GetAll().Where(a => a.UserName == User.Identity.Name).FirstOrDefault();
                if (appUser != null)
                {
                    FileUpload fileUpload = new FileUpload()
                    {
                        file = PhotoFile,
                        CompanyId = appUser.CompanyId
                    };
                    SaveFile(fileUpload);
                }
                excep = "success";
                success = 1;
                return Json(new { excep, success });
            }
            catch (Exception ex)
            {
                excep = "fail";
                success = 0;
                return Json(new { excep, success });
            }
        }
public string SaveFile(FileUpload fileObj)
        {
            Company company = _unitOfWork.Company.GetAll().
                Where(a => a.Id == fileObj.CompanyId).FirstOrDefault();
            if(company != null && fileObj.file.Length > 0)
            {
                using (var ms = new MemoryStream())
                {
                    fileObj.file.CopyTo(ms);
                    var fileBytes = ms.ToArray();
                    company.PhotoAd = fileBytes;
                    _unitOfWork.Company.Update(company);
                    _unitOfWork.Save();
                    return "Saved";
                }
            }
            return "Failed";
        }

A: As far as I know this isn't possible with just IFormFile and you need System.Drawing.Common.
So first you need to convert it like:
using var image = Image.FromStream(PhotoFile.OpenReadStream());

Then you can simply get the height/width with image.height and image.width


text:
Q: Swift - How to create dynamic labels in stackview? I'm trying to create a stackview with dynamic number of lables.
I tried with:
let nValues: String = "A , B, C, D"

if let someArray = nValues.components(separatedBy: ",") {
         let label: UILabel = UILabel()
            for nValue in someArray {
              label.text = nValue
              label.textColor = .black
              nutrientValueLabel?.backgroundColor = .white
              myStackView.addSubview(label)
              print(nValue)
     }
 }

But i get only:
A
B
C
D

and empty stackView.
I don't know what is my mistake.

A: My mistake was that I created my label at the beginning.
I put it in the for loop. And used
myStackView.addArrangedSubview(label)

instead of
myStackView.addSubview(label)

So This is the whole code:
let nValues: String = "A , B, C, D"

if let someArray = nValues.components(separatedBy: ",") {
      for nValue in someArray {
          let label: UILabel = UILabel()
          label.text = nValue
          label.textColor = .black
          nutrientValueLabel?.backgroundColor = .white
          myStackView.addArrangedSubview(label)
     }
 }


text:
Q: how to open listbox upwards I have listbox in a popup under a textbox in my project
the text in textbox is searched and results are shown in listbox
my problem is the textbox is nearly at the bottom of my page and when textbox is got focussed the the page move upwards for the textbox is to be seen when virtual keyboard is on the screen however the listbox stays back of the virtual keyboard
can the listbox open upwards so that it goes above the textbox and will be seen when the virtual keyboard is on the screen as well


text:
Q: Read response data in network events of the JxBrowser I'm trying to fetch the network data from the JxBrowser component (EDIT: it's version 5.4) in my Java application using Network Events:
BrowserContext browserContext = BrowserContext.defaultContext();

browserContext.getNetworkService().setNetworkDelegate(new DefaultNetworkDelegate() {
  @Override
  public void onCompleted(RequestCompletedParams var) {
    // var.getResponseBody() // does not exist
    System.out.println("Requested " + var.getURL());
  }
});

Browser browser = new Browser(browserContext);
browser.loadURL("https://www.example.org/");

I can obtain the URL of all completed requests and print it into the terminal, however there is no function like getResponseBody() to fetch the body data.
The aim is to read the response data of several AJAX calls from within the Host of the JxBrowser component. I'm unable to modify or access the website, directly.


text:
Q: Grails fails to realize Domain class I'm using Grails 3.1.4, I've created some domain object and written unit test.
Tests are executed fine on my computer.
Tests on my computer
But on the other developpers computers and on the continous integration platform, tests fail with exception :
java.lang.IllegalStateException: Either class [ ] is not a domain class or GORM has not been initialized correctly or has already been shutdown. If you are unit testing your entities using the mocking APIs
at org.grails.datastore.gorm.GormEnhancer.stateException(GormEnhancer.groovy:159)
at org.grails.datastore.gorm.GormEnhancer.findValidationApi(GormEnhancer.groovy:173)
at org.grails.datastore.gorm.GormValidateable$Trait$Helper.currentGormValidationApi(GormValidateable.groovy:120)
at org.grails.datastore.gorm.GormValidateable$Trait$Helper.validate(GormValidateable.groovy:87)
at com.cscinfo.platform.constraint.CascadeValidationConstraint.validateValue(CascadeValidationConstraint.groovy:43)
at com.cscinfo.platform.constraint.CascadeValidationConstraint.processValidateWithVetoing_closure1(CascadeValidationConstraint.groovy:29)
at groovy.lang.Closure.call(Closure.java:426)
at com.cscinfo.platform.constraint.CascadeValidationConstraint.processValidateWithVetoing(CascadeValidationConstraint.groovy:28)
at grails.validation.AbstractVetoingConstraint.validateWithVetoing(AbstractVetoingConstraint.java:33)
at grails.validation.ConstrainedProperty.validate(ConstrainedProperty.java:967)
at org.grails.validation.GrailsDomainClassValidator.validatePropertyWithConstraint(GrailsDomainClassValidator.java:211)
at org.grails.validation.GrailsDomainClassValidator.validate(GrailsDomainClassValidator.java:81)
at org.grails.datastore.gorm.GormValidationApi.doValidate(GormValidationApi.groovy:89)
at org.grails.datastore.gorm.GormValidationApi.validate(GormValidationApi.groovy:161)
at org.grails.datastore.gorm.GormValidateable$Trait$Helper.validate(GormValidateable.groovy:87)
at api.mails.MailSpec.Test la validation d'un mail incorrect 2(MailSpec.groovy:66)

It seems that GORM can't get my domain object.
I can't reproduce the bug on my computer.
Any help or documentation will be appreciated.
Thanks !

A: The problem was some oject in my Unit test were not mocked.
I put an array of object in my @Mock annotation and now, it works on my continuous integration platform.
@TestFor(SMTPMailerService)
@Mock([Mail, DestinataireMail, PieceJointeMail])
class SMTPMailerServiceSpec extends Specification {

Hope it will help someone !


text:
Q: Is using multiple for loops compared to one for loop more memory and time costly in Matlab? What's more time and memory efficient in Matlab?
I am writing the pseudo code.
1)
for:
 Open a file
 Read the temperature info
 find the min max and avg temperature value;
for:
 Open a file
 Read the voltage info
 find the min max and avg voltage value;
for:
 Open a file
 Read the resistence info
 find the min max and avg resistence value;

OR the code below?
2)
for:
 Open a file
 Read the temperature info
 find the min max and avg temperature value
 Open a file
 Read the voltage info
 find the min max and avg voltage value
 Open a file
 Read the resistence info
 find the min max and avg resistence value;

A: There should be little difference between the two implementations both in terms of time and memory. The only difference between them is reusing the loop variable, which is negligible.
Btw MATLAB has JIT now so loop itself is not costly anymore (which was many years ago).


text:
Q: invalid column type ~ Sending ArrayList to a pl/sql createdNameQuery This is related to a past question of mine.
I am receiving a List<Employee> and grabbing the ids from the Employee objects and putting them in an ArrayList<String> then sending that ArrayList as a parameter in the createdNameQuery. I am receiving an invalid column type sql exception. I tested the query in pl/sql developer and it returned fields. I have tried building out a string of ids by placing a coma between each id and sending that but, I received an exception from that attempt. I am curious if I have the query setup incorrectly or sending the data incorrectly.
function in my repository:
public List<RequestByRequester> getRequestsByRequesters(
        List<Employee> employeeList)
        throws NoDataFoundException {

    List<String> idList = new ArrayList<String>();
    for(Employee emp : employeeList) {
        idList.add(emp.getId().toString());
    }

    log.debug("Input params[requesters=" + idList + "]");

    List<RequestByRequester> resultList = getEm().createNamedQuery(
            "requestByRequestor.getRequestsByRequesters", RequestByRequester.class)
            .setParameter(1,idList)
            .getResultList();

        if(resultList == null || resultList.size() <= 0)
            throw new NoDataFoundException("No requests found by requesters.");
        else
            return resultList;
}

My named query requestByRequestor.getRequestsByRequesters below:
   @NamedNativeQuery(
    name = "requestByRequestor.getRequestsByRequesters",
    resultClass = RequestByRequester.class,
    query = "SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER," +
            "       R.RQST_ID RQST_ID," +
            "       R.TITLE TITLE," +
            "       R.DESCRIPTION DESCRIPTION," +
            "       DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS" +
            "  FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP" +
            " WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID" +
            "   AND EMP.EMPL_ID IN (?)" +
            " ORDER BY 1, 5 DESC, 2"
    )

EDIT: Adding exceptions as requested.
This exception when I use :ids in the query:
Internal Exception: java.sql.SQLException: Missing IN or OUT parameter at index:: 1
Error Code: 17041
Call: SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER,       R.RQST_ID RQST_ID,       R.TITLE TITLE,       R.DESCRIPTION DESCRIPTION,       DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS  FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID   AND EMP.EMPL_ID IN :ids ORDER BY 1, 5 DESC, 2
Query: ReadAllQuery(name="requestByRequestor.getRequestsByRequesters" referenceClass=RequestByRequester sql="SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER,       R.RQST_ID RQST_ID,       R.TITLE TITLE,       R.DESCRIPTION DESCRIPTION,       DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS  FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID   AND EMP.EMPL_ID IN :ids ORDER BY 1, 5 DESC, 2")
Exception when I use ?1 or (?) in the query :
Internal Exception: java.sql.SQLException: Invalid column type
Error Code: 17004
Call: SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER,       R.RQST_ID RQST_ID,       R.TITLE TITLE,       R.DESCRIPTION DESCRIPTION,       DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS  FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID   AND EMP.EMPL_ID IN ? ORDER BY 1, 5 DESC, 2
    bind => [[2192, 632]]
Query: ReadAllQuery(name="requestByRequestor.getRequestsByRequesters" referenceClass=RequestByRequester sql="SELECT EMP.EMPL_FIRST_NAME || ' ' || EMP.EMPL_LAST_NAME REQUESTER,       R.RQST_ID RQST_ID,       R.TITLE TITLE,       R.DESCRIPTION DESCRIPTION,       DECODE(R.RESOLUTION_DATE, NULL, 'Open', 'Closed') STATUS  FROM TARTS.REQUESTS R, SYS_EMPLOYEES EMP WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID   AND EMP.EMPL_ID IN ? ORDER BY 1, 5 DESC, 2")

A: The issue (I think, because you did not include the definition of your named query), is that you are executing a native SQL query, and a List is not a valid SQL/JDBC parameter value.
EclipseLink support List parameters for JPQL queries, but not for native SQL queries.
You need to either use JPQL, or define each of the parameters in your SQL
i.e.
EMP.EMPL_ID IN (:id1, :id2, :id3)

.setParameter("id1", idList.get(0));
.setParameter("id2", idList.get(1));

A: I think the problem is here
AND EMP.EMPL_ID IN (?)

To indicate positional parameters, you need to suffix the questionmark with the number.
 AND EMP.EMPL_ID IN (?1)

Alternately, you can do
 AND EMP.EMPL_ID IN (:empIds)

and then call your query like so
List<RequestByRequester> resultList = getEm().createNamedQuery(
        "requestByRequestor.getRequestsByRequesters", RequestByRequester.class)
        .setParameter("empIds", idList)
        .getResultList();

A: Query:
List<RequestByRequester> resultList = getEm().createNamedQuery(
    "requestByRequestor.getRequestsByRequesters", RequestByRequester.class)
    .setParameter("ids", idList)
    .getResultList();

NamedQuery WHERE part:
WHERE R.EMPL_ID_REQUESTED_BY = EMP.EMPL_ID
AND EMP.EMPL_ID IN :ids

Notice the :ids is without brackets. This should work.

A: In your code you are mapping emp.getId() to String
List<String> idList = new ArrayList<String>();
    for(Employee emp : employeeList) {
        idList.add(emp.getId().toString());
    }

But I bet the type for this column EMP.EMPL_ID is Numeric or some such thing. When you perform
.setParameter("empIds", idList)

JPA will be converting that to a string value with quotes and escape chars etc. hence:

java.sql.SQLException: Invalid column type

try mapping to List<Long> or some other numeric type.


text:
Q: How to create several 3D plots with plt.addplots I had expect such code to work
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig, axs = plt.subplots(2,2,projection='3d')

but it fails telling me no parameter named projection.
I wonder whether I can create several 3D plots with addplots

A: The projection is an argument of the Axes creator
fig, axs = plt.subplots(2, 2, subplot_kw=dict(projection='3d'))


text:
Q: Button To Download .txt File (PHP & HTML) Ok so I want to my users to be able to download a .txt file with their username on it.
I've checked everywhere, and so far I can't find what I want or if it's even possible.
To give you an example of what I'm trying to do, here is my code:
<button type="button">Download All Your Keys On A .txt
<?php
$file = 'logs/$session->username.txt';

if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");

$type = filetype($file); // Get a date and timestamp $today = date("F j, Y, g:i a"); $time = time(); // Send file headers header("Content-type: $type"); header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0'); // Send the file contents.
set_time_limit(0);
readfile($file);
?>
</button>

I'm trying to make it so that when you click the button, it force download's the .txt file configured with:
$file = 'logs/$session->username.txt';

Sorry if this is confusing and messy, but there's no other way for me to present this.
Thanks in advance!

A: Why don't you have this code in a separate file, say download.php:
<?php
    $file = "logs/{$session->username}.txt";

    if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");

    $type = filetype($file);
    // Get a date and timestamp
    $today = date("F j, Y, g:i a");
    $time = time();
    // Send file headers
    header("Content-type: $type");

    //** If you think header("Content-type: $type"); is giving you some problems,
    //** try header('Content-Type: application/octet-stream');

    //** Note filename= --- if using $_GET to get the $file, it needs to be "sanitized".
    //** I used the basename function to handle that... so it looks more like:
    //** header('Content-Disposition: attachment; filename=' . basename($_GET['mygetvar']));

    header("Content-Disposition: attachment;filename={$session->username}.txt");
    header("Content-Transfer-Encoding: binary");
    header('Pragma: no-cache');
    header('Expires: 0');
    // Send the file contents.
    set_time_limit(0);
    ob_clean();
    flush();
    readfile($file);

    //** If you are going to try and force download a file by opening a new tab via javascipt
    //** (In this code you would replace the onClick() event handler in the html
    //** button with onclick="window.open('www.someurl.com', '_blank');"
    //** - where 'www.someurl.com' is the url to the php page - I keep the file
    //** creation and download handling in the same file, and $_GET the file name
    // - bad practice? Probably, but I never claimed to be an expert),
    //** be sure to include exit(); in this part of the php...
    //** otherwise leave exit(); out of the code.
    //** If you don't, it will likely break the code, based on my experience.

    //exit();
?>

Please note that you have to change the quotes to double quotes, as you use a variable inside the 's. So, to expand the variable, change the first line to:
$file = "logs/{$session->username}.txt";

Here I consider, $session->username, as the variable you are trying to refer.
And have this in the HTML:
<button type="button" onclick="location.href='download.php'">Download All Your Keys On A .txt</button>

And when you click on this button, it redirects to the download.php, that initiates a download of the txt file. As simple as that. But this requires you to have two files. And I don't understand the need for a button here. Why not just use a simple link like this?
Download All Your Keys On A .txt

And if you need, you can style it using CSS.


text:
Q: JSON to java unmarshelling in JAX-RS returning { } in POST I am trying to build a JAX-RS rest api that accepts in the POST method a (JSON) UnMarshelled class and at the moment i am only returning the same class (marshelled back as a JSON).
When I return the object i am getting a plain { } in the browser(postman client). I am using the data provided in this question:.
Is my understanding correct that the same JSON that i am sending should come back as it is ?, if yes not sure why is only  { } being received or have i completely missed something.
Below is my code :
@Path("/metadata")
public class MetadataResource {
//Anil: This is the method that will be called when a post at /metadata comes
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Produces(MediaType.APPLICATION_JSON)
public ObjectA CreateMetadata_JSON(ObjectA metadata) {

    return metadata;

}

Class Object A:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectA")
public class ObjectA {
    @XmlElement(required = true)
    protected String propertyOne;
    @XmlElement(required = true)
    protected String propertyTwo;
    @XmlElement(required = true)
    protected ObjectB objectB;
}

and Class Object B:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "objectB")
public class ObjectB {
    @XmlElement(required = true)
    protected String propertyA;
    @XmlElement(required = true)
    protected boolean propertyB;
}

The json object being sent is :
{
  "objectA" :
  {
    "propertyOne" : "some val",
    "propertyTwo" : "some other val",
    "objectB" :
    {
      "propertyA" : "some val",
      "propertyB" : "true"
    }
  }
}

A: It's because of the root object wrapper
{
  "objectA" :

}

Generally the expected JSON object is everything you have, excluding the above root value wrapper. If there is a requirement to use the JSON exactly how you have it, then the JSON provider needs to be configured to un-wrap the root value. If you don't, then the provider doesn't recognize any properties in the JSON, and you are left with an object with a bunch of nulls. So when you serialize the same object, the provider ignores the null, and you are left with an empty JSON object { }.
So the simple solution is to just use
{
  "propertyOne" : "some val",
  "propertyTwo" : "some other val",
  "objectB" :
  {
    "propertyA" : "some val",
    "propertyB" : "true"
  }
}

If you require the root value wrapper, then I would need to know what JSON provider you are using, before I can try and help with how you can configure it to unwrap the root value.

UPDATE
For MOXy, if you want to configure it to wrap/unwrap the root value, you can setIncludeRoot to true, in the MoxyJsonConfig. You will need to provide a ContextResolver for it to be discovered.
@Provider
public class MoxyConfigResolver implements ContextResolver<MoxyJsonConfig> {

    private final MoxyJsonConfig config;

    public MoxyConfigResolver() {
        config = new MoxyJsonConfig();
        config.setIncludeRoot(true);
    }

    @Override
    public MoxyJsonConfig getContext(Class<?> type) {
        return config;
    }
}


text:
Q: Working with microseconds I'm working with microseconds on PHP and if the difference is very small I'm getting wrong answers.
Why and how fix this?
Example:
$t1 = '1452502847.8248';
$t2 = '1452502847.8247';
$min = (float)($t1 - $t2);
var_dump($min); //9.9897384643555E-5

$t1 = '1452502847.8248';
$t2 = '1452502847.8246';
$min = (float)($t1 - $t2);
var_dump($min); //0.00020003318786621

A: PHP, like many other, can surprise you in terms of precision math. Please take a look at this article for further info on the issue.
So, the results you get are correct, but to make them more useful, you have to round your results to the precision you want (4 decimals in this case). Try this:
$min = round($t1-$t2,4);


text:
Q: 9-Patch, Border around Image button I am trying to apply many picture/photo/avatar user icons (dynamically) so as a user signs up a new button will be added.  I want each button to be surrounded by a polaroid frame.  Im guessing this is a 9-patch thing (never used before).  I have created the 9-patch with transparent centre, but I have no idea how to surround each image button with the polaroid border.  I managed to dynamically program a layout before and that should be no problem.  I am trying to practice surrounding the button in xml at the moment..but nay such luck! please can someone help me! can it even be done?am i going in the right direction?

A: Whey I did it.  Quite easy but if you've never done it, it is hard to know each settings element to go with.  Here's my answer
 </LinearLayout>

    <ImageButton

        android:layout_width="150dp"
        android:layout_height="100dp"
        android:maxHeight="600dp"
        android:maxWidth="300dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        android:id="@+id/imageButton"
        android:src="@drawable/events_selected"
        android:layout_gravity="center_horizontal"
        android:layout_weight="0.05"
        android:background="@drawable/photo_4"
        />

</LinearLayout>

I will post dynamic code when done


text:
Q: Final Fantasy 7 Cloud Saves On PC Just bought FF7 on Steam and I am having an issue with the syncing of my saved games to my Square Enix account. The issue is I'm looking into using the character booster that is offered with the cloud save feature.
I have 3 achievements, 4 save files, enabled cloud saving, linked my Steam account - and it still says no saved games.
I filed a help desk tickets with SE (not sure if that's going to anything), I'm pretty sure this isn't a Steam issue.
Does anyone have any information on how to solve this issue?

A: Chances are you're saving locally. Go into the configuration on the FF7 startup panel and enable cloud saves.

A: Turns out the servers that Square Enix uses are just crap and go down all the time for days on end.
I ended up using Black Chocobo to modify my save instead of using their cloud storage system.


text:
Q: regression coefficient Consider observations on three variables X1;X2 and X3: Suppose that
X1 is regressed on X2: When the residual of the above regression is
regressed on X3; the regression coefficient of X3 is b3: When X1 is
regressed on X2 and X3 simultaneously, the regression coefficient of
X3 is b3* :
(a) Show that |b3|<=|b3*|.
(b) When does the equality hold in (a)?
So I get that X1=a1+b2X2+e;
e=a2+b3X3+e1;
therefore, X1=a1+a2+b2X2+b3X3+e1;
again, X1=a3+b2*X2+b3*X3+e2
Now how to proceed?


text:
Q: How to rewrite urls to get slug in view Django 3.0.7
urls.py
urlpatterns = [
    path('<slug:categories>/', include(('categories.urls', "categories"), namespace="categories")),
]

categories/urls.py
urlpatterns = [
    path('', CategoryView.as_view(), name='list'),
]

views.py
class CategoryView(ListView):

    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["object_list"] = context["object_list"].filter(category__slug="linux") # Hardcoded so far
        return context

    def get_template_names(self):
        return ["categories/post_list.html"]

Then I request http://localhost:8000/linux/
Problem
In the request that arrived kwargs is empty.
Why does this happen and how can I cope with this?

A: Use self.kwargs['categories'] to get the slug value from URL.
class CategoryView(ListView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["object_list"] = context["object_list"].filter(category__slug=self.kwargs['categories'])
        return context

    def get_template_names(self):
        return ["categories/post_list.html"]

But, If I had a choice, I would have override the get_queryset(...) method instead of get_context_data(...), which is more Django way in this case
class CategoryView(ListView):
    model = Post

    def get_queryset(self):
        return super().get_queryset().filter(category__slug=self.kwargs['categories'])

    def get_template_names(self):
        return ["categories/post_list.html"]


text:
Q: How to set TWO first words of a slider header with a different color using variables in php? There is a template https://wordpress.org/themes/bizberg/.
In "Customize" the slider title type is adjustable, and the title's first word color could be replaced with a theme color.
BUT there's no sense to set a different color on an article "the" in sentence "The world is beautiful". It should be at least first TWO words "The Future", "The World" etc.
ANY IDEAS HOW TO MAKE IT WORK?
Thank you in advance!
(php code is below)
functions.php:
return '
' .  ''.$title[0].''.substr(implode(" ", $title), strlen($title[0])) . '
';

front-page-hero.php:
array(
            'element'  => '.slider_title_layout_3 .firstword,.slider_title_layout_4 .lastword',
            'property' => 'color'
        ),

A: Thanks to @CBroe's tip!
"Replace both occurrences of $title[0] with $title[0].' '.$title[1]."
It worked wonderfully!
Also I've received a perfect answer from @Sergei Kirjanov.
So if you need to highlight a few title words only in certain slides, put the " ^ " sign after necessary words and change the php-code for :
$title = explode( strpos($title, "^") ? "^" : " ", $title );

It says, if a string has "^" then separate the colored title part after it, otherwise as usual after the space " ".


text:
Q: Измeнить вид сoхрaнeния фaйлa с сaйтa на кoмпьютeр Есть функция по сoхрaнeнию фaйлa с oпрeдeлённoй стрoкoй с сaйтa:
   function saveToPC(str){
   let blob = new Blob([str], {type: "text/plain"});
   let link = document.createElement("a");
   link.setAttribute("href", URL.createObjectURL(blob));
   link.setAttribute("download", 'Donwload.txt');
   link.click();
   }

Фaйл сoхрaняeтся в .txt фoрмaтe и у меня есть пару вопросов по улучшению прoизводитeльности этой функции, а именно:

*

*Как я могу сoхрaнить фaйл в другом фoрмaте, нaпримeр в .xsl(или может быть другие)? Прoсто пoмeнять тип рaсширения в функции не сработает, выдает ошибку.

*Как я могу измeнить кoнeчный рeзультaт oтoбрaжения стрoки в сохрaненном фaйле? Т.е., например, у меня дана одна, целая стрoкa на сaйтe и в скaчaннoм фaйлe я хотел бы видеть ее рaздeлeннoй на строки, т.е. сделaть рaзрыв (<br>) в каких-то мeстaх (например после oпрeдeлeннoго симвoлa)?


text:
Q: How to logrotate custom log file on system boot I need to logrotate on system boot. I created a custom config for logrotate to zip the file. The solution with @reboot does not work.
In root crontable I have something like this:
@reboot --force /etc/logrotate.conf

but it doesn't work. I am working on Debian 10.

A: I'm going to assume you mean crontab when you say 'crontable', in which case your formatting is just incorrect. Per the crontab man page (1) :
These special time specification "nicknames" are supported,
which replace the 5 initial time and date fields, and are prefixed by the '@' character:

@reboot    :    Run once after reboot.

The @reboot nickname only replaces the 5 time/date fields; you still need to follow the rules on how commands are formatted in crontab (again, from the manpages):
<date fields> <user to run command as> <command to run>
E.g.,
30 12 * 8 * root touch /tmp/file
So if you want to use the @reboot nickname, all you should be replacing are the five time/date fields at the beginning of the string, e.g.
@reboot root touch /tmp/file


text:
Q: Как выбрать из БД значении и поместить их в input type=radio Как выбрать из БД значении и поместить их в
Но чтобы одна из была по-умолчанию checked

$place=mysql_query("SELECT place FROM place");
        while($pla=mysql_fetch_array($place)){
        echo "".$pla['place']."";
}

Если сделать так, то выбрать можно все знач, но надо одну и по-умолч. должна было checked
Вот мой Html код

        <?php
                $place=mysql_query("SELECT place FROM place");
                while($pla=mysql_fetch_array($place)){
                    echo "<input type='radio' value=".$pla['id']."/>".$pla['place']."";
                }
            ?>


text:
Q: how to use variable in update statement - MongoDB i am trying to use a variable value as column name to update all my documents in a collection. i am trying this through robo mongo shell command.
code is below:
doc=db.Symbols.findOne();
for (key in doc)
{
db.getCollection('Symbols').update(
   { key : null },
   {
        $set: { key: ""}
   },
   { multi: true, upsert: false }
)
    }

but this code does not seems to be working for me. seems like value in variable "key" does not replace at runtime and instead of comparing with value in variable key robo mongo compare it with word "key" itself.
Any idea how to do this ?

A: You need a mechanism which loops through the whole collection and  with each iteration, check for each field within a document for null, and update the collection accordingly. A basic approach follows:
db.Symbols.find({}).forEach(function(doc){
    var update = { "$set": { } },
        query = {};
    for (var key in doc) {
        if (doc[key] === null) {
            update["$set"][key] = "";
            query[key] = { "$exists": false }
        }
    }
    if (Object.keys(query).length !=== 0)
        db.Symbols.updateOne(query, update);

});

For very humongous collections, you can leverage your updates to be more efficient with the bulk API which can update your collection in bulk instead of sending the update request per document, thus making the updates a bit faster and more performant. The following example demonstrates this with the bulkWrite() method:
var ops = [];

db.Symbols.find({}).forEach(function(doc){
    var update = { "$set": { } },
        query = {};
    for (var key in doc) {
        if (doc[key] === null) {
            update["$set"][key] = "";
            query[key] = { "$exists": false }
        }
    }
    if (Object.keys(query).length !=== 0) {
        ops.push({
            "updateOne": {
                "filter": query,
                "update": update
            }
        });
    }

    // Send to server in batches of 500 operations only
    if (ops.length % 1000 === 0) {
        db.Symbols.bulkWrite(ops);
        ops = [];
    }
})

// Clear remaining queue
if (ops.length > 0)
    db.Symbols.bulkWrite(ops);


text:
Q: Material UI in Next JS Just to clarify for myself - can i use Material UI in my Next js application the same way i was using it in React js application? Do i need to do anything differently?
Found some sources with complicated adjustments to next js app in order to use Material UI
For example: enter link description here
and
enter link description here
but i just added material UI as usual, with no extra code and it worked. Am i missing something? Will it work ok in prod?


text:
Q: How to set a value to html attribute on a if condition in angular In this case i have to check a value of a variable (returning value of a function) and create a "aria-label" attribute and set a value to it.
Here i'm not just going to set a value for the attribute. I need to create a attribute based on a if condition. Something like "ng-if"

*

*If the value is true : Create the attribute and set the value.

*If the value is false : No need to create the attribute.

This is how i have done it and it's not working. After the page is rendered there isn't a attribute as a "aria-label='selected'".
Thanks in advance.

A: have u tried using


text:
Q: GitHub: What happens to forks when a repo changes ownership? If a repo changes ownership from owner/theRepo to newOwner/theRepo are its forks automatically updated to reference the new location of the moved repo? Or does anything need to be done manually?

A: From the documentation:

If the transferred repository has any forks, then those forks will remain associated with the repository after the transfer is complete


text:
Q: Return range anlong with worksheet name from a UDF I want to run a advanced filter. so i want to write a function as advancedfilter which will take three parameter as range(Listrange,criteria range and copied range)...But every time my range will be different .So at first i write a formula which return the range from worksheet name and other parameter (See below function for clarity).
Public Function ConvertRange(ByVal sh As Worksheet, ByVal StartingRow As Long, ByVal StartingCol As Long, ByVal TotalCol As Long, ByVal LastRow As Long)
As Range
With sh

Set ConvertRange = .Range(.Cells(StartingRow, StartingCol), .Cells(LastRow - StartingRow + 1, StartingCol + TotalCol - 1))
End With
End Function

So this function returns the range but Listrng in one worksheet but Criteriarng and copied rng in another sheet..so along with range address i need find the name of the sheet..How can i do that?
AdvancedFilter Function:
Public Sub AdvancedFilter(Listrng As Range, criteriarng As Range, targetrng As Range)

'Set the target range where the unique values will be copied to.
Set targetRange = targetrng
'Calculating last non blank row of column A in Sh1 worksheet.
'Set the collection range from where the values will filter out.
Set rngCollectFrom = Listrng
'Use Advanced Filter
rngCollectFrom.AdvancedFilter Action:=xlFilterCopy, criteriaRange:=criteriarng, CopyToRange:=targetRange, Unique:=False
End Sub

Public Sub M()
Dim sh As Worksheet
Set sh = Worksheets("Logical operation")
Dim sh1 As Worksheet
Set sh1 = Worksheets("Transaction")
Dim Listrng As Range
Dim criteriarng As Range
Dim targetrng As Range
Set Listrng = ConvertRange(sh1, 1, 1, 4, 22)
MsgBox Listrng.Parent.Name & "!" & Listrng.Address
Set criteriarng = ConvertRange(sh, 1, 13, 4, 2)
MsgBox criteriarng.Parent.Name & "!" & criteriarng.Address
Set targetrng = ConvertRange(sh, 2, 21, 1, 3)
MsgBox targetrng.Parent.Name & "!" & targetrng.Address
Call AdvancedFilter(Listrng.Parent.Name & "!" & Listrng.Address,
criteriarng.Parent.Name & "!" & criteriarng.Address, targetrng.Parent.Name & "!" & targetrng.Address)
End Sub
Call AdvancedFilter(Listrng.Parent.Name & "!" & Listrng.Address, criteriarng.Parent.Name & "!" & criteriarng.Address, targetrng.Parent.Name & "!" & targetrng.Address)

It returns runtime error 424
i think i messed up with below line:
Call AdvancedFilter(Listrng.Parent.Name & "!" & Listrng.Address, criteriarng.Parent.Name & "!" & criteriarng.Address, targetrng.Parent.Name & "!" & targetrng.Address)

A: Firstly, you don't need a ConvertRange function to create a range reference on a particular sheet, so get rid of it.  Note that a Range object refers to a range on a specific sheet and in a specific workbook.
Instead, just fully specify the required ranges (these are the ranges your code is creating.  It's not clear if these are the ranges you intend, so update if required):
Set ConvertRange = sh1.Range("A1:D22")
Set Criteriarng = sh.Range("M1:P2")
Set Targetrng = sh.Range("U2")

Note: all these are implicitly refering to the ActiveWorkbook.  You can (and should) explicitly specify the Workbook too:
Dim wb as Workbook
Set wb = ActiveWorkbook
' or
Set wb = ThisWorkbook
' or
Set wb = Application.Workbooks("NameOfYourBook.xlsm")

And include it in the Sheet references
Set sh = wb.Worksheets("Logical operation")
Set sh1 = wb.Worksheets("Transaction")

Secondly, you've already specified the Parameters of AdvancedFilter as Range.  This is good!  You just need to pass ranges, not strings
Also, use of Call is redundant, and you should not use it (ever)
So:
Call AdvancedFilter(Listrng.Parent.Name & "!" & Listrng.Address, criteriarng.Parent.Name & "!" & criteriarng.Address, targetrng.Parent.Name & "!" & targetrng.Address)

becomes
AdvancedFilter Listrng, criteriarng, targetrng

Comments in your AdvancedFilter Sub suggest you want to manipulate the passed ranges before calling rngCollectFrom.AdvancedFilter.  That's fine if you do.  Otherwise you may not need the sub at all.

Your code, refactored
Public Sub M()
    Dim wb As Workbook
    Set wb = ThisWorkbook

    Dim sh As Worksheet
    Set sh = wb.Worksheets("Logical operation")

    Dim sh1 As Worksheet
    Set sh1 = wb.Worksheets("Transaction")

    Dim Listrng As Range
    Dim Criteriarng As Range
    Dim Targetrng As Range

    Set Listrng = sh1.Range("A1:D22")
    Set Criteriarng = sh.Range("M1:P2")
    Set Targetrng = sh.Range("U2")

    AdvancedFilter Listrng, Criteriarng, Targetrng
    ' or
    'Listrng.AdvancedFilter Action:=xlFilterCopy, criteriaRange:=Criteriarng, CopyToRange:=Targetrng, Unique:=False

End Sub

A: Public Sub M()
Dim sh As Worksheet
Set sh = Worksheets("Logical operation")

Dim sh1 As Worksheet
Set sh1 = Worksheets("Transaction")

Dim Listrng As Range
Dim criteriarng As Range
Dim targetrng As Range
Set Listrng = ConvertRange(sh1, 1, 1, 4, 22)

Set criteriarng = ConvertRange(sh, 1, 13, 4, 2)
Set targetrng = ConvertRange(sh, 2, 21, 1, 1)

AdvancedFilter Listrng, criteriarng, targetrng ' removed Call as obsolete

Debug.Print Listrng.Parent.Name ' print name of sh1 "Transaction"
End Sub

Because .Range is a child of .Worksheet, .Worksheet is the .Parentof .Range
Range.Parent returns the reference to the worksheet and Range.Parent.Parent returns the workbook reference, because Worksheet is a child of Workbook.

A: Answer One:Using List range,Criteria range,paste range as a range and using UDF AdvancedFilter.
'Calling Sub
 Public Sub CallingSub()
'Declaration of variable as worksheet to contain the worksheet name.
Dim sh As Worksheet, sh1 As Worksheet
'Set the required worksheet
Set sh = Worksheets("Logical operation")
Set sh1 = Worksheets("Transaction")
'Variable declaration for finding the range from ConvertRange sub.
Dim Listrng As Range, criteriarng As Range, targetrng As Range
'Finding the List range from where data will be fetched.
Set Listrng = ConvertRange(sh1, 1, 1, 4, 22)
'Finding the criteria range based on which data will be fetched.
Set criteriarng = ConvertRange(sh, 1, 13, 4, 6)
'Finding the range where data will be copied.
Set targetrng = ConvertRange(sh, 2, 21, 4, 3)
'Calling the AdvancedFitler function.
AdvancedFilter2 Listrng, criteriarng, targetrng
End Sub
'ConvertRange Function
 Public Function ConvertRange(ByVal sh As Worksheet, ByVal StartingRow As Long, ByVal StartingCol As Long, ByVal TotalCol As Long, ByVal LastRow As Long) As Range
'Calculating range based on below worksheet.
With sh
    'Find the range based on provided data.
    Set ConvertRange = .Range(.Cells(StartingRow, StartingCol), .Cells(LastRow, StartingCol + TotalCol - 1))
End With
End Function
'UDF AdvancedFilter
Public Sub AdvancedFilter(Listrng As Range, criteriarng As Range, targetrng As Range)
'Use advanced filter based on data passed on this sub.
Listrng.AdvancedFilter Action:=xlFilterCopy, criteriarange:=criteriarng, copytorange:=targetrng, Unique:=False
End Sub

Answer Two:Using List range,Criteria range,paste range as a range and using excel in  AdvancedFilter.
'Calling Sub
 Public Sub CallingSub()
 'Declaration of variable as worksheet to contain the worksheet name.
Dim sh As Worksheet, sh1 As Worksheet
'Set the required worksheet
Set sh = Worksheets("Logical operation")
Set sh1 = Worksheets("Transaction")
'Variable declaration for finding the range from ConvertRange sub.
Dim Listrng As Range, criteriarng As Range, targetrng As Range
'Finding the List range from where data will be fetched.
Set Listrng = ConvertRange(sh1, 1, 16, 3, 19)
'Finding the criteria range based on which data will be fetched.
Set criteriarng = ConvertRange(sh, 1, 17, 3, 6)
'Finding the range where data will be copied.
Set targetrng = ConvertRange(sh, 2, 25, 3, 3)
'Use advanced filter function in place..No need to use UDF(User Defined Function).
Listrng.AdvancedFilter Action:=xlFilterCopy, criteriarange:=criteriarng, copytorange:=targetrng, Unique:=False
End Sub
'ConvertRange Function
 Public Function ConvertRange(ByVal sh As Worksheet, ByVal StartingRow As Long, ByVal StartingCol As Long, ByVal TotalCol As Long, ByVal LastRow As Long) As Range
'Calculating range based on below worksheet.
With sh
    'Find the range based on provided data.
    Set ConvertRange = .Range(.Cells(StartingRow, StartingCol), .Cells(LastRow, StartingCol + TotalCol - 1))
End With
End Function

Answer three: Using List range,Criteria range,paste range address as a string along with their sheet name and using UDF AdvancedFilter
'Calling Sub
 Public Sub CallingSub()
'Declaration of variable as worksheet to contain the worksheet name.
Dim sh As Worksheet, sh1 As Worksheet
'Set the required worksheet
Set sh = Worksheets("Logical operation")
Set sh1 = Worksheets("Transaction")
'Variable declaration for finding the range from ConvertRange sub.
Dim Listrng As Range, criteriarng As Range, targetrng As Range
'Variable declaration for containing the address of range along with sheet name.
Dim a As String, b As String, c As String
'Finding the List range from where data will be fetched.
Set Listrng = ConvertRange(sh1, 1, 1, 4, 22)
'Finding the address of range along with sheet name.
a = "'" & Listrng.Parent.Name & "'!" & Listrng.Address
'Finding the criteria range based on which data will be fetched.
Set criteriarng = ConvertRange(sh, 1, 13, 4, 6)
'Finding the address of range along with sheet name.
b = "'" & criteriarng.Parent.Name & "'!" & criteriarng.Address
'Finding the range where data will be copied.
Set targetrng = ConvertRange(sh, 2, 21, 3, 3)
'Finding the address of range along with sheet name.
c = "'" & targetrng.Parent.Name & "'!" & targetrng.Address
'Calling the AdvancedFitler function.
AdvancedFilter a, b, c
End Sub
'ConvertRange Function
Public Function ConvertRange(ByVal sh As Worksheet, ByVal StartingRow As Long, ByVal StartingCol As Long, ByVal TotalCol As Long, ByVal LastRow As Long) As Range
'Calculating range based on below worksheet.
With sh
    'Find the range based on provided data.
    Set ConvertRange = .Range(.Cells(StartingRow, StartingCol), .Cells(LastRow, StartingCol + TotalCol - 1))
End With
End Function
'UDF AdvancedFilter
 Public Sub AdvancedFilter(Listrng As String, criteriarng As String, targetrng As String)
'Here Listrng,criteriarng and targetrng contain their range address along with sheet name.
'Use advanced filter based on data passed on this sub.
Range(Listrng).AdvancedFilter Action:=xlFilterCopy, criteriarange:=Range(criteriarng), copytorange:=Range(targetrng), Unique:=False
End Sub

A: In your code, passing Range into Public Sub AdvancedFilter() is causing trouble. Hence instead of that, try passing Range.Address in the form of String into Public Sub AdvancedFilter(). Please refer below Code.
Option Explicit

Public Sub M()

    Dim sh As Worksheet, sh1 As Worksheet
    Dim sh_Name As String, sh1_Name As String
    Dim Listrng As Range, criteriarng As Range, targetrng As Range
    Dim a As String, b As String, c As String

    Set sh = Worksheets("Logical operation")
    Set sh1 = Worksheets("Transaction")

    sh_Name = "Logical operation"
    sh1_Name = "Transaction"

    Set Listrng = ConvertRange(sh1, 1, 1, 4, 22)
    'Debug.Print Listrng.Address
    a = Listrng.Address

    Set criteriarng = ConvertRange(sh, 1, 13, 4, 2)
    'Debug.Print criteriarng.Address
    b = "'" & sh_Name & "'" & "!" & criteriarng.Address
    'Debug.Print b

    Set targetrng = ConvertRange(sh, 2, 21, 1, 3)
    'Debug.Print targetrng.Address
    c = targetrng.Address

    Call AdvancedFilter(sh1_Name, a, b, c)

End Sub

'No change in Public Function ConvertRange()
Public Function ConvertRange(ByVal sh As Worksheet, ByVal StartingRow As Long, _
ByVal StartingCol As Long, ByVal TotalCol As Long, ByVal LastRow As Long) As Range

    With sh
        Set ConvertRange = .Range(.Cells(StartingRow, StartingCol), _
        .Cells(LastRow - StartingRow + 1, StartingCol + TotalCol - 1))
    End With

End Function

'All variables passed as Strings instead of Range with small modification in Code
Public Sub AdvancedFilter(sh1_Name As String, a As String, _
b As String, c As String)

        Sheets(sh1_Name).Range(a).AdvancedFilter Action:=xlFilterCopy, _
        CriteriaRange:=Range(b), CopyToRange:=Range(c), Unique:=False

End Sub

Please let me know your feedback.

Note : Please avoid multiple renaming of variables as you pass them from one Sub to another.


text:
Q: Windows Vista /7 command line to launch the "Set up your microphone" wizard (or a mic test wizard) I'm putting together instructions for our users to test their microphones. Vista and 7 changed the Sound Recorder so it doesn't play back sound. Hence it's not good for testing sound (they have to save the file, find it, open it, inevitably get the Windows Media Player "first time" experience... at which time they've forgotten what they were doing).
The only other option I see for testing the Microphone is to click Start> Control Panel> Sound> Microphone > Configure> Set up Microphone  (and hope that they don't have their Control panel in Classic setup.
I know there are ways to launch the Sound dialog via the command line like this.
Any ideas?

A: You should be able to do this with:
control mmsys.cpl sounds

A: The Set up your Microphone wizard is hidden in the SpeechUX.dll. You can call SpeechUX.dll like so:
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard Tutorial (Speech Recognition Tutorial)
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard UserTraining (Voice Training)
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard MicTraining (Microphone Training)
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard UserEnrollment (Set Up Speech Recognition)

So you basically want:
rundll32.exe "%windir%\system32\speech\speechux\SpeechUX.dll", RunWizard MicTraining

A: Control mmsys.cpl sounds doesn't work on Windows 7 (for me at any rate). It just pulls up the same default Sound Control Panel applet as mmsys.cpl does by default.
You can make it somewhat easier for your users by creating a shortcut that links directly to the wizard (or a link to a shortcut). In Windows 7 (and probably in Vista, can't be sure as I don't have access to a copy right now) you can create a shortcut to an item in the Control Panel by opening up the new Control Panel interface, searching for Microphone and then drag the "Set up a Microphone Link" to your desktop or a folder. You can then put it somewhere that they can access and send them a link to that.

A: Thanks to jPerkster for pointing me in the right direction. Didn't occur to me to look for command line parameters here.
mmsys.cpl ,n    NOTE: the space before the "," is absolutely needed or Windows thinks you're trying to launch mmsys.cpl,  and you get an error
n=
1 for recording
2 for Sounds
StackOverflow also has a similar way to do this programatically.


text:
Q: in R: Combining rows that are almost duplicates into one row with differing element combined I've got this data.frame that has the form like:
my_df <- data.frame(id = c(1, 1, 2, 3),
                 title = c("YourMa", "YourMa", "MyMa", "HisMa"),
                autqty = c(2, 2, 1, 1),
                   aut = c("Steve", "Joe", "Albert", "Kevin"),
                  pubb = c("Good", "Good", "Meh", "Fan"))

which looks like:
> my_df
id  title   autqty aut    pubb
1   YourMa     2   Steve  Good
1   YourMa     2   Joe    Good
2   MyMa       1   Albert Meh
3   HisMa      1   Kevin  Fan

Note that for id 1, all of the info is the same except for the one aut entry.  My goal is to slim-down my_df such that the aut data is combined into one element:
  id  title  autqty  aut         pubb
   1 YourMa    2     Steve, Joe  Good
   2 MyMa      1     Albert      Meh
   3 HisMa     1     Kevin       Fan

Note: this is a smaller version of my original data.  I'd like to be able to handle any number of aut's that occur.

A: Using group_by and summarise in dplyr:
my_df %>%
  group_by(id, title, autqty, pubb) %>%
  summarise(aut=paste(aut, collapse=", ")) %>%
  ungroup()

# A tibble: 3 × 5
     id  title autqty   pubb        aut
  <dbl> <fctr>  <dbl> <fctr>      <chr>
1     1 YourMa      2   Good Steve, Joe
2     2   MyMa      1    Meh     Albert
3     3  HisMa      1    Fan      Kevin


text:
Q: Selenium newWindow( ) method is not available I am using Selenium 4 and have configured the selenium-api-4.0.0.jar in the build path.
However, Eclipse complains that it cannot resolve "newWindow( ) method.  The error is: The method newWindow(WindowType) is undefined for the type WebDriver.TargetLocator.  What am I missing?
Thanks.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
.
.
.
.
public void openTab(String urlString) {
        driver.switchTo().newWindow(WindowType.TAB);

        // Open URL In 2nd tab.
        driver.get(urlString);

        // Call switchToTab() method to switch to the first tab
        switchToTab();
}


text:
Q: Count 0 if there is no existing record I have a database with 2 tables.

*

*Projects

+--------------+--------+
| project_name | Active |
+--------------+--------+
| A            | Yes    |
| B            | No     |
| C            | Yes    |
| D            | Yes    |
+--------------+--------+

*form-site_safety_inspection

+---------+-----------------+------------------------------+
| project | inspection_date |      Type_of_Inspection      |
+---------+-----------------+------------------------------+
| A       | 2019-08-20      | Supervisor Weekly Inspection |
| D       | 2019-08-20      | Supervisor Weekly Inspection |
| D       | 2019-08-21      | Supervisor Weekly Inspection |
| A       | 2019-08-22      | Supervisor Weekly Inspection |
+---------+-----------------+------------------------------+

project_name from Projects table = project from form-site_safety_inspection table.
New rows are added to form-site_safety_inspection regularly. On a weekly basis I need to count how many rows were added to form-site_safety_inspection by active projects. If there are no rows added by an active project that week, I need to count 0.
So far I coded a query which counts rows in form-site_safety_inspection added by active projects. I'm missing the part of the code which shows a count of 0 if there are no rows submitted by an active project.
SELECT COUNT(*), project

FROM form-site_safety_inspection

LEFT JOIN projects ON form-site_safety_inspection.project = Projects.project_name

WHERE form-site_safety_inspection.Type_of_Inspection= "Supervisor Weekly Inspection"

AND Projects.Active = "Yes"

AND year(inspection_date) = year(curdate())

AND month(inspection_date) = month(curdate())

AND week(inspection_date) = week(curdate())

GROUP BY form-site_safety_inspection.project

ORDER BY form-site_safety_inspection.project

Using the above code I get the result:

+----------+---------+
| COUNT(*) | project |
+----------+---------+
|        2 | A       |
|        2 | D       |
+----------+---------+

I'm looking for the following result:

+----------+---------+
| COUNT(*) | project |
+----------+---------+
|        2 | A       |
|        0 | C       |
|        2 | D       |
+----------+---------+

A: Your left join approach is correct, except that the restrictions on the date need to appear in the ON clause of the join, rather than in the WHERE clause, because you don't want them to filter off any projects.  Note that the restriction on Active can appear in the WHERE clause, because you don't want to see any inactive projects.
SELECT
    p.project_name,
    COUNT(f.project) AS cnt
FROM Projects p
LEFT JOIN `form-site_safety_inspection` f
    ON p.project_name = f.project AND
    YEARWEEK(inspection_date, 1) = YEARWEEK(CURDATE(), 1)
WHERE
    p.Active = 'Yes'
GROUP BY
    p.project_name;

Demo


text:
Q: position state as a sum of momentum states Leonard Susskind, in his lecture (minute 41) about QFT states that when a field acts on a vacuum state it gives a position state-
$$\Psi^\dagger(x)=\sum_{k}e^{-ikx}a^\dagger(k)\left|0\right>=\sum_{k}e^{-ikx}\left|k\right>=\left|x\right>$$
But i'm not sure how it works. The position states are $\left|x'\right>=\delta(x-x')$ and together with momentum states they satisfy $\left<x'|k\right>=e^{ikx'}$, so -
$$\left<x'|k\right> =\sum_{k}e^{-ikx}\left<x'|k\right>=\sum_{k}e^{-ikx}e^{ikx'}=\sum_{k}e^{-ik(x-x')} $$
does this give $\delta(x-x')$ ?

A: You've got the right idea, but there are several issues with the equations you've written down.
The complex Fourier series representation of the delta function is given by the identity:
$$\delta(x-x') = {1 \over 2\pi} \sum_{k=-\infty}^{\infty}e^{-ik(x-x')}$$
(See Eq 1.17.20 and 1.17.21 here for how to derive this as a limit of $\sum_{k=-n}^{n}$ as $n\to\infty$
So your conclusion is almost right, just missing a factor of $2\pi$.
The representation of a momentum state in terms of position eigenstates is $$|k\rangle = {1 \over 2\pi} \int_{x=-\infty}^{\infty}e^{ikx}|x\rangle$$
As a couple people complained about in the comments, you write $|x'\rangle = \delta(x-x')$ which is sloppy notation.  Yes, $\delta(x-x')$ is the function in the position basis which represents $|x'\rangle$, but the way to write that is not with an equals sign.  Or if you really want to use an equals sign, you write it like this:  $\langle x|x'\rangle = \delta(x-x')$
I think to make everything work out here, using the normalization Lenny is using in his lecture, you have to assume that:
$$\langle k | k' \rangle = {1 \over 2\pi} \delta_{kk'}$$
Putting all this together, we get:
$$\langle k |x\rangle = \sum_{k'} e^{-ik'x}\langle k|k'\rangle = {1\over 2\pi} e^{ik'x}\delta_{kk'} = {1 \over 2\pi} e^{-ikx}$$
Or if you prefer to go the other direction:
$$\langle x |k\rangle = {1\over 2\pi} \int_{x'=-\infty}^\infty e^{ikx'}\langle x | x'\rangle = {1\over 2\pi} \int_{x' = -\infty}^\infty e^{ikx'}\delta(x-x') = {1 \over 2\pi} e^{ikx}$$
There is a more symmetric notation you can also use, where you have a bunch of factors of $\sqrt{2\pi}$ instead.  This is more common to find in texts on non-relativistic quantum mechanics.


text:
Q: Why the underlying Data strcture in TreeSet is marked transient I am aware with the usage of transient in java.
The source code for TreeSet looks like this:
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
/**
 * The backing map.
 */
private transient NavigableMap<E,Object> m;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

/**
 * Constructs a set backed by the specified navigable map.
 */
TreeSet(NavigableMap<E,Object> m) {
    this.m = m;
}

/**
 * Constructs a new, empty tree set, sorted according to the
 * natural ordering of its elements.  All elements inserted into
 * the set must implement the {@link Comparable} interface.
 * Furthermore, all such elements must be <i>mutually
 * comparable</i>: {@code e1.compareTo(e2)} must not throw a
 * {@code ClassCastException} for any elements {@code e1} and
 * {@code e2} in the set.  If the user attempts to add an element
 * to the set that violates this constraint (for example, the user
 * attempts to add a string element to a set whose elements are
 * integers), the {@code add} call will throw a
 * {@code ClassCastException}.
 */
public TreeSet() {
    this(new TreeMap<E,Object>());
}

Here, we observe that although reference is of type NaviagableMap the underlying data structure is TreeMap.
My question is why has it been marked transient ? Won't this lead to lose any TreeSet object its capability to be transported ?