text:
Q: How to grep with like in between 2 texts I have a log file which contains data like :
Customer=100000015 | AP ID=100000687 | StepID=N6MAAPtCzVYKFKVKMMQ | OA=107 | Activity=NegotiateProductConfigurationSyncImplAug | *** Starting Rule Debug Messages March 11, 2016 6:47:23 PM IST ***

I know the StepID but not the OA and Activity Name.
I want to do a like on grep to fetch everything after this line.
Like i will pass the StepID and "*** Starting Rule Debug Messages" to match the line.

A: This could be an approach:

*

*iterate over the file line by line

*look for the StepID expression and remember the result

*if there was a hit in the past then capture every following line

e.g.
final String requiredStepId = "N6MAAPtCzVYKFKVKMMQ";

final List<String> allLines = Files.readAllLines(Paths.get("/var/log/tool/output.log"), StandardCharsets.UTF_8);
final List<String> resultLines = new LinkedList<>();

boolean match = false;
for (final String line : allLines) {
    if (line.contains("StepID=" + requiredStepId)) {
        match = true;
    }

    if (match) {
        resultLines.add(line);
    }
}

A: You can use:
Display N lines after match:
-A is the option which prints the specified N lines after the match as shown below.
Syntax:
grep -A < N > "string" FILENAME
The following example prints the matched line, along with the 3 lines after it.
$ grep -A 3 -i "example" demo_text
Ref:http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/


text:
Q: Why can't MMA solve this system of differential equations? This system of differential equations can be solved in order to
obtain the expression of x[t] y[t] z[t]
DSolve[{x''[t] + x[t] == a, y''[t] == x[t]^2 - y[t],
  z[t] == 2 x[t]*y[t] - z''[t]}, {x, y, z}, t]

But why can' t MMA solve this system of differential
equations?
  We already know the solutions of the following differential equations
DSolve[{x''[t] + x[t] == a, y''[t] == x[t]^2 - y[t],
  z[t] == 2 x[t]*y[t] - z''[t], x[0] == (1 + E) a, x'[0] == 0,
  y[0] == 0, y'[0] == 0, z[0] == 0, z'[0] == 0}, {x[t], y[t], z[t]}, t]

x[t] -> a + a E Cos[t]
y[t] -> -(1/6)
a^2 (2 (3 + E^2) Cos[t] + E^2 Cos[2 t] - 3 (2 + E^2 + 2 E t Sin[t]))
z[t] -> 1/144 a^3 ( ...)

But MMA can' t solve it.

A: That's weird considering that the system can be solved one-by-one with Mathematica itself.
Clear[x, y, z];
eqns = {x''[t] + x[t] == a, y''[t] == x[t]^2 - y[t], z[t] == 2 x[t]*y[t] - z''[t]};
x[t_] = x[t] /. DSolve[eqns[[1]], x[t], t][[1]]
y[t_] = y[t] /. DSolve[eqns[[2]], y[t], t][[1]]
z[t_] = z[t] /. DSolve[eqns[[3]], z[t], t][[1]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Zsh: start new prompt in command mode (vi mode) Is there a way to start each new prompt in Vi "command mode" instead of "insert mode". I do not want to press Esc every time.

A: The solution to this is actually found in the zshzle (or zshall) manual:
zle-line-init() { zle -K vicmd; }
zle -N zle-line-init

This will always put the command line into Vi command mode for each new prompt.


text:
Q: Prove $\ker(T^n)=\ker(T^{n+1})$ and $\operatorname{range}(T^n)=\operatorname{range}(T^{n+1}).$
Let $V$ be an $n$-dimensional vector space over a field $F$ and $T$ an operator on $V.$ Prove $\ker(T^n)=\ker(T^{n+1})$ and $\operatorname{range}(T^n)=\operatorname{range}(T^{n+1}).$

Suppose $v \in \ker(T^n).$ Then $T^n(v) = 0,$ implying that $T^{n+1}(v)=T(T^n(v))=T(0)=0.$ Thus $v \in \ker(T^{n+1})$ and so $\ker(T^n) \subset \ker(T^{n+1}).$
Question: How do I prove  $\ker(T^n) \supset \ker(T^{n+1})?$ I would also like some hints on proving $\operatorname{range}(T^n)=\operatorname{range}(T^{n+1}).$

A: Look at the Lemma in this answer: https://math.stackexchange.com/a/1447742/211913
It immediately proves your statement.
Some more details: With the notation of the cited answer: Assume the kernels of $T^n$ and $T^{n+1}$ do not coincide. We then have $k_{n+1}-k_n \geq 1$. Since the sequence of differences is decreasing, we obtain $k_{j+1}-k_j \geq 1$ for all $j = 0, \dotsc, n$. Of course this implies $k_{n+1} \geq k_0+n+1 = n+1$, which is an obvious contradiction.
One should note that the statement about the ranges obviously follows from the statement about the kernels from dimension formula. No need to show this.

A: By contradiction, suppose that there exists $v\in\ker(T^{n+1})$ such that  $T^nv\neq0$. Then the vectors $v,Tv,...,T^nv$ are all nonzero, and you can see that they are in fact linearly independent by evaluating powers of $T$ on a linear combination $\sum_{k=0}^n\alpha_k\,T^kv=0$. But this is absurd as $\dim V=n$.
Hint for the second statement: write $v=T^nw$ and decompose $w$ as a sum of a vector in $\ker (T^n)$ and a vector in the range of $T$.
Second hint: proceeding as in the first point you can show that $\ker (T^n)\cap\operatorname{range}(T^n)=\{0\}$ (see also the answers to this this question).

A: The argument in MooS's answer is very nice, but here's an alternative proof via Cayley-Hamilton.  Let $p(x)\in F[x]$ be the characteristic polynomial of $T$, and write $p(x)=x^mq(x)$, where $x$ does not divide $q(x)$.  Since $p(x)$ has degree $\leq n$, we have $m\leq n$.  Write $q(x)=xr(x)+c$ where $c\in F$; by definition of $q$, $c\neq 0$.  Now suppose $v\in \ker(T^{n+1})$.    We have $$q(T)T^nv=p(T)T^{n-m}v=0$$
since $m\leq n$ and $p(T)=0$ by Cayley-Hamilton, and $$q(T)T^nv=r(T)T^{n+1}v+cT^nv=cT^nv$$
since $T^{n+1}v=0$.  Since $c\not=0$, this implies $T^nv=0$.  Thus $\ker(T^{n+1})\subseteq \ker(T^n)$.
The statement about ranges can be proven similarly.  Suppose $v\in\operatorname{range}(T^n)$; write $v=T^nw$.  Then as above, we have $$0=q(T)T^nw=r(T)T^{n+1}w+cT^nw.$$
Rearranging this, we get $v=T^nw=T^{n+1}(-c^{-1}r(T)w)$.  Thus $v\in\operatorname{range}(T^{n+1})$.
(Alternatively, the statement about ranges actually follows from applying the statement about kernels to the dual map $T^*:V^*\to V^*$.)


text:
Q: ASP.NET Export to Excel - Lock Cells I'd like to export a table I have on my webpage to an Excel file and lock some cells in the new file.  Here is my current code:
Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click
    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "application/vnd.ms-excel"
    Response.AddHeader("content-disposition", "attachment;filename=EpicSearchResults.xls")
    Response.Charset = ""
    Me.EnableViewState = False

    Dim sw As New System.IO.StringWriter()
    Dim htw As New System.Web.UI.HtmlTextWriter(sw)

    Session("tblResults").RenderControl(htw)

    Response.Write(sw.ToString())
    Response.End()
End Sub

This code works in generating the Excel file. I've searched for an was unable to find much for a solution to lock cells in the new file.  Thanks in advance for the help!

A: Like Leniel said, you probably need a better library. Another one you could check out is EPPlus. Works wonderfully.
The code in EPPlus to lock cells is worksheet.Cells["A1:G60"].Style.Locked = true;

A: I think you'll need a more powerful library to do what you want. This involves changing the way you currently export data to Excel.
Take a look at NPOI: http://npoi.codeplex.com/discussions/252597
References:
Create Excel (.XLS and .XLSX) file from C#


text:
Q: connect the MongoDB shell to an external database error image
I am trying to connect to external database from mongo shell. How to resolve this error?

A: You need to start the mongo shell program with the --host argument, otherwise it will connect to localhost by default (as seen in line #3 of your console output). I believe for MLab you'll also need to supply your credentials to avoid an authentication error.
Try this:
C:\Program Files\MongoDB\server\3.4\bin\mongo.exe --host  ds131492.mlab.com/locations -u username -p password


text:
Q: Get routes of Rails app without running rake routes My understand of rake routes is that it bootstraps the Rails application and then pulls the routes from it. If I want to simply look at the text (no loading of a rails application) and be able to output something similar to what rake routes outputs, how would I do it? I know rake routes actually runs Ruby code and I am worried about doing so as I do not trust these applications.
I am weary to load the Rails application as I do not trust these Rails applications, but if there is a way to sandbox the running of rake routes or some related method, I would be open to that as well.

A: If you have a complex routes file with lots of engines you'd probably be better off using Vagrant to run the app in a sandbox. If it's simple though, this method might work for you.
Rails will generate routes from routes.rb without the underlying application. Create a new dummy app making sure you match the rails version to the version of the app you want to inspect.
> rails new dummy_app
  …

> cd dummy_app
> cp /path/to/untrusted/app/config/routes.rb ./config/

Edit the app name at the top of the route file to match the name of the dummy app, in this case it would be DummyApp.Application.routes.draw do. Then run
> rake routes

Some caveats: If there are any engines or gem speficic routes in there you'll need to add those to the Gemfile or comment out those routes. For example, if the pap uses active_admin you'll need to add that to the gemfile as well as generate the AdminUser class. And then you'll want to recopy over the routes files as the generator adds lines to the routes file. If you run into issues with uninitialized contents you may need an initializer to require certain classes. For example, if you mount Resque::Server, you need an initializer with these two lines:
# config/initializers/dummy_init.rb
require 'resque'
require 'resque/server'


text:
Q: Original error: Error executing adbExec. error while starting app on phone through appium I use:

*

*Appium 1.13.0

*Phone: Samsung S8

*Android version: 9

If I try to start app through Appium on phone-got error:

An unknown server-side error occurred while processing the command. Original error: Cannot start the 'name' application. Visit https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/android/activity-startup.md for troubleshooting. Original error: Error executing adbExec. Original error: 'Command 'C:\pathtoadb\platform-tools\adb.exe -P 5037 -s 45678888 shell am start -W -n appname -S' timed out after 20000ms'. Try to increase the 20000ms adb execution timeout represented by 'adbExecTimeout' capability

A: If you are using UIAutomator2 then you can set this capability "appWaitForLaunch : false", by default it is set to true.

A: I have a bare working configuration for real Pixel Android Device
{
  "automationName": "UiAutomator2",
  "platformName": "Android",
  "platformVersion": "8.1",
  "deviceName": "Pixel",
  "appPackage": "com.disney.wdw.android.debug",
  "appActivity": "com.disney.wdpro.park.activities.LoaderActivity",
  "udid": "<unique_identifier>
}

Notes:

*

*Your UDID can be located when you access adb devices on your terminal/cmd.

*You can replace appPackage and appActivity with app capability where you indicate the path where your apk resides.

*deviceName is required but I believe Appium ignores it for real devices.

*I suggest you use latest version of Appium Desktop or CLI.

*You can use default Appium for automationName as your automation engine, mine I use UIAutomator2, adjust it to your preference.

Refer to Appium main site for full documentation of capability usage.
http://appium.io/docs/en/writing-running-appium/caps/

A: The reason behind that error is lack of proper permission from developer options or we have to disable some options which is preventing the apps to install in real devices.
We have enable these options:

*

*USB debugging.

*Install via USB.

*USB Debugging (Security settings).

With the above setting in MIUI and POCO devices need some extra settings to be disabled to make this error go i.e. disable following options:

*

*Verify apps over USB.

*Verify bytecode of debuggable apps.

A: Try restarting your adb here's how you do it go to the terminal or cmd and type this adb kill-server && adb start-server then try launching again

A: Downgrade your Android SDK by Downloading Platform tools version and replace it with existing Platform SDK from android studio. If it doesn't work try this -> Uninstall your Android SDK and re install it .


text:
Q: JavaScript runtime error: Object doesn't support property or method 'jqGrid' I am having some issues trying to implement Jqgrid in ASP.net MVC 4. The grid and other Jquery functions they don't work in Firefox and Google Chrome.
In IE 11 all the Jquery ajax calls works properly, but the Jqgrid does not work and I get the error on the title.
My Code is this:
@{
ViewBag.Title = "Reserva de Turno";
<link href="~/Content/ui.jqgrid.css" rel="stylesheet" />

}

Reserva de Turno

<fieldset>Datos del medico</fieldset>

I don't know how to use firebug or any tools for debuggin js.
Thanks

A: After surfing in the internet and many tests, I found the issue. The problem is with bundles configuration.
Bundles uses other version of Jquery script. Comment on the lines fixed the problem
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
          "~/Scripts/jquery-ui-{version}.js"));

A: Another source for this issue is the use of Bootstrap bundle.

    @Scripts.Render("~/bundles/bootstrap")

For me, I remove the Bootstrap bundle under _Layout.cshtml and jqGrid works in IE 10.  Also I have tested this on Chrome and Firefox and jqgrid can work under this configuration.

    @*@Scripts.Render("~/bundles/bootstrap")*@

A: If you receive this error message on any version of MVC while you have references for both JQuery and JQGrid, check to make sure you don't have duplicate JQuery.  In my case, I had JQuery reference on both the index.cshtml and _Layout.cshtml.  If that's the case, removing the reference from the index.cshtml will resolve the problem.


text:
Q: Using Google ReCaptcha I am keen on using Google ReCaptcha. I have got the captcha on the page using the public key but don't know how to use the private key in my form processor document:
    <?php

//SMTP SETTINGS
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.webhost.co.nz'; // Specify main and backup server
$mail->SMTPAuth = true;  // Enable SMTP authentication
$mail->Username = 'xxxxx@xxxxxxxx.co.nz';  // SMTP username
$mail->Password = 'xxxxx@@xxxxxx';  // SMTP password
$mail->SMTPSecure = 'ssl';   // Enable encryption, 'ssl' also accepted
$mail->Port = 465;
$mail->isHTML(true);  // Set email format to HTML
//SMTP SETTINGS

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
print_r($_POST);

$mailheader = "From: $email";
$to = "tony@finelinecreative.co.nz";  // Here is email send to
$subject = "Finelinecreative Enquiry";
$message = "Name: $name
Email: $email
Message: $message";

// Send the mail
$mail->From=$mail->Username;
$mail->FromName = 'finelinecreative';
$mail->addAddress($to);
$mail->addReplyTo($email, $email);
$mail->Subject = $subject;
$mail->Body    = $message;
$mail->IsHTML(true);
$result = $mail->send();

header('location: http://www.finelinecreative.co.nz/index.php/thanks');

?>

Ideas please?

A: There's a great tutorial at https://codeforgeek.com/2014/12/google-recaptcha-tutorial/ that explains it pretty well.
In essence, you're checking if the $_POST variable 'g-recaptcha-response' exists (which, by including recaptcha on your form, is sent along with the other values on the form). If it is, you send a file_get_contents call (sending the secret key, the g-recaptcha-response POST value, and the user's IP address). You decode the result of that (which is sent as JSON, and you probably want to access it as key-value pairs), and find out whether the query was successful.
This is the relevant portion of their implementation.
if(isset($_POST['g-recaptcha-response'])){
    $captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
    echo '
Please check the the captcha form.
';
    exit;
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
    echo '
You are spammer ! Get the @$%K out
';
} else {
    // Send the email. In your case, you can wrap pretty all of your preprocessor in this.
}


text:
Q: Swapping JTextField contents I have one Jframe which includes two TextFields and I want to exchange two integer numbers after clicking on exchange button.

A: Get the value from one text box and store it in the other.

.getText() is used to get the value from the textbox.
.setText() is used to set the value of a textbox.

private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String temp = jTextField1.getText();
    jtextField1.setText(jTextField2.getText());
    jtextField2.setText(temp);

}
// Variables declaration - do not modify
private javax.swing.JButton jButton;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;

A: Since JTextFields use Strings this works pretty much everywhere.
String temp = text1.getText();
text1.setText(text2.getText());
text2.setText(temp);


text:
Q: How to keep different folders in different repositories in sync? (Only certain folders not the whole repo) I am currently examining git submodules, one part of my question can be solved with it. As I've understood submodules do synch a whole remote repo with a  directory in my current repo (maybe I'm wrong).
What I would like to achieve would be to keep only certain folders in different repositories in synch, an Example:
REPO X -> folder A -> subfolder "contract" should be in sync with
REPO Y -> folder B -> subfolder "s1" -> subfolder "contract"

Is that possible with submodules? If not, is there another way?


text:
Q: add value to textarea based on selected autocomplete option in opencart One new column added to DB by me to add descriptions to attributes in Opencart and i can easily add/edit descriptions from admin panel but i have a problem in product_form page. I want to add automatically attribute description to every product when i choose attribute name.
In Opencart admin can choose attributes for products from autocomplete box but every time admin should add attribute descriptions manually. For example attribute 'Gold'. Every time when admin choose attribute 'Gold' he have to add description for gold manually. I want to retrieve attribute description from DB column 'protext' to automatically fill related textarea when admin. So when selected 'Gold' from input box related  text should be appear in related textarea for description.
This is code that edited by me in product form but doesn't work.
your help will be appreciated.
function attributeautocomplete(attribute_row) {
    $('input[name=\'product_attribute[' + attribute_row + '][name]\']').autocomplete({
        'source': function(request, response) {
            $.ajax({
                url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(request),
                dataType: 'json',
                success: function(json) {
                    response($.map(json, function(item) {
                        return {
                            category: item.attribute_group,
                            label: item.name,
                            label2: item.protext,
                            value: item.attribute_id
                        }
                    }));
                }
            });
        },
        'select': function(item) {
            $('input[name=\'product_attribute[' + attribute_row + '][name]\']').val(item['label']);
            $('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').val(item['value']);
            $('input[name=\'related\']').val('');
        }
        $('textarea[name=\'product_attribute[' + attribute_row + '][product_attribute_description][text]\']').autocomplete({
            'append': function(item) {
            $('textarea[name=\'product_attribute[' + attribute_row + '][product_attribute_description][text]\']').val(item['protext']);
            }
    });
}

A: For this you have to change code in Controller file from where ajax is returning result. Path Admin > Controller > Catalog > Attribute -> function autocomplete(). Add "protext" code after name row or after any other key you want (I wrote 1 so that you can find code in file and can add after this)
'name'            => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),

line
'protext'          => html_entity_decode($result['protext'], ENT_QUOTES, 'UTF-8'),

This is how, you will get this in tpl file.

*

*Database is already fetching with * so you don't need to change any code there.

*You already added code for tpl so it will work fine.

Note - It's better to make these changes using vqmod or ocmod. My OC version 2.0.2.0


text:
Q: Recovering Windows Partition How can I recover my Windows partition after installing Ubuntu 12.04 on the last partition of my HDD.  I desperately need to recover all the information on my Windows XP Home partition for schoolwork purposes.  When booting I can see the Windows XP partition, but cannot access it.  All I can do is boot into Ubuntu.

A: If you dual booted it, you can go to File System and look for a folder called "host" in there should be all your stuff from xp, if you don't have that folder, you may need to do what  Geppettvs said.


text:
Q: Выборка из базы mySQL и замена Есть две таблицы t1 и t2, в таблицах есть аналогичные столбцы text, attribute и id. id повторяются и отличаются только по attribute. в таблице t2 столбец text заполнен, а в таблице t1 столбец text пустой и его надо заполнить как в t2.
Пример:
t1
id_____attribute_____text
1.........11..........
1.........12..........
2.........11..........
2.........12..........

t2
id_____attribute_____text
1.........11.........abc
1.........12.........efg
2.........11.........igk
2.........12.........xyz

Пишу вот такую конструкцию:

UPDATE t1 SET text = REPLACE (text,t1.text) WHERE
t1.id = t2.id AND t1.attribute=t2.attribute

Выпадает ошибка - #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 1
Второй день бьюсь, помогите!

A: UPDATE t1
INNER JOIN t2 ON
    t1.id = t2.id AND t1.attribute = t2.attribute
SET t1.text = t2.text;

Больше по даному вопросу можно найти здесь https://stackoverflow.com/questions/1293330/how-can-i-do-an-update-statement-with-join-in-sql


text:
Q: How can I sort date in javascript? Considering that I have the below response, which consists of date and time, I want them in sorted format. How can I sort the json of date time in descending format.
let data =
[
  {
    "created_at" : "2020-12-01T05:11:08Z",
    "id" : "1"
  },
  {
    "created_at" : "2022-10-10T06:18:08Z",
    "id" : "2"
  },
  {
    "created_at" : "2021-11-12T02:48:08Z",
    "id" : "3"
  },
  ,
  {
    "created_at" : "2021-11-12T02:49:08Z",
    "id" : "4"
  }
]

After applying the sorting code, I need the data should look like:
result =
[
  {
    "created_at" : "2022-10-10T06:18:08Z",
    "id" : "2"
  },
  {
    "created_at" : "2021-11-12T02:49:08Z",
    "id" : "4"
  },
  {
    "created_at" : "2021-11-12T02:48:08Z",
    "id" : "3"
  },
  {
    "created_at" : "2020-12-01T05:11:08Z",
    "id" : "1"
  }

]


text:
Q: Is it a data-race when several thread *read* the same memory at the same time? cppreference.com says:

Threads and data races
When an evaluation of an expression writes to a memory location and
another evaluation reads or modifies the same memory location, the
expressions are said to conflict. A program that has two conflicting
evaluations has a data race unless...

This speaks about the scenario of 'thread1-write thread2-read' (W-R) and about the scenario of 'thread1-write thread2-write' (W-W).
What about 'thread1-read thread2-read' (R-R)?

A: No. Multiple threads reading memory sequenced is not a data race as long as no thread is writing unsequenced in that memory location.
That scenario was probably left out of that description of data races, because that scenario is not a data race.


text:
Q: Deleting a structure from a doubly linked list based on its contents (in C) My program is a basic C interface that allows the user to enter, print forwards, print backwards and delete MP3 records from a list. The list is implemented as a doubly linked list of MP3 structures in the C language.
All my functions except Delete work fine. Delete takes in a pointer to the head node of the list and a character string signifying which artist's records you would like deleted. In my main I record the user input and have verified it is being recorded correctly. Then I pass the user input and the head reference into the following function to delete said MP3 records. However, my program builds and executes fine but does not actually delete any records when the delete function is called. Any help is appreciated.
For clarity, I have looked at multiple questions on stack regarding deleting nodes from a DLL, however they all are regarding simple DLL holding integer values and don't seem to translate well to my scenario. I apologize if this is considered a duplicate question, if so, please point me to the question I am duplicating. Thanks again for any and all assistance. Below is my function
void deleteMP3(struct MP3* head_ref, char* artist)
{
    //Declaring a temp struct to hold the node that needs to be deleted
    struct MP3* temp;

    //Check if the head node contains the artist to be deleted
    if(head_ref->artist == artist)
    {
        //Set temp to the current head ref so it can be deleted
        temp = head_ref;

        //Set head_ref to the next node in the list
        head_ref = head_ref->next;

        //Free the memory associated with the MP3 to be deleted
        free(temp->artist);
        free(temp->title);
        free(temp->date);
        free(temp);
    }

    //Traverse the list checking each MP3's artist field
    while(head_ref != NULL)
    {
        //Check the artist of the current MP3 against the input. Delete it if it needs to be deleted
        if(head_ref->artist == artist)
        {
            //Set temp to the current MP3
            temp = head_ref;

            //Check if the MP3 is the last MP3. If not, change the field of the next node in the list
            if(head_ref->next != NULL)
            {
                //Sets the previous field of the next node in the list to the previous field of the node to be deleted
                head_ref->next->prev = head_ref->prev;
            }

            //Change the next pointer of the previous MP3 in the list to the MP3 following the one to be deleted
            head_ref->prev->next = head_ref->next;

            //Free the memory
            free(temp->artist);
            free(temp->title);
            free(temp->date);
            free(temp);
        }

        //Traverse forward
        head_ref = head_ref->next;
    }
}

A: There are some issues in the code, but the following two are the most critical ones:
1.) use strcmp to compare strings. head_ref->artist == artist compares the pointers, not the contents, and it's usually unlikely that you pass in the same pointer to which the DLL elements point to.
2.) if the head is deleted, you need to pass back the "new" head to the caller of deleteMP3; otherwise the variable passed to deleteMP3 will still hold a pointer to the (deleted) node. So change void deleteMP3(struct MP3* head_ref, char* artist) to struct MP3 *deleteMP3(struct MP3* head_ref, char* artist) and return the actual head of the DLL (whether changed or not).


text:
Q: Sorting a list based on calculated values I'm struggling trying to sort a list based on values that need to be calculated.
In a university I have different departments. Every department has a number of studyareas that in their turn have a number of students.
Currently all of those studyareas are in one big list, but I would like to sort the list based on the total number of students in every department.
public class StudyAreasClass()
{
   public string Name {get; set;}
   public string Students {get; set;}
   public string Department {get; set;}
}

In the list there might be four StudyAreaClass-items where the Department is the same. So I would need to calculate the total amount of students where the Department is the same.
Then I would need to sort that comparing the value of this department with the other departments in the university.
The tricky part is that I don't have a fixed value to compare with. So I won't know which departments are in my list. So I can't just say:
University
.OrderBy(s => s.Students)
.Where(c => c.Name == "NameOfADepartment")
.ToList();

I'm thinking that there should be a somewhat easier way to sort this class using Linq, but I have no idea how to do it.
Can anybody point me out in the right direction?
Thanks

A: you can use linq query to do this
    static void Main()
    {
        List<StudyAreasClass> areas = new List<StudyAreasClass>();
        areas.Add(new StudyAreasClass() { Name = "A", Students = 5, Department = "D1" });
        areas.Add(new StudyAreasClass() { Name = "B", Students = 1, Department = "D1" });
        areas.Add(new StudyAreasClass() { Name = "C", Students = 2, Department = "D2" });
        areas.Add(new StudyAreasClass() { Name = "D", Students = 10, Department = "D3" });

        var sortedList =
            from area in areas
            join sub in (from a in areas
                         group a by a.Department into g
                         select new
                         {
                             Department = g.Key,
                             StudentCount = g.Sum(x => x.Students)
                         }) on area.Department equals sub.Department
            orderby sub.StudentCount, area.Students
            group area by area.Department into g2
            select g2;

        foreach (var departmentList in sortedList)
        {
            Console.WriteLine(departmentList.Key);
            foreach (var area in departmentList)
                Console.WriteLine(area.Name);
        }

        //D2
        //C
        //D1
        //B
        //A
        //D3
        //D
    }

basically you use a sub query to compute the sum of total students group by department and join the original list. Then you can sort based on the total count and get the result after.


text:
Q: Rspec unit testing without database Guys bear with me on this. I would highly appreciate any advise provided.
So lets say I have a controller with the below code:
class PersonController < ApplicationController
  serialize_with personSerializer
  string: title
  int: age

  def update
    authorize(person, can_update?)
    person.update(title:title,age:age)

    serialize person
  end
end

So in terms of Business Logic we have here:

*

*check for authorize

*update the object

*return the serializer of the object (it's just a json result)

Now I want to test this piece of code with RSpec, but there is no DB to save or receive an object (well there was one earlier, but I want to remove it when running tests).
So far I have tried using nulldb gem to remove the db dependency. But the problem arrives when the created object cannot be retrieved.
If I want to test the authorize (1). It's a function of another gem that tests if the user can even use this controller.
Do I need to completely mock it? If so, how? Which tool to use?
Same for the update, if I do person.update, how should I check if it works if I don't have access to the active record?

A: Unless this is a system test, you probably shouldn't be be testing #authorize's functionality in your controller tests. Same goes for ActiveRecord#update. Unit tests should test the logic that exists in the unit of code that you are testing, not external dependencies. Therefore a perfectly acceptable solution would be to assert that those methods are called:
it "#update updates a person when can_update? is true" do
  # However you are creating person objects w/o a database.
  # Can also be any object.
  person = ""
  title = "Bob"
  age = 81
  can_update = true

  expect_any_instance_of(YourController).to receive(:authorize).with(person, true)
  expect(person).to receive(:update).with({ title: title, age: age })

  patch update, params: { title: title, age: age }

  expect(response).to have_http_status(:ok)
end

If you still want to test the business logic that lives in 3rd party libraries, you can define separate tests that isolate the desired functionality:
describe "authorize" do
  it "authorizes a person with permission" do
    person = Person.new(name: "Bob", age: 81)

    # Replace with what you expect to happen
    expect(authorize(person, true)).to be_truthy
  end
end

If you are committed to testing your external business logic in the controller, you'll need to manually mock out every method that the third party library calls. I would highly not recommend this approach as it is

*

*brittle: if the library changes you may have to mock out more methods

*verbose: you'll be writing a lot of code that does very little

*non-specific: you'll be testing external business logic in test that should be focused on which code is rendered from a request

A: eventually, I used nulldb, and just mock everything.
also used FactroyBot.
There is no easy way to do so, just hard work and mock all the stuff you need. mainly the DB calls.
For the authorize part i mocked the policy used:
allow_any_instance_of(MyPolicy).to receive(:model).and_return(true)


text:
Q: How to batch transfer rename? There are two folders holding equal amounts of files between them.
I'd like to apply the names from one set ; to the other set of files in no particular order. Inherit the name, but retain the extension .
Input files are .bmp Output files are .ini  ( has a gear symbol ).
Example :
 folder 1-  Flowers.bmp  ; folder 2- blank.ini
. To this:
 folder 1-  Flowers.bmp  ; folder 2- Flowers.ini

There would be more files , but equal  .
The .ini files are all copies .  So they may have a generic name and numbered   if that matters to know . Those would all receive one name each from the other .bmp files in the other folder.
Normally I have both folders situated on the Desktop .
I make sure both folders have equal number of files between them . That would be a constant .
I'm trying to stream line some menial repetitive daily tasks .
I did search and what I have found does not really help.
@ECHO OFF
SET "vers=%~1"
IF "%vers%" == "" SET /P "vers=Enter Vers: "
FOR %%F IN (file_XX_*.*) DO CALL :process "%%F"
GOTO :EOF

:process
SET "name=%~nx1"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "name=!name:_XX_=_%vers%_!"
RENAME %1 "%name%"
ENDLOCAL

Hoping to find a solution to this finally .

A: Ok, here is a slightly long version, but it makes sure it gets the content of each folder.
Note You must ensure that the path to both folders are correctly specified in the third and fourth line:
@echo off
setlocal enabledelayedexpansion
set "source=%userprofile%\Desktop\folder 1"
set "destination=%userprofile%\Desktop\folder 2"
set /a num=0
for %%a in ("%source%\*") do (
  set /a num+=1
  set "fr!num!m=%%~na"
)
set /a oldn=!num!
set /a num=0
for %%b in ("%destination%\*") do (
  set /a num+=1
  set "to!num!r!=%%~nxb"
  set "ext=%%~xb"
)
pushd "%destination%"
for /l %%i in (1,1,!oldn!) do ren "!to%%ir!" "!fr%%im!%ext%"
popd
pause

You can remove pause at the bottom of the script, once you are happy with the output.

A: This is not the most effective way, but considering your limited batch experience, I guess an understandable approach is better than an optimized one (using array-like variables).
@echo off
setlocal enabledelayedexpansion

(for %%A in ("folder 1\*.bmp") do echo %%~nA)> "%temp%\names.txt"

<"%temp%\names.txt" (
for %%A in ("folder 2\*.ini") do (
  set /p "name="
  ECHO ren "%%A" "!name!.ini"
))

The first for loop creates a list of the desired names (from Folder 1). The modifier %%~nA returns the name only.
The second for processes each file in Folder 2 and takes a name from the previously generated file for each file. This depends on the fact that the number of files in both folders are the same, else you may get undesired results.
I disabled the actual ren command by just echoing it. Check the output and only when you are satisfied, remove the ECHO.


text:
Q: How to change text of a button without creating object in android I have tried to do like this,
findViewById(R.id.button1).setText("HI");

But it is not working.
is there any other way to do it?

A: ((Button) findViewByid(R.id.button1)).setText("Hi");

Not sure what you are trying to realize though!

A: try this way
Button btn=(Button)findViewById(R.id.button1);
btn.setText("HI");

A: Try this
Button btn = (Button) findViewById(R.id.btn1);
btn.setText("HI");

A: have to create a button object. if you want to change the name in another class, define the button object global
      import android.widget.Button;

      Button button = (Button)findViewById(R.id.button1);
      button.setText("text change");

A: Try this
((Button) findViewByid(R.id.button1)).setText("Hi");

If you are trying to instantiate button inside subclass like adapters or dialogs etc , use the respective view before findViewByid.
((Button) view.findViewByid(R.id.button1)).setText("Hi");

or
((Button) dialog.findViewByid(R.id.button1)).setText("Hi");


text:
Q: Voice calls not working over gtalk with empathy With Empathy Internet messaging in ubuntu11.04, written messages are working but I can't obtain voice call from my gmail account and with people using googtle talk.
any help? thanks

A: According to the Empathy FAQ:

How can I test if audio/video is working?
Collabora is hosting an echo service: echo@test.collabora.co.uk .
  This is a jabber contact you can add to your roster. When you call it,
  anything you say will be echoed to you.
Does Empathy support audio and video chat with Google Talk?
Yes, you can have a audio or video chat on the Gtalk protocol with
  someone using Gmail's video chat feature, Empathy or Pidgin.
Note that if your contact is using Google Video, be sure he has the
  latest version of the plugin which can be downloaded from this
  page.
Which video codec do I need?
For calls between empathy and empathy, all you need is theora, which
  is installed by default on all distributions.
For calls between empathy and gtalk, you need h264 encoder. On ubuntu
  you can get it by installing gstreamer0.10-plugins-ugly-multiverse
  and gstreamer0.10-ffmpeg . To know if a codec is installed, you can
  use that command:
$ gst-inspect-0.10 | grep 264

Make sure you have encoder and decoder in the list. For h264 you'll
  have x264enc encoder for example. Similar command can be used for
  other codecs.

So have you troubleshot the application with the above steps mentioned and are still having the problem? If so, please add any necessary information to the post above and leave a comment on this answer (so that I can delete it off). However, if the problem has been solved due to this answer, please mark it accepted :)


text:
Q: Setting volume with java Good day!
I'm developing an application that plays a MIDI. It plays fine, but I often get quasi-bug reports: 'there is no sound playd'. The answer is always, to enter into volume controller and turn the synthesizer sound on (make it not muted).
The question is - how to change it automatically - by software? Till now I can only change the master volume and I couldn't really anywhere find how to change only for 'wave' 'SW synthesizer' etc...
I'm generally looking for platform indenpendent solutions (pure java), however solution only for Windows (all sorts of windows) are also welcomed ;) Thank you ahead!
Edit: Well, looking at the answers, I see, I should specify my question better. I append image. The control selected with green is what I can already do (i.e. as Cliff linked) however I need something for controls in red (the most important in my case is the 3rd from the left - synthesizer volume). Image is taken from win XP, but other operating systems (linux also) have similar controls. Java has to have such possibility.

A: I've looked in Ubuntu, Fedora, and Windows and the only commonalities across these OS's is the master volume and the alert (or "beep" on Windows) volume. This leads me to believe that there is no platform-independent way of doing this, meaning no standard Java way.
That being said, there is most likely APIs (probably different) for all of these OS's which allow you to control these finer-grain settings. If so, it will almost definitely require separate Java libraries for interacting with these APIs on each platform.
Sorry I can't point you in the right direction but I am hoping to at least help you eliminate the possibility of having a standardized way of doing this function. Good luck!

A: Try peeking at what happens in the background when you adjust the wave/synthesizer levels using the tool in the screenshot using sysinternal's Process Monitor, and then have your java code do the same native system/dll call.

A: Are you working with some sort of interface or using the system's default Mixer? And what level of control are you talking about? Unfortunately I'm learning this API as well but my first thought is that each of those would be a different line, right? Have you tried getting all of the system lines and using the MASTER_GAIN on each of the lines? Like the person above me said I'm sure there are API's for this but if I were going to do it in my own code for educational purposes or something that is where I would start. Speaking of API's there is a Control API that manipulates the audio data itself but as far as I know doesn't affect the hardware's volume control.


text:
Q: changing the port 80 if it was busy i have an assignment to make a web server on the TCP by using LAN , the project is to make a request to localhost on port 80 and present "hi" in a browser and to present "404 not found" if the request is wrong, i have a problem with being port 80 is busy, it stop working when using any port but 80, the hint from the assignment is "If you run your server on a host that already has a Web server running on it, then you should use a different port than port 80 for your Web server." and my code is :
from socket import *

import os

def test():
    serverPort = 80
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.bind(('', serverPort))
    serverSocket.listen(1)

    print("web server on port", serverPort)

    while True:
        print("ready to serve")
        connectionSocket, addr = serverSocket.accept()
        try:
            message = connectionSocket.recv(1024)
            print(message)
            filename = message.split()[1]
            print(filename[1:])
            print(filename, '||', filename[1])
            f = open(filename[1:])
            outputdata = f.read()
            connectionSocket.send(outputdata.encode())
            connectionSocket.close()
        except Exception:
            print("404 Not Found")
            connectionSocket.send("""404 Not Found\r\n""".encode())
        pass
    pass

if __name__ == "__main__":
    test()

A: simply you need to check if port already in use or not
def check(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    return s.connect_ex(('localhost', serverPort)) == 0


text:
Q: Nav menu custom html: I've been looking to the answers on this site, but they lack information on what files to edit and/or the path to them, and where or how you activate and can see the changes.
For example, this question:
Edit html for menu items in default frontend menu
or this:
https://wordpress.stackexchange.com/a/64034/166781
I want to add my custom html items in the nav menu, and I guess that I have to add my code, in this case copied from the questions and answers provided here, to functions.php, but I can't see any change anywhere.
As an example, if I want to add an item to de nav menu like the code below (taken from one of the question I posted):
add_filter('wp_nav_menu_items', 'wps_add_login_logout_link', 10, 2);
function wps_add_login_logout_link($items, $args) {
    $login = __('Sign in');
    $logout = __('Sign out');

    $menu_id = '15';
    $menu_id2 = '16';

    if ( ! is_user_logged_in() )
        $link = '' . $login . '';
    else
        $link = '' . $logout . '';

    if ( $args->menu == $menu_id )
        $items .= '
'. $link .'
';
    elseif ( $args->menu == $menu_id2 )
        $items .= '
'. $link .'
';

    return $items;
}

*

*Which file should I add this?

*Once added, where can I see the changes made effect?
Thanks for your patience.

A: WordPress themes can be set up in many different ways, which is both a blessing (you can do things however you like) and a curse (there's not always a single file you need to look at to make a particular change).
You're on the right track, looking into the theme. What you'll need to do first is to create a child theme. That way, when you update your theme, your edits won't be overwritten.
Once you have a child theme, you'll want to look in the parent theme to find out how they are calling the particular nav menu you want to modify. Many themes use more than one menu, so you need to isolate that one. Then, look and see how it is called. You will see something like this:
<?php wp_nav_menu(
    // everything inside this array will vary, depending on your theme
    array(
        'menu' => 'topnav'
        'walker' => new custom_walker()
    )
); ?>

What you want to find out is whether there is a "walker" in the array. (There is above.) If there is, you're in for more complexity, as your theme (now the "parent" theme) is already using a custom walker that builds different HTML than WP Core does by default. You'll then need to search through your parent theme's files. Most often the walker class is inside functions.php but not always. Find that class, then copy it into your child theme's functions.php and then change the name of the class.
Or, if the nav menu you want to affect doesn't use a walker at all, go into your child theme's functions.php and create a walker.
In either case, you now need to look into what it takes to create a walker. Look for examples online and start very simple, and then as you run into questions you can check back here with a new question.
One last note - if you're doing something like top navigation and you have a static set of pages to include there, along with your custom HTML, it might be a lot simpler to just not use a WP nav menu. You can use other functions like wp_list_pages() to list all the Pages, or even hard-code, depending on your needs and how willing you are to maintain the code.


text:
Q: Book suggestion for real analysis help. I am looking for a good book to supplement my class book on analysis.
I am struggling with concepts and I would like a book that can help me learn how to learn analysis.

A: 1) Charalambos D. Aliprantis, Principles of Real Analysis.
2) J. Yeh, Theory of Measure and Integration.
3) Sterling K. Berberian, Fundamentals of Real Analysis.
4) Russell A. Gordon, Integrals of Lebesgue, Denjoy, Perron, and Henstock.

A: I think that one book that has really helped me this semester is How to  Think About Analysis by Laura Alcock. She goes through many of the concepts that are in an introductory analysis class and some best practices for studying the material, as it can be very difficult if you do not approach it the right way.

A: When I was learning introductory real analysis, the text that I found the most helpful was Stephen Abbott's Understanding Analysis. It's written both very cleanly and concisely, giving it the advantage of being extremely readable, all without missing the formalities of analysis that are the focus at this level. While it's not as thorough as Rudin's Principles of Analysis or Bartle's Elements of Real Analysis, it is a great text for a first or second pass at really understanding single, real variable analysis.


text:
Q: How can you make the updates/second constant? As far as I know, love.update and love.draw is called every frame. You can turn vsync off (unlimited calls to love.update) or leave it on (fixed to refresh rate). Since different computers have different refresh rates, you need to be able to support different ups's, otherwise the game will run at different speeds for different computers.
There are 2 solutions I can think of:

*

*Cap UPS.

*Run at an arbitrary UPS.
There were a few issues with 2, so I think a constant UPS might be better. My computer's refresh rate is 57Hz so I used that in the code.
function love.update(dt)
  t = t + dt
  while t >= 1/57 do
    t = t - 1/57
    --stuff
  end
end

The game runs fine if I turn vsync on, but if it's off, then it's slightly jittery and I think it would probably be like that regardless of vsync on other PC's. Is there a way to cap the UPS better or should I just use solution 2?

A: you need to use the dt in update function,
let's say you have a sprite moving 1 pixel every frame
function love.update(dt)
   sprite.x = sprite.x + 1
end

for you with a refresh rate of 57 fps the sprite will move of 57 pixel per second, but others would see it move at say 60 pixel per second
function love.update(dt)
   sprite.x = sprite.x + 60*dt
end

now at 57 fps, you call 57 time update in one second and your sprite would move exactly 60 pixel (60*(1/57)*57), and others running at 60fps would also see it moving of 60 pixels (60*(1/60)*60)
using dt you are doing computation time relative, not frame relative discarding the problem altogether

A: It seems like you know how to set vsync, but here's the code I'm using in love.load() to set it:
love.window.setMode(1, 1, {vsync = false, fullscreen = true})

At the start of my update loop I have the following code:
self.t1 = love.timer.getTime()

This grabs the time at the beginning of the loop and is paired with the following code at the end end of the loop:
self.delta = love.timer.getTime() - self.t1
if self.delta < self.fps then
    -- sleep to maintain 60fps
    love.timer.sleep(self.fps - self.delta)
end
-- calculate frame rate
self.delta = love.timer.getTime() - self.t1
self.frameRate = 1 / self.delta

If your computer is able to run the update at faster than 60FPS then the game will sleep at the end of the update loop to enforce a constant frame rate. Unfortunately this only caps the frame rate (solution 1 in your post). That being said, this method runs with no jitters (I have tested on multiple Windows machines).
I believe I got this method from this link.

A: Be careful with vsync since some computer screens can run at different frame-rate (like 60fps, 120fps...). And even with computer screens that run at the same frame-rate, enabling vsync in love2d is a setting that can be overridden by the graphic card settings. So you should always consider using the delta-time (dt). Refer to @nepta answer to know how the delta-time should be used.


text:
Q: How to escape special characters in Code Igniter I'm building a website in Code Igniter and i'm trying to save products in a database. I don't know what kind of products i get. It's a XML file. There ara some times special characters in it so Code Igniter crashes.
I fixed it like this
$search = array('â', 'à', 'á', 'ã', 'ä', 'å', 'Â', '€', 'š', '¢', 'Ã');
str_replace($search, '', $string)

But this is not nice and i haven't coverd all the possible special characters.
My question is: is there a eassier way to get this done?

A: Sorry for the short answer but I think you have issues regarding handling UTF8 encoded characters and need to read this (a guide to working with PHP, MySQL and UTF8 character encoding - other guides are available )  -
http://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql

A: I believe you should take look at convert_accented_characters() function of Text Helper in CI

It transliterates high ASCII characters to low ASCII equivalents,
  useful when non-English characters need to be used where only standard
  ASCII characters are safely used, for instance, in URLs.
$string = convert_accented_characters($string); This function uses a
  companion config file application/config/foreign_chars.php to define
  the to and from array for transliteration.


text:
Q: Maximum Independent Set on Path and Ring I known this question is more appropriate to cs.stackexchange.com, nevertheless I want to ask it in Mathematics part because for solving the following problem strong understanding of probabilistic methods is required.
Let's consider distributed version of algorithm for finding MIS of any graph $A$.
For details, MIS - Maximimal Independent Set.
Slow version of distributed algorithm for MIS, page 2 -  Distributed algorithms. Maximal Independent Set
The algorithm is:
Every node v executes the following code:
if all neighbors of v with larger identiers have decided not to join the MIS
then
  v decides to join the MIS
end if

In worst case, time complexity of the algorithm is $\text{O}(n)$ and a message complexity is $\text{O}(m)$. If nodes of the network are not unique than it's not possible to find MIS.
I am interested in few special cases, when the graph is a path and ring.
Exercise: Consider a path graph $G$ with vertex UIDs to be a random permutation of $\{1,…,n\}$, time complexity of MTS_Slow is $T \leq c\log n$ for a constant $c$ with probability $1-\frac{1}{n}$.
What is a time complexity and it's probability on a ring $G$ with vertex UIDs to be a random permutation of $\{1,…,n\}$.
Ideas: The probability of time complexity $c\log n$ is given for MIS for a path and the exercise asks to find a time complexity and it's probability for  a ring graph. Besides finding it for a ring I am interested in proving it for a path. Time complexity has $\log n$ factor, therefore on each phase number of candidates
for MIS nodes from a path graph $G$ should be divided by constant factor.
Case with ring should be similar to a path graph case.
I will appreciate any help in solving this exercise.


text:
Q: Discrete Math: How do I proof this problem by the Proof by contradiction? I have been trying to solve this proof of sets but I keep getting something other than he result it can you please how me how I would go about solve this problem?

A: I didn't see you needed a proof by contradiction.
For this not to be true you either need an $x \in Q_2$ but $x \not\in Q_1$, or an $x \in Q_1$ but $x \not\in Q_1$.
Case 1: Suppose $x \in Q_1 \not \implies x \in Q_2$.
Then there is an $x \in Q_1$ but $x \not \in Q_2$.
So $x = m/n; m, n \in Z$. Let $d = \gcd(n,m)\ne 1$ because $x \not \in Q_2$ then $m = dm'$ for some integer $m'$ and $n = dn'$ for some integer $n'$. So $ x = m/n = m'd/n'd = m'/n'$ but $x \not \in Q_2$ so $e=\gcd(m',n') \ne 1$.  So $m'=em''$ and $n' = en''$.  So $n= edn''$ and $m=edm''$ and $e*d > d$ is a common divisor.  So $d$ not the greatest common divisor after all.
So that's a contradiction. So $x\in Q_1 \implies x \in Q_2$.
Suppose $x\in Q_2 \not \implies x\in Q_1$.
Then there is an $x \in Q_2$ so that $x \not \in Q_2$.  So $x = a/b; a\in Z,b\in Z; \gcd(a,b) = 1$.  But $x\not \in Q_1 $ so $a$ and $b$ can not both be integers.  But I just said they were.  So that's a contradiction.
So $x \in Q_2 \implies x \in Q_1$.
So the two definitions are equivalent.
===== old answer ===
Prove if $x \in \mathbb Q_1$ then $x \in \mathbb Q_2$.  That proves that $\mathbb Q_1 \subset \mathbb Q_2$.
Then prove if $y \in \mathbb Q_2$ then $y \in \mathbb Q_1$.  That proves that $\mathbb Q_2 \subset \mathbb Q_1$
And that proves that $\mathbb Q_1 = \mathbb Q_2$.
Hint: if $m = m'\gcd(m,n)$ and $n = n'\gcd(m,n)$ then  $\frac {m}{n} = \frac {m'*\gcd(m,n)}{n'*\gcd(m,n)}= \frac {m'}{n'}$


text:
Q: How to make this script also remove certain items from recommended in Windows 11 I have this powershell script that will remove (not delete!) certain items from the recent files section in Windows 11 File Explorer.
However I ALSO want it to remove certain recent files from the Windows 11 start menu recommended section.
Does anyone know how to do this?
$Namespace = "shell:::{679f85cb-0220-4080-b29b-5540cc05aab6}"
$QuickAccess = New-Object -ComObject shell.application
$RecentFiles = $QuickAccess.Namespace($Namespace).Items()
$FilteredFiles = $RecentFiles | ? {$_.Path -like "*C:\CertainDir*"}
$FilteredFiles | % {$_.InvokeVerb("remove")}


text:
Q: displaying data from MySQL in PHP according to a condition I am trying to display data from MySQL database using PHP according to availability.
Here is the snippet:
include_once ('functions.php');
    $con = new DB_con();
    $res=$con->selectemployer();
    while($row=mysql_fetch_assoc($res))
    {
        ?>
<?php

if ($row['stat'] == 'Available') {
    echo '' . $row['stat'] . '	';
} else {
    echo '' . $row['stat'] . '	';
}
?>

Here is functions.php :
class DB_con
{
public function selectemployer()
 {
   $res=mysql_query("SELECT * FROM employer");
  return $res;
 }
}

My issue is that whenever I select Unavailable,it displays correctly(i.e only rows with Unavailable status).But on selecting 'Available' option,it shows both unavailable and available rows.
Where am I wrong here ?
EDIT:Resolved the issue , the problem was because of a JS script which was performing the sorting.

A: Your query does not have a where clause, fix it this way
$res=mysql_query("SELECT * FROM employer WHERE status = '".$_Post['stat']."'");

I am assuming the column that contains Available/Unavailable is status and the status field name that you post in your html is $_Post['stat']


text:
Q: Parsing figure name on Beautiful Soup This is my first time posting, so please be gentle.
I'm extracting data from trip advisor. The reviews are interpreted with a figure that is represented like this.

As you can see, there is a "40" in the end that represents 4 stars. The same happens with "20" (2 stars) etc...
How can I obtain the "ui_bubble_rating bubble_40"?
Thank you in advance...

A: I'm not sure if this is the most efficient way of doing that, but here's how I'd do it:
tags = soup.find_all(class=re.compile("bubble_\d\d"))

The tags variable will then include every tag in the page that matches the regex bubble_\d\d. After that, you just need to extract the number, like so:
stars = tags[0].split("_")[1]

If you want to be fancy, you can use list comprehensions to extract the numbers from every tag:
stars = [tag.split("_")[1] for tag in tags]

A: I am not sure what kind of data you are trying to scrape,
but you can obtain that span tag like so (I tested it and left some prints in):
from urllib import urlopen
from bs4 import BeautifulSoup
import re

html = urlopen("YOUR_REVIEWS_URL")
bs1=BeautifulSoup(html, 'lxml')

for s in bs1.findAll("span", {"class":"ui_bubble_rating bubble_40"}):
        print(s)

More generic way (scrape all ratings (bubble_[0-9]{2})):
toFind = re.compile("(bubble_[0-9]{2})+")
for s in bs1.findAll("span", {"class":toFind}):
        print(s)

Hope that answers your question


text:
Q: Databinding causing other functions on page not to work when filling datagrid I have a datagrid in my View. The datagrid's itemssource property is bound as such
ItemsSource="{Binding}"

Addtionally in the codebehind I have set datacontext by doing the following:
DataContext = ProcedureDatabaseViewModel.Procedures();

The Procedures function in the viewmodel successfully outputs a list which the DataGrid successfully displays.
The issue now is that the datacontext of the entire page is now set to the above. The result of this is that other elements that interect with the VM no longer work. I.E. buttons with commands that are found in the VM. I have tried removing the setting of the datacontext in the code behind but cannot figure out how to populate the datagrid otherwise. Please note that when the DataContext is not set in the code behind the context is changed to the VM, I believe, and thus, the other elements begin working again. I have tried changing the Itemssource property to target the list of objects that I wish to populate the datagrid with but it hasnt worked.
The list is
List<procedure> Procedures

and it is in the ProdureDatabaseViewModel. I tried to target it as
ItemsSource="{Binding ProdureDatabaseViewModel.Procedures}"

But this has not worked either.
Can someone please advise me on the correct way to do this?

A: The cleanest way is to use ItemsSource to bind your Procedures collection to your DataGrid. For this to work, Procedures has to be a Property. To avoid further issues, use an ObservableCollection. It should look like this:

ObservableCollection<procedure> Procedures { get; set; }

Then you should be able to simply bind it via

ItemsSource="{Binding Procedures}"

A: I prefer to set the DataContext in the constructor of the view to the complete ViewModel (which I created for this special view).
So I do something like this in the constructor of the view:
public View(ProcedureDatabaseViewModel viewModel)
{
    this.DataContext = viewModel;
}

This way everything else should still work and you can use more than just the procedures.
Next you bind the procedures to your datagrid:
ItemsSource="{Binding ProcedureList}"
Do note that for this to work, "Procedures" needs to be a property. It's not clear in your question if it is a function, a property or just a simple class member. If it is a function, you can do it like this in your view model:
public List<procedure> ProcedureList
{
    get { return this.Procedures(); }
}

A:
I have tried removing the setting of the datacontext in the code
  behind but cannot figure out how to populate the datagrid otherwise.

You can set the DataContext of your DataGrid separately like so, MyDataGrid.DataContext = ProcedureDatabaseViewModel.Procedures();.
And apply separate DataContext for your Page.


text:
Q: Workflow graph as RDF? I am new to RDF and, perhaps, my question is too silly to be asked.
I have the following workflow, which I am trying to be represent as an RDF. I understand the theories behind RDF and its uses, but I am stuck at how to get started to creating an RDF for this graph. I would appreciate any help.
Thanks in advance.
~Codera

A: To start, you'd want to model the edges are RDF properties like:
:propose rdf:type rdf:Property;
    rdfs:label "propose".
:accept rdf:type rdf:Property;
    rdfs:label "accept".

Then you can use those to relate M(1..N):
:M1 :propose :M2.
:M2 :propose :M3.

That will roughly form an RDF graph representing the diagram you have above.  You can attach additional properties to each M(1..N) as required by your application, or you can model them as rdfs:Class objects and have your properties relate instances of those classes.
If you have not read the primer that's a pretty decent place to start, it's got some examples that will look pretty close to what you're trying to model.  For schema or ontology authoring, creating and maintaining a simple one by hand in a text editor is not too bad, but you might want to look at using Protege as the complexity grows, especially if you want to start using OWL.
As far as tools to build your application, your best bet to start with are either the Sesame or Jena APIs.  They provide all the bits you'll need for reading, writing, and using RDF.  I recommend Sesame, I think it's easier to use, and has more database options available.  If you're not a Java programmer, there are some options out there, rdflib for python and dotNetRdf for .Net are a couple examples.


text:
Q: How to calulate a cumulative sum for each observation by id My problem is about calculating the cumulative sum for each id and for each date taking into account a sliding period of 15 previous days. If the cumulative sum exceeds 10k, the variable top is incremented.
The treatment is done for Juen only.
Here is an exemple of the desired result :
id  app_date    price   cum top
1   29-juin-20  4000                 4 000  .
1   13-juin-20  5000               45 000   1
1   13-juin-20  6000               40 000   2
1   11-juin-20  7000               34 000   3
1   10-juin-20  8000               27 000   4
1   01-juin-20  9000               19 000   5
1   30-mai-20   10000              10 000   .

proc sort data = tab out= tab1;
by id descending app_date;

run;

data tab2;

set tab1;

%let annee=2020;

%let month=06;

by  id;

retain last_date date_last_d CUM;

if first.id then do;

      last_date =app_date;

      date_last_dem = app_date;

      CUM=0;

end;

if month(date_last_d) =&month. then do ;

diff= date_last_d -app_date;

CUM= price+ CUM;

end;

if diff>15 then do;

      diff = .;

      CUM =.;

      last_date =app_date;

      date_last_d = app_date;

end;

if last.id and CUM>10000 then top= top+1 ;

output;

last_date=app_date;

format last_date DDMMYY10.;

format date_last_d DDMMYY10.;

format CUM 14.2;

run;

I can do it for the first iteration but I cannot do it for all the lines.

A: How about this?
data have;
input Cnt Price ID App_date :ddmmyy10.;
format App_date ddmmyy10.;
datalines;
1  2265 534    30/05/2020
2  2330 4594   27/06/2020
3  1360 723    14/05/2020
4  1393 723    14/05/2020
5  2400 101666 12/06/2020
6  2411 101666 12/06/2020
7  2400 101666 11/06/2020
8  2400 101666 11/06/2020
9  2527 101666 10/06/2020
10 2536 101666 10/06/2020
11 2458 101666 04/06/2020
12 2758 1088   30/05/2020
13 4412 1056   13/06/2020
14 1870 1255   30/06/2020
15 4198 1255   14/05/2020
;

data want(drop = c k p dt);

   dcl hash h(ordered : "Y");
   h.definekey("c");
   h.definedata("c", "p", "dt");
   h.definedone();
   dcl hiter i("h");

   do c = 1 by 1 until (last.ID);
      set have(rename=(App_Date=dt Price=p));
      by ID notsorted;
      h.add();
   end;

   do k = 1 by 1 until (last.ID);
      set have;
      by ID notsorted;
      cum = 0;
      do while (i.next() = 0);
         if App_Date - 15 <= dt <= App_Date & k <= c then cum + p;
      end;
      if cum > 10000 then top + 1;
      else top = .;
      output;
   end;

   h.clear();
run;


text:
Q: É uma má prática armazenar CPF e CNPJ em uma mesma coluna do banco de dados? Em um fluxo que permita o cadastro de pessoas físicas e pessoas jurídicas já vi as duas abordagens, mas não tenho certeza se é uma boa prática armazenar as duas informações em uma coluna cpf_cnpj e aí ter um campo de flag para informar o tipo do campo, ou até mesmo utilizar a quantidade de caracteres no campo me parece um tanto quanto forçado.
Será que como estou utilizando ORM (Entity Framework) poderia ser melhor prática ter uma derivação do tipo User para PersonalUser e BusinessUser?

A: Pesquise aqui mesmo no site oque eu e outras pessoas acham sobre "boas práticas".
Boa prática é fazer o certo para o que precisa. E só você com seu caso concreto pode dizer o que é certo para aquele caso.
Eu separo sempre pessoa física de jurídica, porque claramente elas são entidades muito diferentes. Mas funciona manter junto, eu acho que dá mais trabalho e complica algumas coisas. Minha experiência é que ainda que dê um pouco de trabalho separar é mais correto conceitualmente e acaba simplificando algumas coisas. Se souber abstrair bem isso nem é tão difícil lidar com ambos.
E esse último ponto é importante porque não adianta você tomar uma decisão certa e todas as outras que virem a seguir, até em consequência dessa, forem erradas. E esse é só mais um motivo para a adoção de boa prática pode ser uma péssima prática, a pessoa acha que ela basta e tudo ficará ótimo.
É como as pessoas adotando a "boa prática" de microsserviços porque escala mais facilmente. Ela só não sabe que está adotando o problema mais difícil da computação na sua arquitetura e que ela provavelmente fará tudo errado e será muito pior.
Aí entramos naquela coisa: "a melhor ferramenta é aquela que você conhece", ou dito de outra forma:

A melhor prática é aquela que você conseguirá fazer certo

Eu só acho estranho um usuário poder ser jurídico. Não me lembro de ter visto isso em algum lugar. Vi entidades de relacionamento serem empresas, mas não usuários. Parece, mas não posso afirmar que há uma confusão de conceitos aí. Novamente, você é quem sabe dos seus requisitos.
O que eu não faço é separar atividades dessas entidades como clientes, fornecedores, etc.
Já dei algumas respostas sobre isso:

*

*O que fazer se cliente pode ser tanto PF quanto PJ?

*Como se modela um papel em orientação a objetos?

*Modelagem de lançamentos usando clientes e fornecedores

*Pode ser considerada uma má prática de modelagem armazenar todas as pessoas (clientes, funcionários, fornecedores) em uma mesma tabela?

A: A princípio entendo boa prática sim tem numa mesma coluna o cadastramento de cpf e cnpj no mesmo campo.
você criaria um cadastro único de pessoas (tanto jurídicas quanto físicas) evitando situações de duplicação desses cadastros.
Está correto também a situação de usar um campo (flag) que defina o tipo de pessoa, o que também poderia ser dispensável, se considerarmos que cpf tem 11 dígitos e cnpj tem 14. Na programação você pode diferenciar isso pelo length da variável que trouxer essa informação.
Um exemplo da boa utilidade que essa prática teria:
Suponha que uma empresa vai fazer uma compra no seu estabelecimento.
É pertinente que nessa situação esse cadastro da pessoa jurídica tenha relação com alguma pessoa física a título de representante legal.
Agora suponha que essa pessoa física já cadastrada como representante legal deseja fazer uma compra particular, sem vínculo com a pessoa jurídica que ele representa.
neste caso você já terá o cadastro dessa pessoa sem ter que ficar duplicando as informações.
Caso haja dúvida em como proceder essa vinculação do representante legal à empresa, a sugestão é criar uma tabela para essa vinculação (n pra n).
Assim, conforme o caso ou necessidade, será possível incluir vários representantes legais (pessoas físicas) para cada empresa (pessoa jurídica), bem como será possível informar uma mesma pessoa física como representante legal de várias empresas.
Além de evitar duplicações de cadastros nesses casos, quando ocorrer situações de ser necessário atualizar cadastro de uma pessoa, não será necessário ficar procurando se ele é representante legal de empresas para atualizar nesses casos também.
No geral eu sempre recomento e aplico essa prática, mas como o Maniero bem disse, cada caso deve ser analisado e feito conforme realmente for necessário e mais eficiente.

A: Eu não gosto muito da ideia de juntar tudo e usar flags ou tamanho de strings para diferenciar PF de PJ. Amanha o governo pode criar um terceiro (tipo ONG) que não é nem fisico nem juridico. E ai sua flag fica sem sentido. Definir pelo tamanho tambem nao acho uma boa, pois os numeros podem crescer. Ja vi lugares que reservam 15 digitos para PJ, 12 para PF, 9 para telefones fixos... e por ai vai...
Eu prefiro a abordagem que vi numa empresa em que trabalhei: Uma tabela para pessoa contendo dados comuns a ambos os tipos, uma tabela para PF e uma tabela para PJ. A tabela PJ armazenava somente a base do CNPJ e existia uma outra tabela que armazenava as filiais, a parte que vem depois da '/'. Porque uma coisa que muitos nao lembram são as filiais de um CNPJ.
Confuso né? Mas pra facilitar, foi criada uma view que juntava tudo, PF, PJ e suas filiais.
Alguns torcem o rabo para views, por questões de performance, etc.. So what? As maquinas estão cada vez mais rápidas, não vejo preocupação pra isso.


text:
Q: How can I run a future before build in flutter? I am not able to run getMapCurrencies before the build, and I need values in listCurrencies before the view. I can not put the future builder in the build because I dont want to bring listCurrencies many times, just once.
Please help
getMapCurrencies() {
    currencies.getCurrenciesCheck().then((val) {
      listCurrencies = val;
    });
  }

class _CurrencyWidgetState extends State<CurrencyWidget> {
  @override
  void initState() {
    // TODO: implement initState
    getMapCurrencies();
    super.initState();
  }

A: What do you mean by "I dont want to bring listCurrencies many times, just once"
FutureBuilder is one way you can do this. It will render the widget once listCurrencies is populated.
Another way is to use a ternary operator
listCurrencies != null ? (widget using listcurrencies) : (a progress indicator)

Edit:
Also you should set listCurrencies using
setState((){
    listCurrencies = val;
})


text:
Q: How can I designate range within an column when making an awk file? I have this data file which I want to sort out by making an awk file. I want to find the average rate within certain range of ages. For example, from  10<age<20and 20<age<30. And I can't find a way to calculate averages only for those people. How can I do this?
name rate hours age sex
AIDAN 3.5 19 22 M
AMELIA 5.25 16 13 F
NOAH 4.5 24 25 M
ISABELLA 4.25 17 15 F
LIAM 4.5 23 23 M
AVA 5.5 24 25 F
CAYDEN 6 21 28 M

A: select line with $4 < 20 && $4 > 10
awk 'BEGIN { c=0 ; s=0 ; }
     ($4 < 20) && ($4 > 10) { c++ ; s+=$2 ; }
     END { if (c>0 ) printf "average %.1f\n",s/c ;}' ...

with an error message if no lines are selected.

A: I'm not sure I understand the question.
Do you want to be able to get two results?
In case it's not obvious, Archemar's answer can be extended to collect multiple statistics:
awk '($4 > 10) && ($4 < 20) { c10++; s10+=$2; }
     ($4 > 20) && ($4 < 30) { c20++; s20+=$2; }
     END { if (c10>0) print "average for 10-20:", s10/c10
           if (c20>0) print "average for 20-30:", s20/c20 }' …

*

*Of course it's good programming practice to initialize your variables.
But awk initializes variables to null,
which acts like zero when used in mathematical contexts,
so it's not really necessary.

*As Archemar pointed out, you can exercise some control
over the output format (i.e., how the result is written) with printf.
But awk's defaults (i.e., how it implements the print statement)
are reasonable.

*As Archemar pointed out, you might want
to issue an explicit error message when there are no people in a range
(rather than just not reporting an average).

A: awk '{if ($4>=10&&$4<=20) {X=X+1;Y=Y+$2}} END {print Y/X}' < infile


text:
Q: Android Add horizontalscrollbar and verticalscrollbar to a view dynamically HI, I have a problem in dynamically adding horizontal and vertical scrollbar to a view . Basically the application zoom in and zoom out an image. I want to put horizontal and vertical scrollbar dynamically whenever view is out bounds. i.e. when zoom in is click and view is gonna out of bond, then it automatically add scrollbar. I am using these two methods but they didn't work correctly.

     setVerticalScrollBarEnabled(true);

    setHorizontalScrollBarEnabled(true);

Does i have to put these methods inside onDraw(Canvas canvas) method of the view?

Note: I am not creating view using xml file. I am creating view using a class which is inherited from View.
Thank you!!

A: not quite the same thing but this may give you a clue:
    mTextView = new TextView(this);
    mTextView.setGravity(Gravity.CENTER_VERTICAL);
    mTextView.setText(R.string.instructions);
    mTextView.setTextColor(0xFF000000);
    mTextView.setPadding(20, 8, 8, 20);
    //mTextView.setBackgroundColor(0xCCFFFFFF);
    mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);

    mScroll = new ScrollView(this);
    mScroll.setScrollbarFadingEnabled(false);
    mTextPane = new RelativeLayout(this);
    mTextPane.setVisibility(View.GONE);
    //mScroll.setVisibility(View.GONE);

    mScroll.addView(mTextView);
    mTextPane.addView(mScroll);

    Resources res = getResources();
    Drawable drawable = res.getDrawable(R.drawable.text_pane_feather2);
    mTextPane.setBackgroundDrawable(drawable);

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( 420, 420 );
    //mBackground.setImageBitmap(R.drawable.text_pane);
    lp.setMargins(0,0,0,30);
    lp.addRule(RelativeLayout.CENTER_HORIZONTAL );
    lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

    layout.addView(mTextPane, lp);


text:
Q: How to define format of nested lists while dumping to yaml I would like to dump a nested Python list into a yaml file so that the list appears in one line:
Example:
import sys
import yaml

d = {'list1': [[1, 2], [3, 4]],
     'list2': [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]}
yaml.dump(d, sys.stdout)

Desired output:
list1: [[1, 2], [3, 4]]
list2: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

Actual output:
list1:
- - 1
  - 2
- - 3
  - 4
list2:
- - - 1
    - 2
  - - 3
    - 4
- - - 5
    - 6
  - - 7
    - 8

What I tried so far was the default_flow_style option:
yaml.dump(d, sys.stdout, default_flow_style=None)

resulting however in only the most nested lists being dumped into the same line:
list1:
- [1, 2]
- [3, 4]
list2:
- - [1, 2]
  - [3, 4]
- - [5, 6]
  - [7, 8]

Any hints?


text:
Q: Using Reflection to Count Methods. I have to write a function
public static int[] countGettersandSetters (String classname)

to count the number of get and set methods and return as an array where index 0 are sets and index 1 are gets.
Can anyone give me a high level approach to how to solve this problem?

A: public static int[] countGettersandSetters (String className)
    int[] count = new int[2];
    Method[] methods = Class.forName(className).getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().startsWith("set")) {
            count[0]++;
        } else if (method.getName().startsWith("get") ||
                   method.getName().startsWith("is")) { // to incl. boolean properties
            count[1]++;
        }
    }
    return count;
}

For a concise tutorial on Reflection API take a look here.

A: public static int[] countGettersandSetters(String c) throws ClassNotFoundException {
    int[] count = new int[2];
    Class<?> classs = Class.forName(c);
    Field[] fields = classs.getDeclaredFields();
    for (Field field : fields) {
        String name = field.getName();
        try {
            classs.getMethod("set"+name.substring(0, 1).toUpperCase()+name.substring(1) , null);
            count[0]++;
        } catch (NoSuchMethodException e) {
        }
        try {
            classs.getMethod("get"+name.substring(0, 1).toUpperCase()+name.substring(1), field.getType());
            count[1]++;
        } catch (NoSuchMethodException e) {
        }
    }
    return count;
}

A: Considering the standard naming convention, check that there exists a method with "get" or "set" prefixed to the name of a field of the class:
public static int[] count(Class<? extends Object> c) {
    int[] counts = new int[2];

    Field[] fields = c.getDeclaredFields();
    Method[] methods = c.getDeclaredMethods();

    Set<String> fieldNames = new HashSet<String>();
    List<String> methodNames = new ArrayList<String>();

    for (Field f : fields){
        fieldNames.add(f.getName().toLowerCase());
    }

    for (Method m : methods){
        methodNames.add(m.getName().toLowerCase());
    }

    for (String name : methodNames){
        if(name.startsWith("get") && fieldNames.contains(name.substring(3))){
            counts[0]++;
        }else if(name.startsWith("set") && fieldNames.contains(name.substring(3))){
            counts[1]++;
        }
    }

    return counts;
}

If you want to get all inherited getters/setters as well, replace getDeclaredFields() and getDeclaredMethods() with getFields() and getMethods().


text:
Q: Changing varactor capacitance based on different frequencies I am working on a project that uses a varactor diode in a VCO to output a certain frequency. As I understand it, changing the voltage amplitude changes the capacitance of the varactor diode. The input, however, is supposed to be varying frequencies and not varying amplitudes.
Is there a quick way to change the varactor capacitance based of different frequencies? If not, is there a way to change amplitude based on different frequencies?
Also let me know if my understanding of varactors is lacking and the circuit works with varying frequencies already. It was hard to make a SPICE model of the circuit due to the lack of varactor models, so I simulated the circuit with changing capacitance, which works.

The changed values of R, L, and Cs are to suit my purpose.

A:
I am working on a project that uses varactor diode in VCO to output certain frequency.

The VCO frequency depends mostly on the capacitance of C2, C1 and L1, with some influence from C3 and C4, and a smaller influence from the parasitics of Q1 and the other components round it.

As I understand changing the voltage amplitude changes the capacitance of the varactor diode.

Amplitude of what voltage? Amplitude of the output RF voltage, yes, a little, but that's a second order effect. Amplitude of the tuning voltage V-varicap? Yes, but we don't normally describe a DC voltage as having an 'amplitude'.
I notice you are driving V-varicap from an AC source. If you are expecting this input to frequency modulate the VCO, then the AC modulation source should be in series with a DC bias source. For instance, V-varicap might swing between 1.0 V and 2.0 V, being 1.5 V on average. You could make this with a DC bias of 1.5 V, added to an AC modulation source of 0.5 V peak amplitude.
To first order, the bias component controls the average, or centre, frequency.
The amplitude of the modulation component of V-varicap controls the frequency deviation away from the centre frequency.
As the voltage -> capacitance -> frequency tuning curve of the varactor+VCO is non-linear, then to second order, the amplitude of the modulation voltage does alter the average frequency a little.

The input however is supposed to be varying frequencies and not varying amplitudes. Is there a quick way to change the varactor capacitance based of different frequencies? If not is there a way to change amplitude based on different frequencies?

I have no idea what this means, or what you are asking.

Also let me know if my understanding of varactors is lacking and the circuit works with varying frequencies already.

It sounds like your understanding of varactors and oscillators is lacking.

It was hard to make a spice model of the circuit due to the lack of varactor models so I simulated the circuit with changing capacitance which works.

Modelling a varactor as a constant value capacitor, whose value can be changed as a function of the V-varicap, will give you an excellent first order model.


text:
Q: Resizing React component that holds SVG (d3) I have following component structure in simple react app
<div id='app'>
 <Navbar />
 <Graph />
 <Footer />
</div>

Navbar has fixed height 80px
Footer has fixed height 40px
Graph is a d3-wrapper div that contains SVG with graph elements.

*

*How to fit Graph into the remaining height of the screen so it always occupies the remaining height the screen?

*How to update react component containing d3-wrapper/SVG on resize event?
PS. As I want the graph to be responsive I should not hardcode width and height of the SVG.
Here is codepen snippet where I tried to solve this issue.

A: Ok so I have found solution for this.
The shortest way is to leave majority of work to css:
.d3-wrapper {
  width: 100%;
  height: calc(100vh - #{$footerHeight + $navbarHeight});
}

svg {
 width: 100%;
 height: 100%;
}

Then in d3-wrapper component, if needed, create ref to the div
and pass clientWidth and clientHeight to svg component as props.
For on resize update, add resize listener and make svg component update itself.


text:
Q: Check if a table item doesn't exist. How to check returned 'Items' array if empty? Javascript/DynamoDB I am trying to see if an item exists in the DynamoDB database. However I can't find a straight forward answer. So I am using the getItem() operation.
This returns a JSON. In the documentation it says that the Item returned should be empty if no item was found in the database. However, I can't seem to figure out how to check if this returned value is empty. I have tried variations of if(data == "undefined"){
//PutItem - DynamoDB table: check if group exists
                var dynamodb5 = new AWS.DynamoDB({ region: AWS.config.region });
                var identityId = AWS.config.credentials.identityId;
                var params = {
                      Key: {
                       "groupName": {
                         S: groupname
                        }
                      },
                      TableName: "group"
                     };
                dynamodb5.getItem(params, function(err, data) {
                if (err){
                    console.log(err, err.stack); // an error occurred
                     alert("This group doesnt exist.")
                }else{
                   // successful response console.log(data);

                    if(data.Items[0] == "undefined"){
                        console.log("ITS WORKING");
                    }

}

A: The getItem response doesn't include Items, it includes Item (see the documentation). It will return one item, if there is an item with the given key, or no item.
You can detect this as follows:
const AWS = require('aws-sdk');

const ddb = new AWS.DynamoDB({ region: 'us-east-1' });

const params = {
  Key: {
    'groupName': {
      S: groupname,
    },
  },
  TableName: 'group',
};

ddb.getItem(params, (err, data) => {
  if (err) {
    console.log(err, err.stack);
  } else if (data.Item) {
    console.log(JSON.stringify(data));
  } else {
    console.log('Success, but no item');
  }
});

Minor note: there's little reason to use var now that we have let and const.

A: Two things to add:
Item is for GetItem, Items is for Query.
Also AWS documentation mentions ResourceNotFoundException "for the operation that tried to access a nonexistent table or index". To avoid the confusion:

*

*Getting a non-existing item will return undefined on the Item

*Trying to get something from non-existing table or non-existing index will cause that error. For example you mistype the table name or the primary index.


text:
Q: How can I get the real size of image from the cropped image? I crop the image with 600x600 pixels but when I get it to bitmap like this
if(requestCode==PIC_CROP&&resultCode == Activity.RESULT_OK)
    {

    Bundle extras = intent.getExtras();
    //get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");
    //retrieve a reference to the ImageView
    }

my bitmap height and width are 300x300 pixels , why they are like that?
my crop method:
Intent cropIntent = new Intent("com.android.camera.action.CROP");
    //indicate image type and Uri
    cropIntent.setDataAndType(outputFileUri, "image/*");
    //set crop properties
    cropIntent.putExtra("crop", "true");
    //indicate aspect of desired crop
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1);
    //indicate output X and Y
    cropIntent.putExtra("outputX", 600);
    cropIntent.putExtra("outputY", 600);
    //retrieve data on return
    cropIntent.putExtra("return-data", true);
    //start the activity - we handle returning in onActivityResult
    startActivityForResult(cropIntent, PIC_CROP);

and my activity result:
if(requestCode==PIC_CROP&&resultCode == Activity.RESULT_OK)
    {

    Bundle extras = intent.getExtras();
    //get the cropped bitmap
    Bitmap thePic = extras.getParcelable("data");
    //retrieve a reference to the ImageView

    sourceFileUri="example.jpg";

    FileOutputStream out = null;
    try {
           out = new FileOutputStream(sourceFileUri);
           thePic.compress(Bitmap.CompressFormat.JPEG, 100, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
           try{
               out.close();
           } catch(Throwable ignore) {}
    }
        }

and I check the size like this:
Bitmap  photo_Share = null ;
        try {
            photo_Share= BitmapFactory.decodeFile(sourceFileUri,options);
        } catch (Exception e) {

        }

        int imageHeight = photo_Share.getHeight();
        int imageWidth = photo_Share.getWidth();

But when I look in the gallery I see the my cropped image 600x600 but when I look it code (my purpose save it another place it is 300x300)
How can find the image with real size?


text:
Q: How can i make an RFM Table In Flutter I'm working on a crm system and need an RFM table. I haven't seen anything like this before and I don't know how to do it. I didn't come across anything like this when I was researching packages. How can I do it?
Does anyone can help?


text:
Q: How to fix video and audio out-of-sync (sometimes)? I have a avi video file which plays perfectly on Linux (using e.g. mplayer) and on one TV, but when using another TV the audio happens to be out-of-sync with the video by about 5 seconds! This does not happen to every video file on that TV, but turning the TV off and on again does not solve this problem.
Could this problem be solved by using a different video format/container, or by re-encoding all video files? Is there some video format/container known to have hardware/OS dependant issues like the ones I reported?


text:
Q: How to brush up on calculus? It's been years since I took calculus, and while I have a good understanding of the theorems of single variable calculus from my real analysis courses, computationally I am a bit slow. It takes me longer than it should to compute basic derivatives and integrals, and I don't really remember how to do all the standard problems from differential/integral calculus (related rates, volume of a solid of revolution, etc.). I can typically derive the needed solution if necessary but I'd like to start doing some private tutoring and so I'd need to be able to explain the problems at a level the students would understand.
Also, I have some gaps in my knowledge of multivariable calculus, as I took it seven years ago and have not used much of it since then. In particular I don't remember anything about line integrals, surface integrals, Green's theorem, flux, divergence, etc.
What are some good books/references I can use to brush up on this material? As far as my background, I have a master's degree in a math-related field and took PhD level courses in real analysis, operator theory, probability theory, and stochastic processes, so I would like to be proving the theorems as I go along. But I also need to do plenty of example problems like you would see in an undergraduate calculus sequence so I can be quick at solving them.

A: What you are telling is that you probably forget almost all the advanced undergraduate materials in both algebra and analysis. You have a big gap to fill at this point. You could restart your learning by reading an intro to analysis book along with algebra or linear algebra. I guess that your algebra and linear algebra core knowledge content is long gone. I also propose that you make time to attend a lecture in either of these courses at a university so you can pose questions and get immediate live answer back. Don't try to learn on your own.
There is an old saying that you could liken it to an adage: " a teacher should not give too much wisdom to his students ". I agreed. But in this case, I am willing to go the extra mile.....
Again, base on your inputs, you need to find an advisor who can tell you what to do to get your terminal degree in the shortest possible time frame...

A: Khan Academy has topics in calculus (videos and problem engines).
It also has everything leading up to calculus (algebra, trig, etc.) in a similar format.
Oh, and it's free.


text:
Q: What kind of task will be done with the following code? What kind of task will be done with the following code ?
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
    int n, m;
    cin>>n;
    m = 0;
    while (n > 0)
    {
        m = m * 10 + n % 10;
        n = n / 10;
    }
    cout<<m;
}

A: The program builds a new number reversing the order of decimal digits of the entered number. For example if 123 was entered then the result will be 321.
By the way why do not to compile it and see the result?:)

A: So simple it is.
Why do not you compile it and see the result?
521 -> 125
789998122 -> 221899987
reverse order of the integer inputted.


text:
Q: How to track the model Progress/status when Sagemaker Kernel is dead? While training a model on AWS Sagemaker(let us assume training takes 15 hours or more). If our laptop lose internet connection in between, the Kernal on which it is training will die. But the model continues to train (I confirmed this with model.save command, and the model did save in the s3 bucket).
I want to know if there is a way, to track the status/progress of our model training when Kernel dies at Sagemaker environment.
Note: I know we can create a training job under Training - Training Jobs - Create Training Jobs. I just wanted to know if there is any other approach to track if we are not creating the Training Job.

A: Could you specify the 'Job Name' of the sagemaker training job? You can get the status using an API call if you have the job name. https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DescribeTrainingJob.html
Another note: you can specify the job name of a training job using the 'TrainingJobName' parameter of training requests: https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateTrainingJob.html

A: Simply check of status
When you run a training job, a log tracker is automatically created in CloudWatch within the "/aws/sagemaker/TrainingJobs" group with the name of your job and in turn one or more sub-logs, based on the number of instances selected.
This already ensures you can track the status of the job even if the kernel dies or if you simply turn off the notebook instance.
Monitor metrics
For sagemaker's built-in algorithms, no configuration action is required since the monitorable metrics are already prepared.
Custom model
On custom models, on the other hand, to have a monitoring graph of metrics, you can configure the log group related to them in CloudWatch (Metrics) as the official documentation explains. at "Monitor and Analyze Training Jobs Using Amazon CloudWatch Metrics" and "Define Metrics".
Basically, you just need to add the parameter metric_definitions to your Estimator (or a subclass of it):
metric_definitions=[
   {'Name': 'train:error', 'Regex': 'Train_error=(.*?);'},
   {'Name': 'validation:error', 'Regex': 'Valid_error=(.*?);'}
]

this will capture from the print/logger output of your training script the text identified by the regexes you set (which you can clearly change to your liking) and create a tracking within cloudwatch metrics.

A complete code example from doc:
import sagemaker
from sagemaker.estimator import Estimator

estimator = Estimator(
    image_uri="your-own-image-uri",
    role=sagemaker.get_execution_role(),
    sagemaker_session=sagemaker.Session(),
    instance_count=1,
    instance_type='ml.c4.xlarge',
    metric_definitions=[
       {'Name': 'train:error', 'Regex': 'Train_error=(.*?);'},
       {'Name': 'validation:error', 'Regex': 'Valid_error=(.*?);'}
    ]
)


text:
Q: Nested cursor performance tuning I have 2 cursors , one to fetch records from a table of 50 columns and 10,000 + data and another to check if a particular column exists in another big table (2 million data). I should write to a file all the records from cursor 1 for a year , if that column exists in cursor 2 then i should print an error message as exists and not delete them . If it does not exist then i should delete the row and write it to the same file and message as record deleted.
I used a nested cursor , the performance is too bad as it is processing each row from cursor 1 against cursor 2 , every time .
       CURSOR cursor1
         IS
             select a.* ,a.rowid
              FROM table1 a
              WHERE a.table1.year = p_year;

    CURSOR check_c2(lv_cd )
     IS
      Select DISTINCT 'Y'
       from table2
       where table2 ='R'
       AND table2.year= p_year
       and table2_code= lv_cd ;

BEGIN :
   FOR r in cursor1 LOOP
            EXIT WHEN cursor1%NOTFOUND;

              OPEN check_c2(r.cd);
              FETCH check_c2 INTO lv_check;
                IF check_c2%NOTFOUND THEN
                    lv_check :='N';
                END IF;
                CLOSE check_c2;

                  IF lv_check ='Y' THEN
                   lv_msg =(r.col1,r.col2....r.col50, R code exists do not delete)
                   utl_file.put_line(lv_log_file, lv_msg, autoflush=>TRUE);

                ELSE
                  DELETE from table1 where rowid= r.rowid
                  lv_msg =(r.col1,r.col2....r.col50, delete row)
                   utl_file.put_line(lv_log_file, lv_msg, autoflush=>TRUE);
                   END IF;
                   END LOOP;

A: Don't have enough reputation to write comments som will write as an answer.
Didn't you try to add some time marks to understand which parts are the most time spending?
Does table2 have index by year and code? What's the explain plan of cursor2 query? If yes - how many rows are there average for year+code combination?
If the amount of data selected overall from table 2 is huge - then it probably can be faster to do a single query with full scan/index range scan by year on table2, grouping and hash left outer join from table1 to table2 like
select a.*, a.rowid, nvl2(c.code, 'Y', 'N') check_col
from table1 a,
(
    select distinct code
    from table2 b
    where b.year = p_year
) c
where a.year = p_year
  and c.code(+) = a.cd

A: How about this? A 3-steps-operation:
Step 1: "save" rows you'll later delete
create table log_table as
select *
from table1 a
where exists (select null
              from table2 b
              where b.year = a.year
                and b.code = a.code
             );

Step 2: delete rows:
delete from table1 a
where exists (select null
              from table2 b
              where b.year = a.year
                and b.code = a.code
             );

Step 3: if you must, store rows saved in the LOG_TABLE into that file of yours. If not, leave them in LOG_TABLE.

A: utl_file.put_line in the loop will be an overhead.Try appending to lv_msg till length  of the string is 32767 bytes and write just once.
This will definitely reduce the I/O and performance should be improved.