text:
Q: Debian 10 does not recognize HDMI and problems to switch to Nvidia Hi I'm having to many problems to connect a Samsung HDMI monitor to my Laptop with Debian GNU/Linux 10 (buster) I've already done reasearch but nothing seems to work.
These are my outputs to some commands
lspci -nn | egrep -i "3d|display|vga"
00:02.0 VGA compatible controller [0300]: Intel Corporation UHD Graphics 630 (Mobile) [8086:3e9b]
01:00.0 VGA compatible controller [0300]: NVIDIA Corporation GP107M [GeForce GTX 1050 Mobile] [10de:1c8d] (rev a1)

xrandar
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 344mm x 193mm
   1920x1080     60.01 +  60.01*   59.97    59.96    59.93    40.00
   1680x1050     59.95    59.88
   1600x1024     60.17
   1400x1050     59.98
   1600x900      59.99    59.94    59.95    59.82
   1280x1024     60.02
   1440x900      59.89
   1400x900      59.96    59.88
   1280x960      60.00
   1440x810      60.00    59.97
   1368x768      59.88    59.85
   1360x768      59.80    59.96
   1280x800      59.99    59.97    59.81    59.91
   1152x864      60.00
   1280x720      60.00    59.99    59.86    59.74
   1024x768      60.04    60.00
   960x720       60.00
   928x696       60.05
   896x672       60.01
   1024x576      59.95    59.96    59.90    59.82
   960x600       59.93    60.00
   960x540       59.96    59.99    59.63    59.82
   800x600       60.00    60.32    56.25
   840x525       60.01    59.88
   864x486       59.92    59.57
   800x512       60.17
   700x525       59.98
   800x450       59.95    59.82
   640x512       60.02
   720x450       59.89
   700x450       59.96    59.88
   640x480       60.00    59.94
   720x405       59.51    58.99
   684x384       59.88    59.85
   680x384       59.80    59.96
   640x400       59.88    59.98
   576x432       60.06
   640x360       59.86    59.83    59.84    59.32
   512x384       60.00
   512x288       60.00    59.92
   480x270       59.63    59.82
   400x300       60.32    56.34
   432x243       59.92    59.57
   320x240       60.05
   360x202       59.51    59.13
   320x180       59.84    59.32
DP-1 disconnected (normal left inverted right x axis y axis)
HDMI-1 disconnected (normal left inverted right x axis y axis)

nvidia-settings
ERROR: Unable to load info from any available system

xrandr --listproviders
Providers: number : 1
Provider 0: id: 0x45 cap: 0xf, Source Output, Sink Output, Source Offload, Sink Offload crtcs: 3 outputs: 3 associated providers: 0 name:modesetting

I'm new to Debian and Linux/Unix.
I tried to follow the instructions based on the answer on this question: Debian 10 [Buster]: HDMI Input Not detected but it still without working
Can someone help or explain what should I do?

A: Install nvidia drivers: use
nouveau.modeset=0.

In grub To use nvidia drivers


text:
Q: OpenCover shows 100% coverage with no valid tests To a visual studio solution with 6 projects (class libraries & wcf services) I add a new Test project with one test, with just one line Assert.AreEqual(1,1). OpenCover shows a 100% coverage (100% Sequence and 100% Branch).
OpenCover.Console.exe -target:"nunit3-console.exe" "-targetargs:Services.nunit" -register:user -skipautoprops -mergebyhash

Only when I instantiated a class from the other projects in the test the coverage dropped to 0.1 %.
So looks like if a dll is not loaded, OpenCover cannot calculate its code coverage.
Now the question is if a new class library is added and it is never instantiated in a unit test, Will OpenCover just ignore the dll while calculating the coverage metrics.
This is important because we have a distributed team and a developer might just create a class library and never write tests for it. It does eventually show up in code reviews, but can OpenCover be configured to detect this situation.

A:
So looks like if a dll is not loaded, OpenCover cannot calculate its code coverage.

This is expected behaviour

Now the question is if a new class library is added and it is never instantiated in a unit test, Will OpenCover just ignore the dll while calculating the coverage metrics.

It doesn't ignore it, the runtime doesn't load the assembly and so OpenCover does not see it.

It does eventually show up in code reviews, but can OpenCover be configured to detect this situation.

Not as it stands but you could write a test that tries to load every .dll in its folder. This will cause it to load and OpenCover will see it (assuming the pdb s available and the filters allow it etc etc)

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSF datascroller problem As a requirement i have two datatables for the same List. Can I use one datascroller to control both the tables. Please help me on solving this.

A: This could be solved easily in HTML but not in JSF; In JSF the two lists are completely separate things. My guess is that you must look at the source code of the JSF list implementation and create your own UI component from that. Create one which creates the list without the scrollbar and then wrap those in a kind of "scrolled area" (i.e. a DIV that has the correct overflow style).


text:
Q: How to obtain boostrap estimates for multiple parameters I want to create a function using boostrap to estimates mean and median on multiple parameters. I have been able to generate for a single parameter, but the multiple seems I would need to get a loop that will be able to loop through and return the mean and meadian for me. The code is for single;
def get_boostrap_estimates_single_param(sample_size):
    """
    Generate a bootstrap sample but harcode df within the function
    so that we can use Pool.map() later
    :param sample_size: how many rows to sample from the input dataframe
    :returns mean and median of this particular bootstrap sample
    """

    # Load the age.csv file into a dataframe here
    dataPath = '/home/faustus/Documents/Review Courses/Big Data Analysis/age.csv'
    age = pd.read_csv(dataPath, index_col = False)

    # shuffle the dataframe by using pd.DataFrame.sample() with
    # n = df.size
    df = pd.DataFrame.sample(age, n = age.size)

    # Get bootstrap sample with replacement
    df_sample = df.sample(sample_size, replace = True)

    # return mean and median
    return df_sample.mean(), df_sample.median()

Output:
get_boostrap_estimates_single_param(2000)
(age    23.057
 dtype: float64,
 age    19.0
 dtype: float64)

Now I want to get for multiple parameters, but instead of hard-coding the dataframe, I want to pass it as an argument using the fuction;
def get_boostrap_estimates_multiple_params(df, sample_size):
    """
    Generate a bootstrap sample
    :param df: input dataframe
    :param sample_size: how many rows to sample from the input dataframe
    :returns mean and median of this particular bootstrap sample
    """

How can I solve this problem?


text:
Q: nginx try_files with static image or fallback to php file with rewrite location /image_mini {
#  try_files /static_images/$2.jpg;
  rewrite ^/image_mini/([^.]+)-00([0-9]+)\.jpg$ /image.php?a=$2 last;
}

I use this rewrite rule to display images on my website. For example, if I want to display Image ID #123456789, I would use https://www.example.com/image_mini/some_cool_seo_keywords-00123456789.jpg
Then, image.php will check if /static_images/00123456789.jpg is found in local cache, if not it will create the file.
I assume I would get much better performance if nginx could look for the local static file before fallback to image.php
I tried doing this with try_files but I am unsure how to extract the image ID from the URL and i'm stuck here :( Any help would be appreciated

A: You can use your regular expression in the location statement. For example:
location ~* ^/image_mini/[^.]+-00([0-9]+)\.jpg$ {
    try_files /static_images/$1.jpg /image.php?a=$1;
}

Note that the evaluation of regular expression location statements is ordered. See this document for more. Also, this document on the correct syntax for try_files.


text:
Q: How to setting values in mysql trigger This is mysql query and I want to set avg into variable, and mb.HELP is getting null sometimes and i want to close this ticks. if its null divide 3, when its not, divide 4. Also set value to other column by this value, but query getting syntax error its like ;

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 'IF mb.Dynamic_Help  IS NULL THEN
          SET @newavg := (mb.Dynamic_Delivery_Sp' at line 6

query;
CREATE TRIGGER computeColor
AFTER INSERT ON merchant_rates
FOR EACH ROW

   UPDATE merchant_branches as mb
    IF mb.Dynamic_Help  IS NULL THEN
        SET @newavg := (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3
     ELSE
        SET @newavg := (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4
    END IF;

CASE
    WHEN @newavg >= 9   THEN  mb.Dynamic_Rank_Color = "#FFD300"
   WHEN @newavg >= 8,5  AND @newavg < 9     THEN  mb.Dynamic_Rank_Color = "#FFD300"
   WHEN @newavg >= 8    AND @newavg < 8,5   THEN  mb.Dynamic_Rank_Color = "#FFD320"
   WHEN @newavg >= 7,5  AND @newavg < 8     THEN  mb.Dynamic_Rank_Color = "#FAD300"
   WHEN @newavg >= 7    AND @newavg < 7,5   THEN  mb.Dynamic_Rank_Color = "#CCD300"
   WHEN @newavg >= 6,5  AND @newavg < 7     THEN  mb.Dynamic_Rank_Color = "#FED300"
END
    WHERE mb.id = NEW.Branch_ID

A: You can manipulate your update clause to -
UPDATE merchant_branches as mb
    SET mb.Dynamic_Rank_Color = CASE
                                WHEN mb.Dynamic_Help IS NOT NULL
                                THEN
                                    CASE
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4 >= 9 THEN "#FFD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4 BETWEEN 9 AND 8.5 THEN "#FFD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4 BETWEEN 8.5 AND 8 THEN "#FFD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4 BETWEEN 8 AND 7.5 THEN "#FAD320"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4 BETWEEN 7.5 AND 7 THEN "#CCD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service+mb.Dynamic_Help)/4 BETWEEN 7 AND 6.5 THEN "#FED300"
                                    END
                                WHEN mb.Dynamic_Help IS NULL
                                THEN
                                    CASE
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3 >= 9 THEN "#FFD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3 BETWEEN 9 AND 8.5 THEN "#FFD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3 BETWEEN 8.5 AND 8 THEN "#FFD320"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3 BETWEEN 8 AND 7.5 THEN "#FAD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3 BETWEEN 7.5 AND 7 THEN "#CCD300"
                                    WHEN (mb.Dynamic_Delivery_Speed + mb.Dynamic_Flavor + mb.Dynamic_Service)/3 BETWEEN 7 AND 6.5 THEN "#FED300"
                                    END
                                END
    WHERE mb.id = NEW.Branch_ID


text:
Q: How can I access list values in a WFFM list field? I'm trying to make a poll results page with the results from a WFFM form. I initially took all the entered data(using AnalyticsFormsDataProvider), queried it, and then displayed the results. However, if no one votes for a particular answer, it wouldn't be in the entered data so it wouldn't show.
I want to display that the field had 0 votes, so now I'm trying to compare the possible answers to the queried list. However, I can't seem to find a way to access the values of the list items. Does anyone know the class those values are stored in and/or how to access them?
I'm using WFFM 8.1 rev. 151217 (Update-1) with MVC. It's a radio list field if that makes a difference from the other list fields.
Thanks,

A: You are able to get WFFM field as regular Sitecore item via standard API.
Available list items values are saved in "Parameters" and "Localized Parameters" fields. You can use Sitecore.Form.Core.Utility.ParametersUtil from Sitecore.Forms.Core to parse values saved in these fields.

A: This data is stored on your Radio List Field's Item in the fields Parameters and Localized Parameters.
If your code is within the Form's SaveAction or a Validator you will have access to the Field in the for AdaptedResultList args the SaveAction or via this.classAttributes["fieldid"] for the Validator. That will be enough for you to get the Radio List Item and then the Parameter fields.
If your code is not in a SaveAction / Validator I recommend passing the Form Item into your code possibly by Datasource and then retrieving the Radio List Item from that.
Finally the Items of the your Radio List field is stored in the format
<item><item>

If your radio items are actually items you will want to parse them using a regex
var regexItems = new Regex(@"<item>(.*?)</item>".ToLower());
var itemNodes = regexItems.Matches(FieldItem["Parameters"].ToLower());

Then you should be free to play with the list for your poll


text:
Q: How to implement Update Mechanism in MySql? My Use Case :
I am trying to create a GUI and implement it with MYSQL Database. The problem I am facing is the scenario when I have to update a certain entry in the Database.
I know that we can update an Entry in MYSQL database using :
ALTER TABLE <TABLENAME> SET <PARAMETERS=NEW VALUES> WHERE <CONDITION> ;
For eg : If I want to change the name of the guy who id is 2 , I have to write :
ALTER TABLE StudentInfo SET Name='ABC' WHERE id=2 ;
But the problem is , in a GUI based environment , a user can choose to update any particular value wihtout having a constant condition like id in the previous example.

In the UI , the user can opt to select anything from the parameters and modify it and then click the update button.
Now How will I figure out what <CONDITION> to put in the MYSQL query when I need to update the database ?
Any help would be greatly appreciated !

A: you update a by using the UPDATE command not ALTER, which will change table. Your gui already knows ho tow identify the row in your case for example by the column name
UPDATE StudentInfo SET Name='ABC' WHERE Name='QUERTY';

SEE example

CREATE TABLE StudentInfo(

    Name VARCHAR(20),
    class int,
    section VARCHAR(2),
    roll_no int
);
INSERT INTO StudentInfo VALUES ('abc',12,'A',18), ('xyz',12,'A',17),('QUERTY',12,'A',16)

UPDATE  StudentInfo SET Name='ABC',class = 15,section = 'B',roll_no= 99 WHERE Name='QUERTY';

SELECT * FROM StudentInfo

Name | class | section | roll_no
:--- | ----: | :------ | ------:
abc  |    12 | A       |      18
xyz  |    12 | A       |      17
ABC  |    15 | B       |      99

db<>fiddle here
The main problem is to identify the correct row, so you should have a field that is unique.
Like an id auto_increment, that is invisible for the user, but you can identify every row and use this id to update the row.
 UPDATE StudentInfo SET Name='ABC' WHERE id = 3;

So that if you have two rows with John Smith you still could update the right one


text:
Q: Outgoing CALL_STATE How can I access the current status of an outgoing call (dialing, active, etc.)?
In my application I want it that all the LEDs on the device are inactive for the duration of the "call-active status", but during the "dialing status" and after the call is ended the LEDs should be on. I need to read out (or capture) the status - but how?
I have already read that one can not question the CALL_STATE_OFFHOOK.
Is it possible to infer the status via the GUI (phone screens)?
Or is there another possibility?
I know that this is not a new topic but I´m only looking for the "dialing/active/disconnected" statuses - the rest (holding, alerting, incoming,...) don´t matter.
If the gui changes there must be a possibility to read that "changing behaviour out" and use it .... or am I too naive?

A: You can use AudioManager to get the current audio state, effectively seeing if you are currently in a call or not.
mAudioManager.getMode() == AudioManager.MODE_IN_CALL

if that returns true, then your user is in a call, otherwise they aren't. I know this isn't a full solution to your problem, but it might help if other things are not possible.


text:
Q: Durable Functions to Unzip Blob storage file and copy the files to another blobStorage I have a Az function using implementation similar to this
https://github.com/FBoucher/AzUnzipEverything/blob/master/Unzipthis.cs
I have BLOB trigger when a zip file is dropped. Az function Unzips it and copies the files to a new AZ blob location. I get zip files with thousands of files inside it, so the copy process takes a very long time using foreach loop.
i tried using Parallel for each Async https://github.com/Dasync/AsyncEnumerable that only works when running locally, when deployed it does not seems to work at all, no errors nothing, but nothing happens.
I want to try this Durable functions instead like in example below where each file copy is done by a another activity function. This will help speed up the process by having separate task for copy job, but problem is how do i pass the file to be copied to another blob location in Activity function?
https://github.com/Azure/azure-functions-durable-extension/blob/master/samples/precompiled/BackupSiteContent.cs

A: My suggestion is that after triggering the condition, first copy the .zip file directly to the new blob, and then decompress it. Because I think the direct decompression and transfer speed will be very slow, similar to copying data from a computer in a USB flash drive.
You can refer to this post to copy the .zip file. You also can see my code in github. When copy finished, you can find the file and unzip it. You can see rGiosa's answer in this post . It will help you.


text:
Q: JS crashes sometimes with Timer scramble My Javascript timer is for people with a rubiks cube with generates a scramble (nevermind all this, but just to tell you I'm generating after each solve a new scramble will be generated) and my scrambles do actually have a while (true) statement. So that does crash my script, but it 95/100 times stops just before the script crashes but I don't wanna have any times.
Let me explain a bit more detailed about the problem.
Problem: javascript crashes because my script takes too long to generate a scramble.
Below you have 3 functions I use.
This function generates a scramble with the Fisher-Yates shuffle.
Timer.prototype.generateScramble = function(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
};

This function validates the input e.g. I receive an array as the following:
Here I only have to check the first character. That's why I use the seconds [ ] notation. I don't want people get an F with an F2 e.g.
var scr = ["F","R","U","B","L","D","F2","R2","U2","B2","L2","D2","F'","R'","U'","B'","L'","D'"]

Timer.prototype.validateScramble2 = function(array) {
    var last = array.length-1;
    for (var i = 0; i < array.length-1; i++) {
        if (array[i][0] == array[i+1][0]) {
            return false;
        }
    }
    for (var i = 0; i < array.length-2; i++) {
        if (array[i][0] == array[i+2][0]) {
            return false;
        }
    }

    if (array[0][0] == [last][0]) {
        return false;
    }

    return true;
};

The above functions are just waiting to be called. Well in the function below I use them.
Timer.prototype.updateScramble2 = function(scrambleArr, len, type) {
    var self = this;
    var scramble = '', j, updatedArr = [];

    while (updatedArr.length < len) {
        j = (Math.floor(Math.random() * scrambleArr.length));
        updatedArr.push(scrambleArr[j]);
    }

    while (!self.validateScramble2(updatedArr)) {
        updatedArr = self.generateScramble(updatedArr);
    }

    for (var i = 0; i < updatedArr.length; i++) {
        scramble += updatedArr[i] + ' ';
    }

    scrambleDiv.innerHTML = scramble;
};

I assume you guys understand it but let me explain it briefly.
The first while-loop adds a random value from the given array(scrambleArr) into a new array called updatedArr.
The next while-loop calls the validateScramble2() function if there isn't in an array F next to an F2.
The for-loop adds them into a new variable added with a whitespace and then later we show the scramble in the div: scrambleDiv.innerHTML = scramble;
What do I need know after all this information?
Well I wanna know why my updateScramble2() functions lets my browser crash every time and what I do wrong and how I should do it.

A: I'm not entirely sure I understand the question, but from the way your code looks, I think you have an infinite loop going on. It appears as if validateScramble2 always returns false which causes your second loop in updateScramble2 to perpetually run.
I suggest you insert a breakpoint in your code and inspect the values. You could also insert debugger; statements in your code, works the same way. Open dev tools prior to doing these.

A suggestion is instead of using loops, use a timer. This breaks up your loop into asynchronous iterations rather than synchronous. This allows the browser breathing space for other operations. Here's an example of a forEachAsync:
function forEachAsync(array, callback){
  var i = 0;
  var timer = setInterval(function(){
    callback.call(null, array[i]);
    if(++i >= array.length) clearInterval(timer);
  }, 0);
}

forEachAsync([1,2,4], function(item){
  console.log(item);
});

You can take this further and use Promises instead of callbacks.


text:
Q: Duplicate elements when cleaning and re-applying bindings with child viewModels I have a viewModel containing child viewModels in an observableArray that is bound to some markup using a foreach binding.
Later in the page life cycle, I need to remove the old viewModel and apply a new one in its place. I do this by calling ko.cleanNode() and then calling applyBindings with the new view model.
For some reason when this happens, all of the child view models end up getting duplicated markup even though the parent observableArray has the correct number of viewModels in it.
I am sure I am just using some knockout functionality incorrectly, but I cannot figure out how to get it working.
Issue is replicated here: http://jsfiddle.net/a7xLxwxh/
Markup:

    RANGES

            START

            END

JS:
var ParentViewModel = function (data) {
    var self = this;

    self.ranges = ko.observableArray([]);

    data.Ranges.forEach(function (range) {
        self.ranges.push(new RangeViewModel(range));
    });
};

var RangeViewModel = function (data) {
    var self = this;

    self.start = ko.observable(moment(data.Start).format('MM/DD/YYYY'));
    self.end = ko.observable(moment(data.End).format('MM/DD/YYYY'));
};

var vm = new ParentViewModel({
    Ranges: [{
        Start: '/Date(1439438400000)/',
        End: '/Date(1439611200000)/'
    },
    {
        Start: '/Date(1439265600000)/',
        End: '/Date(1439352000000)/'
    }]
});

var element = $('.container')[0];
ko.applyBindings(vm, element);

ko.cleanNode(element);
ko.applyBindings(vm, element);

A:
Later in the page life cycle, I need to remove the old viewModel and
  apply a new one in its place.

The better way to replace the view-model is to make the view-model itself an observable:
var vm = ko.observable(new ParentViewModel(
{
    Ranges: [{
        Start: '/Date(1439438400000)/',
        End: '/Date(1439611200000)/'
    },
    {
        Start: '/Date(1439265600000)/',
        End: '/Date(1439352000000)/'
    }]
}));

ko.applyBindings(vm);

Then when you want to replace it:
vm(new ParentViewModel({
    Ranges: [{
        Start: '/Date(1439438400000)/',
        End: '/Date(1435611200000)/'
    }]
}));

See Fiddle

A: Use the with binding in order to swap out view models. cleanNode is an undocumented method.

    ...

http://jsfiddle.net/a7xLxwxh/3/


text:
Q: Dell XPS15 Ubuntu 18.04 ethernet not connecting I have recently installed Ubuntu 18 on my dell xps 15, to my surprise wifi is working perfectly but I cannot get wired ethernet to connect.
The output of lshw is:
sudo lshw -C network
  *-network
       description: Wireless interface
       product: QCA6174 802.11ac Wireless Network Adapter
       vendor: Qualcomm Atheros
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlp2s0
       version: 32
       serial: 9c:b6:d0:fc:1f:33
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=ath10k_pci driverversion=4.15.0-38-generic firmware=WLAN.RM.4.4.1-00079-QCARMSWPZ-1 ip=10.168.85.54 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:144 memory:ed200000-ed3fffff
  *-network
       description: Ethernet interface
       physical id: 2
       logical name: enx34298f9231a4
       serial: 34:29:8f:92:31:a4
       size: 1Gbit/s
       capacity: 1Gbit/s
       capabilities: ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8152 driverversion=v1.09.9 duplex=full link=yes multicast=yes port=MII speed=1Gbit/s

So I think the problem is that for the Ethernet interface no product is found!
As the dell XPS 15 does not have a ethernet port I am using a USB C adapter. The adapter is a 10-in-1 hub (https://www.amazon.com/gp/product/B07GDHD3VC/ref=s9_acsd_hps_bw_c_x_1_w) and the output of lsusb -v is posted here https://paste.ubuntu.com/p/TNnF7FSYby/
More diagnostic:
> lsmod | grep r8152
r8152                  61440  0
mii                    16384  2 usbnet,r8152

>  ifconfig
enx34298f9231a4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        ether 34:29:8f:92:31:a4  txqueuelen 1000  (Ethernet)
        RX packets 63  bytes 11158 (11.1 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 19788  bytes 37449974 (37.4 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 19788  bytes 37449974 (37.4 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.169.130.213  netmask 255.255.248.0  broadcast 10.169.135.255
        inet6 fe80::539a:877a:c301:4d3f  prefixlen 64  scopeid 0x20<link>
        ether 9c:b6:d0:fc:1f:33  txqueuelen 1000  (Ethernet)
        RX packets 1913953  bytes 2450518697 (2.4 GB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1090058  bytes 119134130 (119.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

> dmesg | grep enx34298f9231a4
[    8.784167] r8152 4-1.3.1:1.0 enx34298f9231a4: renamed from eth0
[   10.103739] IPv6: ADDRCONF(NETDEV_UP): enx34298f9231a4: link is not ready
[   10.109374] IPv6: ADDRCONF(NETDEV_UP): enx34298f9231a4: link is not ready
[   12.310544] r8152 4-1.3.1:1.0 enx34298f9231a4: carrier on
[   12.310558] IPv6: ADDRCONF(NETDEV_CHANGE): enx34298f9231a4: link becomes ready
[ 6455.709355] r8152 4-1.3.1:1.0 enx34298f9231a4: carrier off
[11793.133656] r8152 4-1.3.1:1.0 enx34298f9231a4: Stop submitting intr, status -71
[11836.892211] r8152 4-1.3.1:1.0 enx34298f9231a4: renamed from eth0
[11836.933975] IPv6: ADDRCONF(NETDEV_UP): enx34298f9231a4: link is not ready
[11836.938515] IPv6: ADDRCONF(NETDEV_UP): enx34298f9231a4: link is not ready
[11840.292564] r8152 4-1.3.1:1.0 enx34298f9231a4: carrier on
[11840.292591] IPv6: ADDRCONF(NETDEV_CHANGE): enx34298f9231a4: link becomes ready

Thank you!


text:
Q: My ImageView won't work in position which I set in my xml, but when is it top left corner it works finse.So how can I adjust position? I have problem with imageView, after I add layoutParams and set width and height my image goes in TOP LEFT corner after compiling it.How can I fix it...Thank you in andvance.
I'm new in android studio so I'am not sure if I was working everything properly for now and I was started making some small game and this happened.
Here is my XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintGuide_end="100dp"
android:background="@drawable/spacebackground"
tools:context=".MainActivity">

<ImageView
    android:id="@+id/plane"
    android:layout_width="wrap_content"
    android:layout_height="150dp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="119dp"
    android:layout_marginBottom="29dp"
    android:layout_x="116dp"
    android:layout_y="343dp"
    android:src="@drawable/warplane" />
  </RelativeLayout>

And here is my code
package com.example.marko.warmachine;

  public class MainActivity extends Activity {

//variable
private ViewGroup mainLayout;
private ImageView image;
private int xDelta;
private int yDelta;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mainLayout = (RelativeLayout) findViewById(R.id.main);
    image = (ImageView) findViewById(R.id.plane);

    plane.setOnTouchListener(onTouchListener());
}

private View.OnTouchListener onTouchListener() {
    return new View.OnTouchListener() {

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent event) {

            final int x = (int) event.getRawX();
            final int y = (int) event.getRawY();

            switch (event.getAction() & MotionEvent.ACTION_MASK) {

                case MotionEvent.ACTION_DOWN:
                    RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
                            view.getLayoutParams();

                    xDelta = x - lParams.leftMargin;
                    yDelta = y - lParams.topMargin;
                    break;

                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    break;
                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                            .getLayoutParams();
                    layoutParams.leftMargin = x - xDelta;
                    layoutParams.topMargin = y - yDelta;
                    layoutParams.rightMargin = 0;
                    layoutParams.bottomMargin = 0;
                    view.setLayoutParams(layoutParams);
                    break;
            }
            mainLayout.invalidate();
            return true;
        }
    };
}

I EDITET code so this is what I get but still not work.

A: You should not initialize layoutParams from scratch. Get a previously defined attributes from image view instance itself:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) image.getLayoutParams();


text:
Q: How to give a 'percent watched' of dailymotion player? I am developing a simple web application and I need to use Dailymotion player and upload the percentage watched each 5 seconds but I don't understand how to catch the percentage value with a event progress of this documentation: https://github.com/dailymotion/dailymotion-sdk-js
I found the next implementation: https://github.com/dailymotion/dailymotion-sdk-js/tree/master/tests. This implementation show video time in seconds but when user doing to click on the progress video bar.
Thank you


text:
Q: How can I change the font of section numbers such as \thechapter? I would like to change the font of the chapter and section numbers appearing in my titles. I found that I can change the number style from arabic to roman etc. but I couldn't find a way to change the font of the number itself.
When I tried changing the font of the chapter heading it changed only the heading title text and not the numbering. So I get "1.1" in times roman and "section name" in sans serif :/
I tried using sectsty, titlesec and renewing the \chapter command.
class definition is: \documentclass[twoside,12pt,a4paper,pointlessnumbers,headsepline,idxtotoc]{scrbook}
Any tips or advice would be great!

A: From the tagging, it seems that you are using KOMAscript and the class scrbook. Then you change the font either with  \setkomafont or \addtokomafont (see section 3.6, page 51 in the revised manual), and with the modifier chapterprefix. Try:
\setkomafont{chapterprefix}{\rmfamily\Large\bfseries}

or, to change to a serif typeface only:
\addtokomafont{chapterprefix}{\rmfamily}

To change all sectioning to the default Roman font, reverse all font changes you have done to chapter, and try
\addtokomafont{sectioning}{\rmfamily}

It seems from your comment that somebody has tampered with the definitions in your classfile. This minimal example works for me, giving me sans serif in heading and body text.
\documentclass[twoside,12pt,a4paper,pointlessnumbers,headsepline,idxtotoc]{scrbook}
\usepackage{fixltx2e}
\usepackage[UKenglish]{babel}
\usepackage{tgheros}
\renewcommand*\familydefault{\sfdefault}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{blindtext}

\begin{document}
\blinddocument
\end{document}

In your document, comment out (or delete) all usepackage{secsty} etc. that changes the headings. Or add packages and commands from you preamble to my code.
If you are going to use Helvetica as sans serif font, I suggest  using the Tex-Gyre version instead, by loading the package tgheros. I have changed my MWE correspondingly.

A: Here's a way you can change the number formatting:

\documentclass[twoside,12pt,a4paper,pointlessnumbers,headsepline,idxtotoc]{scrbook}
\makeatletter
\renewcommand*{\chapterformat}{% Chapter number formatting
  \mbox{\chapappifchapterprefix{\nobreakspace}{\normalfont\itshape\thechapter}\autodot\enskip}%
}
\renewcommand*{\@seccntformat}[1]{% Section number formatting
   \protect\othersectionlevelsformat{#1}{%
     \expandafter\aftergroup\noexpand\@gobble}{\normalfont\itshape\csname the#1\endcsname}%
}
\makeatother
\begin{document}
\chapter{A chapter}
\section{A section}
Here is some text
\subsection{A subsection}
\end{document}

Printing of the chapter and section numbers are done by \chapterformat and \@seccntformat, respectively. In the above MWE I've inserted \normalfont\itshape which you can change to your liking/preference. It should also be possible to do this a little cleaner using etoolbox.

A: Without knowing the class you are using, this is a very general answer. Here sectsty package is used. A MWE will be:
\documentclass{book}
\usepackage{sectsty}
\allsectionsfont{\sf}
\begin{document}
  \chapter{First chapter}
  This is first chapter
  \section{First section}
  First section and
  \subsection{Also first}
  First sub section
  \subsubsection{Again first}
  What do you think?
  \section{Second section}
  And here is second section.
  \chapter{Second chapter}
\end{document}


text:
Q: Write the following limit as a derivative and evaluate. Write the following limit as a derivative and evaluate.
$$\lim_{x\to \frac \pi4} {\tan(x)−1\over x−\frac \pi4}$$
the derivative $$f'(x)= \lim_{\Delta x\to 0} {f(x+\Delta x)−f(x)\over \Delta x}$$
I have seen similar problems here, but they not involved $\tan$ and it has confused me.
I'm not familiar with L'Hopital rule. Please do not suggest it.
Therefore, if $1= \tan (\frac \pi4)$ and if we set, $h = x - \frac \pi4$, hence $$\lim_{h\to 0} {\tan(\frac \pi4 +h)−\tan(\frac \pi4)\over h}$$
$$\tan(\frac \pi4 +h)= \frac{\tan(\frac\pi4)+\tan(h)} {1-\tan(\frac\pi4)\tan(h)}$$
so, $$\frac{\tan(\frac\pi4)+\tan(h)} {1-\tan(\frac\pi4)\tan(h)}-\tan(\frac\pi4)\over h$$
$$\frac{1+\tan(h)} {1-tan(h)}-1\over h$$
make it to the common denominator
we get $$2\tan(h)\over h(1-\tan(h))$$
what should I do next?
any help will be appreciated.
is there any other ways to evaluate?

A: You are very close. Use the hint to find
$$\lim_{h\to 0} {\tan(\frac \pi4 +h)−\tan(\frac \pi4)\over h}=\tan'(\frac\pi4).$$

A: Since $\displaystyle f^{\prime}(c)=\lim_{x\to c}\frac{f(x)-f(c)}{x-c}$, $\;\;$ letting $f(x)=\tan x$ gives
$\hspace{.88 in}\displaystyle\lim_{x\to\frac{\pi}{4}}\frac{\tan x-1}{x-\frac{\pi}{4}}=f^{\prime}\big(\frac{\pi}{4}\big)=\sec^2\frac{\pi}{4}=(\sqrt{2})^2=2$


text:
Q: How to convert a byte array into a string that preserves lowercase? im trying to convert a byte array from a hash function into a string, i used a bitconverter.tostring() at first but it just creates a string with all uppercase bytes separated by dashes
This is my basic method
public string Hash(string password)
    {
        using var hasher = SHA512.Create();
        {
            var asBytes = Encoding.Default.GetBytes(password);
            var hashed = hasher.ComputeHash(asBytes);
            string stringhashed = BitConverter.ToString(hashed);
            return stringhashed;
        }
    }

the output hashes correctly, however it gets formated into a string as BYTE-BYTE-BYTE-BYTE-BYTE....
while i needed the output to be a normal string, with lowercase and all.
Is there any way to convert a byte array into a string meeting these requirements?

A: Either use String.Replace() and String.ToLower() to modify the string output from BitConverter.ToString():
return stringhashed.Replace("-", "").ToLower();

... or implement your own stringification extension method:
public static class BitUtils {
    public static string ToHexString(this byte[] bytes)
    {
        StringBuilder sb = new StringBuilder(bytes.Length * 2);
        foreach(byte b in bytes)
        {
            // use the `x` format string to get lowercase hexadecimal
            sb.AppendFormat("{0:x2}", b);
        }

        return sb.ToString();
    }
}

So you can do:
return asBytes.ToHexString();


text:
Q: Copy a file every 60 seconds bash I have a thecus nas server, and they seem to do some tricky things to their templates to display their files, currently at boot I'm running a shell command to copy one file over another, so that It boots with my custom template, however after a certain amount of time (I'm not sure what this time is) it overwrites it again with the original and my custom template is gone.
Here is my current boot script:
#!/bin/bash
cp /customTemplates/login.tpl /www/img/templates/adm/login.tpl

Is there a way, to perform that copy command, say every 60 seconds? the login.tpl file is only 2kb, so I wouldn't think this could cause any problems.
Is there anything wrong with doing this, this way? Or is there another trick I could use?

A: To answer the general question, two ways to do this, put it in a while/sleep loop or use a crontab
1) while/sleep
#!/bin/bash
while true; do
  cp -f /customTemplates/login.tpl /www/img/templates/adm/login.tpl
  sleep 60
done

2) crontab (preferred)
Run crontab -e and put the following line there
* * * * * cp -f /customTemplates/login.tpl /www/img/templates/adm/login.tpl

This will run the command every minute of every hour of every day of every month of every day of the week. (ergo every 60 seconds)
But, as Aaron Digulla said it would be better to get to where it's pulling the config from and edit it there, rather then overwriting it every 60 seconds.

A: A better solution would be to find out where the NAS takes the original file from.
Execute this command to find possible candidates:
find / -name "login.tpl"

You can also use patterns: "*login*"
I suggest to use the quotes when you use patterns, otherwise it might match files in the local folder and the shell will then replace the name before it passes the argument to find.
To find out who changes the file, use auditctl (see this question).

A: try the following solution:
chmod +x /tmp/test.sh

your script test.sh:
#!/bin/bash
cp -f /customTemplates/login.tpl /www/img/templates/adm/login.tpl

then do:
touch /tmp/cronjob
echo "* * * * * ./test.sh" > /tmp/cronjob
/etc/init.d/crond/start
crontab /tmp/cronjob

A: If you're looking for a throw-away, one time sort of solution, you can use the watch utility
watch -n 60 ./test.sh

runs ./test.sh every 60 seconds and echoes the output to stdout


text:
Q: Intel network card "Not Ready" to use on an HP G71 Fellow Ubuntu users! I recently dual-booted Windows 7 and Ubuntu 11.10, and I am in a bit of a fix. When I want to connect to the internet with Ubuntu, Network Manager is showing that my device is not ready to use (exactlty device not ready). It works fine on Windows, however, since I'm using the same computer to type this as the one that is having the problem right now.
Here are the specs. If you need more, let me know! :)

*

*Computer: HP G71 Notebook

*Internet card: Intel(R) WiFi Link 1000 BGN

*OS: MS Windows 7 Home Premium 64-bit, Ubuntu 11.10 64-bit.

This is the result of using the command sudo lshw -class network:
  *-network DISABLED
       description: Wireless interface
       product: Centrino Wireless-N 1000
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlan0
       version: 00
       serial: 00:1e:64:4d:39:04
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlagn driverversion=3.0.0-12-generic firmware=39.31.5.1 build 35138 latency=0 link=no multicast=yes wireless=IEEE 802.11bgn
       resources: irq:44 memory:d3500000-d3501fff
  *-network
       description: Ethernet interface
       product: RTL8101E/RTL8102E PCI Express Fast Ethernet controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: eth0
       version: 02
       serial: 00:26:9e:7b:b0:c0
       size: 10Mbit/s
       capacity: 100Mbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list rom ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=N/A latency=0 link=no multicast=yes port=MII speed=10Mbit/s
       resources: irq:42 ioport:2000(size=256) memory:d1410000-d1410fff memory:d1400000-d140ffff memory:d1420000-d142ffff

A: try to turn the wireless on with hotkey

usually Fn + F[1 - 12] (just look for button that have signal / antenna icon)

in my laptop its Fn + F3


text:
Q: How to make shell script launch python script? I need a .command file that can launch a python script in the same directory as it.
I have so far gotten this:
#!bin/bash
python /Users/username/Desktop/IF.py

But every time the Terminal returns the same error.
Last login: Sun Oct 11 01:48:38 on ttys000
MacBook-Pro:~ username$ /var/folders/m7/yf7p3vdj2mx0l9r7qb68rttc0000gn/T/Cleanup\ At\ Startup/run 466235498.368.command.command ; exit;
/var/folders/m7/yf7p3vdj2mx0l9r7qb68rttc0000gn/T/Cleanup At Startup/run-466235498.368.command.command: line 3: bin/bash: No such file or directory
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

Please note the error is on line 3 of the 2 lines of code I have...

A: Why not just launch the python script itself from the get-go? You can add a shebang at the top like so:
#! /user/bin/env python
... the rest of your python script here

Then just give the script executable permissions:
chmod +x nameofscript.py

Then just launch it like so:
./nameofscript.py

In case you don't want the script to rely on the environment, just use the following shebang instead:
#! /usr/bin/python

A: Maybe because the shebang (or hashbang). About what is shebang (wiki).

#!bin/bash
  ^
python /Users/username/Desktop/IF.py

This means the system will use bin/bash to run this program, but bin/bash means path/bin/bash.
For example, if you're in /home then the system will use /home/bin/bash to run this program.

I think you need this:
#!/bin/bash
python /Users/username/Desktop/IF.py

Note that I replaced #!bin/bash to #!/bin/bash.


text:
Q: why Tensorflow-gpu is still using cpu I am using Keras with tensorflow-gpu in backend, I don't have tensorflow (CPU - version) installed, all the outputs show GPU selected but tf is using CPU and system memory
when i run my code the output is: output_code
I even ran device_lib.list_local_device() and the output is: list_local_devices_output
After running the code I tried nvidia-smi to see the usage of gpu and the output is:
nvidia-smi output
Tensorflow-gpu = "1.12.0"
CUDA toolkit = "9.0"
cuDNN = "7.4.1.5"

Environment Variables contain:
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\bin;
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0\libnvvp;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\WINDOWS\System32\OpenSSH\;
C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;
D:\Anaconda3;D:\Anaconda3\Library\mingw-w64\bin
D:\Anaconda3\Library\usr\bin;
D:\Anaconda3\Library\bin;
D:\Anaconda3\Scripts;D:\ffmpeg\bin\;

But still when i check for memory usage in task manager the output is
CPU utilization 51%, RAM utilization 86%
GPU utilization 1%, GPU-RAM utilization 0%
Task_manager_Output
So, I think it is still using CPU instead of GPU.
System Configuration:
Windows-10 64 bit; IDE: Liclipse; Python: 3.6.5

A: It is using the GPU, as you can see in logs.
The problem is, that a lot of things can not be done on the GPU and as long your data is small and your complexity is low, you will end up with low GPU usage.

*

*Maybe the batch_size is to low -> Increase until you run into OOM Errors

*Your data loading is consuming a lot of time and your gpu has to wait (IO Reads)

*Your RAM is to low and the application uses Disk as a fallback

*Preprocsssing is to slow. If you are dealing with image try to compute everything as a generator or on the gpu if possible

*You are using some operations, which are not GPU accelerated

Here is some more detailed explanation.


text:
Q: How to extend two Backbone views correctly Question: How to extend BaseView and Marionette.LayoutView in correct way?
I have: a view like:
var MyView = BaseView.extend({
    initialize: function(options) {
       this._super(options); // backbone-super.js
       ...
    }
});

I want: to move MyView to Marionette view. There are two ways:
1) The problem is that this._super stop working. I suppose Backbone tries to find initialize method inside Marionette.LayoutView
var MyView = BaseView.extend(Marionette.LayoutView.prototype).extend({
    initialize: function(options) {
       this._super(options); // NOT WORK
       this.regionManager.addRegions(options.regions); // WORK
       ...
    }
})

2) The problem of this approach is that MyView.regionManager is undefined. I suppose prototype points to BaseView
var MyView = Marionette.LayoutView.extend(BaseView.prototype).extend({
    initialize: function(options) {
       this._super(options);  // WORK
       this.regionManager.addRegions(options.regions); // NOT WORK
       ...
    }
})

A: Try like this:
var View = BaseView.extend({
    constructor: function () {
        BaseView.prototype.constructor.apply(this, arguments);
        Backbone.LayoutView.prototype.constructor.apply(this, arguments);
    }
});

_.extend(View.prototype, Backbone.LayoutView.prototype);


text: Q: Unparse a command line from a dict in Python Python's argparse library allows parsing command line arguments into a Namespace which can then be turned into a dict using vars(). However, can I use an ArgumentParser in reverse, to output a command line string from a dict, and if so, how?


text:
Q: how to have a child process forked through sys_fork() to have its kernel stack contain the trap frame? I am working on the implementation of system call sys_fork() on the kernel level. I did the copying of the parent process to the child process as per requirements. The problem is how to copy the child's trapframe (copy of the parent trapframe) onto the child's kernel stack to pass the assertion in mips_usermode()?

A: I figured out my problem.
But what I am going to say is related to OS161 system. So anyone working on this system, this will be helpful.
Ok, there is a function on the kernel side which deals with context switch. This function stores all the data related to context switch frame onto the threads kernel stack.
So all you need to do is follow the same steps and instead of switch frame structure, you need to replace it with trap frame structure.
Here is the implementation for it:-
vaddr_t stacktop;
struct trapframe *tf;
stacktop = ((vaddr_t)thread->t_stack) + STACK_SIZE;  //t_stack is the kernel stack
tf = ((struct trapframe *) stacktop) - 1;

t_stack is just a chunk of memory on the kernel side to store anything related to exceptions or context switch.
Be sure to first clean out the t_stack before you load it with trapframe as it will contain data related to context switch frame incase of sys_fork implementation.
Any corrections or comments on this are welcomed.

A: I'm working on OS161 too. Here is how I tackle the problem.
In sys_fork, I copy parent's trapframe into a kernel heap space allocated via kmalloc:
struct trapframe* ctf = (struct trapframe*)kmalloc(sizeof(struct trapframe));
*ctf = *tf; // tf points to parent's trapframe;

Then I use thread_fork to create a child thread:
// passing address space using the second parameter of
// child_forkentry, quite dirty
thread_fork(curthread->t_name, child_forkentry, ctf, (unsigned long)as, NULL);

In child_forkentry, which is the first function called by the child, I do the following:
struct trapframe tf; // tf will be allocated on child's kernel stack
tf = *ctf
misp_usermode(&tf);

This will pass the stack check in mips_usermode.


text:
Q: Redirect URL with ?aid=ind/234/ to third party URL with #affid I need to redirect my page from abc.com/page.html?aid=ind/234/ to xyz.com/pagename#affid
I want to do this by adding meta redirect or any javascript that run locally on abc.com/page.html
I do not want to use htacess.
Please help me out.
Best Regards

A: use php for getting request parameter: http://php.net/manual/en/reserved.variables.request.php
and redirect to needed page like here:
How to make a redirect in PHP?
Enjoy


text:
Q: Weekly count - occurrence of unique column values, and display max count I am attempting to create a weekly count of unique column value occurrences, and find the top weekly count for each occurrence over the given time-period. An example of the initial DataFrame can be seen below.

date            company

2014-12-01  bank of america corp
2014-12-01  bank of america corp
2014-12-01  jpmorgan chase & co
2014-12-01  jpmorgan chase & co
2014-12-01  morgan stanley
2014-12-01      morgan stanley
2014-12-01  intel corp
2014-12-01  goldman sachs group inc
2014-12-01  bank of america corp
2014-12-01  jpmorgan chase & co
2014-12-02      berkshire hathaway inc
2014-12-02  berkshire hathaway inc
2014-12-02      berkshire hathaway inc
2014-12-02  berkshire hathaway inc
2014-12-02  bank of america corp
2014-12-02  bank of america corp
2014-12-02  jpmorgan chase & co
2014-12-02      jpmorgan chase & co
2014-12-02      morgan stanley
2014-12-03  morgan stanley
2014-12-03  jpmorgan chase & co
2014-12-03  bank of america corp
2014-12-03  morgan stanley
2014-12-03  goldman sachs group inc
2014-12-03      bank of america corp
2014-12-03  jpmorgan chase & co
2014-12-03  goldman sachs group inc
.....           ...........

I am attempting to create a company count with the DataFrame grouped by week, with the top week for each company occurrence shown. Each company should have one row containing the week with the most mentions. An example of the intended DataFrame can be seen below:

date            company                   top_week_count

2014-12-07  bank of america corp      22
2014-12-07  jpmorgan chase & co       12
2014-12-14  morgan stanley            15
2014-12-14  goldman sachs group inc   29
2014-12-21  berkshire hathaway inc    35
.....           ....                      ..

The above DataFrames are only a brief snippet of the entire DF's, which span over a number of years.
Any assistance anyone could provide would be greatly appreciated!

A: Try
from pandas.tseries.offsets import *
df['weekend'] = df['date'] + Week(weekday=4)
df.groupby(['weekend', 'company']).size().reset_index(name = 'top_week_count')

    weekend     company                top_week_count
0   2014-12-05  bank of america corp    7
1   2014-12-05  berkshire hathaway inc  4
2   2014-12-05  goldman sachs group inc 3
3   2014-12-05  intel corp              1
4   2014-12-05  jpmorgan chase & co     7
5   2014-12-05  morgan stanley          5

A: Try :
df.groupby([pd.Grouper(freq='W', key='date'),'company'])['company']\
.agg(['count']).reset_index().sort_values('count',ascending=False)
        date                      company  count
0 2014-12-07         bank of america corp      7
5 2014-12-07          jpmorgan chase & co      7
6 2014-12-07               morgan stanley      5
1 2014-12-07       berkshire hathaway inc      4
2 2014-12-07      goldman sachs group inc      2
3 2014-12-07  goldman sachs group inc/the      1
4 2014-12-07                   intel corp      1


text:
Q: Rails Rspec allow multiple method call in one line desc 'Remove credential state users who no longer request for confirm otp within 10 minutes'
 task failed_user_cleaner: :environment do
 puts "Daily UserRecord Cleaning CronJob started - #{Time.now}"

 @user = User.with_state("credentials").with_last_otp_at(Time.now - 10.minutes)
 Users::Delete.new(@user).destroy_all

 puts "Daily UserRecord Cleaning CronJob ended - #{Time.now}"
end

Above is crop job rake file code.
then I've tried in many times and found in many times.
But I couldn't find the way to write unit test case for above job.
Help me to write test case correctly.
here is my spec code
require 'rails_helper'

describe 'users rake tasks' do
  before do
    Rake.application.rake_require 'tasks/users'
    Rake::Task.define_task(:environment)
  end

  context 'when remove credential state users who no longer request for confirm otp within 10 minutes' do
    let(:user) { create(:user, last_otp_at: Time.now - 11.minutes, state: "credentials") }
    let (:run_users_rake_task) do
      Rake.application.invoke_task 'users:failed_user_cleaner'
    end

    it 'calls right service method' do
      @users = Users::Delete.new([user])
      expect(@users).to receive(:destroy_all)

      run_users_rake_task
    end
  end
end

here is the error log
Failures:
  1) users rake tasks when remove credential state users who no longer request for confirm otp within 10 minutes calls right service method
 Failure/Error: expect(@users).to receive(:destroy_all)

   (#<Users::Delete:0x0000556dfcca3a40 @user=[#<User id: 181, uuid: nil, phone: "+66969597538", otp_secret: nil, last_otp_at: "2021-09-30 09:32:24.961548000 +0700", created_at: "2021-09-30 09:43:24.973818000 +0700", updated_at: "2021-09-30 09:43:24.973818000 +0700", email: nil, avatar: "https://dummyimage.com/300x300/f04720/153572.png?t...", refresh_token: "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MzI5Njk4MDQsImV4c...", first_name_en: "Jenise", first_name_th: "Damion", last_name_en: "McCullough", last_name_th: "Beatty", nationality: "TH", thai_national_id: nil, thai_laser_code: nil, company_id: 200, role: nil, state: "credentials", date_of_birth: "2020-10-30 00:00:00.000000000 +0700", deleted_at: nil, password_digest: "$2a$04$jfR9X9ci06602tlAyLOoRewTK1lZ12vJ2cZ9Dc2ov4F...", username: "zreejme238", shopname: nil, access_token: nil, locked_at: nil, login_attempts: 0, locale: "th", scorm_completed: false>]>).destroy_all(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments
 # ./spec/tasks/users_spec.rb:19:in `block (3 levels) in <top (required)>'

A: You are creating two instances of Users::Delete when running this test, one within the test and one within the task. Since the instance within the test is not used, it is incorrect to expect it to receive a message.
Rspec has an expectation, expect_any_instance_of, that will fix this however consider reading the full page since it can create fragile or flaky tests. If you wanted to use this method, your test would look something like:
it 'calls right service method' do
  expect_any_instance_of(Users::Delete).to receive(:destroy_all)

  run_users_rake_task
end

Personally I'd instead check that the expected users were deleted with something like:
it 'removes the user' do
  expect { run_users_rake_task }.to change { User.exists?(id: @user.id) }.to(false)
end

A: Unless you want to use any_instance_of (which is a code smell) you need to stub the Users::Delete method so that it returns a double and put the expectation on the double:
require 'rails_helper'

describe 'users rake tasks' do
  before do
    Rake.application.rake_require 'tasks/users'
    Rake::Task.define_task(:environment)
  end

  context 'when remove credential state users who no longer request for confirm otp within 10 minutes' do
    let(:user) { create(:user, last_otp_at: Time.now - 11.minutes, state: "credentials") }
    let(:run_users_rake_task) do
      Rake.application.invoke_task 'users:failed_user_cleaner'
    end

    let(:double) do
       instance_double('Users::Delete')
    end

    before do
      allow(Users::Delete).to receive(:new).and_return(double)
    end

    it 'calls right service method' do
      expect(double).to receive(:destroy_all)
      run_users_rake_task
    end
  end
end

However this really just tells us that the API of the service object is clunky and that you should write a class method which both instanciates and performs:
module Users
  class Delete
    # ...
    def self.destroy_all(users)
      new(users).destroy_all
    end
  end
end

desc 'Remove credential state users who no longer request for confirm otp within 10 minutes'
 #...

 Users::Delete.destroy_all(@user)

 # ...
end

require 'rails_helper'

describe 'users rake tasks' do
  # ...
  context 'when remove credential state users who no longer request for confirm otp within 10 minutes' do
    # ...
    it 'calls right service method' do
      expect(Users::Delete).to receive(:destroy_all)
      run_users_rake_task
    end
  end
end


text:
Q: how to tokenize list values n number of times    public void readTemplateInput() {
        BufferedReader inputfile = null;
        try {
            File file = new File("D:\\inputparam.txt");
            inputfile = new BufferedReader(new FileReader(file));
            String line = inputfile.readLine();
            if(line!=null){
            StringTokenizer reporttokens = new StringTokenizer(line,"-");
            while (reporttokens.hasMoreTokens()) {
                 String tokens= reporttokens.nextToken().toString();
                 reportslist=new ArrayList();
                 reportslist.add(tokens);
                 getReportTokens(reportslist);
              }
            }
    } catch (FileNotFoundException ex) {
            Logger.getLogger(InputTemplateData.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(InputTemplateData.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally {
            try {
                inputfile.close();
            } catch (IOException ex) {
                Logger.getLogger(InputTemplateData.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void getReportTokens(List reportslist) {
        List reports=reportslist;

}

here i need to get the first list and need to assign that list to a string and need tokenization.This procedure repeats like list2 assigned to a string and tokenizing it ,and list3...... so on according to the .txt file.
    I dont have idea to resolve this.
    Will any body help with correct code.

A: Here's your code modified to use split() instead, except I have no idea how is your data actually formatted, and how should it be parsed .. the code will split all lines along with all delimiters I can see in your example in one final list ..
public ArrayList<String> readTemplateInput()
{

    BufferedReader inputfile = null;
    ArrayList<String> finalList = null;

    try
    {
        File file = new File("D:\\inputparam.txt");
        inputfile = new BufferedReader(new FileReader(file));
        String line = inputfile.readLine();

            finalList = new ArrayList<String> ();

        if(line!=null)
        {
            String[] listA = line.split("-");

            ArrayList<String> listB = new ArrayList<String>();

            for (String str : listA)
            {
                listB.addAll(str.split("#").asList());
            }

            ArrayList<String> listC = new ArrayList<String>();

            for (String str : listB)
            {
                listC.addAll(str.split("$").asList());
            }

            ArrayList<String> listD = new ArrayList<String>();

            for (String str : listC)
            {
                listD.addAll(str.split("\(|\)").asList());
            }

            ArrayList<String> listE = new ArrayList<String>();

            for (String str : listD)
            {
                listE.addAll(str.split(",").asList());
            }

            // filter

            for (String str : listE)
            {
                str.replaceAll("\s+"," ");

            }

            for (int i=0; i<listE.size(); i++)
            {
                if(listE.get(i).equals(" ") || listE.get(i).equals(""))
                {
                    listE.remove(i);
                    i--;
                }
            }

                    finalList.addAll(listE);
        }

    }
    catch (FileNotFoundException ex)
    {
        Logger.getLogger(InputTemplateData.class.getName()).log(Level.SEVERE, null, ex);
    }
    catch (IOException ex)
    {
        Logger.getLogger(InputTemplateData.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally
    {
        try
        {
            inputfile.close();
        }
        catch (IOException ex)
        {
            Logger.getLogger(InputTemplateData.class.getName()).log(Level.SEVERE, null, ex);
        }

            return finalList;
    }

}


text:
Q: Visual Studio 2010 local testing server stopped working Just recently I tried to build my mvc 3 project, however the local server will not load in the browser, it just says that the web page cannot be displayed almost instantly on both IE9 and Firefox...
Strange thing is it was working fine not two weeks ago, I have tried searching google but have not come up with any solutions.
Does anyone know how to fix this?
Thanks,
Alex.

A: sometime MVC project have a infected build so try these step

*

*try to rebuild , clean and do  the disk clean then restart your system. maybe it's possible code work fine.

are you can show browser snapshot then i am sure what was matter with project you trying to run.

A: Ok after looking high and low I found this article Is Your ASP .Net Development Server Not Working?. It was some changes that were made to my hosts file by a seperate installer, after modifying my hosts file as suggested in the article it once again works.


text:
Q: SSH с двумя IP, как это называется? Заказчик (ИТ отдел) предоставил SSH-доступ вот такого вида:
ssh server_user_name@server_address@server_address

Через командную строку все ок, но я хочу подключаться через bitvise ssh, подскажите, пожалуйста, как такое подключение называется? Или как подключиться через bitvise ssh?


text:
Q: Checking if a number is present in string I have a working function that takes an input as string and returns a string. However, I want my function to return an empty string ("") if the input contains any number in whatever position in the string.
For example :
>>> function("hello")

works fine
>>> function("hello1")

should return ""

A: The main thing you need for that is the method "isdigit()" that returns True if the character is a digit.
For example:
yourstring="hel4lo3"
for char in yourstring:
  if char.isdigit():
    print(char)

Will output 4 and 3.
I think it is a good exercise for you trying to do your code from that!


text:
Q: MIPS assembly not running on different machine I'm doing a group project with MIPS assembly, and when I uploaded my copy of the code with my groups they're unable to run it. I've also tried it on my laptop and its still not working, just when its on my desktop I can run it.
When I run it on the laptop it gives me a runtime exception and address out of range. The desktop runs just fine.
Any idea what's causing this? Thank you


text:
Q: Looping through nested arrays in php 7.2 I am trying to access values in a nested array that I send to my API but when do something like $data['inputs']{0} it only gives me back the first letter of the key when what I want is the whole value of the value and not the key but if I try something like $data['inputs']['type'] it gives me an offset error I ament sure how to correctly access the values the way I need to
public function saveEdit(Request $request)
{
    try {
        $unsanitizedData = $request->all();
        $data = [];
        $fid = $unsanitizedData['formId'];
        $data['form_name'] = json_encode($unsanitizedData['cred']['name']);
        $data['org'] = json_encode($unsanitizedData['cred']['organization']);
        $data['updated_by'] = json_encode($unsanitizedData['updatedBy']);
        $data['user_id'] = json_encode($unsanitizedData['id']);
        $data['activated'] = json_encode($unsanitizedData['cred']['activated']);
        $data['inputs'] = json_encode($unsanitizedData['cred']['inputs']);
        $pattren = array("[","]","'",'"',"/","\\");
        $data = str_replace($pattren,'', $data);
        foreach ($unsanitizedData as $st) {
            admin_form::where('id', $fid)->update([
                'form_name' => $data['form_name'],
                'org' => $data['org'],
                'updated_by' => $data['updated_by'],
                'user_id' => $data['user_id'],
                'activated' => $data['activated']
                ]);
                foreach ($data['inputs'] as $input) {
                    admin_form_fields::where('form_id', $fid)->update([
                        'type' => $input,
                        'name' => $input
                    ]);
                }
        }

        $res['status'] = true;
        $res['message'] = 'Success';
        return response($res, 200);
    } catch (\Illuminate\Database\QueryException $ex) {
        $res['status'] = false;
        $res['message'] = $ex->getMessage();
        return response($res, 500);
    }
}

I thought if I use a foreach loop inside another foreach loop it would work because its a nested array so loop through the main one and then through the nested one but that did also not work
Data Structure when I do a data dump:
array:6 [
    "form_name"  => "Testname",
    "org"        => "TestOrg",
    "updated_by" => "test",
    "user_id"    => "29",
    "activated"  => "false",
    "inputs"     => "{type:number,name:Phone},{type:input,name:Name},{type:input,name:Address},{type:email,name:Email}"
]

A: In your case, $data['inputs'] is a JSON encoded string from which you have removed the [ and ] characters so when you try to access its first element it's the first char (since strings are kind of arrays of strings in PHP, they are really array of strings in C).
The problem is that you call json_encode() in the first place. If it's how you sanitize input, you're doing it wrong. Since you're using an ORM, there's no real need to manually sanitize the input. Just keep your input as sent by the client and perform all your operations then use them unsanitized in the QueryBuilder

A: As far as I can see, you just need to use json_decode($data['inputs']) since your array is in fact just a string :)


text:
Q: Undefined method field_changed? when trying to update attributes in Rails 3.2.12 I'm trying to upgrade my app from Rails 3.2.1 to 3.2.12 and am encountering a field_changed problem (method undefined) when trying to update attributes. I know it was changed to _field_changed in 3.2.9 and I think my gems are up-to-date, but I can't seem to find the issue. Any ideas? Here's my relevant code:
Controller
@user_role = Role.find_or_create_by_constituent_id(session[:user_id])
@user_role.update_attributes(:constituent_id => session[:user_id], :login => session[:username], :role => session[:user_role], :timestamp => Date.today)
@user_role.save

Gemfile
gem 'rails', '3.2.12'
gem 'execjs'
gem 'therubyracer'
gem "composite_primary_keys"
gem "tiny_tds", "~> 0.5.1"
gem "csv_builder", "~> 2.1.0"  #provides easy csv downloads
gem 'activerecord-sqlserver-adapter', :git => "git://github.com/timkleier/activerecord-sqlserver-adapter.git", :ref => "6bfb3b59e1f0adef59c91ded519ae160fe28b386"
gem 'by_star', :git => "git://github.com/radar/by_star.git", :ref => "13b594c758"
gem 'twitter-bootstrap-rails'
gem "less-rails"
gem "carrierwave"
gem "fog"
gem "figaro"

group :assets do
  gem 'sass-rails', '~> 3.2.4'
  gem 'coffee-rails', '~> 3.2.2'
  gem 'uglifier', '~> 1.2.3'
end

group :development do
  gem 'annotate', ">=2.5.0"
  gem 'rspec-rails'
end

gem 'jquery-rails', '2.0.2'
gem 'client_side_validations'
gem 'jquery_datepicker'

gem 'capistrano'
gem 'rvm-capistrano'

bundle show
  * actionmailer (3.2.12)
  * actionpack (3.2.12)
  * activemodel (3.2.12)
  * activerecord (3.2.12)
  * activerecord-sqlserver-adapter (3.2.12 6bfb3b5)
  * activeresource (3.2.12)
  * activesupport (3.2.12)
  * annotate (2.5.0)
  * arel (3.0.2)
  * builder (3.0.4)
  * bundler (1.2.4)
  * by_star (2.0.0.beta1 13b594c)
  * capistrano (2.15.4)
  * carrierwave (0.8.0)
  * chronic (0.9.1)
  * client_side_validations (3.2.5)
  * coffee-rails (3.2.2)
  * coffee-script (2.2.0)
  * coffee-script-source (1.6.2)
  * commonjs (0.2.6)
  * composite_primary_keys (5.0.8)
  * csv_builder (2.1.1)
  * diff-lcs (1.2.4)
  * erubis (2.7.0)
  * excon (0.6.6)
  * execjs (1.4.0)
  * figaro (0.6.4)
  * fog (0.9.0)
  * formatador (0.2.4)
  * highline (1.6.19)
  * hike (1.2.3)
  * i18n (0.6.4)
  * journey (1.0.4)
  * jquery-rails (2.0.2)
  * jquery_datepicker (0.4)
  * json (1.8.0)
  * less (2.3.2)
  * less-rails (2.3.3)
  * libv8 (3.11.8.17)
  * mail (2.4.4)
  * mime-types (1.23)
  * mini_portile (0.5.0)
  * multi_json (1.7.8)
  * net-scp (1.1.1)
  * net-sftp (2.1.2)
  * net-ssh (2.6.7)
  * net-ssh-gateway (1.2.0)
  * nokogiri (1.6.0)
  * polyglot (0.3.3)
  * rack (1.4.5)
  * rack-cache (1.2)
  * rack-ssl (1.3.3)
  * rack-test (0.6.2)
  * rails (3.2.12)
  * rails_sql_views (0.8.0 be67a84)
  * railties (3.2.12)
  * rake (10.1.0)
  * rdoc (3.12.2)
  * ref (1.0.5)
  * rspec-core (2.13.1)
  * rspec-expectations (2.13.0)
  * rspec-mocks (2.13.1)
  * rspec-rails (2.13.2)
  * ruby-hmac (0.4.0)
  * rvm-capistrano (1.3.1)
  * sass (3.2.9)
  * sass-rails (3.2.6)
  * spork (1.0.0rc3)
  * sprockets (2.2.2)
  * therubyracer (0.11.4)
  * thor (0.18.1)
  * tilt (1.4.1)
  * tiny_tds (0.5.1)
  * treetop (1.4.14)
  * twitter-bootstrap-rails (2.2.7)
  * tzinfo (0.3.37)
  * uglifier (1.2.7)
  * webrat (0.7.3)

A: Turns out composite_primary_keys was the culprit. For whatever reason, bundle was using 5.0.8 and I needed to upgrade it to version 5.0.9 (where field_changed was changed to _field_changed).


text:
Q: Python function in subprocess I would like to run a bash command that takes as input the argument of a python function, like this example:
def myfunc(r1, r2):
    import subprocess
    subprocess.run(['r1 + r2'])

I actually have a more complicated bash code that anyway should take as input the arguments of the function, so I think this example explain this. Thank you!

A: i usualy use this function:
import os
def python_to_bash(cli_args):
    output = os.popen(cli_args).read()
    return output

return = python_to_bash([r1,r2])
print(return)


text:
Q: Sign of a Permutation using Polynomials One way to define sign of permutation is to consider the polynomial
$P(x_1,x_2,\cdots, x_n)=\prod_{1\leq i<j\leq n} (x_i-x_j)$ and define
$$Sign(\sigma)= \frac{P(x_{\sigma(1)},x_{\sigma(2)},\cdots, x_{\sigma(n)})}{P(x_1,x_2,\cdots, x_n)}.$$
I want to see the proof of $Sign(\sigma\tau)=Sign(\sigma)Sign(\tau)$. For this,
$$ Sign(\sigma\tau)=\frac{P(x_{\sigma\tau(1)},x_{\sigma\tau(2)},\cdots, x_{\sigma\tau(n)})}{P(x_1,x_2,\cdots, x_n)}$$
$$=\frac{P(x_{\sigma\tau(1)},x_{\sigma\tau(2)},\cdots, x_{\sigma\tau(n)})}{P(x_{\tau(1)},x_{\tau(2)},\cdots, x_{\tau(n)})}\times\frac{P(x_{\tau(1)},x_{\tau(2)},\cdots, x_{\tau(n)})}{P(x_1,x_2,\cdots, x_n)}.$$
I didn't get why the first term on RHS in last step is $Sign(\sigma)$. Can anybody help me?
(This could be elementary, but I am not justified.)

A: Hint:
The definition
$$
Sign(\sigma){}={}\dfrac{P(x_{\sigma(1)},x_{\sigma(2)},\cdots, x_{\sigma(n)})}{P(x_1,x_2,\cdots, x_n)}
$$
is valid for any initial order of $x_1,\ldots,x_n\,$.
For example,
$$
\dfrac{(x_1-x_2)}{(x_2-x_1)}{}={}\dfrac{(x_2-x_1)}{(x_1-x_2)}{}={}-1\,.
$$

A: $\newcommand{\Q}[0]{\mathbb{Q}}\newcommand{\Sign}[0]{\mathrm{Sign}}$The main point here is that you can define an action of the symmetric group $S_{n}$ on the set $\Q(x_{1}, \dots, x_{n})$ of rational functions with rational coefficients in the indeterminates $x_{1}, \dots, x_{n}$.
This action is given by declaring it on the indeterminates
$$
\sigma(x_{i}) = x_{\sigma(i)}.
$$
This is immediately verified to be an action on the set $\{ x_{1}, \dots, x_{n} \}$.
Then you extend it to the whole of $\Q[x_{1}, \dots, x_{n}]$ via the universal property of polynomials, and then also on rational functions $\Q(x_{1}, \dots, x_{n})$ - you have to prove it is well defined here, but that's easy enough. Here you let every constant be fixed by every permutation, so that in the end the action is just
$$
\sigma\left(R(x_{1}, x_{2}, \dots, x_{n})\right) = R(x_{\sigma(1)}, x_{\sigma(2)}, \dots, x_{\sigma(n)})
$$
if $R(x_{1}, x_{2}, \dots, x_{n}) \in \Q(x_{1}, \dots, x_{n})$.
Once you have that, your answer is easily obtained as
$$ \Sign(\sigma\tau)
=
\frac{P(x_{\sigma\tau(1)},x_{\sigma\tau(2)},\cdots, x_{\sigma\tau(n)})}{P(x_1,x_2,\cdots, x_n)}
=\\=
\frac{P(x_{\sigma\tau(1)},x_{\sigma\tau(2)},\cdots, x_{\sigma\tau(n)})}{P(x_{\sigma(1)},x_{\sigma(2)},\cdots, x_{\sigma(n)})}
\cdot
\frac{P(x_{\sigma(1)},x_{\sigma(2)},\cdots, x_{\sigma(n)})}{P(x_1,x_2,\cdots, x_n)}
=\\=
\sigma\left( \frac{P(x_{\tau(1)},x_{\tau(2)},\cdots, x_{\tau(n)})}{P(x_{1},x_{2},\cdots, x_{n})} \right)
\cdot
\frac{P(x_{\sigma(1)},x_{\sigma(2)},\cdots, x_{\sigma(n)})}{P(x_{1},x_{2},\cdots, x_{n})}
=\\=
\sigma(\Sign(\tau)) \cdot \Sign(\sigma) = \Sign(\tau) \cdot \Sign(\sigma),$$
as $\Sign(\tau) \in \{ 1, -1 \}$, and a constant is fixed by definition by any permutation.


text:
Q: Qt ListWidget icon's color changed because of background color This question might be a little complicated to understand...
Let's say you have a QListWidget with blue icons. When you click on any items inside the QListWidget, the item will be highlighted with blue background color(the exact color identical to the color of the icons). In this way, the icon will be invinsible because all you will see is blue.

So in order to see the icon when the item is clicked and highlighted, I have to invert the color of the icon when clicked. My solution is to make another icon identical to the previous one but with white color. So when the item is clicked, the icon is supposed to turn white so that we could see the icon clearly. However, things go sideways and all we see is that:

I cannot understand why the icon is light blue when it is supposed to be white. Here are the two different color of icons I am talking about. They are in .png format.

Additional information:
In order to highlight the item when clicked, I used QSS. The code is as the following:
    QListWidget
    {
        background-color: #ffffff;
        border: none;
        border-raduis: 10px;
        font: 10.5pt "Microsoft Yahei";
        outline: 0px;
        padding-top: 55px;
    }
    QListWidget::item
    {
        background-color: transparent;
        color: #000000;
        border: 0px;
        padding-left: 5px;
        height: 38px;
    }
    QListWidget::item:selected
    {
        color: #ffffff;
        background-color: rgb(46, 123, 253);
        border-radius: 9px;
    }

In order to change the icon when the item is clicked, I used the following code: (Actually I don't think the following code matters! If you want to learn more you can continue)
def change_icon(self):
    icon_list = ['resources-inverted/all_music.png', 'resources-inverted/favourite_music.png',
                 'resources-inverted/recommended.png',
                 'resources-inverted/MV.png', 'resources-inverted/bilibili.png']
    index = self.ui.listWidget.currentRow()
    img = QImage(icon_list[index])
    pixmap = QPixmap(img)
    fit_pixmap = pixmap.scaled(23, 23, Qt.IgnoreAspectRatio,
                               Qt.SmoothTransformation)
    self.ui.listWidget.item(index).setIcon(fit_pixmap)
    self.ui.listWidget.setIconSize(QSize(23, 23))
    self.set_list_icon(exception=index)

self.set_list_icon is a function that sets all the icons for the QListWidget. It takes in an arguement exception which tells the function which row of the QListWidget it should skip. The reason why I called this function at the end of the change_color function is that if you don't call such a function, when you click on another item in the QListWidget, the last item's icon color will remain white. But rather, we want to keep the icon's color blue when not selected.
The full project is at:https://github.com/Zhu-Aemon/music_gallery, including all the .png files, the .ui file and all the code. Thank you for your help!


text:
Q: Polymorphic Nested Form I'm having issue creating a nested polymorphic form. I am following the solution from this problem:
Rails: has_many through with polymorphic association - will this work?
The description was: A Person can have many Events and each Event can have one polymorphic Eventable record
Here are the relevant models:
class Event < ActiveRecord::Base
  belongs_to :person
  belongs_to :eventable, :polymorphic => true
end

class Meal < ActiveRecord::Base
  has_one :event, :as => eventable
end

class Workout < ActiveRecord::Base
  has_one :event, :as => eventable
end

class Person < ActiveRecord::Base
  has_many :events
  has_many :meals, :through => :events, :source => :eventable,
    :source_type => "Meal"
  has_many :workouts, :through => :events, :source => :eventable,
    :source_type => "Workout"
end

My controller looks like this:
def
  @person = Person.new
  @person.meals.new
  @person.workouts.new
new

My view looks like this:
<%=  form_for @person do |person| %>
 <%= person.fields_for :meals, @person.meals.build do |meals| %>
   <%= meals.text_field :food %>
  <% end %>
<% end %>

The error I am currently getting is:
unknown attribute: person_id
I would think that the polymorphic association is hindering the creation of the object because meals can't be create until person has been created? Did I set up the form correctly? Thanks!

A: You'll need to include a person_id attribute in the events table (as per the belongs_to association)
There are also some other issues you should resolve:

Controller
def new
    @person = Person.build
end

def create
    @person = Person.new(person_attributes)
    @person.save
end

private

def person_attributes
    params.require(:person).permit(:your, :attributes, events_attributes: [:eventable_type, :eventable_id, meal_attributes: [:params], workout_attributes: [:params]])
end

Models
#app/models/person.rb
Class Person < ActiveRecord::Base
    has_many :events
    has_many :meals, :through => :events, :source => :eventable,
        :source_type => "Meal"
    has_many :workouts, :through => :events, :source => :eventable,
        :source_type => "Workout"

    def self.build
        person = Person.new
        person.events.build.build_meal
        person.events.build.build_workout
    end

end

Views
#app/views/people/new.html.erb
<%=  form_for @person do |person| %>
 <%= person.fields_for :events do |e| %>
   <%= e.fields_for :meal %>
       <%= e.text_field :food %>
   <% end %>
  <% end %>
<% end %>


text:
Q: Storing an HTTP request in an array using C I am trying to catch an HTTP request and store it in an array using C . How can I possibly do this ?
The request I get from is of the following form :
POST /box/update HTTP/1.1
Accept : application/json
Content-Type : application/x-www-form-urlencoded
host:121.158.41.104:1338
content-length : 83
Connection : close

serial=1234&pin=1234&poweState=true&startState=true&temperature=11&macAdress=113

Code I have tried so far :
/*
  WiFi Web Server
 A simple web server that shows the value of the analog input pins.
 using a WiFi shield.
 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.
 Circuit:
 * WiFi shield attached
 * Analog inputs attached to pins A0 through A5 (optional)
 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>

// your network name also called SSID
char ssid[] = "MySSID";
// your network password
char password[] = "MyPassword";
// your network key Index number (needed only for WEP)
int keyIndex = 0;
WiFiServer server(Mport);
int array_number = 3;
void setup() {
  Serial.begin(115200);      // initialize serial communication
  pinMode(RED_LED, OUTPUT);      // set the LED pin mode
  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to Network named: ");
  // print the network name (SSID);
  Serial.println(ssid);
  // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
  WiFi.begin(ssid, password);
  while ( WiFi.status() != WL_CONNECTED) {
    // print dots while we wait to connect
    Serial.print(".");
    delay(300);
  }

  Serial.println("\nYou're connected to the network");
  Serial.println("Waiting for an ip address");

  while (WiFi.localIP() == INADDR_NONE) {
    // print dots while we wait for an ip addresss
    Serial.print(".");
    delay(300);
  }
  // you're connected now, so print out the status
  printWifiStatus();

  Serial.println("Starting webserver on port 80");
  server.begin();                           // start the web server on port 80
  Serial.println("Webserver started!");
}

void loop() {
  // listen for incoming clients
  WiFiClient client = server.available();
  String buffer = "";
  String post_str1 = "";

  /*
  int temperatures;
  String macAddresses;
  */

  String status_message;
  int status_code;
  boolean powerStates[3]= {true,true,true};
  boolean startStates[3]= {true,true,true};
  //int temperatures[3]={11,22,33};
  char * macAddresses[3] = {"155","156","157"};
  char *  temperatures[3] = {"11","22","33"};
  // powerStates[3]
  //startStates[3]
  /*
  temperatures = 11;
  macAddresses = "155";
  */
  status_code = 1;
  status_message = "success";

  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    int check = 0;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        buffer +=c;
        Serial.write(c);

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
       //if(c == '\n' && currentLineIsBlank){
       if(buffer.indexOf("true")>=0||buffer.indexOf("false")>=0){

          // you're starting a new line

          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println();

          client.print("{\"serial\":\"");
          client.print("1234");
          client.print("\",\"pin\":\"");
          client.print("1234");

          client.print("\",\"powerStates\":");
          client.print("[1,1,1]");
          client.print(",\"startStates\":");
          client.print("[1,1,1]");
          client.print(",\"temperatures\":");
          client.print("[11,22,33]");
          client.print(",\"macAddresses\":");
          client.print("[\"125\",\"136\",\"137\"]");

/*
          client.print("\",\"powerStates\":");
          client.print("[\"true\",\"true\",\"true\"]");
          client.print(",\"startStates\":");
          client.print("[\"false\",\"false\",\"false\"]");
          client.print(",\"temperatures\":");
          client.print("[\"11\",\"22\",\"33\"]");
          client.print(",\"macAddresses\":");
          client.print("[\"155\",\"156\",\"157\"]");
*/
          client.print(",\"status_code\":");
          client.print(status_code);
          client.print(",\"status_message\":\"");
          client.print(status_message);
          client.print("\"}");

          Serial.print("\n\r");

          Serial.print("{\"serial\":\"");
          Serial.print("1234");
          Serial.print("\",\"pin\":\"");
          Serial.print("1234");

          Serial.print("\",\"powerStates\":");
          Serial.print("[\"true\",\"true\",\"true\"]");
          Serial.print(",\"startStates\":");
          Serial.print("[\"true\",\"true\",\"true\"]");
          Serial.print(",\"temperatures\":");
          Serial.print("[\"11\",\"22\",\"33\"]");
          Serial.print(",\"macAddresses\":");
          Serial.print("[\"155\",\"156\",\"157\"]");

          Serial.print(",\"status_code\":");
          Serial.print(status_code);
          Serial.print(",\"status_message\":\"");
          Serial.print(status_message);
          Serial.print("\"}");

          Serial.print("\n\r");

          buffer="";
          check==0;
          break;
          }
          if(c == '\n'){
            currentLineIsBlank=true;
           }
          else if (c !='\r'){
            currentLineIsBlank=false;
          }

      }// carrage
      }//client avable
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");

  }//if client
}//while

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("Network Name: ");
  Serial.println(WiFi.SSID());
  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

My program requires to store each variable and value for further use.I have been able to read this request and output on my console , but further from that I am stuck.

A: I don't know what did you try since I'm usingStack Overflow for Android (buggy) and I can't see your whole code buffer
Be specific in your code next time please
If you want to store the buffer you get in an array (requests)
the best way I can think of is the dynamic memory allocation with a 2D pointer.
You can start with that code
#include <stdio.h>
#include <stdlib.h>
#define MAX_BUF 1024
char* arrOfBuffers[1000]; // stored requests
int requests = 0; // number of http requests stored
const char* getHttp(const char* URL)
{
    char* buf;
    // Some http GET functions
    // send(socket, "GET / HTTP/1.0", ...);
    // ...
    // memset(buf 0, MAX_BUF)
    // ...
    // recv(socket, buf, sizeof(buf), ...);
    // ...
    // Save it
    buf = "some buffer"; // example
    arrOfBuffers[requests] = buf;
    puts(arrOfBuffers[requests]);
    ++requests;
    return buf;
}
int main ()
{
    for(int i = 0; i <= 1000; ++i) // 1000 requests
    {
        char* request = (char*)calloc(1, 80);
        sprintf(request, "http://www.stackoverflow.com/users/%d/", i);
        getHttp(request);
    }
    return 0;
}

I really want to make a real live example of my code but I can't use socket libraries right now cause I'm PC afk.


text:
Q: Greatest common divisors in Integral Domain Let $R$ be an integral domain and $r,s\in R-\{0\}$ such that $\text{gcd}(r,s)=g.$ Suppose $\text{gcd}(kr,ks)$ exists, where $k \in R -\{0\}.$ Could anyone advise me on how to prove $kg= \text{gcd}(kr,ks)$ ?
Hints will suffice, thank you.

A: Here in we denote: x\y <==> x divides y. Since g = gcd{r,s}, g\r and g\s. Thus there are p, and q in R such that: r = pg, and s = qg. So kr = kpg = p(kg),and so kg\kr. Similarly: kg\ks. Now if t\kr and t\ks, we show: t\kg. t\kr ==> kr = tu, and ks = tv ==> r = k^(-1)*tu, and s = k^(-1)*tv ==> k^(-1)*t divides both r, and s. So k^(-1)*t divides gcd{r,s} = g. So g = w(k^(-1)*t) ==> kg = wt ==> t\kg ==> kg = gcd{kr,ks}.


text:
Q: Fix broken boot image I think I did something that stopped my default ubuntu image to load USB items. This includes the following:

*

*Mouse

*Keyboard

*Wireless USB Adaptor

When the computer starts I get an error message, which I cannot read (because it goes away too fast).

When I start up if I open grub I can select an older image 4.10.0-33-generic everything loads and works fine.
I however, want to load the default which isn't working 4.10.0-35-generic.
Is there a way for me to fix the broken image/kernel?

A: You may have two separate issues. File system corruption and secure boot...
To check the file system on your Ubuntu partition...

*

*boot to the GRUB menu

*choose Advanced Options

*choose Recovery mode

*choose Root access

*at the # prompt, type sudo fsck -f /

*repeat the fsck command if there were errors

*type reboot
Stop the reboot at the BIOS and check to make sure that secure boot is disabled.


text:
Q: realloc: invalid next size This question is definitely related to this and it's answer is what I based my function off of.
char *get_next_line(FILE *fp) {
char ch = 0;
int CUR_MAX = 4095;
char *buffer = (char*) malloc(sizeof(char) * CUR_MAX); // allocate buffer.
char *temp = (char*) malloc(sizeof(char) * CUR_MAX); // allocate buffer.
int count = 0;
int length = 0;

while ((ch != '\n')) {
  if (ch == '\377') { return NULL; }
  if(count ==CUR_MAX) {
    CUR_MAX *= 2;
    count = 0;
    if ((temp = realloc(buffer, CUR_MAX)) != NULL) {
      buffer = temp;
      free(temp);
    }
  }
  ch = getc(fp);
  buffer[length] = ch;
  length++;
  count++;
}

For some reason, when reading in very large strings I'm faced with:
glibc detected - realloc() invalid next size.
Is there something I'm missing here?
Thanks!

A: When you:
free(temp);

buffer is also freed, since:
buffer = temp;

So later on you're trying to:
realloc(buffer, CUR_MAX)

which cannot work because buffer has been freed indirectly through temp. You cannot realloc() a freed pointer.

A: I believe you're accessing memory outside of your malloced/realloced region.
Not setting count = 0 inside your while look should fix this.

To try and elaborate...
When starting the formula:
count = 0
length = 0
CUR_MAX = 4095

These will increment until they reach 4095. Once we reach 4095, we will have:
count = 0
length = 4096
CUR_MAX = 8190

We will then increment until count is 8190. Shorly before then, we have:
count = 8100
length = 12196
CUR_MAX = 8190

Your array is only 8190 in length, but you're dereferencing buffer[12196], which is an invalid index.

Also, you probably want to handle the else case for when temp == NULL. This probably can be handled by an assert or a big old failure. And don't free(temp) inside your success side. That's freeing the memory you just attempted to allocate. And is causing your new segmentation fault.

A: realloc(buffer, CUR_MAX)) returns pointer to void.
I believe the correct statement is (char *)realloc(buffer, CUR_MAX))


text:
Q: Css how to create navigation bar I'am trying to make this in css. Trying to make this navigation bar. Any help would be great.
This is what iam trying to do:

So the first pic is how it should look like when the user enter the website. Then if they hover over the any of the tabs it should just change color. Any help on trying to make this would be great. I tried this but wont work.
HTML:

Home

Register

Rules

Just need to see what the css would look like. Thanks again
EDIT what i have done as people want 2 see:
div.horizontal
{
width:809px;
height:63px;
position:relative;
top: -1046px;
left: 104px;
}
div.horizontal ul
{
list-style-type:none;
margin:0;
padding:0;
}
div.horizontal li
{
  display: inline-block;
  margin-left: 5px;
}
div.horizontal a
{
display:block;
width:809px;
}
div.horizontal a:link,div.horizontal a:visited
{
font-weight:bold;
color:#FFFFFF;
background-color:#000000;
text-align:center;
padding:4px;
text-decoration:none;
text-transform:uppercase;
}
div.horizontal a:hover,div.horizontal a:active
{
background-color:#999999;
}

Like i said this is not right but this is all i can do atm. Thanks

A: Using your HTML, you can do something like this:
CSS
ul{
    list-style:none;
}

li{
    float:left;
    width:100px;
    height:50px;
    background:black;
    border:2px solid gray;
    text-align:center;
}

a{
    color:white;
    text-decoration:none;
    font-size:24px;
    font-weight:bold;
    line-height:50px;
    font-style:italic
}

li:hover{
    background:gray;
}

JSFiddle.
Just change the colors.


text:
Q: Why do I see a blank screen after form submission in PHP? For the life of me I can't find what's wrong. It's just a search using the "num" field to pull from database and display all other row info for the corresponding number. Please help :/
<form action="search.php" method="post">
    Number :<input type="text" value="<?php if(isset($num)) echo $num;?>" name ="number"/>
    <input type="submit" value="Search"/>
</form>
<?php
    if($_POST)
    {
        $query = "SELECT * FROM r5s WHERE num = '$num'";
        $result = mysql_query($query) or die();
        $count=mysql_num_rows($result);

        if($count==0 & $num!="")
        {
            echo "The number is not found.
Please try again with correct number.";
        }

        while($row = mysql_fetch_array($result))
        {
?>

Renter profile

Name

<?php echo $row['name'];?>

SSN

<?php echo $row['num'];?>

DOB

<?php echo $row['birth'];?>

Rating

<?php echo $row['rank'];?>

History

<?php echo $row['hist'];?>

Comments

<?php          enter code here`echo $row['comments'];?>

<?php
        }
        mysql_close($conn);
    }
?>

A: Currently, it sounds like your PHP is configured to not show any errors at all. The following will let you show errors for a particular folder in your website:
To do so, create a file named ".htaccess" in the same folder as your PHP file.
Make it's contents like this:
php_flag log_errors 1
php_value error_log /tmp/php_error.log (NOTE: This file has to exist and be writable)
php_flag session.use_trans_sid on
php_flag display_errors on
php_flag display_startup_errors on
php_flag magic_quotes_runtime on
php_value error_reporting 2047 or use value 497 for just errors (no notices or warnings)
php_flag magic_quotes_gpc off
php_flag register_globals off
php_value include_path .:/path/that/you/want/to/use
Options All -Indexes

Note that you'll want to be sure you can delete this file if required, as this can cause errors if your server doesn't support some of these features. So make a new directory, and put this .htaccess file in it. Then try and access a simple php file in that folder to see if it throws an error or not. If it doesn't, then it's fine to put in your real folder with your problem PHP file. Note that you need to change some file paths above to make it really work.