text:
Q: VHDL If Statements if you had a process like this for example:
process (clk)
if (var = '1') then
   var2 = '1';
end if;

if (var2 = '1') then
   //do something
end if;
end process;

Would the 2nd if statement get executed on the next clock cycle, or would it get executed as soon as var2 = '1' is executed?
Would the below code do exactly the same thing as the code above?
process (clk)
if (var = '1') then
   var2 = '1';
end if;
end process;

process (var2)
if (var2 = '1') then
   //do something
end if;
end process;

If someone could explain the timing issues that would be great.

A: If your vars are variables, then you can't sensibly do the second option as you can't use variables across processes (in most circumstances, see later).  If they are actually signals, then yes you can.
In the first code - if they are variables, then yes, they will update immediately and the second part of the code will run.
If they are signals then the second if block will only run next time around, as signals are only updated at the end of the process that writes to them.
The second example code will run the second process in the next "delta cycle" after the first one runs, as it is sensitive to the change on var2.

You can use variables between processes, but they have to be specified as shared variables.  If you do that with "straight" shaed variables, you run the risk of hideous Verilog-like race conditions as the order of reading and updates is undefined.
You should make them of a protected type which is a bit OO-like and has methods to operate on the values which allows accesses to be atomic across multiple processes.

A: In your first piece of code - As var2 is a variable it will get the new value immediately. Therefore the if statement will see the new value, and //do something would happen in the same time slice.
(// comments? Really? This is VHDL. We used --)
Your second piece of code wont work. Variables are scoped to a process, and can't be used to transfer values between processes. You have to use signals, and so the rules change. Consider this code:
signal sig  : std_logic := 1;
signal sig2 : std_logic := 0;

process (clk)
  if (sig = '1') then
    sig2 <= '1';
  end if;

  if (sig2 = '1') then
    -- do something
  end if;
end process;

process (sig2)
  if (sig2 = '1') then
    -- do something else
  end if;
end process;

Initial conditions: sig is 1 and sig2 is 0, so we're just waiting for a clk edge.
When the clock edge arrives we enter the first process we see that sig is 1 and assign 1 to sig2. All simple so far, but because sig2 is a signal the assignment wont happen until the process completes. Than means than when we compare sig2 to 1 on the next line, it will be false (sig2 is still 0 for now), and we won't -- do something. We then end the process.
Now, because at the end of the first process sig2 changed value 0 -> 1 the second process will be triggered (it's sensitive to sig2). It sees that sig2 is 1 and so it will -- do something else.
When the next clock edge comes (and it could be a negative edge with this code), sig2 is still 1 and so now we'll -- do something, and we'll do that for every clock edge.
In summary the order of events for this code would be:
Clk  : 0->1
Sig2 : 0->1
-- Do Something Else
Clk  : 1->0
-- Do Something
Clk  : 0->1
-- Do Something
Clk  : 1->0
-- Do Something
Clk  : 0->1
-- Do Something
.........

When you understand that ordering, you'll understand an important part of how VHDL schedules things.


text:
Q: cannot find crt0.o: No such file or directory I'm trying to learn operation system using i386-elf-gcc on my mac pro. Os version is Sierra. I use Macports to install the compile environment by typing sudo port install i386-elf-gcc in bash. But when I compile a helloworld program it goes wrong.
gcc hello.c

/opt/local/lib/gcc/i386-elf/4.7.2/../../../../i386-elf/bin/ld: cannot find crt0.o: No such file or directory
collect2: error: ld returned 1 exit status

then I use sudo find / -name "crt0.o", but in my mac there only has crt1.o, crt3.o and so on. And I use -nostdlib and -nostartfiles it still goes wrong:
gcc -nostdlib -nostartfiles hello.c

/opt/local/lib/gcc/i386-elf/4.7.2/../../../../i386-elf/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000008048054
/var/folders/wc/0c_zn09x12s_y90ccmvjb6900000gn/T//cc384VWr.o: In function `main':
hello.c:(.text+0x11): undefined reference to `puts'
collect2: error: ld returned 1 exit status

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does a Min Loser Tree with 11 players look like? Basically I have to create a min loser tree with 11 players but I'm not entirely sure what it should look like. So far my best guess is:
                               W
                               |
                              L4
                        /           \
                  L3                      L3
              /      \                 /     \
           L2         L2             L2       P11
        /   \         /   \         /\
      L1     L1     L1     L1     P9  P10
      /\     /\     /\     /\
    P1  P2 P3  P4 P5  P6 P7  P8

Sorry for the terrible ASCII representation, but I think you get the general idea. Is this visualization correct? I'm mostly concerned about the placement of the players.
I've searched the internet but all I get are results for bracketing software.

A: i'm pretty sure that you already found the answer, but maybe someone else directed to this page would be happy to have it right under the question ...
in a loser tree, the parent of two child nodes is the loser of the two, the winner is further compared, so the tree should look like this (if we assume that the player with the min ID wins):
                 P1=W
                  |
                  P5
           (compare P1 to P5)
           /              \
        P3                  P7
 (compare P1 to P3)  (compare P5 to P7)
     /      \            /      \
   P2        P4        P6        P8
  / \       / \       / \       / \
P1   P2   P3   P4   P5   P6   P7   P8


text:
Q: jquery filter as well as returning expression that evaluated to true I'm using a jQuery search method with multiple || expressions, any one of which can return true in order to display the result. My goal is to retrieve which of the expressions actually evaluated to true:
return this.itemAry.filter(function(item){
   var that = this;
   return (
     item.name.toLowerCase().indexOf(that.search.toLowerCase())>=0 ||
     item.description.toLowerCase().indexOf(that.search.toLowerCase())>=0
   )
 });

So if the item.name piece evaluated to true, I'd like to not only filter results that return true, but to also know that it was item.name versus item.description that evaluated to true.
Edit with example:
In my itemAry I can have
{item1: {name: "foo", description: "bar"}, item2: {name:"baz", description:"bar"}}

So if I search "foo" - I'd like to not only return the item1 object, but to also let me know that it was this expression item.name.toLowerCase().indexOf(that.search.toLowerCase())>=0 that evaluated to true

A: Truthfully, not possible without either changing the object (add a new key to object), or checking again by loop.
Logical operators just don't work that way.
To add a new key just add both to the object, as a simple && won't work(you would actually have use both AND and XOR).

A: One approach would be to store the field you found it in:
const searchResults = this.contractsAry
    .map(function(item) {
        return ({
            item: item,
            nameMatches: item.name.toLowerCase().indexOf(this.search.toLowerCase()) >= 0,
            descriptionMatches: item.description.toLowerCase().indexOf(this.search.toLowerCase()) >= 0
        })
    }.bind(this))
    .filter(function(item) {
        return item.nameMatches || item.descriptionMatches
    });

searchResults.forEach(function(result) {
    console.log(result.item, result.nameMatches, result.descriptionMatches)
})


text:
Q: Can't drawLine in TextView's onDraw I can't draw anything in my custom TextView class.
Sorry thats not strictly true, it works in Eclair but not in honeycomb!!!
The onDraw() method is definitely being called but nothing is getting drawn (in honeycomb).
Here is my onDraw method.
super.onDraw(canvas):
this.bluePaint.setColor(getResources().getColor(R.color.actionBlue));
float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, getResources().getDisplayMetrics());
this.bluePaint.setStrokeWidth(pix);
canvas.drawLine(0,0,this.getWidth(),20,this.bluePaint);

Is onDraw handled differently in Eclair to Honeycomb? Am I missing something?
Thanks in advance

A: I didn't manage to solve this problem.
What I did in the end was create my own custom text view using an object that extends View and manually drawing the text on there.
I'm not sure why TextView doesn't allow line drawing but hey, just another solution to a never ending stream of problems.


text:
Q: Group by Query - Select row with maximum date Hi I have this scores table, And in my report on front end, I have to display the keyword and url and score for latest scan.
CREATE TABLE `scores` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `keyword` varchar(200) DEFAULT NULL,
  `url` varchar(200) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  `check_date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

Here is my Example Data:
Sample Data
| id | keyword  | url                  | score | check_date |
|----|----------|----------------------|-------|------------|
| 1  | facebook | https://facebook.com | 10    | 2020-10-21 |
| 2  | facebook | https://facebook.com | 30    | 2020-10-25 |
| 3  | fb       | https://facebook.com | 55    | 2020-10-23 |
| 4  | fb       | https://facebook.com | 20    | 2020-10-24 |

My Query
SELECT s1.*
FROM scores s1
JOIN scores s2
  ON s1.id = s2.id
WHERE s1.check_date = s2.check_date
GROUP BY keyword,url

It returns correct check_date for a specific keyword, url but score is not according to that date. Please help.

A: Do not use aggregation for this.  A simple method is a correlated subquery:
select s.*
from scores s
where s.check_date = (select max(s2.check_date)
                      from scores s2
                      where s2.keyword = s.keyword and s2.url = s.url
                     );

If you are intent on using an explicit join you can use a left join, look for a larger date, and return the rows that have no larger date:
select s.*
from scores s left join
     scores slater
     on slater.keyword = s.keyword and
        slater.url = s.url and
        slater.check_date > s.check_date
where slater.check_date is null;


text:
Q: How to backup iCloud only files? How can I securely backup files, which are purged from the local harddrive due to the Optimize-Storage feature in macOS?

*

*They are NOT backed up in Timemachine

*They are NOT backed up with CCC (see here)

Currently I am manually copying them to an external drive but it does NOT seem, that they get downloaded doing this: It seems to only copy the placeholder files.
There has to be a way, to securely back them up


text:
Q: Accessing the files of the Plug and Play android device via WIN API Let me keep my explanation simple. I am writing a simple windows service, to detect android devices connected to the computer via USB and access the device's memory to read camera photos.
Using RegisterDeviceNotification() in the WIN API we can get registered to get notified for any device change (Devices added/removed from the computer). In my case I register to get notified when the USB devices are connected to the computer.
So when a volume device is connected we can get the drive letter using dbcv_unitmask from the PDEV_BROADCAST_VOLUME structure. This works absolutely well for a USB drive. I can then access my USB drive because of the known drive letter.
But, in my case the android device connects using MTP protocol and windows does recognize a new USB device being attached but does not seem to assign a drive letter to it. So, now I have no way to access the memory of the device programmatically.
Please let me know if there is a way to access the android PNP device via WIN API.
Thanks!

A: So, the alternative was to use WPD (Windows portable device API ) to access the mtp device.


text:
Q: How to check state (enabled/disabled) of a form's close button I'm disabling and enabling form's close button like in this code:
uses WinApi.Windows;
...
//disabling
EnableMenuItem(GetSystemMenu(MyForm.Handle, False), SC_CLOSE, MF_BYCOMMAND OR MF_DISABLED);
//enabling
EnableMenuItem(GetSystemMenu(MyForm.Handle, False), SC_CLOSE, MF_BYCOMMAND OR MF_ENABLED);

I'm trying to check if the close button's currently enabled or disabled. After checking this MSDN page I wrote this code:
var
  ItemInfo : TMenuItemInfo;
  MyForm : TForm;
begin
  MyForm := GetAFormInSomeWay();
  ItemInfo.fMask := MIIM_STATE;
  GetMenuItemInfo(GetSystemMenu(MyForm.Handle, False), SC_CLOSE, False, ItemInfo);
  if(ItemInfo.fState = MFS_ENABLED)
  then ShowMessage('Enabled')
  else ShowMessage('Disabled');

It always shows 'Disabled' (ItemInfo.fState is always 5395358).
What am I doing wrong?
Update:
Now it works, thanks to your suggestions.
uses
  WinApi.Windows, Vcl.Forms, System, System.SysUtils;

...

var
  ItemInfo : TMenuItemInfo;
  MyForm : TForm;
  SystemMenu : HMENU;
begin
  MyForm := GetAFormInSomeWay();
  ItemInfo.fMask := MIIM_STATE;
  ItemInfo.cbSize := SizeOf(MENUITEMINFO);

  SystemMenu := GetSystemMenu(MyForm.Handle, False);
  if((SystemMenu = 0) OR (GetMenuItemInfo(SystemMenu, SC_CLOSE, False, ItemInfo) = False))
  then raise Exception.Create(SysErrorMessage(GetLastError()));

  if((ItemInfo.fState AND MFS_DISABLED) = 0)
  then ShowMessage('Enabled')
  else ShowMessage('Disabled');
end;

A: You are making the classic mistake of Win32 programming. You are calling Win32 API functions and failing to check for errors. How do you know whether or not they succeed? And the answer is that you do not. Because you do not check. You must switch your mindset so that checking for errors becomes second nature when calling Win32 API functions. These functions do not raise exceptions. They signal failure by other means, typically through the return value. Find out how be reading the documentation for each function that you call.
The call to GetMenuItemInfo fails because you do not follow the instructions in the documentation. Specifically this part covering the item info argument:

Note that you must set the cbSize member to sizeof(MENUITEMINFO) before calling this function.

Following that instruction resolves your problem.
If you had checked for errors you would have seen that GetMenuItemInfo returns False, and GetLastError returns ERROR_INVALID_PARAMETER.
Your code calls the following API functions: GetSystemMenu, EnableMenuItem and GetMenuItemInfo. You fail to check for errors in each of these calls.
You should use bitwise and to check for the flag in the state, rather than equality. Although your test worked on my system it is semantically wrong. It will fail if the item is the default item, for instance.
Frankly, the problem at hand is insignificant when compared to the importance of checking for errors. I hope you take away that lesson. So, please don't just set cbSize and move on, please do add error checking as well.


text:
Q: Upgrade from 13.10 to 14.04 no unity dash for default user special compiz config I've upgraded my Ubuntu from 13.10 to 14.04 using the Ubuntu suggested option, everything went well -- meaning no report of corrupted update or anything - but when I rebooted and logged in again there was no desktop, meaning all I was getting was a black screen and the mouse pointer. I looked through the other threads on here and tried the solutions on there, it didn't really worked.
All I've been able to do was after removing and re-installing the lightdm manager I was able to get the top bar in the logging screen, but after actually logging in with the default user I only get a top bar with File Wiew Help etc and I can't open a terminal using Ctrl AtlT. I had some special compiz configuration in 13.10, but I've removed it and the problem is still not solved. Another thing, if I log in with a guest user I get both the top and side bar in Ubuntu.
If you guys have any idea what I could do it would be appreciated.
L.E.
Thanks for your input but none of them helped sadly.
Dpn I tried to do what you suggested and I couldn't run the first command, I got the following error:
 Error: cannot autolaunch D-Bus without X11 $DISPLAY

And, Daniel your solution didn't change anything at all, I already had that files in the place with configured exactly as you suggested.
Is there a way for me to copy the settings from the guest account in the default account? Or a way to compare the 2 configurations and see what's different?
Thanks, any advice would be appreciated!
L.L.E. I fixed it, I don't know if it helps anyone but, what I did was to reinstall the compiz-core:
sudo apt-get install --reinstall compiz-core

and then to remove the files in the .cache and .config folders
sudo rm -rf ~/.config/dconf/user
sudo rm -rf ~/.cache/compizconfig-1

Hope this helps others!
Thanks for the support!

A: ITs because your lightdm is crashed. Do the following things
Press ALT+CTRL+F1
You will get tt1
Login as username = root
Password what you set for you system
Now enter the following lines
vim /etc/lightdm/lightdm.conf.d/50-unity-greeter.conf.dpkg-bak //an editor opens b4 u
Delete what is there and add the following lines
[SeatDefaults]
greeter-session=unity-greeter
user-session=ubuntu
greeter-show-manual-login=true
Also edit the following file
vim /usr/share/lightdm/lightdm.conf.d/50-ubuntu.conf
[SeatDefaults]
greeter-session=unity-greeter
user-session=ubuntu
greeter-show-manual-login=true
Now Restart the system using the following command
init 6 //Reboot system

A: Press Alt+Ctrl+F2, black screen appears.Now, login with your username & password & type this
dconf reset -f /org/compiz/
then
setsid unity
then Press Alt+Ctrl+F7 to see your desktop
Guest User will show default settings because its a different user. Every user has its own settings.


text:
Q: Do photons change velocity instantaneously? Any object traveling at c is observed as traveling at c in all reference frames. When a photon travels through a vacuum at c, all reference frames observe it traveling at c.
When a photon passes through a medium, it's speed is less than c. The moment that it begins to slow down, there is a reference frame in which the photon is stationary, as all reference frames at a speed of less than c (perceived in another reference frame) are equally possible and valid.
This would imply that if a photon were to change speed at all, in some reference frame, the photon is traveling at c, and then its velocity immediately goes to zero. Is this the case?

A: The "slowing" of light in a medium can be entirely explained using a classical wave-based approach.  An incoming EM wave wiggles the electron clouds around the atoms in the material.  These electrons clouds re-emit a much weaker EM wave having a very small amplitude.  This re-emitted wave is 90-degree phase shifted from the original wave but superposes with the original wave.  This results in a tiny backward phase shift in the net field of the wave at each atom.  After traversing many atoms, the original wave plus the superposed re-emitted waves yield a net wave that appears to be travelling slower in the medium.  Nothing is slowing down.
Another classical example:  Consider a long lightweight rope tied on one end to a heavy metal chain.  If you send a wave pulse down the rope, the speed of the pulse changes at the interface with the chain to a much slower (and narrower) wave pulse, but there is no deceleration taking place.
This is not to say that actual photons are waves in the classical sense, but they should NOT be thought of little bullets having mass which can be accelerated.  The interaction of photons with actual particles having mass does appear to take place locally, giving them the appearance of having a definitive position when detected, as if they were particles.


text:
Q: An easy way to extend java syntax I want to make some changes in java syntax. For example I want to use operator '+' to add vectors. So I want this code:
public class Vector2 {
    public float x, y;
    public Vector2(float x, float y) {this.x = x;this.y = y;}
    public String toString() {...}

    public static Vector2 operator+(Vector2 a, Vector2 b) {
        return new Vector2(a.x + b.x, a.y + b.y);
    }

    public static void main(String[] args) {
        Vector2 a = new Vector2(3, 6);
        Vector2 b = new Vector2(2, 8);
        System.out.println(a + b);
    }
}

will be transleted into this standart java-code:
public class Vector2 {
    public float x, y;
    public Vector2(float x, float y) {this.x = x;this.y = y;}
    public String toString() {...}

    public static Vector2 operator_plus(Vector2 a, Vector2 b) {
        return new Vector2(a.x + b.x, a.y + b.y);
    }

    public static void main(String[] args) {
        Vector2 a = new Vector2(3, 6);
        Vector2 b = new Vector2(2, 8);
        System.out.println(Vector2.operator_plus(a, b));
    }
}

Is there some good and safe way to extend java syntax easier as writing an own compiler?
(I mean not only operator overloading, but essentially a good way to extend java syntax.)

A: Since Java does not support operator overloading, if you really really want that syntax you will need to change languages.

A: You can take a look at the source codes of Project Lombok for inspiration. They do some pretty cool transformations.

A: You talking about preprocessor. Fast answer is No - java doesn't have possibility to extend language.
But I suggest you to look at MPS - this is tool for creating translators and DSL's. But it contains some examples of extending java language(video).
Also one of the main benefits of MPS is that it have plugin for IntelliJ IDEA - so you can easily attach created extensions to this IDE and use them as syntactic sugar.

A: It will really depends on the type of extensions you want to do. If you want extension that are typical of an functional language, you may use scala that combine both OOP and functional paradigms. Maybe your extension can be solve combining AspectJ and annotations. In the last resource you can use an pre-compiler, but if you think that your extensions are little bite off of whats it is the purpose of Java you may consider to use the another language that best fits your current needs.

A: I suggest this way:

*

*write your own or get a preprocessor which would make simple

*substitutions  create a script which would call preprocessor to
create temporary files

*build those temporary files with java compiler

A: If you can stay within the java grammar, you can create annotation processors (javac plugins) to do what you want. An annotation processor is basically java code run at compile time. (Note that annotation processors does not need to have anything to do with annotations)
Using a few hacks (basically casts) in your code for your annotation processor, you can get access to javac's internal AST - this includes rewriting the AST during compile time!
A good introduction: The Hacker's Guide to Javac
All a user has to do to use your plugin is to include your .jar on the classpath when compiling with javac, so it is very easy to use. (You probably want to do IDE plugins too)
This is what the "Java-OO" javac-plugin does to add operator overloading to Java (operator overloading doesn't require any grammar changes, so it works fine with annotation processors). It is what the popular Project Lombok does as well.

The hacks needed to get access to the internals of javac are however "undocumented/unsupported", so there is always the danger that they stop working on new releases of javac.


text:
Q: CSS fluid columns (depending on content width) Can anyone help me to find CSS solution (yep, no JS) to this problem:
+---------+----------------------+-------------------------------+
| Fixed   |   Variable           |  Flexible width               |
|   width |      width content   | (adjusting to content width)  |
+---------+----------------------+-------------------------------+

Fixed width

Variable width content

Flexible width (adjusting to content width)

NOTE: IE7 support is needed. All columns are transparent and CAN NOT overlap with each other.

*

*1st column is fixed width;

*2nd column is variable width (depending from image dimensions);

*3rd column must take all remaining space.

A: How about this one.
parent -> position:relative;
parent:after -> clear:both
 fixed -> position:absolute
 variable -> float:left;padding-left:a-fixed-num
 flex -> display:block

A: @Rufus has the right idea, but it is missing out on one thing. Height. I'll recommend pretty much the same thing with some minor modifications:
.parent {
    position:relative;
}
.parent:after {
    clear: both;
}
.fixed {
    position: absolute;
    left: 0px;
    top: 0px;
    bottom: 0px; /* Conflicting absolute position trick */
    width: 150px; /* Or whatever the width you need is */
}
.variable {
    margin-left: 150px; /* Or, again, whatever you need */
    float: left;
    min-height: 100%; /* Don't use a border or padding or this will be messed up */
}
.flex {
    min-height: 100%; /* Same as variable, border or padding could mess this up */
}

All columns should be the same height, and you should be ready to go

A: Try this:
.group {
    display: table;width: 100%; table-layout: fixed;
}

.group > div {
    display: table-cell
}

jsFiddle example
That way, the right div is not 100% width, but the middle div does not expand with it's content...


text:
Q: Retrieve minsdk of another installed application Given packageinfo and applicationinfo objects, is there any way to directly pull the minsdk value of another installed app? Or failing that to directly pull out the manifest and parse it?

A: This is possible. You have to create the package context and then use that to pull out the manifest and parse it manually. Here is the code snippet I used to accomplish what I needed.
Context otherAppContext = context.createPackageContext(packageName, CONTEXT_RESTRICTED);
XmlResourceParser xmlResourceParser = otherAppContext.getAssets().openXmlResourceParser("AndroidManifest.xml");
int eventType = xmlResourceParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
    if (eventType == XmlPullParser.START_DOCUMENT) {
             Log.i(DEBUG_TAG, "Start document");
    } else if (eventType == XmlPullParser.START_TAG) {
        String startTag = xmlResourceParser.getName();
             Log.i(DEBUG_TAG, "Start tag " + startTag);
        if (startTag.equals("uses-sdk")) {
            int count = xmlResourceParser.getAttributeCount();
            for (int i = 0; i < count; i++) {
                String text = xmlResourceParser.getAttributeName(i);
                if (text.equals("minSdkVersion")) {
                    minSdkVersion = xmlResourceParser.getAttributeIntValue(i, -1);
                    break;
                }
            }
        }
    } else if (eventType == XmlPullParser.END_TAG) {
            Log.i(DEBUG_TAG, "End tag " + xmlResourceParser.getName());
    } else if (eventType == XmlPullParser.TEXT) {
            Log.i(DEBUG_TAG, "Text " + xmlResourceParser.getText());
    }
    eventType = xmlResourceParser.next();
}

works like a charm. don't forget to close the resource parser somewhere.


text:
Q: Text input doesnt work inside Bootstrap popover I have the following HTML to open a popup. Here the button works fine. It is clickable, but not an input. The text input seems to have a hidden disabled=true, but it's not.
What could be the problem?

const pop = new bootstrap.Popover(document.querySelector('[data-bs-toggle="popover"]'));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<img src="https://via.placeholder.com/100"
  data-bs-toggle="popover"
  data-bs-offset="0,14"
  data-bs-placement="top"
  data-bs-html="true"
  data-bs-content="

  <input type='text' class='form-control' placeholder='https://...'/>
  <button class='btn btn-primary'>Save</button>
"
>


text:
Q: pad creation and some mistakes on gst_parse_launch I am a newbie to gstreamer and I would like to know if we have to create source and sink pads for convert like video convert in a pipeline. I have a pipeline like this
gst-launch-1.0 v4l2src ! video/x-raw,format=YUY2 !  videoconvert ! xvimagesink

I am trying to create a simple c application to understand the creation of pads and would like to know if video convert has a source pad and sink pad too. I am creating a source and sink pad for the filter.
EDIT:
yeah well you see, I tried following the dynamic pipelines example and wrote the code below
#include <gst/gst.h>

// easier to pass them as callbacks
typedef struct _CustomData{
  GstElement *pipeline;
  GstElement *source;
  GstElement *convert;
  GstElement *sink;
}CustomData;

// callback function

// here src is the v4l2src, newpad is gstpad that has just been added to src element. This is usually the pad to which we want to lnk
// data is the pointer we provided when attaching to the signal.

static void pad_added_handler(GstElement *src, GstPad *new_pad,CustomData *data)
{
  g_print("In pad handler\n");
  GstPad *sink_pad = gst_element_get_static_pad(data->convert, "sink");
  GstPadLinkReturn ret;
  GstCaps *new_pad_caps = NULL;
  GstStructure *new_pad_struct = NULL;
  const gchar *new_pad_type = NULL;

  if(gst_pad_is_linked(sink_pad))
    {
      g_print("we are linked. igonring\n");
    }
  // check the new pad types
  // we have previously created a piece of pipeline which deals with videoconvert linked with xvimagesink and we will nto be able to link it to a pad producing video.
  //gst-pad_get_current_caps()- retrieves current capabilities of pad
    new_pad_caps = gst_pad_get_current_caps(new_pad);
    new_pad_struct = gst_caps_get_structure(new_pad_caps, 0);
    new_pad_type = gst_structure_get_name(new_pad_struct);
     g_print ("It has type '%s' which is not raw audio. Ignoring.\n", new_pad_type);

     if(!g_str_has_prefix(new_pad_type, "video/x-raw,format=(string)YUY2"))
     {
         g_print("It has new pad type");
      }

  // gst_pad_link tries to link two pads . the link must be specified from source to sink and both pads must be owned by elements residing in same pipeline
  ret = gst_pad_link(new_pad, sink_pad);
  if(GST_PAD_LINK_FAILED(ret))
    {
      g_print("type is new_pad_type");
    }
  if(new_pad_caps !=NULL)
    {
      gst_caps_unref(new_pad_caps);
        }
    gst_object_unref(sink_pad);
}

int main(int argc, char *argv[])
{
  GMainLoop *loop;
  CustomData data;
    GstBus *bus;
  GstMessage *msg;
  gboolean terminate = FALSE;
  gst_init(&argc, &argv);
  //  loop = g_main_loop_new(NULL, FALSE);
  // create the elements
  data.source = gst_element_factory_make("v4l2src", "source");
  data.convert = gst_element_factory_make("videoconvert", "convert");
  data.sink = gst_element_factory_make("xvimagesink", "sink");

  data.pipeline = gst_pipeline_new("new-pipeline");

  if(!data.pipeline || !data.source || !data.convert || !data.sink)
    {
      g_printerr("Not all elements could be created\n");
      return -1;
    }

  //we did not link source at this point of time, we will do it later
  gst_bin_add_many(GST_BIN(data.pipeline), data.source, data.convert, data.sink, NULL);
  // we link convert element to sink, do not link them with source. we dont have source pads here. so we just have videoconvert->sink unlinked
  //    gst_element_link(data.source, data.convert);
  if(!gst_element_link( data.convert,data.sink))
    {
      g_printerr("elements could not be linked\n");
      gst_object_unref(data.pipeline);
      return -1;
    }

  // we set the device source
  //g_object_set(source, "device", "/dev/video0", NULL);

  //connect to pad added signal.
  // we want to attach pad added signal to source element. to do so, we are using g_signal_connect and provide callback function and datapointer.
  // when source element has enough information to start producing data, it will create source pads and trigger the pad added signal. at this point, our callback is called
  g_print("before signal connect\n");
        gint id= g_signal_connect(G_OBJECT(data.source), "pad-added", G_CALLBACK(pad_added_handler), &data );
    g_print("after signal connect with id = %d\n", id);
  //g_signal_connect(G_OBJECT(data.source), "pad-added", G_CALLBACK(handler), &data);
    //   gst_element_link(data.source, data.convert);
     GstStateChangeReturn ret;
  ret =gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
   if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr ("Unable to set the pipeline to the playing state.\n");
    gst_object_unref (data.pipeline);
    return -1;
    }
   //   g_main_loop_run(loop);
    /* Listen to the bus */
  bus = gst_element_get_bus (data.pipeline);
  do {
    msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE,
        GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS);

    /* Parse message */
    if (msg != NULL) {
      GError *err;
      gchar *debug_info;

      switch (GST_MESSAGE_TYPE (msg)) {
        case GST_MESSAGE_ERROR:
          gst_message_parse_error (msg, &err, &debug_info);
          g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
          g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
          g_clear_error (&err);
          g_free (debug_info);
          terminate = TRUE;
          break;
        case GST_MESSAGE_EOS:
          g_print ("End-Of-Stream reached.\n");
          terminate = TRUE;
          break;
        case GST_MESSAGE_STATE_CHANGED:
          /* We are only interested in state-changed messages from the pipeline */
          if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data.pipeline)) {
            GstState old_state, new_state, pending_state;
            gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
            g_print ("Pipeline state changed from %s to %s:\n",
                gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
          }
          break;
        default:
          /* We should not reach here */
          g_printerr ("Unexpected message received.\n");
          break;
      }
      gst_message_unref (msg);
    }
  } while (!terminate);

  /* Free resources */
  gst_object_unref (bus);

  gst_element_set_state(data.pipeline, GST_STATE_NULL);
  gst_object_unref(data.pipeline);
  return 0;
}

and it gave me an error
before signal connect
after signal connect with id = 1
Pipeline state changed from NULL to READY:
Pipeline state changed from READY to PAUSED:
Error received from element source: Internal data stream error.
Debugging information: gstbasesrc.c(3055): gst_base_src_loop (): /GstPipeline:new-pipeline/GstV4l2Src:source:
streaming stopped, reason not-linked (-1)

(The above code works if I write gst_elements_link(data.source, data.convert) after the element link statement for convert and sink)
So I tried the normal way in which I just added and linked all the elements together and it began to work without use of the pads.
#include <gst/gst.h>

int main(int argc, char *argv[])
{
  GstElement *pipeline, *source, *convert, *sink;
  GstBus *bus;
  GstMessage *msg;

  gst_init(&argc, &argv);

  source = gst_element_factory_make("v4l2src", "source");
  convert = gst_element_factory_make("nvvidconv", "convert");
  sink = gst_element_factory_make("xvimagesink", "sink");

  pipeline = gst_pipeline_new("pipe");

  gst_bin_add_many(GST_BIN(pipeline), source,convert,sink, NULL);
  gst_element_link_many(source,convert,sink,NULL);
  gst_element_set_state(pipeline,GST_STATE_PLAYING);

bus = gst_element_get_bus (pipeline);
  msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);

  /* Parse message */
  if (msg != NULL) {
    GError *err;
    gchar *debug_info;

    switch (GST_MESSAGE_TYPE (msg)) {
      case GST_MESSAGE_ERROR:
        gst_message_parse_error (msg, &err, &debug_info);
        g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
        g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
        g_clear_error (&err);
        g_free (debug_info);
        break;
      case GST_MESSAGE_EOS:
        g_print ("End-Of-Stream reached.\n");
        break;
      default:
        /* We should not reach here because we only asked for ERRORs and EOS */
        g_printerr ("Unexpected message received.\n");
        break;
    }
    gst_message_unref (msg);
  }

  /* Free resources */
  gst_object_unref(bus);

  gst_element_set_state(pipeline,GST_STATE_NULL);
  gst_object_unref(pipeline);

}

But, inorder to fully grasp the knowledge of pads, I wanted to execute simpler pipelines with pads.
I just don't fully understand the usage of pads and link them and all.
EDIT2:
Ultimately I want to write application for pipeline like this which works on command line perfectly well,
gst-launch-1.0 v4l2src device='/dev/video0' ! 'video/x-raw,format=(string)YUY2,width=(int)640,height=(int)480' ! nvvidconv ! 'video/x-raw(memory:NVMM),format=(string)NV12,width=(int)640,height=(int)480' ! nvvidconv ! 'video/x-raw,format=(string)NV12,width=(int)640,height=(int)480' ! nvvideoconvert ! 'video/x-raw(memory:NVMM),format=(string)NV12,width=(int)640,height=(int)480' ! mux.sink_0 nvstreammux live-source=1 name=mux batch-size=1 width=640 height=480 ! nvinfer config-file-path=/opt/nvidia/deepstream/deepstream-4.0/sources/apps/sample_apps/deepstream-test1/dstest1_pgie_config.txt batch-size=1 ! nvmultistreamtiler rows=1 columns=1 width=640 height=480 ! nvvideoconvert ! nvdsosd ! nvegltransform ! nveglglessink sync=false -v

But as I don't understand the usage of both pads and bins, I am unable to implement them in my above pipeline. However, I tried this,
#include <gst/gst.h>
#include <glib.h>
#include <stdio.h>
#include "gstnvdsmeta.h"

#define MAX_DISPLAY_LEN 64

#define PGIE_CLASS_ID_VEHICLE 0
#define PGIE_CLASS_ID_PERSON 2

gint frame_number = 0;
gchar pgie_classes_str[4][32] = { "Vehicle", "TwoWheeler", "Person",
  "Roadsign"
};

static GstPadProbeReturn osd_sink_pad_buffer_probe(GstPad *pad, GstPadProbeInfo *info, gpointer u_data)
{
  GstBuffer *buf=(GstBuffer *)info->data;
  guint num_rects =0;
  NvDsObjectMeta *obj_meta = NULL;
    guint vehicle_count = 0;
    guint person_count = 0;
    NvDsMetaList * l_frame = NULL;
    NvDsMetaList * l_obj = NULL;
    NvDsDisplayMeta *display_meta = NULL;

    NvDsBatchMeta *batch_meta = gst_buffer_get_nvds_batch_meta (buf);

    for (l_frame = batch_meta->frame_meta_list; l_frame != NULL;
      l_frame = l_frame->next) {
        NvDsFrameMeta *frame_meta = (NvDsFrameMeta *) (l_frame->data);
        int offset = 0;
        for (l_obj = frame_meta->obj_meta_list; l_obj != NULL;
                l_obj = l_obj->next) {
            obj_meta = (NvDsObjectMeta *) (l_obj->data);
            if (obj_meta->class_id == PGIE_CLASS_ID_VEHICLE) {
                vehicle_count++;
                num_rects++;
            }
            if (obj_meta->class_id == PGIE_CLASS_ID_PERSON) {
                person_count++;
                num_rects++;
            }
        }
        display_meta = nvds_acquire_display_meta_from_pool(batch_meta);
        NvOSD_TextParams *txt_params  = &display_meta->text_params[0];
        display_meta->num_labels = 1;
        txt_params->display_text = g_malloc0 (MAX_DISPLAY_LEN);
        offset = snprintf(txt_params->display_text, MAX_DISPLAY_LEN, "Person = %d ", person_count);
        offset = snprintf(txt_params->display_text + offset , MAX_DISPLAY_LEN, "Vehicle = %d ", vehicle_count);

        /* Now set the offsets where the string should appear */
        txt_params->x_offset = 10;
        txt_params->y_offset = 12;

        /* Font , font-color and font-size */
        txt_params->font_params.font_name = "Serif";
        txt_params->font_params.font_size = 10;
        txt_params->font_params.font_color.red = 1.0;
        txt_params->font_params.font_color.green = 1.0;
        txt_params->font_params.font_color.blue = 1.0;
        txt_params->font_params.font_color.alpha = 1.0;

        /* Text background color */
        txt_params->set_bg_clr = 1;
        txt_params->text_bg_clr.red = 0.0;
        txt_params->text_bg_clr.green = 0.0;
        txt_params->text_bg_clr.blue = 0.0;
        txt_params->text_bg_clr.alpha = 1.0;

        nvds_add_display_meta_to_frame(frame_meta, display_meta);
    }

    g_print ("Frame Number = %d Number of objects = %d "
            "Vehicle Count = %d Person Count = %d\n",
            frame_number, num_rects, vehicle_count, person_count);
    frame_number++;
    return GST_PAD_PROBE_OK;

}

int main(int argc, char *argv[])
{
   GstElement *pipeline,  *source, *filter1, *convert,*filter2, *filter3, *vidconv, *filter4, *mux, *infer, *tiler, *osd, *transform , *sink, *bin, *convert2 , *vidconv2;
   GMainLoop *loop;
   GstCaps *caps1, *caps2, *caps3, *caps4;
   GstPad *osd_sink_pad =NULL, *srcpad, *sinkpad;

   loop = g_main_loop_new(NULL,FALSE);
   gst_init(&argc, &argv);
   pipeline = gst_pipeline_new("nv_pipeline");
   gchar *string1 = "video/x-raw(memory:NVMM),format=(string)NV12";

   source = gst_element_factory_make("v4l2src", "source");
   filter1 = gst_element_factory_make("capsfilter", "filter1");
   convert = gst_element_factory_make("nvvidconv", "convert");
   filter2 = gst_element_factory_make("capsfilter", "filter2");
   filter3 = gst_element_factory_make("capsfilter", "filter3");
   filter4 = gst_element_factory_make("capsfilter", "filter4");
   vidconv = gst_element_factory_make("nvvideoconvert", "vidconv");
   mux = gst_element_factory_make("nvstreammux", "mux");
   infer = gst_element_factory_make("nvinfer", "infer");
   tiler = gst_element_factory_make("nvmultistreamtiler", "tiler");
   osd = gst_element_factory_make("nvosd", "osd");
   transform = gst_element_factory_make("nvegltransform", "transform");
   sink = gst_element_factory_make("nveglglessink", "sink");
   convert2 = gst_element_factory_make("nvvidconv", "convert2");
   vidconv2 = gst_element_factory_make("nvvideoconvert", "vidconv2");

   gst_bin_add_many(GST_BIN(pipeline), source,filter1,convert,filter2, convert2,filter3,vidconv, filter4,mux,infer, tiler,vidconv2, osd,transform,sink,NULL);

   gst_element_link_many(source,filter1,convert,filter2, convert2,filter3, vidconv, filter4,mux,infer, tiler,vidconv2, osd,transform,sink,NULL);

   osd_sink_pad = gst_element_get_static_pad(osd, "sink");
   gst_pad_add_probe(osd_sink_pad, GST_PAD_PROBE_TYPE_BUFFER, osd_sink_pad_buffer_probe, NULL, NULL);

   caps1 = gst_caps_new_simple("video/x-raw", "format",G_TYPE_STRING,"YUY2",NULL);
   caps2 = gst_caps_from_string(string1);
   caps3 = gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING,"NV12", NULL);
   caps4 = gst_caps_from_string(string1);

   g_object_set(G_OBJECT(filter1), "caps", caps1, NULL);
   g_object_set(G_OBJECT(filter2), "caps", caps2, NULL);
   g_object_set(G_OBJECT(filter3), "caps", caps3, NULL);
   g_object_set(G_OBJECT(filter4), "caps", caps4, NULL);

   g_object_set(G_OBJECT(mux), "live-source", 1, "name", "mux", "batch-size", 1, "width", 1280, "height", 720, NULL);
   g_object_set(G_OBJECT(infer), "config-file-path","/opt/nvidia/deepstream/deepstream-4.0/sources/apps/sample_apps/deepstream-test1/dstest1_pgie_config.txt",NULL);
   g_object_set(G_OBJECT(infer), "batch-size", 1, NULL);
   g_object_set(G_OBJECT(tiler), "rows", 1, "columns", 1, "width", 1280, "height", 720, NULL);

   gst_caps_unref(caps1);
   gst_caps_unref(caps2);
   gst_caps_unref(caps3);
   gst_caps_unref(caps4);

   gst_element_set_state(pipeline, GST_STATE_PLAYING);
   g_print("Running ...\n");
   g_main_loop_run(loop);

   gst_element_set_state(pipeline,GST_STATE_NULL);
   gst_object_unref(pipeline);
   return 0;
}

which gives the exact same output as the command line gst-launch-1.0 like,
(deep_pads:15648): GLib-GObject-WARNING **: 11:29:18.761: cannot register existing type 'GstInterpolationMethod'

(deep_pads:15648): GLib-GObject-CRITICAL **: 11:29:18.761: g_param_spec_enum: assertion 'G_TYPE_IS_ENUM (enum_type)' failed

(deep_pads:15648): GLib-GObject-CRITICAL **: 11:29:18.761: validate_pspec_to_install: assertion 'G_IS_PARAM_SPEC (pspec)' failed

(deep_pads:15648): GStreamer-CRITICAL **: 11:29:18.814: gst_element_get_static_pad: assertion 'GST_IS_ELEMENT (element)' failed

(deep_pads:15648): GStreamer-CRITICAL **: 11:29:18.814: gst_pad_add_probe: assertion 'GST_IS_PAD (pad)' failed
0:00:00.843318172 15648   0x5591be52c0 INFO                 nvinfer gstnvinfer.cpp:519:gst_nvinfer_logger:<infer> NvDsInferContext[UID 1]:initialize(): Trying to create engine from model files
0:00:20.693301580 15648   0x5591be52c0 INFO                 nvinfer gstnvinfer.cpp:519:gst_nvinfer_logger:<infer> NvDsInferContext[UID 1]:generateTRTModel(): Storing the serialized cuda engine to file at /opt/nvidia/deepstream/deepstream-4.0/samples/models/Primary_Detector/resnet10.caffemodel_b1_int8.engine

except It doesn't display an output window from the above c application and doesn't display the rest.

A: Your first example fails because data.source element is actually never linked to data.convert element. Since both elements have static pads you need to "manually" create them and link them before setting pipeline to GST_STATE_PLAYING:
GstPad *source_pad = gst_element_get_static_pad(data.source, "src");
GstPad *sink_pad = gst_element_get_static_pad(data.convert, "sink");
ret = gst_pad_link(source_pad, sink_pad);

You probably expected that static source pad of your data.source element will somehow be automatically created so you registered
g_signal_connect(G_OBJECT(data.source), "pad-added", G_CALLBACK(pad_added_handler), &data );

But, as you can see from your debug, pad_added_handler was never called because g_signal_connect can be registered and will be called for elements that have dynamic pads. For example, demultiplexer tsdemux will dynamically create its source pads during discovery of elementary streams so, in that case, registration of pad-added callback would be necessary.
The first step in your learning curve would be to understand fundamental differences between "static" (mandatory, always exists, "manually" created), dynamic (exists sometimes, automatically created by element) and request (optional, "manually" created when needed) gstreamer pads. After that everything will be much easier for you.


text:
Q: How to get filename in awk I have a zip file with below name and record:

*

*Filename : OMS_Profile_20150922.list.Z

Sample Record:
1234568194|301776931|301344831|301745924|4000247920|5|1|14|
1234525025|300667099|300316999|300645099|300624099|5|1|14|
1234586176|301121638|301131238|301145638|301124638|5|1|14|
1234597373|300689187|345664087|302464187|300624187|5|1|21|

Now I want to get the below desired output by awk command:
field1|field6|field7|field8|OMS_Profile_20150922.list.Z

A: something like this should work:
unzip -c /tmp/test.zip >/tmp/test.txt
awk -F "|" 'START {OFS="|"} {print $1,$6,$7,$8,FILENAME}' /tmp/test.txt

A: read s d t f_name < <(unzip -qql OMS_Profile_20150922.list.Z)
unzip -p OMS_Profile_20150922.list.Z |
awk -F'|' '{print $1,$6,$7,$8,f_name}' OFS='|' f_name="$f_name"

A: Assuming that .Z file is a compress-compressed file (as the .Z extension implies as opposed to PKZIP archives that zip file would suggest):
FILE='OMS_Profile_20150922.list.Z'
export FILE
zcat < "$FILE" | awk -F'|' -v OFS='|' '
  {print $1,$6,$7,$8, ENVIRON["FILE"]}'


text:
Q: arrange line in txt file in ASCII order using array and display them #include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>

using namespace std;

int main() {
    ifstream infile;          // ifstream is reading file
    infile.open("read.txt");  // read.txt is the file we need to read
    std::cout << infile;
    string str;
    if (infile.is_open()) {
        while (getline(infile, str)) {
            char str[2000], ch;
            int i, j, len;
            len = strlen(str);
            for (i = 0; i < len; i++) {
                for (j = 0; j < (len - 1); j++) {
                    if (str[j] > str[j + 1]) {
                        ch = str[j];
                        str[j] = str[j + 1];
                        str[j + 1] = ch;
                    }
                }
            }
        }
        cout << "\nProcessed data:" << str;
    }

    return 0;
}

My txt file:
Today is a fine day.
It's sunny.
Let us go out now!

My result should be:
    .Taaaddefiinosyy
 '.Innsstuy
    !Legnooosttuuw

Spaces is consider here as well.
I'm new to C++.
I need some pros help.
Thank you very much!

A: Making use of the STL:

*

*Read your file line by line into a std::string using std::getline.

*Sort every line using std::ranges::sort.

*Print it.

The example below:

*

*also uses the fmt library instead of std::cout, and

*reads from a std::istringstream instead of a std::ifstream.

[Demo]
#include <algorithm>  // sort
#include <fmt/core.h>
#include <sstream>  // istringstream
#include <string>  // getline

int main() {
    std::istringstream iss{
        "Today is a fine day.\n"
        "It's sunny.\n"
        "Let us go out now!\n"
    };

    fmt::print("Original file:\n{}\n", iss.str());

    fmt::print("Processed file:\n");
    std::string line{};
    while (std::getline(iss, line)) {
        std::ranges::sort(line);
        fmt::print("{}\n", line);
    }
}

// Outputs:
//
//   Original file:
//   Today is a fine day.
//   It's sunny.
//   Let us go out now!
//
//   Processed file:
//       .Taaaddefiinosyy
//    '.Innsstuy
//       !Legnooosttuuw

A: Your code does not work, because:

*

*The line std::cout << infile; is wrong. If you want to print the result of istream::operator bool() in order to determine whether the file was successfully opened, then you should write std::cout << infile.operator bool(); or std::cout << static_cast<bool>(infile); instead. However, it would probably be better to simply write std::cout << infile.fail(); or std::cout << !infile.fail();.

*The function std::strlen requires as a parameter a pointer to a valid string. Maybe you intended to write str.length()? In that case, you should delete the declaration char str[2000], because it shadows the declaration string str;.

*You should print the sorted result immediately after sorting it, before it gets overwritten by the next line. Currently you are only printing the content str a single time at the end of your program, so you are only printing the last line.

After performing the fixes mentioned above, your code should look like this:
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <iostream>

using namespace std;

int main() {
    ifstream infile;          // ifstream is reading file
    infile.open("read.txt");  // read.txt is the file we need to read
    std::cout << infile.fail();
    string str;
    if (infile.is_open()) {
        while (getline(infile, str)) {
            char ch;
            int i, j, len;
            len = str.length();
            for (i = 0; i < len; i++) {
                for (j = 0; j < (len - 1); j++) {
                    if (str[j] > str[j + 1]) {
                        ch = str[j];
                        str[j] = str[j + 1];
                        str[j + 1] = ch;
                    }
                }
            }

            cout << "\nProcessed data:" << str;
        }
    }

    return 0;
}

For the input
Today is a fine day.
It's sunny.
Let us go out now!

this program has the following output:
0
Processed data:    .Taaaddefiinosyy
Processed data: '.Innsstuy
Processed data:    !Legnooosttuuw

Note that the input posted in your question contains a forward tick ' instead of an apostrophe '. This could cause trouble. For example, when I tested your program, this forward tick was encoded into a multi-byte UTF-8 character, because it is not representable in 7-bit US-ASCII. This caused your sorting algorithm to fail, because it only supports single-byte characters. I was only able to fix this bug by replacing the forward tick with an apostrophe in the input.


text:
Q: How to start serial value from 1 after deleting all values from table? I am using sqlite in my android application.
When i delete all the records from the table then also the next entry is the increment of the last serial.If i delete all records from table,I need to start it from 1
How to do it?

A: It sounds like you want to reset your AUTO_INCREMENT to 0.
DELETE FROM tablename;
DELETE FROM SQLITE_SEQUENCE WHERE name='tablename';

A: You can do it like this,
delete from sqlite_sequence where name='your_table';

Altering SQLITE_SEQUENCE Table is not a good option because it is likely to disturb AUTOINCREMENT Key generation Algorithm. You can see this Answer.


text:
Q: Following Feature From Michael Hartl's Rails Tutorial I am trying to implement the follower feature from Hartl's RoR tutorial, chapter 12.
I have the feature working in that I can login, go to another user profile, click follow and (after refreshing the page) I see I am now following them. Same with unfollowing.
However, my integration tests fail, the Ajax doesn't work, and I get this error in my Rails server log when I click follow or unfollow:
Rendered users/_follow.html.erb (1.7ms)
Rendered relationships/destroy.js.erb (2.5ms)
Completed 500 Internal Server Error in 17ms
NoMethodError - undefined method `id' for nil:NilClass:

My code matches Hartl's exactly (I think). However, I am using FriendlyID on my User model and Devise, one of which (likely FriendlyID) is causing problems.
I believe this is all the relevant code.
Any ideas would be much appreciated... now on hour 5 or so of this!
controllers/users_controller.rb
def following
@title = "Following"
@user  = User.friendly.find(params[:id])
@users = @user.following
render 'show_follow'
end

def followers
@title = "Followers"
@user  = User.friendly.find(params[:id])
@users = @user.followers
render 'show_follow'
end

controllers/relationships_controller.rb
def create
user = User.friendly.find(params[:followed_id])
current_user.follow(user)
respond_to do |format|
  format.html { redirect_to @user }
  format.js
 end
end

def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
respond_to do |format|
  format.html { redirect_to @user }
  format.js
end
end

models/user.rb
# follows a user
def follow(other_user)
active_relationships.create(followed_id: other_user.id)
end

# unfollows a user
def unfollow(other_user)
  active_relationships.find_by(followed_id: other_user.id).destroy
end

# returns true if user is following the other user
def following?(other_user)
following.include?(other_user)
end

_unfollow.html.erb
<%= form_for(current_user.active_relationships.find_by(followed_id: @user.id),
html: { method: :delete }, remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn" %>
<% end %>

_follow.html.erb
<%= form_for(current_user.active_relationships.build(followed_id: @user.id), remote: true) do |f| %>

<%= hidden_field_tag :followed_id, @user.id %>

<%= f.submit "Follow", class: "btn" %>
<% end %>

A: In your relationships_controller.rb you haven't defined the @user variable, which is why you're receiving the undefined method error. Try this:
def create
  @user = User.friendly.find(params[:followed_id])
  current_user.follow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end

def destroy
  @user = Relationship.find(params[:id]).followed
  current_user.unfollow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
end


text:
Q: Is it possible to use a function in an SQLAlchemy filter? I have a function that checks an object for some properties and returns boolean values depending on the result. It's too complex to write it in filter, but it works and returns the right value.
Now I want to use sqlalchemy to return all objects that this function returns True for. I tried:
DBSession.query(MyObject).filter(self.check_attributes(MyObject) == True).all()

and
DBSession.query(MyObject).filter(self.check_attributes(MyObject)).all()

Both failed to select the right objects. What am I doing wrong?

A: As I said in my comment, hybrid_method/hybrid_property is the appropriate pattern for your use case. It may at first seem complicated, but it's actually quite simple. The first version of the function operates exactly like a Python method or property, and the second part acts as a class method. SQLAlchemy filters work on the class to generate SQL.
This is just a useless example, but instead of therabouts your example could have a complicated calculation.
If you don't need to pass any parameters then I suggest using hybrid_property instead.
class MyObject(Model):
  name = Column(String)
  num = Column(Integer)

  @hybrid_method
  def therabouts(self, n):
     return self.num > n - 5 and self.num <= n + 5

  @therabouts.expression
  def therabouts(cls, n):
     return and_(cls.num > n - 5, cls.num <= n + 5)

  @hybrid_property
  def is_al(self):
     return self.name.lower().startswith('al')

  @is_al.expression
  def is_al(cls):
     return cls.name.ilike('al%')

# When used as a class method @thereabouts.expression is called
near20 = session.query(MyObject).filter(MyObject.therabouts(20)).first()

# When used as an instance, @hybrid_method is called
near20.therabouts(20) # True
near20.therabouts(22) # Maybe True
near20.therabouts(50) # False

# filter example (class)
all_als = session.query(MyObject).filter(MyObject.is_al).all()
for al in all_als:
  print al.name
# output Alan, Alanzo, Albert...

# instance example (self)
bob = MyObject(name='Robert')
print bob.is_al # False

A: If by "use a function" you mean write the filters inside a function, you certainly can - you just need to pass the correct argument to it (the query) and use its return (the filtered query) in the proper place
Let's take an example from SQLAlchemy's tutorial:
wendy = session.query(User).filter_by(name='wendy').one()

You can move the filter(s) to a function easily:
def my_filter(query):
    return query.filter_by(name='wendy')

wendy = my_filter(session.query(User)).one()

However, if by " function that checks an object for some properties and returns boolean values depending on the result" you mean a function that accepts a database record as an argument, I don't think it can be done (without subverting the whole purpose of using SQL).
--EDIT-- As doog abides points out, the hybrid extension, while not operating on database records, does something that's equivalent for many practical purposes.

Of course, some people will insist in writing something like:
all_users = session.query(User).all()
wendy= filter( lambda u:u.name=='wendy', all_users )

But, for the sake of the sanity of your fellow programmers and users, please don't do that.


text:
Q: Core Java - Create custom AOP I was wondering how does AOP actually works and is there a way that we can create our own AOP. what should be the steps taken and best practice for the same?

A: Essentially there are two different concepts for AOP:

*

*Class-weaving: using this concept you create "advices", that can be translated into regular java code while compiling bytecode. (altough there are possibilities to do this in run-time). This approach allows you to write a code once, and (through advices) distribute this code across many classes that might have no relation to each other whatsoever.

*Proxy-based: this you can imagine as an example usage of the "Decorator" design pattern. Using bytecode instrumentation certain libraries (like cglib) you can intercept function calls and add your own code to be executed beforehand. This is a more "natural" (and surely simpler) approach, so if you are really going to implement your own AOP library then probably this is the better approach to go with.

A: There are different steps for AOP, but the basics turn around doing automatically another action on specified condition, for example:

*

*before calling any method on any class of a dedicated package, log something

*get the time before executing a specific method and after to time it

*replace any access to a specific attribut of a class with a direct access to a database element

The first 2 examples are easier to implement because they involve methods. So if the methods are public a proxy mechanism will be enough. The third one really requires bytecode editing.
So the first question you must ask yourself is what is your real need. If you need full AspectJ power, the only way will be bytecode editing. My advice here would be to not try to reinvent the wheel and rely on AspectJ implementation
If the only interception points are public method calls, you could try to mimic the Spring AOP which is based on JDK proxies. It can also use cglib proxies which are slightly more intrusive but a little more powerful (do not need interfaces and can deal with not public methods).
TL/DR: So you have 3 implementation levels from simpler/less powerfull to harder/full power:

*

*rely on JDK proxies : can only process public method calls, but certainly the simplest way; another limit, cannot process internal calls (calls originating from the class itself)

*rely on CGLib proxies : intermediary way: requires limited bytecode editing, and can process private method calls, but still cannot deal with direct attribute access

*reimplement AspectJ : full power but... good luck on it!


text: Q: Matlab: how do you lock the secondary y-axis when zooming in or out of a plot? How do you lock the secondary y-axis when zooming in or out of a plot? I am using plotyy (Matlab R2010a) and would like to zoom, both vertically and horizontally, data plotted against the primary y-axis but have the secondary y-axis be vertically static.


text:
Q: The inverse image of an interval Someone help me to find $f^{-1}(](x^2+1)-\varepsilon,(x^2+1)+\varepsilon[)$ where $$f(x)=\begin{cases} 0,~\text{if}~ x<0\\ x^2+1,~\text{if}~ x\geq0\end{cases}$$
I know that
$f^{-1}(](x^2+1)-\varepsilon,(x^2+1)+\varepsilon[)=\{y\in \mathbb{R}, f(y)\in ](x^2+1)-\varepsilon, (x^2+1)-\varepsilon[\}$
let $y<0$ then $f(y)=0$ so $f(y)\in ](x^2+1)-\varepsilon, (x^2+1)-\varepsilon[ $ if $x^2+1-\varepsilon <0$ that is $ \varepsilon >x^2+1$
so if $\varepsilon >x^2+1$ $f^{-1}(y)=]-\infty,0[$ right ?
someone have an idea on how to do this ?

A: Hint:Based on the graph of $f(x)$
$${{f}^{-1}}\left( \left] a,b \right[ \right)=\left\{ \begin{align}
  & \phi \ \quad \quad \quad \quad \quad \quad \quad \quad ,if\ b\le 0\  \\
 & \left] -\infty ,0 \right[\quad \quad \quad \quad \quad \quad ,if\ b\le 1\ AND\ a<0 \\
 & \phi \quad \quad \quad \quad \quad \quad \quad \quad ,if\ b\le 1AND\ a\ge 0 \\
 & \left] \sqrt{a-1},\sqrt{b-1} \right[\quad \ \quad ,if\ a\ge 1 \\
 & \left] 0,\sqrt{b-1} \right[\quad \quad \quad \ \quad ,if\ b>1\ AND\ a\ge 0 \\
 & \left[ 0,\sqrt{b-1} \right[\quad \quad \quad \ \quad ,if\ b>1\ AND\ a<0 \\
\end{align} \right\}
$$


text:
Q: Subsite access without being a member of the subsite in wp multisite network How can a user access a subsite without being the member of that subsite in a wp multisite network?
What I understand is that a user can not access a private post in a subsite if he is not the member of that subsite but I want to remove this restrictions.
I tried to use the method add_user_to_blog but it is not what I am looking for.
Any help would be appreciated.


text:
Q: How to set Height of linerlayout through java code In xml file I am Using Relative layout as parent ..
In that i am using Linerlayout as child..
How can i set the height of linear layout?
Thanks in advance

A: Try this code which will set the height of the linear layout.. It will correspond to the
parent ie in your case RelativeLayout.. hope it will work correctly...
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout0);
linearLayout .setMinimumHeight(minHeight);


text:
Q: C++ std::hash_map: What is the key's role Both maps and hash_maps are designed so hold pairs of <key, data>. It's clear to me why the map should have a key for it's sorting (more precisely: treeing), but I don't understand why hash_maps need a key, why can't it's data alone be hashed and placed into the hash table?
I couldn't find the answer neither in the documentation nor by searching around the net.

A: std::unordered_set works precisely in the way you describe. However, there are times when you want to map from one piece of data to another; that's where std::unordered_map comes into play.

A: Walk to the cupboard. Get the phone book out and look up a number. It has a mapping between a name and number

A: you are looking for set, where a key is also data.
C++ offers some different flavour of them: set, unordered_set, etc...

A: Hash Map which is also called Unordered Map uses a HASH of the KEY as an index of buckets or Slots.In other word, any Hash Table needs a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.These index are the Key of the Hash Table, which are used for accessing the data in O(1) time in best case.

A: If you want to use the data itself as the key, the appropriate container is std::set or std::unordered_set. A map holds both a key and a value; the difference between std::map and std::unordered_map is in how the data is organized; std::map sorts by the key, and std::unordered_map hashes by the key.


text:
Q: Pyarrow.flight.do_get segfault when pandas Dataframe over 3GB I have two dataframes in my flight server: v1 and v2. V1 is quite small and v2 is a around 3gb. I can ask the server for v1 successfully but when asking for v2 a segfault occurs.
import numpy.random as rnd
import pandas as pd
import pyarrow as pa
import pyarrow.flight as fl
import numpy as np

class MyFlightServer(FlightServerBase):
    def __init__(self, location=None, options=None, **kwargs):
        super().__init__(location, **kwargs)
        self.tables = {}
        rng = rnd.default_rng()
        df = pd.DataFrame(np.random.standard_normal((1000, 5))).rename(
            columns={k: "col" + str(k) for k in range(5)}
        )
        self.tables[b"v1"] = pa.Table.from_pandas(df)

        df2 = pd.DataFrame(np.random.standard_normal((100000000, 5))).rename(
            columns={k: "col" + str(k) for k in range(5)}
        )
        print(df2.info())
        self.tables[b"v2"] = pa.Table.from_pandas(df2)

    def do_get(self, context, ticket):
        return RecordBatchStream(self.tables[ticket.ticket])

def main():
    with MyFlightServer() as server:
        # This works
        client = fl.connect(("localhost", server.port))
        data = client.do_get(fl.Ticket("v1")).read_pandas()

        # This will get a seg fault
        data = client.do_get(fl.Ticket("v2")).read_pandas()

main()

The above produces the below output (maybe relevant for df details):
RangeIndex: 100000000 entries, 0 to 99999999
Data columns (total 5 columns):
 #   Column  Dtype
---  ------  -----
 0   col0    float64
 1   col1    float64
 2   col2    float64
 3   col3    float64
 4   col4    float64
dtypes: float64(5)
memory usage: 3.7 GB
None
Segmentation fault (core dumped)

The machine this is running on has 64GB RAM of which around 15GB are in use at the time of running. Therefore I'm discounting (perhaps naively) the possibility of it not finding a continuous block of memory.
Am I misusing the flight server/record batch streamer or could this be a bug?
versions involved:
numpy==1.21.0
pandas==1.2.5
pyarrow==4.0.1
python-dateutil==2.8.1
pytz==2021.1
six==1.16.0

Python 3.9.5 (default, May 19 2021, 11:32:47)
[GCC 9.3.0]

A: This is a bug in Arrow Flight. See ARROW-13253 for details. Essentially, it's because the Flight handler sends the data as a single RecordBatch, but right now, Flight does not support sending record batches > 2GiB in size. However, the internal serialization handler returns an error without initializing the output buffer, which gRPC tries to blindly manipulate without checking for an error, leading to a crash.
You can work around this by explicitly chunking the data:
def do_get(self, context, ticket):
    table = self.tables[ticket.ticket]
    batches = table.to_batches(max_chunksize=65536)
    return fl.GeneratorStream(table.schema, batches)


text:
Q: JIT compiler and inner loop Why is the JIT-compiler not working for the following code?
And every individual loop seem to take too long time
(see my other post about executing time. Speed of simple loop
 public static void main (String[] args) {
    for (int j = 0; j < 10; j++) {
        float f;

        long start = System.nanoTime();

        for (int i = 0; i < 2000000000; i++) {
            f = i * 0.0001F;
        }
        long end = System.nanoTime();
        long timeToCallNanoTime = System.nanoTime() - end;
        long time = Math.max(0, end - start - timeToCallNanoTime);
        System.out.println("time: " + time + " ns.");
    }

}

RESULT:
 time: 6639317628 ns.
 time: 6630196045 ns.
 time: 6632583856 ns.
 time: 6617596798 ns.
 time: 6605243858 ns.
 time: 6609097755 ns.
 time: 6627151876 ns.
 time: 6623427381 ns.
 time: 6632506712 ns.
 time: 6615870257 ns.

A: It works for me in as you can see in my answer to your previous question.
Most likely you are using the client JVM which comes with 32-bit Windows. The client JVM doesn't optimise the code as much to minimise startup time.  I suggest you use the 64-bit JVM which uses the -server JVM by default and it will optimise the code more aggressively.
BTW I was using Java 7 update 40.  If you have a really old version of Java, it might not optimise the loop away.


text:
Q: Caused by: net.sqlcipher.database.SQLiteException: file is not a database: , while compiling: select count(*) from sqlite_master Here is the code I am using.
if (appDatabase == null) {
        byte[] passEncryptionKey = encryptText();
        SafeHelperFactory factory = new SafeHelperFactory(passEncryptionKey);
        appDatabase = Room.databaseBuilder(context, KioskEngineDatabase.class, "dbname")
                    .allowMainThreadQueries().openHelperFactory(factory).build();
 }

A: Downgrading your sqlcipher version to
implementation 'net.zetetic:android-database-sqlcipher:3.5.7@aar'

may solve your problem.
Edit: it seems you are trying to encrypt your room database using saferoom. this link may help you.


text:
Q: How to create list of Pairs? I want to create some Pair in Dart (Flutter) e.g.
Pair('text', 'some text here')
Pair('my_value', '233')

and pass it to Android activity (kotlin) via MethodChannel
How Can I do that?
I've create a Dart function which takes HashMap but I a bit lost in it and not sure how proceed with that.
 static Future<void> sendMessage({
    HashMap? customData
  }) async {
    _eventChannel.invokeMethod('message', {
      'customData': customData
    });
  }

A: Just use Map, something like this would work:
final data = <String, dynamic>{'text': 'some text here'};
data['my_value'] = '123';
methodChannel.invokeMethod('method', data);

override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
  val arguments = call.arguments as HashMap<String, Any>
  val text = arguments["text"] as String
  val myValue = arguments["my_value"] as String
}


text:
Q: Creating Customer in Quickbooks Online from C# I need to add new customers to QuickBooks Online from C#.
I'm struggling to find any working end-to-end samples. Based on this:
how to add invoice or sales receipt quickbooks rest api v3.0  I need accessToken, accessTokenSecret, consumerKey, consumerKeySecret, realmId.
Based on this: IPP .NET SDK for QuickBooks v3.0 Create Invoice Error - Bad Request I need accessToken, accessTokenSecret, consumerKey,consumerKeySecret, appToken, companyId.
I only have App Token, Oauth Consumer Key, OAuth consumer Secret, possibly realmId (App ID)
Where do I find the access token, access token secret, realm id and/or company ID?
I don't have a reputation to post images, but the developer settings page on
https://developer.intuit.com/Application/Manage/IA?appId=XXX shows the following informations:
App ID: what is this? realm Id, company id?
App Token,OAuth Consumer Key,OAuth Consumer Secret
I'm using the QuickBooks Online REST API v3.0 for .Net
The code follows:
   var customer = new Customer();

   customer.GivenName = txtFirstName.Text;
   customer.FamilyName = txtLastName.Text;
   customer.MiddleName = txtMiddleName.Text;
   customer.CompanyName = txtCompany.Text;

   customer.PrimaryEmailAddr = new EmailAddress() { Address = txtEmail.Text, Default = true };
   customer.PrimaryPhone = new TelephoneNumber() { FreeFormNumber = txtPrimaryPhone.Text };

   OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
   ServiceContext context = new ServiceContext(accessToken, consumerKey, IntuitServicesType.QBO, oauthValidator);

   DataService service = new DataService(context);
   var c = service.Add(customer);
   // do something with c.Id

A: You need to implement the 3 legged oauth flow in your app using C2QB button to get the access token and secret.
Please see our sample apps to see how this is implemented. Download the sample app and then configure the consumer key and secret in the config file.
Then check how the 3-legged oauth happens.You can try making calls to the V3 API using the local copy of the sample apps too.
https://github.com/IntuitDeveloperRelations/
Also refer:
https://developer.intuit.com/docs/0025_quickbooksapi/0010_getting_started

A: Intuit Anywhere Developer Playground provides facility to get accessToken, accessTokenSecret and realmId.
Go to QuickBooks playground by clicking link mentioned below –
https://appcenter.intuit.com/Playground/OAuth/IA
Make sure that you are already logged into your Intuit account.
Fill consumer Key, Consumer Secret and Access Token Duration (120000 seconds).

Click on Connect to QuickBooks icon as shown in the picture. You will be asked to select company. If you have more than one company connected to your sandbox account, choose any according to your requirement.
Then click Authorize Button.
You will get Access Token, Access Token Secret, RealmId (Company Id) and DataSource. Now you have all the keys to implement Accounting API. These keys will expire after 120000 seconds.
I have written a blog on how you can add, update, find and delete Customer.
https://vivekkumar11432.wordpress.com/2016/06/07/implement-intuits-quickbooks-online-api-in-restful-service-c/

A: I'm new to the QuickBooks Online API and had trouble getting the code working for a .NET 5.0 WPF application, so here's some sample code that worked for me:
Install the required QBO dependencies:

*

*IppDotNetSdkForQuickBooksApiV3

*IppOAuth2PlatformSdk

WPF Window C# Code:
using Intuit.Ipp.Data;

public partial class MainWindow : Window
{
    QuickbooksOnline qbo = new QuickbooksOnline();

    public MainWindow()
    {
        qbo.FindCustomerResponse += HandleFindQBOCustomerResponse;
        qbo.FindInvoiceResponse += HandleFindQBOInvoiceResponse;
        qbo.FindCreditMemoResponse += HandleFindQBOCreditMemoResponse;
    }

    private void btnTest_Click(object sender, RoutedEventArgs e)
    {
        //Get IDs to test from QBO website URL when accessing a record

        string customerId = "737";
        qbo.FindCustomer(customerId);

        string invoiceId = "3198";
        qbo.FindInvoice(invoiceId);

        string creditMemoId = "3077";
        qbo.FindCreditMemo(creditMemoId);
    }

    private void HandleFindQBOCustomerResponse(object sender, Intuit.Ipp.Data.Customer customer)
    {
        if (customer == null)
        {
            MessageBox.Show("Customer not found");
        }
        else
        {
            MessageBox.Show(customer.DisplayName);
        }
    }

    private void HandleFindQBOInvoiceResponse(object sender, Intuit.Ipp.Data.Invoice invoice)
    {
        if (invoice == null)
        {
            MessageBox.Show("Invoice not found");
        }
        else
        {
            MessageBox.Show(invoice.TotalAmt.ToString());
        }
    }

    private void HandleFindQBOCreditMemoResponse(object sender, Intuit.Ipp.Data.CreditMemo creditMemo)
    {
        if (creditMemo == null)
        {
            MessageBox.Show("CreditMemo not found");
        }
        else
        {
            MessageBox.Show(creditMemo.TotalAmt.ToString());
        }
    }
}

Quickbooks Online Class:
using System;
using System.Threading.Tasks;
using Intuit.Ipp.Core;
using Intuit.Ipp.Data;
using Intuit.Ipp.Security;
using Intuit.Ipp.DataService;
using System.Windows;
using System.Reflection;
using Intuit.Ipp.OAuth2PlatformClient;

class QuickbooksOnline
{
    //Get this information from the OAuth 2.0 Playground: https://developer.intuit.com/app/developer/playground
    private string ClientId = "";
    private string ClientSecret = "";
    private string RedirectURI = "https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl";
    private string RealmId = "";
    private string AccessToken = "";
    private string RefreshToken = "";
    private string QBOBaseURL = "https://quickbooks.api.intuit.com/";
    private string QBOMinorVersion = "55";

    private OAuth2Client OAuthClient;

    public event EventHandler<Intuit.Ipp.Data.Customer> FindCustomerResponse;
    public event EventHandler<Intuit.Ipp.Data.Invoice> FindInvoiceResponse;
    public event EventHandler<Intuit.Ipp.Data.CreditMemo> FindCreditMemoResponse;

    public QuickbooksOnline()
    {
        this.OAuthClient = new OAuth2Client(ClientId, ClientSecret, RedirectURI, "production");
    }

    public async void FindCustomer(string customerId)
    {
        OAuth2RequestValidator oAuthValidator = new OAuth2RequestValidator(AccessToken);
        ServiceContext serviceContext = new ServiceContext(RealmId, IntuitServicesType.QBO, oAuthValidator);
        serviceContext.IppConfiguration.BaseUrl.Qbo = QBOBaseURL;
        serviceContext.IppConfiguration.MinorVersion.Qbo = QBOMinorVersion;
        DataService service = new DataService(serviceContext);

        Customer customer = new Customer();
        customer.Id = customerId;

        service.OnFindByIdAsyncCompleted += HandlePrivateFindByIdResponse;

        service.FindByIdAsync(customer);
    }

    public void FindInvoice(string invoiceId)
    {
        OAuth2RequestValidator oAuthValidator = new OAuth2RequestValidator(AccessToken);
        ServiceContext serviceContext = new ServiceContext(RealmId, IntuitServicesType.QBO, oAuthValidator);
        serviceContext.IppConfiguration.BaseUrl.Qbo = QBOBaseURL;
        serviceContext.IppConfiguration.MinorVersion.Qbo = QBOMinorVersion;
        DataService service = new DataService(serviceContext);

        Intuit.Ipp.Data.Invoice invoice = new Intuit.Ipp.Data.Invoice();
        invoice.Id = invoiceId;

        service.OnFindByIdAsyncCompleted += HandlePrivateFindByIdResponse;

        service.FindByIdAsync(invoice);
    }

    public void FindCreditMemo(string creditMemoId)
    {
        OAuth2RequestValidator oAuthValidator = new OAuth2RequestValidator(AccessToken);
        ServiceContext serviceContext = new ServiceContext(RealmId, IntuitServicesType.QBO, oAuthValidator);
        serviceContext.IppConfiguration.BaseUrl.Qbo = QBOBaseURL;
        serviceContext.IppConfiguration.MinorVersion.Qbo = QBOMinorVersion;
        DataService service = new DataService(serviceContext);

        CreditMemo creditMemo = new CreditMemo();
        creditMemo.Id = creditMemoId;

        service.OnFindByIdAsyncCompleted += HandlePrivateFindByIdResponse;

        service.FindByIdAsync(creditMemo);
    }

    private async void HandlePrivateFindByIdResponse(object sender, CallCompletedEventArgs<IEntity> entity)
    {
        // The Intuit.Ipp.DataService.AsyncService class is not public, so that to use reflection
        // to get the requestedEntity object and determine the sender type.
        // This is useful when the authToken has expired and after refreshing the tokens
        // the request has to be sent again.
        string entityType = sender.GetType().GetField("requestedEntity", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sender).GetType().FullName;

        if (entity.Error != null && entity.Error.Message.Equals("Unauthorized-401"))
        {

            if (await RefreshTokens())
            {
                switch (entityType)
                {
                    case "Intuit.Ipp.Data.Customer":
                        Customer senderCustomer = (Customer)sender.GetType().GetField("requestedEntity", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sender);
                        FindCustomer(senderCustomer.Id);
                        break;
                    case "Intuit.Ipp.Data.Invoice":
                        Intuit.Ipp.Data.Invoice senderInvoice = (Intuit.Ipp.Data.Invoice)sender.GetType().GetField("requestedEntity", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sender);
                        FindInvoice(senderInvoice.Id);
                        break;
                    case "Intuit.Ipp.Data.CreditMemo":
                        Intuit.Ipp.Data.CreditMemo senderCreditMemo = (Intuit.Ipp.Data.CreditMemo)sender.GetType().GetField("requestedEntity", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sender);
                        FindCreditMemo(senderCreditMemo.Id);
                        break;
                }
            }
            else
            {
                MessageBox.Show("Error refreshing tokens.");
            }
        }
        else if (entity.Entity != null)
        {
            switch (entity.Entity.GetType().FullName)
            {
                case "Intuit.Ipp.Data.Customer":
                    if (FindCustomerResponse != null)
                    {
                        FindCustomerResponse(this, entity.Entity as Intuit.Ipp.Data.Customer);
                    }
                    break;
                case "Intuit.Ipp.Data.Invoice":
                    if (FindInvoiceResponse != null)
                    {
                        FindInvoiceResponse(this, entity.Entity as Intuit.Ipp.Data.Invoice);
                    }
                    break;
                case "Intuit.Ipp.Data.CreditMemo":
                    if (FindCreditMemoResponse != null)
                    {
                        FindCreditMemoResponse(this, entity.Entity as Intuit.Ipp.Data.CreditMemo);
                    }
                    break;
            }
        }
        else if (entity.Entity == null)
        {
            switch (entityType)
            {
                case "Intuit.Ipp.Data.Customer":
                    if (FindCustomerResponse != null)
                    {
                        FindCustomerResponse(this, null);
                    }

                    break;
                case "Intuit.Ipp.Data.Invoice":
                    if (FindInvoiceResponse != null)
                    {
                        FindInvoiceResponse(this, null);
                    }
                    break;
                case "Intuit.Ipp.Data.CreditMemo":
                    if (FindCreditMemoResponse != null)
                    {
                        FindCreditMemoResponse(this, null);
                    }
                    break;
            }
        }
    }

    private async Task<bool> RefreshTokens()
    {
        var tokenResp = await OAuthClient.RefreshTokenAsync(RefreshToken);

        if (tokenResp.AccessToken != null && tokenResp.RefreshToken != null)
        {
            this.AccessToken = tokenResp.AccessToken;
            this.RefreshToken = tokenResp.RefreshToken;
            return true;
        }
        else
        {
            return false;
        }
    }

}


text:
Q: In the category of uniform spaces, is the completion of a quotient map also a quotient map? I asked this question about 2 months ago on math.stackexchange, but so far I received neither comments nor answers.
Let $X$ and $Y$ be two Hausdorff uniform spaces. A surjective uniformly continuous map $f: X \to Y$ is a quotient map if for every map $g$ from $Y$ to a uniform space $Z$ such that $g \circ f$ is uniformly continuous, $g$ is uniformly continuous.
Let $\hat X$ and $\hat Y$ denote the completions of $X$ and $Y$ respectively, and let
$\hat f : \hat X \to \hat Y$ be the unique uniformly continuous extension of $f$.
Is $\hat f$ a quotient map?
If the answer is positive, a reference would be appreciated.

A: I think the answer to the question is yes, but there is a little gap (called "Gap-Statement" below) that needs to be filled - and of course there is still the possibility that the "Gap-Statement" is false.
Let's split the answer in two steps.
Step 1. Let $f:X\to Y$ be uniformly continuous, let  $\hat f: \hat X \to \hat Y$ be the uniformly continuous extension, and take a uniform space $Z$ and a non-continuous map $g:\hat Y \to Z$. Then we show that $g\circ \hat f: \hat X \to Z$ is not continuous.
I'm not entirely sure the following statement is correct - but if it is, it answers the question positively:
"Gap-Statement". Let $X$ is a Hausdorff uniform space and let $i:X\to \hat X$ be the canonical map from $X$ to its extension. Let $Z$ be a uniform space and $g:\hat X \to Z$ be a map. Then $g$ is uniformly continuous if and only if $g\circ i: X\to Z$ is uniformly continuous.
(One direction is trivial.)
So let $f:X\to Y$ be uniformly continuous, let  $\hat f: \hat X \to \hat Y$ be the uniformly continuous extension, and take a uniform space $Z$ and a non-continuous map $g:\hat Y \to Z$. Let $i_X:X\to \hat X$ and $i_Y:Y\to \hat Y$ be the canonical maps from $X,Y$ to their extension. Using the "Gap-Statement" we get that $g\circ i_Y: Y\to Z$ is non-continuous. Since $f:X\to Y$ is a quotient map, the map $g\circ i_Y \circ f: X\to Z$ is non-continuous. Note that
$$g\circ i_Y \circ f= g\circ \hat f \circ i_X.$$
So if $g\circ \hat f$ were continuous, then so would be $g\circ \hat f \circ i_X = g\circ i_Y \circ f$. But we just proved that this map is not continuous, so $g\circ \hat f: \hat X \to Z$ is not continuous, as desired.
Step 2. We have to show that if $f:X\to Y$ is surjective, then so is the continuous extension $\hat f: \hat X \to \hat Y$.
The proof for this is as follows. Note that the elements of $\hat Y$ are minimal Cauchy filters on $Y$, so let ${\cal G} \in \hat Y$ be a minimal Cauchy filter on $Y$. Then $$\{f^{-1}(V): V\in {\cal G}\}$$ is a filter base for a Cauchy filter on $X$ which contains a minimal Cauchy filter ${\cal F}$. It is not hard to show that $\hat f({\cal F}) = {\cal G}$, so $\hat f$ is surjective.


text:
Q: What storage to use for android app content, SQLite or XML-file? I need to store my android app content and want tips on what storage i should use. SQLite database or XML file(s)?
Some characteristics of the app and the data:

*

*The application is used for tracking (daily) the body measurements of weight, waist, chest, ++

*The measurement types are divided in separately tabs and are not dependent on/related to each other

*Entities contains small amount of data, 4-5 attributes

*The amount of data is expected to be moderate. Maximum (30 measurement in the months x 5 measurement types = 150 measurements in months/1800 in the year)

*None advanced queries are going to be used. Mainly reading (all data elements) and adding new measurements.

*I want to enable easy sharing/exporting of the measurement data to for instance dropbox or email.

I guess that there are none performance issues storing the data in XML-file with these requirements/characteristics. If so, should I separate each measurement type in separately XML-file and where on the mobile device should I store the files?

A: I would read over the Storage Options you have available on Android to try to dig up some more information.
What you described, one time writing to files that are in drop box seems like writing out to an XML file that is saved in your dropbox seems like a good choice. No complexed queries, just read in one record at a time.
However, I feel it wouldn't be that much more work to go with a SQL database. And this would be way more flexible in the long run. Right now you don't want to do queries, but you may some day. Plus you won't have to worry about splitting your data into several files and parsing things. Parsing can quickly become bothersome when you try scaling.
What I would recommend is to write a ContentProvider and then put all your details in there. That way your program won't care about how the data is stored in case you want to change it later because the Provider does all heavy lifting for you. I would much rather use a CursorAdapter than anything else, and your get from using SQLite. Plus all the new CursorLoader keep up the performance of you application.

A: The best long-term solution would be to use an SQLite database.
But if you wish to use XML, a great solution is already presented here:
Store static data in Android - custom resource?

A: If your XML data is large. XML parsing and then insert is a very expensive operation and is time-consuming.
Some issues which you will face with XML parsing and insert.
a. XML parsing is memory intensive and so you heap size will grow, you need to keep an eye on this as this might cause crash. b. Inserts in SQLite DB will take around ~100ms per tuple (row), so you can calculate the time it will required to pump in thousands of rows of data.
If you data is not too large don't bother about using SQLite.


text:
Q: Comparing two pandas dataframe cells, and if equal ==, copy other content over - results in error I am importing excel files with products and product specific data. They look like this:
dfA
EAN Code    Product Name    Color    Price
12345       AAA             xxx      9
45678       BBB             zzz      10

and
dfB
EAN Code    Product Name    New Price
12-345      AAA             10
45-678      BBB             11

I am importing these as always:
dfA = pd.DataFrame (dfA, columns=["Season", "EAN Code", "Product Name", "..."] , dtype=str)

And I am merging them, since there are multiple different excel files:
dfA = pd.concat([dfA1, dfA2, dfA3, dfA4, dfA5, dfA6, dfA7, dfA8, dfA9, dfA10, dfA11], ignore_index=False)

Then I am deleting the hyphen in the EAN column, because in excel file b there is an unnecessary hyphen in the EAN number.
for col in dfB.columns:
   dfB["EAN"] = dfB["EAN"].str.replace('-', '')

So far, so good.
Now I try to search through the EAN code column of dfA and search for the same product in dfB. When there is a match, I want to copy over the new price.
This worked great in my old code, although it took about 15 minutes for the script to search through a half million rows...
This worked quite well in the past, but now I am trying to achieve the same, but I get an error message. This is my simplified code:
for i in dfA.index:
   for j in dfB.index:
      if dfA.loc[i, "EAN"] == dfB.loc[j, "EAN"]:
         print ("EAN", number,"times found!")
         number=number+1
         dfA.loc[i, "Price"] = dfB.loc[j, "New Price"]

The print statement is only a feedback for me, so that I see wether the script is still doing something.
Traceback (most recent call last):
  File "c:...", line 72, in <module>
    if dfA.loc[i, "EAN"] == dfB.loc[j, "EAN"]:
  File "C:...", line 1527, in __nonzero__
    raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Why am I getting this now?

A: Use a merge, after setting up a common EAN Code:
out = dfA.merge(
          dfB.assign(**{'EAN Code': dfB['EAN Code'].str.replace('-', '')
                                    .astype(int) # only if dfA has an int
                     }),
          on='EAN Code')

output:
   EAN Code Product Name_x Color  Price Product Name_y  New Price
0     12345            AAA   xxx      9            AAA         10
1     45678            BBB   zzz     10            BBB         11

A: Your code is trying to test a condition somewhere, it's obviously in the if-part: if dfA.loc[i, "EAN"] == dfB.loc[j, "EAN"].
dfA.loc[i, "EAN"] happens to be a Series sometimes and/or dfB.loc[j, "EAN"] too.
So the result of ... == ... is a Series, but if expects a boolean. You need to reduce this Series to a boolean using the appropriate method (they propose empty, bool(), any(), etc.)
I assume that you expect dfA.loc[i, "EAN"] to give you a scalar and not a Series but it's not always the case (idem for dfB.loc[j, "EAN"]). So check your data. How are your i and js?

Remark
I recommend you to use df.at[i, col] rather than df.loc[i, col], when you know that you should get a scalar. It's faster and will send errors if you can't get a scalar, so it will be easier to debug.


text:
Q: Why is the majorana particle a fermion? My knowledge of quantum mechanics is rather limited, but what I always understood was that Bosons have integer spins and Fermions have half-integer spins.
My question is very simple: the Majorana particle has no spin according to this paper and this Physics Today article which (without wanting to go into a philosophical mathematical discussion) I would call integer spin. That would make the particle a Boson. So what is the reason that the particle is classified as a Fermion?

A: Majorana fermions are by definition fermions which are their own antiparticles, i.e. the do have spin and it's 1/2. An introduction to these fermions can be for example found here: http://arxiv.org/abs/0806.1690. In contrast bosons are their own antiparticles, e.g. photons, i.e. one does not need a "Majorana-boson" definition.
Now, one has to say that these Majorana fermions have not been observed in nature except as quasiparticle excitations in seminconductors.


text:
Q: MFP 7.1 Drop Down Menu not function well in iOS 11 I'm using MFP7.1 and xcode 9 to develop my application on ipad platform. I'm facing an error when clicks on drop down menu button. When I select a value, the drop down list will close and re-open. Then, when I tap on the second drop down menu button, the first drop down list will re-open but the selection on the first drop down list will missing. The second drop down list will not appear.
The drop down menu button is function normally when I develop using xcode 8. This issue only happen when the application is develop using xcode 9 and running in iOS 11.
Anyone have an idea to solve this issue?

A: This is a known case and happens because of Apple's Webview rendering. This is not a MobileFirst or Cordova issue.
The Apple forum that discusses this issue:
https://forums.developer.apple.com/thread/84585


text:
Q: What is the value of $\lim_{x\to 0} \frac{\cos(1/x)}{\cos(1/x)}$? $$\lim_{x\to 0} \frac{\cos\left(\frac{1}{x}\right)}{\cos\left(\frac{1}{x}\right)}$$
I think the answer should be $1$ , I understand that the value of $\cos(1/x)$ would be oscillating quickly as $x$ approaches $0$ . But , wouldn't both the numerator and denominator get cancelled ?
My teacher said that the limit does not exist in this question , I dont understand.

A: $\dfrac{\cos(1/x)}{\cos(1/x)}$ is just a convoluted way of writing the constant function $1$ defined on the domain
$$\mathbb R \setminus\{0\} \setminus \Bigl\{\frac1{\pi/2+k\pi} \Bigm| k\in\mathbb Z \Bigr\} $$
Whether this function has a limit for $x\to 0$ depends more on which precise conventions you use for limits, than on the function itself.
In most of higher mathematics we'd have no problem speaking of a limit towards any limit point of the function's domain, and in that case the limit is easily $1$.
On the other hand, many introductory texts try to avoid confusion by insisting that $\lim\limits_{x\to a} f(x)$ is only defined when the domain of $f$ contains an entire punctured neighborhood of $a$ (as a subset of $\mathbb R$). If that convention is used, your limit doesn't exist, and it seems your teacher is assuming that way of thinking.
(Whether this convention actually avoids any confusion is debatable).