Find Number(length) of items before condition and after condition in javascript array

Question: I have a array in which number of items will be changing upon other conditions
my response
[
  id:2,
  ages:[{
    name:'alex',
    age_id:1,
  },
    name:'mike',
    age_id:2,
  },
  {
    name:'sike',
    age_id:2,
  },
  {
    name:'hike',
    age_id:3,
  },
  {
    name:'ben',
    age_id:3,
  }]
]

I am getting the above response and storing it into my agePeople array like this
axios.get('/people').then((res)=>{
  this.agePeople  = res.data
})

then i am looping over it to check the number of items length before certain condition and after as i want to remove them using pop and shift functions
for(var i=0; b < this.agePeople.length; i++) {
  for(var b=0; b < this.agePeople[i].ages.length; b++) {
    if(this.agePeople[i].id == this.agePeople[i].ages[b].age_id) {
      //So when condition meets it should pop the elements before it and after it but both number of items before the condition and after are different
    }
  }
}

I have tries storing their count and the pop and shift the array that many times but it doesn't gives desired results  as the number of unmatched items can be changed on every other response
Comment: Please accept an answer if this solved your problem. Have a great day
Answer: forEach makes iteration on arrays much easier.
You haven't mentioned on which array you want to execute pop and shift, so I have assumed on ages array:
         this.agePeople.forEach(item1 => {
            item1.ages.forEach((item2,index) => {
               if (item1.id !== item2.age_id) {
                   item1.ages.splice(index,1);
               }
             })
         })

Comment: @Qiimiia if you edit an array whilst looping through it you will find yourself looking for `index = 6` but now that you've removed an earlier index you are actually looking at `index = 7`, for example
Comment: you shouldn't edit an array while looping through it
Comment: @KevinPotgieter Why not? I have done that  alot!
Comment: It will only show the first record with age_id = 2 i want both of them
Comment: @MohammadFahadRao Then I did edit my answer. Please check this one.
Comment: Run this : `let data = [0,1,2,3,4,5];` `data.forEach(function (index, value) { data.shift(); console.log(index, value); })` Notice how the index and value is not matched anymore
Comment: @KevinPotgieter You were right about changing the next index! It was a mistake. but I guess changing the index that I'm already iterating on, won't make a problem. e.g. check my edited answer.
Comment: Its good practice make a new array and not alter the original one you are iterating through
Answer: You can achieve this without looping through the array. You should also never add or remove to an array while looping through it, doing so changes the length of the array and can cause your indexes to reference the wrong value.
const data = {
  "id": 2,
  "ages": [
    {
      "name": "alex",
      "age_id": 1
    },
    {
      "name": "mike",
      "age_id": 2
    },
    {
      "name": "sike",
      "age_id": 2
    },
    {
      "name": "hike",
      "age_id": 3
    },
    {
      "name": "ben",
      "age_id": 3
    }
  ]
}

const id = data.id; // set id in variable
const has_matching_age_id = data.ages.filter(d => d.age_id === id); // find a mathing item in array, return an array

if (has_matching_age_id.length) // if there was an item in the array that matched the condition
    data.ages = has_matching_age_id[0] //replace data.ages

console.log(data)
// {
//   "id": 2,
//   "ages":
//     {
//       "name": "mike",
//       "age_id": 2
//     }
// }

// or if you want all the matching age_id's

if (has_matching_age_id.length) // if there was an item in the array that matched the condition
    data.ages = has_matching_age_id //replace data.ages

console.log(data)
// {
//   "id": 2,
//   "ages": [
//     {
//       "name": "mike",
//       "age_id": 2
//     },
//     {
//       "name": "sike",
//       "age_id": 2
//     }
//   ]
// }

Comment: I want both records with age_id =2
Comment: See the second comment in my answer


Force Android TTS to parse time as text?

Question: I'm building an app that speaks a custom message that includes the current time.  I've noticed that some voices seem to parse the time correctly- that is, when I pass in a string like "The time is now 7:07" it actually speaks it as "seven-oh-seven."
However, other voices insist on saying "the time is now seven colon zero seven."  It would be simple enough to write a function to parse it myself, but I'm trying to find something built-in so I won't have to worry about localization.  Is there something I can do within TTS (attributed-string-related, maybe?) or even a Java library that will provide me with a localized "text" string of a time?  I've dug through the TTS documentation and didn't find anything, and all the Java time-formatting patterns I've seen are numbers-only, no words.
Answer: Figured it out- the TtsSpan is what's needed.  Took me a while to get the format right; there are basically zero examples out there on how to do this.  Here are the basics for what worked for me, if anyone else comes across this with the same need (in kotlin):
<code>var h:Int = Calendar.getInstance().get(Calendar.HOUR)
if (DateFormat.is24HourFormat(ApplicationContext))
    h = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
val m:Int = Calendar.getInstance().get(Calendar.MINUTE)
val whenStr = getFormattedTime() // internal function I'm using to format it visually
wholeString = message.replace("|TIME|",whenStr) // my time doesn't always appear at the same place in the custom message
val spannedMsg:Spannable = SpannableString(wholeString)
val span:TtsSpan = TtsSpan.TimeBuilder(h, m).build()
spannedMsg.setSpan(span, wholeString.inexOf(whenStr),wholeString.indexOf(whenStr) + whenStr.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
tts.speak(spannedMsg, TextToSpeech.QUEUE_FLUSH, params, "UTT_ID")
</code>
According to the TtsSpan documenation page, there are plenty of other options aside from TimeBuilder, as well, so be sure to check that out if you're looking for different customizations- just be aware that there aren't any code examples.


Can you change your icon color in Spore?

Question: In Spore, tribal stage and beyond. You have an "icon color" of blue. Is there an option somewhere that lets you change this? I glanced over the game settings to no avail. In a game that lets you customize practically everything, it seems off that you can't change your icon color.
Answer: The colour of your tribe/country/empire is mainly based on your creature's Coat colour (second layer). I do not believe it will change if you alter your creature afterwards, but at least you can control it before you enter the Tribal stage.
Comment: Didn't know that, I think my empie was green, and my creature was greenish too IIRC.
Comment: I'm not sure about that. My creature color was yellow/white yet my empire color was blue
Comment: I think it likes picking blue when it gets a colour it doesn't want, like white, grey, or black. I don't have enough experience to be sure; I only have one data point of a white coat that created a blue icon colour.
Answer: From what other people said, I'm pretty sure its random, but there is a bug where if you start a new save game and get to tribal stage, your original save's color will match the new save.


REST API using Swagger and Node.js with SQL Server as DB

Question: I've created a working REST API with Node.js Express that operates CRUD operations within SQL Server. Now, I am given task to document my API using Swagger. However, my API do not have Swagger modules installed during its creation.
I've tried to create a copy of my API using SwaggerHub and generate Node.js server from the API, but found no solution to get it work with SQL Server.
Can anyone please enlighten me on Swagger and how to connect my created Swagger API to SQL Server using Node.js Express?
Answer: Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document and consume REST APIs
OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs
If you already created a swagger definition file for your API then you can use following tools to generate what you need

swagger-node-codegen - Generate JS,ES6,Express API backend
Swagger tool - Swaggercodegen - Generates Nodejs code

Either ways you will have to create database connection and map your data into db table and javascript model. Like explained in here
Comment: Thanks, Nuwan! I appreciate your answer. I've generated the API in form of node.js server. All that's left is to connect it to a SQL server that I've created. Any tips on editing the controller file so that it matches the value in the server?


Multiple SQLite libraries on a single process

Question: OS: arm-based Linux.
Programming language: C, C++
Compiler: arm gcc
We build a shared library (let's call it libFoo.so) which depends on a certain SQLite version. The SQLite library is compiled statically and linked against libFoo.so. They are all compiled with a hidden visibility (-fvisibility=hidden) and libFoo.so only exports its API symbols, so the SQLite symbols are not visible using "nm -D libFoo.so". This is to avoid symbol collisions.
This shared library only performs read-operation to a set of specific database files. These databases are expected to be opened through libFoo.so only.
Our partner builds an application using libFoo.so and links against Qt Service framework from the platform. The Qt service framework depends on the SQLite shared library from the platform which has a different version than mine. This would mean that this process loads two copies of SQLite libraries, but the one coming from libFoo.so is hidden.
Questions:

How likely will I end-up in the database corruption issue mentioned in How to corrupt - Multiple copies of SQLite linked into the same application? I am curious about the case(s) where it could go wrong.
SQLite keeps a global list of open SQLite database files. Is there any chance that the SQLite shared library accesses the global list of open database files from the SQLite static library?

In the SQLite page above, there was a solution mentioned to link against one copy of SQLite library only which means to change the build procedure of the platform which is not accessible by me.
I googled it and found an interesting discussion:

In The multiple SQLite problem, there is a comment stating that it might be possible to use a SQLite as a static library and hide SQLite symbols as I did.

Thanks!
Answer: I have come across this problem when I compile my code into apple ios. Another sdk lib using another version of sqlite3.
I just rename the string sqlite3 to another random string(for example hrbw) in my sqlite3 source code and my caller of sqlite3 source code.
Then the problem will be fixed.


java fx: scene's lookup method

Question: If a node is having fx:id (say a) as well as normal id(css id) (say b). If lookup is used to search this node:
Node node=scene.lookup("#a")
The above statement returns null. But if there is no css id corresponding to node in discussion, then above statement returns the correct node.
While using the below given statement always returns the correct result:
Node node=scene.lookup("#b")
Can anyone please explain why lookup method is behaving so weirdly?
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>

<GridPane hgap="14.0" maxHeight="+Infinity" maxWidth="+Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="223.0" prefWidth="323.0" vgap="20.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <children>
    <VBox maxHeight="+Infinity" maxWidth="+Infinity" minHeight="-Infinity" spacing="7.0" GridPane.rowIndex="0">
      <children>
            <HBox alignment="TOP_RIGHT">
               <children>

               </children>
            </HBox>
            <HBox alignment="TOP_RIGHT" spacing="5.0">
               <children>

                  <TextField fx:id="qtyT" />
               </children>
            </HBox>
            <HBox alignment="TOP_RIGHT" spacing="5.0">
               <children>

                  <TextField fx:id="nameT" />
               </children>
            </HBox>
            <HBox alignment="TOP_RIGHT" spacing="5.0">
               <children>

                  <TextArea fx:id="remarksT" prefHeight="60.0" prefWidth="149.0" wrapText="true" />
               </children>
            </HBox>
      </children>
    </VBox>
    <HBox maxHeight="-Infinity" maxWidth="+Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="25.0" prefWidth="253.0" GridPane.rowIndex="1">
      <children>
        <Pane maxWidth="+Infinity" HBox.hgrow="ALWAYS" />
        <Button id="cancel-button" fx:id="cancelButton" cancelButton="true" minWidth="80.0" mnemonicParsing="false" text="Cancel" HBox.hgrow="NEVER">
          <HBox.margin>
            <Insets />
          </HBox.margin>
        </Button>
        <HBox fx:id="okParent" alignment="CENTER">
          <children>
            <Button id="ok-button" fx:id="okButton" minWidth="80.0" mnemonicParsing="false" text="Ok" HBox.hgrow="NEVER">
              <HBox.margin>
                <Insets left="14.0" />
              </HBox.margin>
            </Button>
          </children>
        </HBox>
      </children>
    </HBox>
  </children>
  <columnConstraints>
    <ColumnConstraints halignment="CENTER" hgrow="ALWAYS" maxWidth="+Infinity" minWidth="-Infinity" />
  </columnConstraints>
  <padding>
    <Insets bottom="14.0" left="14.0" right="14.0" top="14.0" />
  </padding>
  <rowConstraints>
    <RowConstraints maxHeight="+Infinity" minHeight="-Infinity" valignment="CENTER" vgrow="ALWAYS" />
    <RowConstraints maxHeight="-Infinity" minHeight="-Infinity" vgrow="NEVER" />
  </rowConstraints>
</GridPane>

In the above fxml, lookup works fine on fxml id's for the nodes which don't have any css id. If css id is present, then it return nulls
Label headerMessage = (Label) alertStage.getScene().lookup("#headerMessage");
                final TextField qty = (TextField) alertStage.getScene().lookup("#qtyT");
                Label name = (Label) alertStage.getScene().lookup("#name");
                final TextArea remarksT = (TextArea) alertStage.getScene().lookup("#remarksT");
                final TextField nameT = (TextField) alertStage.getScene().lookup("#nameT");

lookup method fails only for given below statement.
Button okButton = (Button) alertStage.getScene().lookup("#okButton");

Comment: That is strange. I am sure with `fx:id`, it should always return `null`. Can you add a [MCVE](http://stackoverflow.com/help/mcve) depicting this behaviour?
Answer: Edit - After the OP added the MCVE
Digging into the matter. I got a simple statement written deep inside the documentation of FXML which explains about the behaviour. Actually, the fx:id is assigned as the default id of the control / layout by calling the setId().
Unless overridden, fx:id stays as the default id of the object.
From Introduction To FXML :

Assigning an fx:id value to an element creates a variable in the document's namespace that can later be referred to by variable dereference attributes, such as the "toggleGroup" attribute shown above, or in script code, discussed in a later section. Additionally, if the object's type defines an "id" property, this value will also be passed to the objects setId() method.

The lookup() is doing its job perfectly and is working for the CSS selectors and not on fx:id.

java fx: scene's lookup method


How to install TP-LINK T2UH Wireless adapter Driver (Ralink mt7610u)

Question: I recently got a wireless adapter (TP-Link Archer T2UH V1). After plugging it in, I found out that the drivers for Linux are not native on Ubuntu. They do, however, have the drivers available for download (in the form of compilable/ makefile). What I am not sure of is how to install these drivers. I know that I need to build the drivers, place things where they need to be, and tie things together with the kernel. I am not sure how to do this, however, and need some help.
TL;DR: I need to know the terminal commands to install these drivers.
Driver/Device info:
http://www.tp-link.com/en/download/Archer-T2UH.html#Driver
Output of lsusb:
Bus 003 Device 004: ID 148f:761a Ralink Technology, Corp.

Answer: Connect to internet by wire, then run in terminal
sudo apt-get install git build-essential
git clone https://github.com/Myria-de/mt7610u_wifi_sta_v3002_dpo_20130916.git
cd mt7610u_wifi_sta_v3002_dpo_20130916
make
sudo make install
sudo mkdir -p /etc/Wireless/RT2870STA
sudo cp RT2870STA.dat  /etc/Wireless/RT2870STA/RT2870STA.dat

Reboot.
The dongle should work. The only problem is that you will have to re-install it after each kernel upgrade.
But if you keep the driver folder mt7610u_wifi_sta_v3002_dpo_20130916, then it will be quite easy.
You will need to run only
cd mt7610u_wifi_sta_v3002_dpo_20130916
make
sudo make install

after a kernel upgrade.
It is also possible to install it using DKMS. In this case it will rebuild automatically on kernel upgrades.
Comment: One more fresh driver for this shit https://github.com/xtknight/mt7610u-linksys-ae6000-wifi-fixes
Comment: And one more: https://github.com/ulli-kroll/mt7610u
Comment: And one more: https://github.com/Hygens/mt7610u_ubuntu_1610
Comment: It is possible to install the driver using DKMS. This way you will not need to re-install after kernel updates.
Comment: @Pilot6 How do I install w/ DKMS? I tried the above method and it isn't working.  Network Manager says device not managed.
Comment: I still want to know how to get it working with DKMS. Also, thoughts on whether to use the fork you linked, or chenhaiq's repo?
Comment: sorry this might sound like a silly question (i'm new), how do you guys know that isn't some virus or something that you are installing? ie the driver is written by some random folks and not the manufacturer
Comment: @Pilot6 true, but i bet of all the folks who installed this nobody has looked at it.. in theory that's true with all open source but in this case it seems particularly true.. no?
Comment: On Ubuntu 17.04 with kernel this fails: `error: 'IEEE80211_NUM_BANDS' undeclared here (not in a function)`
Comment: // , Ugh, really ? Every kernel upgrade? I'm just going to return it.
Comment: It can be installed with DKMS as any other kernel module. There is a lot of guides in the net.
Comment: You can see the source code.
Comment: Did not work for me, broke my distribution and lead to freezes on login screen. Be careful when you try this.
Comment: @Zelphir It is easy to uninstall the driver. So it can't "break your distribution".
Comment: @Pilot6 I take it back: Only when I plug in the device it freezes my system. So you are right. Unfortunately still no joy =(
Comment: @Zelphir You can ask another question regarding this problem.
Comment: On my system it began to work only when I copied file to `/etc/RT2870STA/`
Comment: @Orient I took the path from the github source.
Answer: I have a TP-Link T2U Wi-Fi adapter and I was in struggle to find a working driver for Ubuntu 18.10. All the drivers, original and modified, was for previous version of the kernel but nothing useful for the 4.15 kernel. After a painful morning I found a working link to run the TP-Link T2U on the latest kernel.
Here is the link: Trying to fix the MT7610U chipset driver - GitHub
After following the instructions everything worked! I found the link on TP-LINK Archer T2U v2 - WikiDevi.
If you would install the driver you will need to compile the source. To do this you will need install git and clone the repository in your home directory.
sudo apt install git
cd ~
git clone https://github.com/xtknight/mt7610u-linksys-ae6000-wifi-fixes.git
cd mt7610u-linksys-ae6000-wifi-fixes

You can avoid to write the whole directory just type the first letters, for example, mt7610, and press the Tab key.
sudo apt-get install build-essential linux-headers-$(uname -r)
make clean
make
sudo make install

After these steps the device should work. If you want the driver to work after the updating the kernel I advise to follow the next steps that includes the dkms utility. You will need to work in the directory "mt7610u-linksys-ae6000-wifi-fixes" otherwise the process will not work.
sudo apt-get install dkms
sudo cp -R . /usr/src/mt7610u_sta-1.0
sudo dkms add mt7610u_sta/1.0
sudo dkms build mt7610u_sta/1.0
sudo dkms install mt7610u_sta/1.0

I hope to be useful for the further development of this OS.
Comment: This worked for me on Ubuntu 18.04 kernel 4.18.0-24-generic. Thank you @NwalmeThule
Comment: Worked on Ubuntu 18.04 188.8.131.52-generic. Thanks a lot.
Comment: This worked for me on Mint 19.1 kernel 220.127.116.11. Thanks


How do I find the xpath for a Floating Action Button in Android?

Question: So I am writing automation with appium and so far I've been using the appium inspector to gather my xpath data. I'm referencing everything via xpath due to my app not having unique identifiers on all elements.
On the main screen of my app there is a Floating Action Button, taken from the default Android code, that leads to a majority of the functionality of my app.
The Appium Inspector is not seeing the floating action button, just elements underneath it. Is there a special way for me to tell appium to click the FAB?
Thanks so much for any help you can give me.
Answer: So I was able to get past this issue by utilizing the Android Device Monitor to find the FAB.
The Android Device Monitor allowed me to view the FAB's unique resource-id "bottom_navigation_fab" when the Android Inspector would not even highlight the FAB.
I suppose the answer is to utilize both tools simultaneously and experiment a lot. Hope this helps someone else out there.


SQL query to check if a key exists and its value is null in JSON column

Question: I am trying to select rows that has a JSON column where there is an object with a given key and value is null.
Example:
{
  "test": null
}

I tried the below query:
SELECT * FROM Table WHERE JSON_VALUE(Column, '$.test') IS NULL

Result columns:

{"test":null}
{}
{"prod":1}

This returns the expected rows but also returns rows that doesn't have such key.
How to return only the rows that have the key exist.
Answer: SQL Server 2016+:
You may try to parse the JSON with OPENJSON() and default schema. The result is a table with columns key (an nvarchar(4000) value that contains the name of the specified property), value (an nvarchar(max) value that contains the value of the property) and type, so you can implement an appropriate WHERE clause.
SELECT *
FROM [Table] t
WHERE EXISTS (
   SELECT 1
   FROM OPENJSON(t.[Column])
   WHERE [key] = N'test' AND [value] IS NULL
)

SQL Server 2022+:
Another option is a combination of JSON_PATH_EXISTS() and JSON_VALUE():
SELECT *
FROM [Table]
WHERE
  JSON_PATH_EXISTS([Column], '$.test') = 1 AND
  JSON_VALUE([Column], '$.test') IS NULL

Note:
When you use JSON_VALUE() and a strict path modifier, the result is an error for a wrong path expression:
SELECT *
FROM [Table]
WHERE JSON_VALUE([Column], 'strict $.test') IS NULL

Comment: Aren't there any other options? I find openjson to be quite expensive.
Comment: Yes, `... WHERE JSON_PATH_EXISTS([Column], '$.test') = 1 AND JSON_VALUE([Column], '$.test') IS NULL`, but you need SQL Server 2022.
Answer: You have to use JSON_EXTRACT
For example:
Select *
from table
where JSON_EXTRACT(Column, '$.test') IS NOT NULL

Comment: `JSON_EXTRACT` is a MySQL function *not* a SQL Server function.


List AWS snapshots using chef

Question: I am looking for a solution to list all AWS snapshots in chef and pick the latest one. All the snapshots are defined like this servername_service_date and I would like to list them via date and then let the server pick the latest one by date. So it will create the volume from that snapshot. I will be using AWS recipe, but they do not have the feature in it. So I would like to have some tips how to make it happen not a full code of course (if someone does not have it already). I hope you guys can help me.
Answer: Since Chef is just Ruby code, you could easily write a simple library using the AWS Ruby gem. For example:
AWS.ec2.snapshots #=> #<SnapshotCollection>

Answer: you will need the ruby aws SDK
you will need to identify the sections of the ruby SDK you will be leveraging (hint its ec2: https://docs.aws.amazon.com/sdkforruby/api/Aws/EC2.html)
you will need to instantiate a connector
ec2 = Aws::EC2::Client.new(region: 'us-east-1')

then you will do the specifics of your operation.. just be cautious adding random things to chef that work this way!
Leveraging the AWS cookbook (which already has the AWS SDK included) you could piggyback that functionality to extend it with your own.
My suggestion: just create something that gets this data and populates your chef lookups (a list of your snapshots) (maybe just populate json in an environment or something that has the list of your snapshots) (some external k/v store like consul to store the findings etc)

List AWS snapshots using chef


Having multiple Ids on linq-sql join query in c#

Question: I have a linq-to-sql query that fetches records.
First of all, I have a variable that can hold an Id or multiple Ids.
var consumerId = _context.Consumers.Where(x => x.UsrDefault.Equals("True"));
// This can return one or an array of Ids.

Then, I have a linq-to-sql query as follows:
var query = (from users in _context.Users
            join consumers in _context.Consumers
            on usersId equals consumerId
            select new UserConsumerDto
            {
             FirstName = users.FirstName,
             LastName = users.LastName
            }).ToList()

My question is that when I have multiple consumerId, how can I perform this linq-to-sql query ? I want to avoid any foreach loop.
Can someone please advise ?
Comment: If it's an array of Id then equality would never work right. Rather you will have to make it a `IN` clause (`Contains()`)
Answer: Contains is the method to be used here or Any().
See the code snippet below:
var query = (from users in _context.Users
            join consumers in _context.Consumers
            on users.usersId equals consumers.consumerId
            where consumerId.Contains(consumers.consumerId)
            select new UserConsumerDto
            {
             FirstName = users.FirstName,
             LastName = users.LastName
            }).ToList()

for any :
where consumerId.Any(id => id == consumers.consumerId)

Comment: Assalamualaikum Ehsan. Thanks you for your answer.

Another way of doing this could be: `join consumers on
    consumers.Id IN (consumerId)`

Do you advise this ?
Comment: Walaikum Salaam, i am not sure if it will be translated to proper sql, can be tried if it works
Comment: Thank you for your help brother :)


Torrent Not Downloading(Network Problem)

Question: for the last few weeks my torrents have refused to download showing the error: connection timed out to trackers. I recently(around the same time the torrents stopped downloading) changed my ssid and password to my wifi.
I have a laptop with windows 8.1 and ubuntu 16.04 and a desktop pc with arch linux all not downloading torrents and showing the same error("Connection timed out") so i'm guessing the problem is with my router. I've tried restoring my ssid and passwd back but still nothing. Thanks for any help.
Comment: Hi @DeepSidhu1313 I've noticed if i "test port" on my clients it says port closed even though i have enabled uPnP in my router settings. Could that be the problem?
Comment: After a whole day of frustrations i've been able to finally figure it out the problem was the router firewall was set to high this blocked all ports and all incoming connections. It only allowed connections from a predetermined list of ports by the firewall.                                                                       When i set the firewall setting to "off" it changed to No Ports Restricted  and torrents started downloading immediately.
Comment: Have u tried on ethernet cable ?? And also see if uPnP is allowed in ur router settings.
Comment: Hi @DeepSidhu1313 thanks for taking the time to reply. The pc with arch linux is connected by ethernet cable and dosen't download. I did not change any settings regarding upnp before it stopped downloading although i've checked and upnp is not enabled.Security wise is it ok to enable it?
Comment: Which country r u from ?? Bcz recently some isps and governments has blocked torrents. uPnP is a network service discovery protocol helps torrents to find computers behind NAT. Ask your isp if they have blocked torrents. Also try downloading some linux distro via torrent. That will help u determine if all the torrent traffic is blocked or there is some other problem.
Comment: I'm in Kenya and we have no laws regarding torrent downloads. I've also checked with my friends whom we share the same isp and they are torrenting just fine. I've enabled uPnP and still nothing. I've downloaded ubuntu 17.04 from ubuntu and says could not connect to tracker.
Comment: And apart from torrents, internet is working fine.
Comment: Yap. On all three Os's
Comment: Good to hear that you solved your problem. I was about to say that. Apologies i was busy somewhere. :). Please add this as your answer with complete set of steps you followed.
Comment: Thanks a lot for your help.I have posted the solution as my answer @DeepSidhu1313
Answer: After a whole day of frustrations i've been able to finally figure it out, the problem was the router firewall was set to high(High chance i set it when i changed ssid and passwd  but i don't remember it) and blocked all incoming connections. It only allowed connections from a predetermined list of ports by the firewall.
When i set the firewall setting to "off" it changed to No Ports Restricted  and torrents started downloading immediately. I even disabled uPnP and removed port forwarding and it's still working.                                                                                The issue was with the router firewall. I hope this helps someone avoid the frustration i have had.


Playing sound at interval with GCD timer not behaving as expected

Question: Hi !
I'm building a timer using GCD for the purpose of playing a sound at a specific interval, to be more precise, it's a metronome sound. I've been trying for days to solve my issue but nothing. Everything is good but when I set my tempo to a bigger value , let's say 150 bpm or 200 bpm, when the sound starts for the first time, it fires very quickly(almost like two sounds in the same time meaning it does not have the expected interval) and after this , it calibrates. I start the sound the second time , all is good... so this happens only the first time I resume my dispatch source so I'm guessing it has something to do with loading the sound from the disk , like in this post : Slow start for AVAudioPlayer the first time a sound is played . For my sound I used at first an instance of AVAudioPlayer with prepareToPlay and play and also created it in the AppDelegate class, it hasn't work...I have even tried the SoundManager class developed by @NickLockwood,same issue. At present, I'm using a SystemSoundID.  As for the timers, this is my first GCD timer , I've already tried  the classical NSTimer, CADisplayLink and other timers found on git... all in vain.
Another interesting issue is that with the other timers , everything is perfect on the simulator but on the device the same glitch.
Here's the code, I hope someone will bring me to the light.
 -(void)playButtonAction  //
    {
        if (_metronomeIsAnimatingAndPLaying == NO)
        {
            [self startAnimatingArm]; // I start my animation and create my timer

            metronomeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));

            dispatch_source_set_timer(metronomeTimer,dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC),duration * NSEC_PER_SEC,duration *NSEC_PER_SEC);

            dispatch_source_set_event_handler(metronomeTimer, ^{[self playTick];});

            dispatch_resume(metronomeTimer);

            _metronomeIsAnimatingAndPLaying = YES;
        }

    }

-(void)playTick
{
   AudioServicesPlaySystemSound(appDeleg.soundID); // soundID is created in appDelegate
}

In my application didFinishLaunching
NSString *path = [[NSBundle mainBundle] pathForResource:@"tick"
                                                 ofType:@"caf"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path]
                                 , &_soundID);

And BPM setter and getter :
- (NSUInteger)bpm
{
    return round(60.0 / duration);
}

- (void)setBpm:(NSUInteger)bpm
{
    if (bpm >= MaxBPM) {
        bpm = MaxBPM;
    } else if (bpm <= MinBPM) {
        bpm = MinBPM;
    }
    duration = (60.0 / bpm);

}

Answer: This arrangement will fundamentally never work.
GCD is a thread-pool designed to facilitate task-level parallelism. It is usually asynchronous and non real-time.  These are almost precisely the opposite characteristics to those required in an audio application.
Each thread servicing a GCD queue is contending with other threads in the system for an opportunity to execute. Furthermore, the queue may be busy at requested time processing something else.  If that something else is long-running - and long-running tasks are precisely the kind of thing that GCD is made for -  the scheduler may pre-empt the thread before the operation has completed and penalise the queue; it may wait a long time for service.
The Manpage for GCD states the following about timers on GCD queues:
A best effort attempt is made to submit the event handler block to the target queue at the specified time; however, actual invocation may occur at a later time.
NSTimer will not be any better.  Its documentation states A timer is not a real-time mechanism.  Since you'll probably run this on the application's main run-loop, it will also be very unpredictable.
The solution to this problem is to use lower-level audio APIs - specifically Audio Units.  The advantage of doing so is that soft-syth units have an event queue which is serviced by the unit's render handler.  This runs on a real-time thread, and offers extremely robust and predictable service.  Since you can queue a considerable number of events with timestamps in the future, your timing requirements are now quite loose.   You could safely use either GCD or a NSTimer for this.


python tk tkinter multiple canvas can not afford in my scrollable frame

Question: import tkinter as tk
from tkinter import filedialog
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  NavigationToolbar2Tk)
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from data import dataprocess
root = tk.Tk()
root.geometry('1500x800')
container = tk.Frame(root)
main_canvas = tk.Canvas(container, width=1480, height=800,  bg='blue')
scrollbar = tk.Scrollbar(container, orient="vertical", command=main_canvas.yview)
scrollable_frame = tk.Canvas(main_canvas, bg='black')
scrollable_frame.bind(
"<Configure>",
lambda e: main_canvas.configure(
    scrollregion=main_canvas.bbox("all")
    )
)

main_canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

main_canvas.configure(yscrollcommand=scrollbar.set)

for i in range(100):
    f = Figure(figsize=(5,5), dpi=100)
    a = f.add_subplot(111)
    a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
    a.set_title("fig" + str(i))
    canvas = FigureCanvasTkAgg(f,
                           master = scrollable_frame)
    canvas.draw()
    canvas.get_tk_widget().grid(row=i, column=0)

container.grid()
main_canvas.grid()
scrollbar.grid(row=0, column=1, sticky="nse")
container.mainloop()

I would like to generate lots of canvas on my scorllable frame, but it seems failed by maxiumn canvas size. Is there any method to fix it?
code image
Comment: The scrollable frame needs to be a Frame, not a Canvas.
Comment: May be using multiple columns instead of single column.  Or using `main_canvas.create_window()` instead of scrollable frame.  However your approach will significantly slow down your system performance.
Answer: I'll take a guess and say that what you really want is a ScrolledText widget. Try this:
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  NavigationToolbar2Tk)
from matplotlib.figure import Figure

root = tk.Tk()
root.geometry('1500x800')
scrollable_frame = ScrolledText(root)
scrollable_frame.pack(expand=True, fill=tk.BOTH)

for i in range(10):
    f = Figure(figsize=(5,5), dpi=100)
    a = f.add_subplot(111)
    a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5])
    a.set_title("fig" + str(i))
    canvas = FigureCanvasTkAgg(f)
    scrollable_frame.window_create(tk.END, window=canvas.get_tk_widget())
    scrollable_frame.insert(tk.END, '\n')

root.mainloop()

100 graphs will be very taxing no matter what, on the computer and the human. I think it would be better to design your program differently so that the graph is updated rather than scrolling through many graphs.
Comment: The above code worked!  How can I do if I want 'grid'  instead of 'pack' method. I also want to add some widget such as buttons and Labels in ScrolledText.
Thank for your suggestion about my designation, however, it is for specific purpose.
Comment: The widgets do not use grid or pack inside a Text or Canvas, you only use those when adding to a Frame type. To add Buttons you would add them with the `window_create` method, just like I used for the graph. You can add Labels that way too, but the Text widget supports raw text so you probably want to use `insert()` for that.

To put the Text object into the root window I used pack(), but you can just swap that for grid() if you want.
Comment: I success. Here is a new problem about I only want to change figure 1~5 without re-plot all figures. Any suggestion?
Comment: @curry just keep the reference to the plot and update it with set_data(). If you need help with that make a new post.
Comment: I might know your meaning. I still have no idea how to put reference id to each plot and update with set_data(). Can you give me some sample code or reference link. I appreciate it.


Save and refresh language preferences stored in localstorage

Question: I have a bit of the problem trying to implement language switcher/preference
I made a localstorage item for that, but got a problem because of reload need.
function lang_displayed_settings() {
  if (localStorage.getItem("language") === "pl") {
    window.location.hash = "#pl"
    location.reload();
  }
}

I tried to do a function on window load to get a item with preferred language but I can't really make it to be reload automatically. Or I'm getting a loop when window is just reloading on load.
I need a function which works on hrefs etc.
Now I have no idea what I can change to get it working!
Hope someone made it better than me.
(code from above is a clear one, before me uselessly trying)
Comment: I suggest setting [the `lang` attribute of the `html` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang) to the selected language rather than using a hash. It's more standards-friendly.
Answer: If the language item in the localstorage is already set to "pl", your code will reload and will find the property set to the same value again and will just keep reloading your page.
The solution is to add another if condition to check for the existence of #pl in window.location.hash so you wouldn't have to reload the page when the hash is already set:
function lang_displayed_settings() {
  if (localStorage.getItem("language") === "pl") {
    if (window.location.hash === "#pl") {
      return;
    } else {
      window.location.hash = "#pl";
      return location.reload();
    }
  }
}

If you want the language setting to support many languages, you can load it from the localsorage on the first loading of the page and then run the hashing logic as follows:
window.onload(() => {
    const lang = localStorage.getItem("language")
    if (window.location.hash === `#${lang}`) {
        return;
      } else {
        window.location.hash = `#${lang}`;
        return location.reload();
      }
})


How can I insert a Bash variable using the Gedit Snippets plugin?

Question: I use Gedit and enabled the Gedit Snippets plugin. I added a custom snippet for the sh language that shall contain a Bash variable like $LINENO. It looks like this simplified example:
my_command || ( echo "Error on line $LINENO" ; exit 1 )

However, if I let the plugin insert this snippet above, it tries to evaluate the $LINENO itself and removes it from the inserted code, so that I only get this result:
my_command || ( echo "Error on line " ; exit 1 )

Is there a way to make Gedit Snippets simply insert $LINENO literally, instead of trying to evaluate it?
Comment: Can you please give us a short example (only a few lines) that shows what you want to achieve? I'm having troubles to understand you...
Comment: I edited your question and removed all the long story around it and added a simple example. I hope everything I changed still fits your needs?
Comment: After editing a file, I use an or statement to catch if it failed and call my exit function, give the line number of the script, and a short explanation, like this:                || error_exit "$LINENO: File edit failed."
Comment: I want the actual variable '$LINENO' to populate in the script I'm editing, but gedit tries to get the value and inserts a blank space, like this: || error_exit " : File edit failed.".   The idea is that bash should be interpreting the variables value when the script is run, not gedit. Having to cut and paste that variable every time I use the error snippet I made is getting very frustrating.
Comment: did you try quotes or backticks around the variable? I assume you are talking about shell placeholders?
Answer: You must simply edit your snippet and escape the $ in Gedit's snippet manager with a \ backslash, just as you can see in the screenshot below.
That way the $LINENO will not be evaluated by Gedit Snippets, but inserted literally.
Comment: /facepalm... After using sed repeatedly you'd think that would've popped into my head.  It works, thank you very much.
Comment: If this answer solved your problem, please accept it by clicking the grey round check button on its left. You mark your problem as solved that way. Please don't forget to invest two minutes to take our little [tour] as well, where you can learn the basics about how our site works. Thanks and welcome to Ask Ubuntu :-)


Prove that $\frac{g(x)}{\ln(1+x)}$ is integrable over $[0,1].$

Question:
Question: Let $f$ be a measurable function on $[0,1]$ such that
  $$g(x) = |f(x)| \ln(1+x)$$
  is Lebsegue integrable over $[0,1].$
  Prove that $f$ is Lebesgue integrable over $[0,1]$

So the question is asking us to show that
$$\int_0^1 |f(x)|\, dx = \int_0^1 \frac{|g(x)|}{\ln(1+x)}dx$$
is finite.
However, I think that the question is not correct.
Clearly $g(x) = 1$ is Lebesgue integrable over $[0,1],$ as
$$\int_0^1 |g(x)| \, dx = 1,$$
but
$$\int_0^1 \frac{1}{\ln(1+x)}dx,$$
based on Wolfram Alpha, is not finite.
So $f$ is not Lebesgue integrable over $[0,1].$
Is my reasoning correct?
Comment: Yes, it's correct.
Comment: Your reasoning.
Comment: 'It' refers to my reasoning or the question?
Answer: Your reasoning is correct: intuitively, it could be thanks to the fact that $\ln(1+x)$ goes to $0$ as $x$ goes to zero that $g$ is integrable while $f$ alone is not.
The example $f\colon x\mapsto 1/\ln(1+x)$ shows this. It is indeed true that $\int_0^1 \frac{1}{\ln(1+x)}\mathrm dx$ is divergent but this requires a mathematical justification. This is due to the fact that $\lim_{x\to 0}\ln(1+x)/x=1$ and the divergence of $\int_0^1 \frac{1}{x}\mathrm dx$.


How to /testfor a named item in a player's inventory?

Question: I'm working on a PVP map that I have posted to pmc so random people can download it and play it with their friends. My problem is, each kit has a special buff (potion effect) but when they die it leaves them.
I need this to make kinda like a loop that when they have like some armor on when they die it will test for that armor and give more potion effects.
Comment: Please be more direct on what you want help on, it's impossible to understand what you want us to do.
Comment: I agree, more details are needed.  What exactly is in the kit?  What is a buff?  A renamed potion or renamed armor or ...?  You would like to test for specific armor at the time of the players death and apply an effect if they are wearing it?  Take your time to make sure you ask a concise question.
Comment: ok so like i have a leather chestplate called "heros tunic" and i want the command to testfor if somebody is wearing that named piece of armor. and then that player specificaly will get a loop of the potion effect so when they die they will get it right back if you can help thx.
Comment: When would this loop end?  Currently, it sounds as though, if they are ever tested to be wearing the armor, they would have an effect forever after that.  Is that what you want?
Comment: forever untill like you use effect @p clear
Answer: Here is a solution that will give anyone wearing a leather chestplate named Hero's Tunic the tag Wearing.  This tag can then be used to target that person for the effect.  Commands are for 1.12.2.
Note: Using only these commands, if a player ever wears the chestplate, they will be tagged and the effect will be applied forever, even if no longer wearing the chestplate. (unless the tag is manually removed via a command)

Make command block that is RepeatUnconditionalAlways Active with command:
scoreboard players tag @a add Wearing {Inventory:[{Slot:102b,id:"minecraft:leather_chestplate",tag:{display:{Name:"Hero's Tunic"}}}]}

Here is an example command that gives them a level 2 slowness effect for 1 second.  This will be a constant effect if the command is placed into a RepeatUnconditionalAlways Active command block:
effect @a[tag=Wearing] minecraft:slowness 1 2

To remove the tag from a player:
/scoreboard players tag <player_name> remove Wearing

Replace <player_name> with the name of the player that you want to remove the tag from.

To remove the tag from all players:
/scoreboard players tag @a remove Wearing

Edit:  Response to comments.
To have more tags for more pieces of armor you would change the first command:
scoreboard players tag @a add <tagName> {Inventory:[{Slot:102b,id:"minecraft:leather_chestplate",tag:{display:{Name:"..."}}}]}

Replace <tagName> with whatever name you like.  You could use numbers if wanted.  (Wearing1, Wearing2, etc)  You could also use other names that describe whatever you like.  Example: WearingHerosTunic  You can use a different tag for each different chest plate.
Then use those tags in the other commands:
effect @a[tag=WearingHerosTunic] minecraft:slowness 1 2

Comment: thx so much this really helped sorry for the confusion.
Comment: so also with this command:effect @a[tag=Wearing] minecraft:slowness 1 2
could you like make it give the potion effect if the player is wearing that specific named item because i have to make fourteen of these and they just turn each other on. if you can help thx
Comment: So you only want the effect if they are wearing the armor?  You had mentioned the potion effect being applied after a death, that is where the confusion comes in.  You said you have to make 14 of these.  What do you mean?  Fourteen different named armor?  Why?  Fourteen different effects?
Comment: effect @a[tag=Wearing itemname: heros tunic] minecraft:slowness 1 2
i need something like this if it is possible.
Comment: Do you want the effect to wear off if they take off the armor or do you just need 14 different tags?
Comment: 14 different tags
Comment: I updated the answer to include that information.
Answer: Well, honestly it's quite simple, this might not work on Java but I do know it works on bedrock
/execute @a[nbt={Inventory:[{id:"minecraft:diamond_sword"}]}] ~~~ /effect @s slowness 1 2 true
Because the @s is there it will effect the player with the item(s) only


Where can I check the happiness

Question: Where can I check the happiness from my Pokemon on Pokemon White ? I Know that there is a NPC who can say it to you using some phrase. But there is other way to check it or is it the ONLY way to see they happiness ?
I am asking this because I have a lot of Pokemons that need evolution (by happiness) and I want to know how much everyone has before I start leveling them.
Regards
Answer: The two characters listed there are the only ways to check happiness levels in B/W as far as I know. There is no way to find out the exact value in-game.
However, there is an online tool called PokeCheck that can give you all the exact stats of your Pokemon, including happiness. (It works by "intercepting" a connection to the GTS and recording the Pokemon data; nothing is traded away or modified.)
If you need to evolve Pokemon by happiness the easiest solution is to make them old the Soothe Bell and keep them in your party while you train others. You can let them battle a bit, but don't let them faint. Some other methods like massages are listed on Bulbapedia.

Where can I check the happiness


Upload Google Drive API Retrofit 2

Question: Here is the interface for Retrofit2:
public interface OAuthServerIntf {

....
@POST("upload/drive/v3/files?uploadType=multipart")
@Multipart
Call<JsonObject> uploadFileMutil(
        @Header("Authorization") String authToken,
        @Part MultipartBody.Part metaPart,
        @Part MultipartBody.Part dataPart);

}

That's where I call:
public void onActivityResult(...) {
   ....
 MultipartBody.Part filePart =
    MultipartBody.Part.createFormData("image", file.getName(), fileBody);
 Call<JsonObject> request =
    server.uploadFileMutil(oauthToken.getAccessToken(),filePart);
 request.enqueue(new Callback<JsonObject>(){...});

}

oauthToken.getAccessToken()-accesstoken
MultipartBody.Part filePart - file that I want to send to the server
In general, how to conduct an inquiry and that these 2 parameters for metaPart and dataPart?
Read that token need to bring to the Bearer type, how to do it ???
Answer: not sure if you found the answer. still show some code in below, and hope this help someone.
val contentType = MediaType.parse("application/json; charset=UTF-8");
val content = "{\"name\": \"" + srcFile.name + "\"}"
val metaPart = MultipartBody.Part.create(RequestBody.create(contentType, content))
val dataPart = MultipartBody.Part.create(RequestBody.create(MediaType.parse("text/plain"), srcFile))
val headers = HashMap<String, String>()
headers.put("Authorization", "Bearer " + accessToken)

mDriveApi.uploadFile(headers, metaPart, dataPart)

Upload Google Drive API Retrofit 2


Decrypt Rijndael with Passphrase in PHP

Question: A customer is sending us a file encrypted with "AES-256". It arrives as a binary file (I normally get base64-encoded files, but this should be OK) and, in desperation, I have iterated through the PHP options using mcrypt_decrypt but cannot crack it.
<code><?php
$str = file_get_contents($argv[1]);
$key ='jimminny fred owns apple'; //not the actual one, but same length

$modes = array(
    MCRYPT_MODE_ECB,
    MCRYPT_MODE_CBC,
    MCRYPT_MODE_CFB,
    MCRYPT_MODE_OFB,
    MCRYPT_MODE_NOFB);

$cryps = array(
    MCRYPT_RIJNDAEL_128,
    MCRYPT_RIJNDAEL_256,
    MCRYPT_RIJNDAEL_192);

foreach($modes as $mode){
    foreach($cryps as $cryp){
        echo "\n\n$cryp $mode\n\n";
        echo mcrypt_decrypt($cryp, $key, $str, $mode);
    }
}
</code>
My understanding is that I should be receiving a 32-byte key, not a 24 char passphrase, but they are using a program called GlobalScape  and this is all it requires for its 'Rijndael' encryption. (See screenshot attached showing the dialog window that the customer completes at their end).
Comment: After a lot more testing and messing about, I am pretty certain that the GlobalScape file is not encrypted in a standard way. It turns out that the passphrase doesn't have to be 32 bytes - I don't understand why, but PHP seems happy - even in v5.6, which is supposed to insist on keys of 32 bytes according to the mcrypt pages at php.net
Answer: I've checked the site and GlobalScape doesn't offer any details on how they encrypt. Not only do they not specify the key derivation function (KDF) that they use for "Rijndael" encryption. It's unlikely that they directly use the passphrase as a key - unless they are complete muppets - but the KDF could be anything. They do not specify the mode of operation for AES either
Simply do not use trash like that. Just use PGP or one of the standardized options for sending / receiving messages.
Going on a wild goose chase won't help you. Even if you program a solution then it may fail in the future because of any number of factors. Ask your client to clearly specify a protocol instead of giving you a screenshot.
Comment: Thanks. Good advice. Almost exactly what my manager ended up saying too :).

Decrypt Rijndael with Passphrase in PHP


Need help fixing Segmentation Fault

Question: I'm still fairly new to linux and find myself making annoying noob mistakes. Yet, still loving the experience so what does that really say about me?
I ran into an interesting problem that I'm not sure how to correct. I was trying to upgrade my nodejs through npm and began running into a series of problems. However, the one that got me stuck is a segmentation error when using the node command. Nodejs works fine (nodejs - v returns v 0.12.7).
I need to mention that the node command worked fine until I followed one step too many from a forum post and didn't realize what I had done until I hit enter. (How can I update my nodeJS to the latest version?)
I created a symbiotic link using ->  sudo ln -sf /usr/local/n/versions/node//bin/node /usr/bin/node.
This was a step not needed as the installer had already taken care of all this.
I tried reversing my steps and have tried to remove nodejs and npm to the best of my ability and then reinstalling. I was able to reinstall just fine and upgrade but still unable to get the node terminal command to work properly.
I have been looking for how to correct a segmentation fault but keep finding explanations as to what a segmentation fault is and isn't very useful to me as my problem isn't a lack of understanding of the error but lack of understanding of the linux environment and not entirely sure how to go about fixing this problem without causing me errors.
If anyone could shed some light as to possible steps one could take to correct this type of error it would be a HUGE help.
And no this is not a nodejs question it just so happens that's the program I did it to. lol
It's not a huge deal but I'm trying to install the nodejs driver for mongodb and when using npm its looking for the node command and causing an error during install.
Thanks in advance to anyone who can help me out.
Answer: Okay so... I'm dumb. Thanks for listening guys. lol
Basically, all I had to do was run sudo n 0.12.7 to tell it which version to install.
I get the feeling there's a huge mess of things if I start looking at what's been installed more than once but its working for now. I'll do a clean Ubuntu install soon and start again from scratch without all my mistakes.

Need help fixing Segmentation Fault


Escape field inside Control loop

Question: New to SilverStripe and trying to decypher how things work.
I have a field in a page which I used to store some HTML code. When you view their "Holder" page, it loops over each child page and displays them all. The problem I am running into is that when I output the value it's escaping it - so I need to be able to decode it.
<% control Children %>

$Title

    $ExtraHtmlBody
 <% end_control %>

So I tried to add a function inside my Page_Controller, but it seems that I can not call Page_Controller methods from inside the Control loop. I tried moving the function into the Page class, but it doesn't seem to have any data for $this->ExtraHtmlBody. Maybe I'm doing something wrong.
Comment: What datatype is your "ExtraHtmlBody" in $db? As it contains HTML it probable should be HTMLText or HTMLVarchar. As of Silverstripe 3.1 default casting is Text. http://doc.silverstripe.org/framework/en/3.1/changelogs/3.1.0
Comment: It was just Text. I just tried changing it in my class, and edited the page again and still escaped. Is there anything I need to do to update the changes I make in Page class?
Comment: ehm well, /dev/build - and edit?
Answer: You data might already be escaped in the database itself. did you check?
Like @munomono said, if you are storing html use HTMLText or HTMLVarchar.
You can also try to disable auto-escaping in your template with $ExtraHtmlBody.RAW (at your own risks).
some info here:

http://doc.silverstripe.org/framework/en/topics/data-types#casting-html-text
http://doc.silverstripe.org/framework/en/topics/security#what-if-i-can-t-trust-my-editors
http://doc.silverstripe.org/framework/en/reference/templates#formatting-and-casting

Your controller function problem is probably just a scope  issue since <% loop %> changes the scope, $Up/$Top might help. But you probably don't need that function anyway.
Comment: Ahh, .RAW fixed it. Had no idea about that feature.
Comment: well, it isn't advised and most likely a security issue (but narrowed down the issue). Hence using `HTMLText` or `HTMLVarchar`. @LouisW did you try changing the field type? Remember to run `/dev/build` after...
Comment: no offense @colimba but just want to make sure not to build wrong reference marked as solution. apropos reference (hopefully not to confuse even more) one can also set static $casting = array('ExtraHtmlBody' => 'HTMLText'); but it's not needed in this case, since it's default for HTMLText datatype.
Comment: hence the links to the documentation and security pages.

Escape field inside Control loop


If $k$ is odd, then $(k-1)k(k+1)$ is divisible by $24$

Question: How would I show this?
I tried letting $k=2n+1$ for some $n\in\mathbb{Z}$, then
$$(k-1)k(k+1) = 4n(2n + 1)(n+1).$$
I have shown that $4n(n+1)$ is divisible by $8$... but am unsure of how to get the $3$ factor there.
Comment: One of $\,k\!-\!1,\,k,\,k\!+\!1\,$ is divisible by $3.\,$ [Generally](https://math.stackexchange.com/a/2405197/242) a sequence of $d$ consecutive integers has a multiple of $d.\ $
Answer: HINT:
$$4n(2n+1)(n+1)=2n(2n+1)(2n+2)$$ is the product of three consecutive integers, hence exactly one of them must be divisible by $3$
Comment: @Natash1, consider two cases: if $n$ itself is divisible by 2, and when it is not.
Comment: If I just consider $2n(2n+1)(2n+2)$, I can conclude it's divisible by $2$ (since there's a factor of $2$ there) and $3$, since one of them is divisible by $3$. How do I get the factor of $4$ there? (I thought I can look at the coefficient on the LHS... but wouldn't I be "double counting" the factors since 2*2 = 4)?
Comment: I seem to only be able to conclude it's divisible by $12$
Comment: @Natash1 If you have two consecutive even numbers (like 10 and 12; or 104 and 106) then one of them must be divisible by $4$, not just $2$. So your outer two numbers are collectively divisible by $8$ (or maybe even a higher power of $2$).
Comment: @Natash1, See https://math.stackexchange.com/questions/126766/prove-that-one-of-n-consecutive-integers-must-be-divisible-by-n   https://math.stackexchange.com/questions/12065/the-product-of-n-consecutive-integers-is-divisible-by-n-factorial/12070   https://math.stackexchange.com/questions/12067/the-product-of-n-consecutive-integers-is-divisible-by-n-without-using-the-prop
Comment: If there are three consecutive numbers such that the first is even, one will be divisible by 2, one by 3 and one by 4, and that's it. @Natash1
Comment: @Natash1 It is much clearer to view this in terms of $k,\,$ viz. one of $\,k\!-\!1,\,k,\,k\!+\!1\,$ must be divisible by $3.\ $
Answer: An alternative.
Mod $3$, $k^3\equiv k$ by Fermat's Little Theorem.
It's a useful fact that $1^2\equiv3^2\equiv5^2\equiv7^2\equiv1$ mod $8$. In other words, if $k$ is odd, then $k^2\equiv1$ mod $8$. So mod $8$, $k^3\equiv k$.
Together this gives that $k^3\equiv k$ mod $24$ when $k$ is odd. So $24$ divides $k^3-k=k(k-1)(k+1)$ when $k$ is odd.
Answer: This is true for $k=1$ because the product is zero.
Assume it is true for $k=2r-1$, then $$(2r+2)(2r+1)2r-2r(2r-1)(2r-2)=2r(4r^2+6r+2-4r^2+6r-2)=24r$$ so it is true also for $2r+1=2(r+1)-1$ and you are done by induction.
Easier, perhaps, to observe that of three consecutive integers one will be divisible by $3$ and of two consecutive even numbers one will be divisible by $4$.


Updating FirestoreRecyclerAdapter using updateOptions() give Type mismatch error

Question: I'm using Firebase UI to populate my RecyclerView, it all works fine except when I try to change the order of list elements when a button is clicked.
Here is my adapter code:
private var query: Query = FirebaseFirestore.getInstance()
    .collection("restaurant")
    .orderBy("review", Query.Direction.DESCENDING)

var options: FirestoreRecyclerOptions<Restaurant> = FirestoreRecyclerOptions.Builder<Restaurant>()
    .setQuery(query, Restaurant::class.java)
    .build()

private var adapter: FirestoreRecyclerAdapter<*, *> =
    object : FirestoreRecyclerAdapter<Restaurant, RestaurantListAdapter.ViewHolder?>(options) {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RestaurantListAdapter.ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.restaurant_card_view_design, parent, false)
            return RestaurantListAdapter.ViewHolder(view)
        }

        @SuppressLint("ResourceAsColor")
        override fun onBindViewHolder(
            holder: RestaurantListAdapter.ViewHolder , position: Int, model: Restaurant
        ) {
            val sharedPref = getPreferences(Context.MODE_PRIVATE) ?: return
            val defaultValue = resources.getString(R.string.def_loc_key)
            val lat = sharedPref.getFloat(getString(R.string.latitude_key), defaultValue.toFloat())
            val long = sharedPref.getFloat(getString(R.string.longitude_key), defaultValue.toFloat())

            model.calculateDistance(lat, long)

            // sets the text to the textview from our itemHolder class
            holder.distance.text = String.format("%.1f mi", model.distance)
            holder.name.text = model.name
            holder.reviewNum.text = String.format("(%1d)", model.numReview)
            holder.review.rating = model.review
            if (position == 0) {
                //holder.card.setCardBackgroundColor(R.color.recommendedCard)
                holder.card.setCardBackgroundColor(ContextCompat.getColor(holder.card.context, R.color.recommendedCard))
            }
            holder.logo.setImageResource(
                resources.getIdentifier(model.logo , "drawable",
                packageName
            ))
        }
    }

And here is my code for on button click (inside onCreate()):
val sortButton = findViewById<ImageButton>(R.id.sortButton)
sortButton.setOnClickListener {
    query = query.orderBy("numReviews", Query.Direction.DESCENDING) // new campo

    options = FirestoreRecyclerOptions.Builder<Restaurant>()
        .setQuery(query, Restaurant::class.java).build()

    adapter.updateOptions(options)
}

I get an error on the last line saying :

Type mismatch: inferred type is FirestoreRecyclerOptions but Nothing was expected
Answer: When you are using the following query:
private var query: Query = FirebaseFirestore.getInstance()
    .collection("restaurant")
    .orderBy("review", Query.Direction.DESCENDING)

It simply means that are trying to get all documents that exist in the "restaurant" collection, ordered by "review" descending. Which is fine. However, when you are using the following line:
query = query.orderBy("numReviews", Query.Direction.DESCENDING)

It means that you are adding an additional order to your existing query. So after adding the above orderBy, your query looks like this:
private var query: Query = FirebaseFirestore.getInstance()
    .collection("restaurant")
    .orderBy("review", Query.Direction.DESCENDING)
    .orderBy("numReviews", Query.Direction.DESCENDING)

This type of query doesn't work by default, as it requires an index.
Please note, that Cloud Firestore queries are immutable, which means that you cannot change the properties of an existing query. If you change the value by calling an "orderBy()" method, it becomes a new query. So if you only want to change the order, simply change the second query to:
query = FirebaseFirestore.getInstance()
    .collection("restaurant")
    .orderBy("numReviews", Query.Direction.DESCENDING)
//

Comment: Without seeing the changed code, I can not be much of a help. So please post a new question, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you.
Comment: I have done this and added stopListening() before and startListeningAfter() but the UI isn't updated it just flickers like its supposed to do something but the order of the elements does not change.


Materialize css all tabs coming together below each other, but working properly after refresh

Question: I use materialize css tabs and it loads all the divs, one below the other on the first load.
If i refresh the page, it starts behaving properly.

Test 1

Test 2

Disabled Tab

Test 4

Test 1

Test 2

Test 3

Test 4

This just gives me the snippet below on the first load / server restart:
snippet
Now, if i refresh the page. It works as expected.
I imported all the required js(jquery and materialize) and css and I also added the initialization for tabs.
$(window).on("load", function () {
    $('ul.tabs').tabs();
  });

i have tried
$(document).ready(function () {
        $('ul.tabs').tabs();
      });

The issue still persists.
Anyone know the solution to this?
I am facing too many issues like these with materialize.
Also, I use react. If that makes any difference.
Using react-materialize, I face the below issue.
<Tabs className='tab purple darken-4'>

                    <Tab title="All">1</Tab>
                    <Tab title="Ongoing" active>2</Tab>
                    <Tab title="Successful">3</Tab>
                    <Tab title="Failed/Warning">4</Tab>

 </Tabs>

React issue on adding divs
Comment: I don't understand the problem. Can you provide a picture with the issue?
Comment: added snippet in question
Comment: Check the order of script loading in the developer tools.Both before and after refreshing.
Comment: Mixing react and jQuery is not a good idea. I suggest you to consider using a react version of material-ui.
Comment: @HemaNandagopal
The files are loading in the correct order.
1. jQuery
2. Materialize.js
3. then  react bundle js
Comment: @bennygenel Using react-materialize is very restrictive. I cannot wrap my tabs in divs. It just breaks
Comment: What do you mean by restrictive? What do you mean by breaks?
Comment: @bennygenel Please see edit. Tabs just disappear
Answer: When you use Tabs component; react-materialize get the child components and renders them accordingly. Since you are wrapping all components with a single div the render breaks.
You can try doing something like this;

    <Tabs className='tab purple darken-4'>
        <Tab title="All">1</Tab>
        <Tab title="Ongoing" active>2</Tab>
        <Tab title="Successful">3</Tab>
        <Tab title="Failed/Warning">4</Tab>
    </Tabs>

OR
<Tabs className='tab purple darken-4'>
    <Tab title="All">

            1

    </Tab>
    <Tab title="Ongoing">

            2

    </Tab>
    <Tab title="Successful">

            3

    </Tab>
    <Tab title="Failed/Warning">

            4

    </Tab>
</Tabs>

If you like to change the apperiance of the Tabs or a single Tab component you can use className prop for them too.
Comment: Thanks!. This solved one problem, but gave another.
The underline for active is not coming on the first item.
If go to the second tab and come back to the first tab, it appears
Comment: you need to set the initial active tab I think. Check the docs for more info.


Broadcasting System Events

Question: Is it possible for Android Applications (Not Framework Apps) to broadcast System Events like, BOOT_COMPLETED?
I think it is not possible to post since it is way of faking the system Actions, but wanted to know the correct answer.
Is there any place where android developer website talks about this?
Answer: This is not possible via 3rd party Application.
Although, You can send these broadcast via ADB, like
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

or
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n package_name/class_name

Comment: Hi Pankaj, My question was how to send this events pro-grammatically form our apps
Comment: Ohh yes, I updated the answer. I though you are aware that its possible and looking for another way. :)
Comment: I think u were trying to say its not possible in the comment.
"Ohh yes, I updated the answer. I thought you are aware that its possible and looking for another way. :) "
Comment: :D yes. sorry that my mistake. :(

Broadcasting System Events


Mysql select query is not showing result if the search value is small letter

Question: In mysql table I've a file_content column which contain resume text. In my search form I'm searching this resume text using following mysql query.
For example : I've a text in my db table column  is like this :
SUMMARY IS start here.

NOW if i put the summary in serach field it's not showing the result but If I use SUMMARY then it's showing the result.
It's look like sql case sensitivity problem. I don't know exactly. Can anyone tell me how do i fix this search query so that it will result any data whatever the value it is like: capital or small letter.
if(!empty($ad_resume)){
    $getSearch .= "AND BINARY LOCATE('$ad_resume', contact_docs.file_content)"; //is this the resume? yes
}

Comment: @Strawberry Remove the BINARY is not working, is there any other way ?
Answer: You probably just need to set/override the collation for the query to one that supports case insensitivity
http://dev.mysql.com/doc/refman/5.0/en/charset-collate.html
Comment: What is query should be In this case ?
Answer: I found the issue. It's was mysql table column data type problem. if I use text, longtext data type then it's working because it's non-binary data type :)


Newton method for nonlinear system

Question: Use Newton's method (and indicate each successive approximation) to solve the nonlinear system below for $x_1$ and $x_2$ both near $0.6$:
$$x=\sinh(y)\\
2y=\cosh(x)$$
I found the Jacobi matrix, found it's inverse and used the formula: Xo-inverse of $jacobi^{*}f()$ and tried to iterate, but I am no where close to the answer. The answer given is $x=0.6000,0.6367,0.6281,0.6424,0.6389, y=0.6000, 0.5927 0.6048,0.6019,0.6068$. Could anyone please help me out?
Comment: Are you asked to solve it as two equations for two unknowns or are you allowed to reduce it to one equation for one unknown ?
Answer: I suppose that you considered two equations $$F(x,y)=x-\sinh (y)=0$$ $$G(x,y)=\cosh(x)-2y=0$$ So, expanding around a point ($x_0,y_0$), you have two linear equations in ($x-x_0$) and ($y-y_0)$ which write $$0=F(x_0,y_0)+(x-x_0)-(y-y_0) \cosh(y_0)$$ $$0=G(x_0,y_0)-(x-x_0) \sinh(x_0)-2(y-y_0)$$ or $$0=F(x_0,y_0)+\Delta x- \cosh(y_0) \Delta y$$ $$0=G(x_0,y_0)-\sinh(x_0)\Delta x-2\Delta y$$  which you have to solve.
So starting at $(0.6,0.6)$, the iterates are $(0.620357,0.586253)$, $(0.631485,0.595658)$, $(0.637755,0.600937)$, $(0.641342,0.603954)$, $(0.643412,0.605693)$, $(0.644612,0.606702)$, $(0.645310,0.607288)$, $(0.645716,0.607629)$ and so on.
The almost exact solution is $(0.646285,0.608106)$.
As I mentioned in my comment, the problem would be much simpler to solve reducing it to a single equation : eliminating $x$ from the first equation leads to finding $y$ such that $$2 y-\cosh (\sinh (y))=0$$ which corresponds to a very well conditioned function; using Newton method would solve much faster that solving the two equations for the two unknowns.

Newton method for nonlinear system


How should I add a rail on a carpeted stairway that's open on one side?

Question: I'm buying a house with carpeted stairs leading into the basement.  Attached is a picture of it.  I have very little skill when it comes to home improvement.  What's the easiest and most economical way to put a railing on these stairs?  Is there a good tutorial online?  As I mentioned above, these stairs are carpeted. I would not want to ruin the stair carpet in the process.
Comment: Do your local codes require hand rails on stairs (I'd be surprised if they don't)?  If so, use that as leverage to get the seller to do it or to drop the price.  While you're at it, make sure the rest of that finished basement was done to code.
Comment: This is ABSOLUTELY a code violation. If you or a visitor to your home gets injured due to the lack of a railing, you might find your insurance fails to cover it. You can try to force the sellers to fix it, however, I'd expect they would do as cheap a job of it as they can. Better is to ask them to give you relief on the home price. Get an estimate from a contractor for installing a railing that IS according to code. Present them with the documentation, and then have the work done yourself, while deducting the cost from the money paid to the sellers.
Comment: Which side do you want a railing on?  A hand rail mounted to the wall would be easy, a banister on the room side would be harder.  On that side, it looks like the carpet/stairs overhang the support beam, meaning you'd have to either notch the stairs, or build out and around.
Comment: Mention it to your home inspector prior to the sale.They should be familiar with local code.
Comment: This open stairway would get a big red Safety concern in my Home Inspections. I would not close until it was mitigated. There is a very good chance you may not even be able to get any homeowners insurance until this is fixed. If you are not a DIYer, definitely insist on a professional job.
Comment: "This is ABSOLUTELY a code violation" - in the US and probably Canada, it is. Though, oddly, it seems that if you have an expensive home designed by an architect anywhere else in the world, a rail-less (and often, riser-elss) grand stairway seems to be a trademark (I admit they look great...but appear to be ways to send kids to the emergency room)
Comment: I agree that this is a safety hazard and likely not up to code.  My inspection confirmed this.  That being said, I'm buying it anyway.  I'm getting the house for a bargain and this is about the only problem with the house.  I'm not going to use it as a bargaining chip since I've already got the price as low as it can go.

That being said, I'm not a DIYer, but I'd like to be.  I got a quote of $2,000 for someone to do it for me.  Is this about right?  I was hoping for closer to $850.
Answer: You'll have to cut the carpet to attach the railing properly. Go grab the latest newstand issue of Fine Homebuilding. They have a full article on it:

(Not affiliated with the magazine in any-way other than I am a fan and find it to be the best construction magazine out there)
Also, heads up that this will likely be caught on an inspection and/or appraisal. The current homeowners may be required to do this to even get a mortgage approved.


Command not working in crontab, but work in terminal

Question: I have command in crontab:
20 * * * *      root    /usr/bin/find /home/user/temps/ -type f -mmin +20 -delete

If I run this command in terminal everything works fine, but in /etc/crontab doesn't work. What am I doing wrong? Ubuntu 18.04
in journalctl -u cron.service
CRON[17590]: pam_unix(cron:session): session opened for user root by (uid=0)
CRON[17591]: (root) CMD (/usr/bin/find /home/user/temps/ -type f -mmin +15 -delete )
CRON[17590]: pam_unix(cron:session): session closed for user root

if i add > /tmp/output to command - file empty
Comment: verify if command in crontab is executing or check crontab logs referring to  https://askubuntu.com/q/56683/283843
Comment: What crontab are you using ? Did you edit /etc/crontab file with the above line or did you add it to your own / root's crontab with `crontab -e` ?
Comment: I use /etc/crontab
Answer: Strange problem, but i fix it just restart my server. After reboot cron start working.


I tried to install django using pip install django but still i am getting this error any comments

Question: from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\emin\Desktop\fliteplan\gen_angular\arinc_424_19_db\multi\src\manage.py", line 22, in
main()
File "C:\Users\emin\Desktop\fliteplan\gen_angular\arinc_424_19_db\multi\src\manage.py", line 13, in main
raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
Answer: Make sure to have a virtual environment whenever saving new dependencies, most importantly django.
virtualenv env
source env/bin/activate

pip install django

// save the dependency
pip freeze > requirements.txt

*Note the syntax, virtualenv [env name] env can be any name but you would still activate it from [env name]/bin/activate
Answer: Did you active your virtual environment?
If didn't then you can follow this solution to do that
here is the link
And if still unable to install Django then check your python installation.
if python is working perfectly then try
python -m pip install django

and according to your os, you can follow this official documentation link
official documentation of Django to install
Thanks


How to add elements in simple_list_item_2?

Question: I want to add elements in simple_list_item_2. but i don't know how to add. I created 2 ArrayLists. Here is my code
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listv=(ListView) findViewById(R.id.listview);

    arraylist1=new ArrayList<String>();
    arraylist1.add("a");
    arraylist1.add("b");
    arraylist1.add("c");

    arraylist2=new ArrayList<String>();
    arraylist2.add("1");
    arraylist2.add("2");
    arraylist2.add("3");

    adapter= new ArrayAdapter(this,android.R.layout.simple_list_item_2,arraylist1);
    listv.setAdapter(adapter);
}

ArrayList<String> arraylist1,arraylist2;
ArrayAdapter adapter;
ListView listv;
}

Answer: Just as you added the elements before you can add them anytime you want as,
arraylist1.add("a");

And then you just have notify the adapter that the data had been changed, to do that put the below line of code after you add or remove data from the array list...
adapter.notifyDatasetChanged();


Django creating a custom list_filter

Question: I want to create a custom list_filter on AvariaAdmin, to check if env_emp is empty or not , i dont know how to do that
My MODELS
class Avaria(models.Model):
    .......

class Pavimentacao(models.Model):

    avaria = models.ForeignKey(Avaria, related_name='AvariaObjects',on_delete=models.CASCADE)
    env_emp= models.DateField(blank=True,null=True)
    .....

Answer: In your admin.py file, register the Avaria model with something like this:
class EmptyDateFilter(admin.SimpleListFilter):
    title = _('empty date')
    parameter_name = 'env_emp'

    def lookups(self, request, model_admin):
        return (
            ('all', 'All'),
            ('has_no_date', 'Has no date')
        )

    def queryset(self, request, queryset):
        value = self.value()
        if value == 'all':
           return queryset
        isnull = (value == "has_no_date")
        return queryset.filter(AvariaObjects__env_emp__isnull=isnull)

@admin.register(Avaria)
class AvariaAdmin(admin.ModelAdmin):
    list_filter = (EmptyDateFilter, )

You can find more information on the list_filter documentation
Comment: yeh , it is working, but it only shows when it is filled, I want to always show and just make the filter after I fill it
Comment: basically I just want to make the filter after I select it, if it does not select anything, it does not filter
Answer: You can use the isnull field lookup to check if a nullable field is empty:
Pavimentacao.objects.filter(env_emp__isnull=True)

Django creating a custom list_filter


What is the meaning of "block special"?

Question: I tried this command on my Linux Ubuntu prompt in Amazon Web Services
sudo file /dev/xvda1

and the output is
/dev/xvda1: block special

What is the meaning of block special in the output?
Answer: Most of the things you find below /dev are either "block special" or "character special" things, and you rather to not change them manually. Your example shows a disk drive partition provided by Xen (what on a "normal, nonvirtual machine" would be /dev/sda1).
For more details on this special device, please see What is the "/dev/ xvda1 " device?
For more details on what devices, and especially block devices are, you may consult Device file - Wikipedia, the free encyclopedia.
Answer: From the Wikipedia link provided by Izzy:
"A special file is an interface for a device driver that appears in a file system as if it were an ordinary file".
"Block special files or block devices provide buffered access to hardware devices, and provide some abstraction from their specifics. Unlike character devices, block devices will always allow the programmer to read or write a block of any size (including single characters/bytes) and any alignment. The downside is that because block devices are buffered, the programmer does not know how long it will take before written data is passed from the kernel's buffers to the actual device, or indeed in what order two separate writes will arrive at the physical device..."

What is the meaning of "block special"?


Convert values in a column to a single row Python

Question: I have a pandas dataframe that looks like this:
Area1  Area2
  1      2
  1      4
  1      5
  1      9
  2      8
  2      16
  2      4
  2      1
  3      8
  3      9

How can I convert 'Area2' column so that it becomes a list of values for each 'Area1' column
So the output I would want is:
Area1     Area2
  1      2, 4, 5, 9
  2      8, 16, 4, 1
  3      8, 9

I have done this in R previously:
df %>% group_by(Area1) %>% summarise(Area2= toString(sort(unique(Area2))))

I have been trying out groupby() and agg() but have had no success.
Could someone explain what I can use once I have grouped the data using df.groupby('Area1')
Many thanks in advance for any suggestions.
Answer: You can groupby and apply list
import pandas as pd
df=pd.read_csv("test.csv")
df.groupby('Area1')['Area2'].apply(list)

Answer: The R snippet does string concatenation.
The following line keeps the original type of Area2.
import pandas as pd

df.groupby('Area1').Area2.apply(pd.Series.tolist).reset_index()


Using Variables in SQL Queries on Python

Question: I have a list of IDs for which I want to extract other information from a sql table. This is my python 3 code:
ID=['A1','A3','B45','F44']

for i in ID:

    sqlquery="select Name, Age from TABLE where id=%s"
    cursor.execute(sqlquery,i)

I get this error upon running the code:
vertica_python.errors.Error: Argument 'parameters' must be dict or tuple

Answer: The argument must be a tuple. Do it like this:
ID=['A1','A3','B45','F44']

for i in ID:

    sqlquery="select Name, Age from TABLE where id=%s"
    cursor.execute(sqlquery,(i,))

Note: the (i,) treats i as single element tuple


Process.start results in file not found even though the file exists

Question: I am using following code to open an arbitrary file with an arbitrary application that is installed on the system :
if (File.Exists(_document.DocumentFullPath))
{
    Process.Start(_document.DocumentFullPath);
}
else MessageBox.Show(string.Format("Document {0} does not exist!", _document.DocumentFullPath));

When I execute this code I see that the file.Exists returns true, so the file does exist. But then the corresponding application opens, for instance an image viewer or a pdf viewer depending on the file type (jpg or pdf) that I am trying to open, but it shows an error in that application that it cannot find the file. No exceptions are thrown.
This does not happen all the time but only for some files.
If I try to open these files manually by copy pasting the content of DocumentFullPath in the explorer, then the file does open correctly in the applicable application.
Duh I don't understand what is wrong.
Example of a filename that don't work :
C:\Users\stuyckp\Documents\Visual Studio 2010\Projects\WPF\FrakoKlantOpvolgingWPF\FrakoKlantOpvolgingWPF\bin\Debug\ProjectDocumenten\11339_Wigbers\6197_koelkast \big-money.jpg

I am running on windows 10.
Comment: Your example of a filename that doesn't work has a space between "6197_koelkast" and the directory separator; I doubt your directory actually has a space at the end of its name.  Could it be something as simple as that?
Comment: are you using absolute or relative paths?
Comment: Absolute paths, just like in the example.
Comment: Can you add the code that launches the process?
Comment: Apparently not for file.Exists.
Comment: @CodingGorilla, the code that launches the process is there. Or I don't understand your question.
Comment: Sorry... I failed at reading. :)
Comment: If I change the path and remove that extra space, it works. So I guess I'll have to programmatically change the path. And avoid the user from ending with spaces to begin with. That is actually the root cause of this problem.
Comment: Seems to be an error with `File.Exists()`. It seems to trim trailing spaces from folder names.
Answer: Do you have spaces in the file path? File.Exists can handle spaces fine, presumably as can Windows Explorer, but it's possible that Process.Start cannot.
I think this is what you want bud. Use the process start using a ProcessStartInfo object with the file path with spaces passed as a string separately.
Use Process.Start with parameters AND spaces in path
Comment: This is a good point, should probably change the code to be: `Process.Start("\"" + _document.DocumentFullPath + "\"");`.
Comment: Process.Start can deal with it (works for me with for instance a text file) but maybe the viewer associated with the filetype can't.
Comment: Used that way as in the link. Path and filename seperately works fine.
Comment: Problem seems to be `File.Exists("c:\\folder       \\with spaces \\file.jpg")` returns `true` even if the "real" path is `c:\folder\with spaces\file.jpg`


A non-local corner ring

Question: I am searching for a ring $R$ (preferably semisimple) and a nonzero primitive idempotent $e\in R$ such that the corner ring $eRe$ is not local. I am inspired by the theorems on semiperfect rings in which there are idempotents $e_i$ with each corner ring $e_iRe_i$ a local ring. I have also scanned the ERT site (the encyclopedia of ring theory), but to no avail. Thanks for any cooperation!
Answer: You seek a primitive idempotent which is not a local idempotent.
This is not possible in a semisimple ring, since these two notions coincide for semiperfect rings (Proposition 23.5 in Lam's First course in noncommutative rings)
Without additional conditions, it is fairly easy to find such idempotents: for example, $1\in \mathbb Z$ is primitive but not local.
Comment: $(0,1)\in\mathbb Z\times \mathbb Z$ is a "nontrivial" example. For boolean rings: obviously $eRe$ being an indecomposable Boolean ring implies $eRe=F_2$. So it is not possible in Boolean rings.
Comment: @karparvar Because a subset of a boolean ring will satisfy the same identity?
Comment: Thanks for the answer! Would you please give me a "nontrivial" non-local idempotent which is primitive? Could the ring $R$ be Boolean in this regard?
Comment: Sorry! I meant by ERT the database of Ring Theory!
Comment: Why $eRe$ is boolean when $R$ is so?

A non-local corner ring


HTML preserve header when loading another page

Question: I am building a website and when I click on one of my header's page links, it loads the whole page again, rather than preserving the header and only loading the main content. For example:
When you click on a button on the sidebar of YouTube, it will, for example, load the watch later playlist, and preserve the search bar and sidebar. How would I go about doing this on my website?
Comment: What have you looked at? Have you looked at using aJax?
Comment: After looking at aJax I apologise for me being so unaware of it. I feel slightly stupid now that I've looked at it so thank you for pointing me in the right direction and sorry for my slight stupidity.
Answer: Have a look at using aJax. This should resolve your issue.


What type of filters should I use for a 3 stage whole house water filter?

Question: We have city water, but it always manages to taste like metal and chlorine.  I was going to add point-of-use filters, but then decided it would be better to do the whole house to cover showering, hot water heater, bathroom sinks, etc.  I'm hoping this will also extend the life of water-using appliances.
I purchased 3 20"x4.5" Big Blue filter housings.  I plan to use a 5 micron sediment filter, but the other two housings I haven't decided on yet.  I oversized the filters on purpose to hopefully allow adequate flow for the whole house.  A popular design seems to be:
sediment -> Granular Activated Carbon (GAC) -> carbon block
since the GAC allows more contact with the medium, and then the carbon block filters out anything that comes loose in the GAC.
I was considering double sediment filtering (5 micron and then 1 micron), but since it's really the chlorine/chloramine that I want out, the GAC is important.
Sorry, I haven't boiled this down to a question, so here it is:
Is the carbon block good enough to remove any loose carbon from the GAC (especially after filter changes)?  Should I put a spigot inbetween the GAC housing and the carbon block so I can flush that after a GAC filter change without overwhelming the block?  Or is there some other filter arrangement that I haven't discovered yet?
And, as an aside, if I wanted RO at my kitchen sink, do they sell JUST an RO filter/tank setup for systems that already do sediment/carbon for the whole house?  Everything I see is a combo system.
Does anyone who already has a whole house system look at TDS / pressure drop to determine when to change a filter, or is it better to stick to a schedule?  I was also hoping that the large filters would get me longer periods between changing.
UPDATE:
Well, it's not an "answer", but here's what I went with after discussing it with a few ChemEng friends.  They agreed that carbon block is far preferable to GAC, since it forces the water through the carbon instead of just having it flow past.  I initially installed the 5 micron sediment filter in housing 1, left 2 empty, and put a 1 micron carbon block in 3.  At their recommendation, I put a second 1 micron carbon block in housing 2.  Our pressure is great, and oversizing the filters was a good call - flow rates are more than adequate.
Just today, some neighbors were posting to facebook asking if anyone had noticed a much more pronounced chlorine taste over the past few days.  The water company is pointing to salt runoff, but everyone's claiming it smells like pool water is coming from the taps.  I can't smell the chlorine at all, and the taste is very faintly metallic, but no chlorine.  Very pleased with how this worked out.
Comment: Generally the best method is to test your water, determine what's in it, and then design a system based on that. I'm getting the impression you haven't actually done that...
Comment: Great Question as I'm eager to hear the answers.   I have 5 of the Big Blue, 2 of which I'm awaiting an answer like you. the first three are 50, 20 and 5 Micron. the 50 and 20 are inline pre water softener and Manganese greensand, the 5 is after the storage tank to the house. the 2 Empties are in the House. I use Pressure Drop to determine Filter Change time as the 50 needs replacing more often than the 5. I'm also on Well Water.
Comment: I'll cop to that.  I have public water, so I figured chlorine and maybe some iron would be my biggest worries based on the taste.  Looks like there are a lot of 'free' tests out there -- any of them worth it, or just pay for an unbiased service?
Answer: First, look up your municipality's water department site and see what they specify for treatment. Your sediment filter will work fine, if you replace it when it becomes full. For the chlorine smell, your water likely contains chlorine or chloramines. A loose filter filled with granulated activated carbon (GAC) should remove these chemicals. The water will interact well with the pores of the GAC, assuming you size the filter for the maximum flow rate you expect.
It may be reasonable to filter sediment at the house level, but filter out the disinfectants at the points of use. There's no benefit to treating your non-drinking water, and you'll replace the filters more often if you treat the whole house for chemical/odor/smells.


What caulk to use for basement floor control joint?

Question: My basement floor has control joints and some have opened up. Floor was poured 5 years ago and the cracks are stable now.
The worst section is 3/16ths wide.
What caulk should I use to seal this? I want something safe for indoor use.
Comment: What is your purpose in wanting to caulk it?
Comment: Primary purpose is to seal any soil gas coming up from imperfect vapor barrier install below the slab. We have a radon mitigation system as well. I have no idea how accurately that vapor barrier is fit…
Comment: I would use polyurethane caulk.  either the DAP or SILKA products,  the waterproof one...
Answer: I've used this stuff in many a basement or garage.  It is designed to bond to the concrete, the color blends into undyed concrete, and it can be applied with a caulking gun (much easier than the squeezy tubes for doing long cracks).
You don't really have to worry about Radon infiltration if you already have a mitigation system, even if the vapor barrier isn't perfectly sealed.  It's not under pressure or anything so that system of sub-slab pipes and vent stack already provides a path of least resistance for the gas to bypass you and escape to atmosphere.  In high-Radon areas like where I used to live, builders install a fan to pull a slight vacuum as well.

Note: this is not a specific product recommendation FWIW.  Quite a few brands produce this type of sealer.


Piecewise Symmetric Functions

Question: I am unclear as to what precisely is a symmetric function if it is defined piecewise.
For example, (in Maple) is
<code>         A := (x, y) -> piecewise(x < y, 2*x-y, y < x, x-2*y, x = y, 0)
</code>
a symmetric function? And if so, why?.
Also, (in Maple) is
<code>        B := (x, y) -> piecewise(x < y, x-(1-x)*y, y < x, -y+x*(1-y), x = y, 0)
</code>
a symmetric function. And if so, why?
My understanding is that a function is symmetric if f(a,b) = f(b,a) for all a, b. Is this correct?
Thanks for your help.
Answer: Yes, defining a symmetric function by $f(a,b)=f(b,a)$ is very reasonable. If a formula for $f$ is given piecewise,
$$f(x,y)=\begin{cases} g(x,y) \quad & \text{if } \ x<y; \\
h(x,y) \quad & \text{if } \ x>y; \\
k(x) \quad & \text{if } \ x=y \end{cases}
$$
then the symmetry requirement amounts to $g(x,y)=h(y,x)$. What $k$ is does not matter.
The two examples you gave satisfy a different identity, $f(a,b)=-f(b,a)$. Such functions are called antisymmetric. In the above notation, the antisymmetry requirement amounts to $g(x,y)=-h(y,x)$, and   $k$ being identically zero.

Piecewise Symmetric Functions


Service invoked too many times for one day: gmail read

Question: I have a script that polls the inbox every minute and then does some processing accordingly.  I am receiving this error:

Service invoked too many times for one day: gmail read.

What is the limit per day?
Answer: out of date>>gmail reads are capped at 10000/day.
See current quotas> choose the Quota Limits tab>
 See Quotas here.


How to run c++ in vscode

Question: I cannot for the life of me figure out how to run and debug a c++ file in vscode. There are always at least one or two things wrong.
I've already used the basic tutorials, but they don't seem to work for me.
Can someone explain it to me like I am 5 years old? Or point me in the direction of a place that will? I am totally burnt out and feel like a total dunce. I can't get a hello world program running and it is driving me crazy. Any help would be appreciated.
Comment: Why not use Visual Studio to code in C++?
Comment: Here is the official doc: https://code.visualstudio.com/docs/languages/cpp  How far through that does it work for you?
Comment: Personally, I perfer visual studio 2022 for writing C++ as well, however, I am a linux user which forces me to write C++ in VS Code or CLion.
Comment: So there are tutorials for MVSC, MingW, & GNU's GCC/G++, and CLang's compiler. I have a feeling if I write a GNU tutorial for Linux it isn't going to help you very much. You probably need a tutorial for a compiler in windows or mac, but you need to state which one.
Comment: FYI, Chief fans are ban-wagon riders. Just saying...
Answer: Is it on Windows or Linux ?
If on windows, first download and install the mingw setup. You can find it here :
https://sourceforge.net/projects/mingw/
After installation, add the location of th bin of g++ to PATH so that you can access it via the command line.
You can also add some extensions to your VS Code to make debugging C++ code easier, then in VS Code, open the terminal, and , while in the directory where you have your cpp file, simply do a g++ filename.cpp to compile, then run the executable, a.exe, unless otherwise specified in the previous command .
Hope this helps
Answer:
Make sure that you have c++ compiler I prefer mingw.
Open vscode and go to Extensions or by keyboard shortcut ctrl + shift + x.
Search for .run and install
Search for C/C++ and install.
Go to settings ctrl + ,

By GUI

In the search bar, search for code runner and Code-runner: Run In Terminal will be unticked by default. You tick it and close settings tab. Refer the pic for better understanding.

Finally create a C++ file and save. Go to Terminal and select Run Build Task then click ctrl + alt + n to run the code. Again refer image for better understanding.

This should work, but if still didn't work let me know. Else refer any youtube video , you might have committed small mistake.
Let me know if this didn't work my dear 5 years old guy ;)

How to run c++ in vscode