text:
Q: Cannot establish connection with socket.io - Angular 7 I trying to establish connection for the first time with web sockets inside my angular app.
But its not working and its replacing the url path
My socket service
 public initSocket(): void {
        this.socket = socketIo('http://11.11.11.111/demo-api/status/');
    }

Error
Access to XMLHttpRequest at 'http://11.11.11.111/?EIO=3&transport=polling&t=Meccctccu' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

A: You need to enable cors in your backend.
You should read more about what cors mean and enable it in the backend

A: The error you are seeing is quite self-explanatory. You can't connect to another domain via ajax or using web socket if the current domain you are accessing it from does not exist in the allowed origins (Access-Control-Allow-Origin header).
There is a very good explanation of what CORS is on the Mozilla Developer website.
To fix this you will need to add a few headers into the backend you are trying to access which are:

*

*Access-Control-Allow-Origin: * (which means allow ANY origin and is not a good idea in production!)

*Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS, any other you might need

*Access-Control-Allow-Headers: Accepts, Authorization, Access-Control-Allow-Headers, Access-Control-Request-Headers, Access-Control-Request-Method, DNT, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Content-Range,Range
If you are running your Angular app as an Electron one (for example), you can disable CORS checks: Electron (chromium) disable web security

const win = new BrowserWindow({
    webPreferences: { webSecurity: false }
  });


text:
Q: Cannot not restart a docker container with existing mounted host directory I pulled a nginx+php container (https://hub.docker.com/r/imagine10255/centos6-lnmp-php56/) and had started that, it will create a folder to specific location i.e.(D:\xampp\htdocs\centos6-lnmp-php56\home\website), but now i can't restart it, anyone know how to do restart it with out deleting the folder above ?
error message is here:
Error response from daemon: Cannot restart container centos6-lnmp-php56: error while creating mount source path '/c/Users/hkveg/Documents/Kitematic/centos6-lnmp-php56/home/website': mkdir /c/Users/hkveg/Documents/Kitematic/centos6-lnmp-php56: file exists

command tried:
$ docker restart centos6-lnmp-php56

Error response from daemon: Cannot restart container
  centos6-lnmp-php56: error while creating mount source path
  '/c/Users/hkveg/Documents/Kitematic/centos6-lnmp-php56/home/website':
  mkdir /c/Users/hkveg/Documents/Kitematic/centos6-lnmp-php56: file
  exists

As same as mysql container:
$ docker restart mysql

Error response from daemon: Cannot restart container mysql: error
  while creating mount source path
  '/c/Users/hkveg/Documents/Kitematic/mysql/var/lib/mysql': mkdir
  /c/Users/hkveg/Documents/Kitematic/mysql: file exists

redpajama_set_name: RedPajamaStackExchange


text:
Q: php patch method curl request send I need below code to php curl request to remote server. i am not able to do this and not getting source from google
curl -X PATCH
--header "Content-Type: application/json"
--header "Accept: application/json"
--header "x-api-token: API_TOKEN"
--header "x-api-user: API_USER"  --data '{"profile_id":"string","msg_product":["A2P","P2P"]}'
"https://api.telnyx.com/messaging/numbers/{tn}"

A: Some php equivalent could be :
using curl :
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.telnyx.com/messaging/numbers/'.$tn,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'PATCH',
  CURLOPT_POSTFIELDS =>'{"profile_id":"string","msg_product":["A2P","P2P"]}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json',
    'Accept: application/json',
    'x-api-token: API_TOKEN',
    'x-api-user: API_USER'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

or using guzzle :
<?php
$client = new Client();
$headers = [
  'Content-Type' => 'application/json',
  'Accept' => 'application/json',
  'x-api-token' => 'API_TOKEN',
  'x-api-user' => 'API_USER'
];
$body = '{
  "profile_id": "string",
  "msg_product": [
    "A2P",
    "P2P"
  ]
}';
$request = new Request('PATCH', 'https://api.telnyx.com/messaging/numbers/'.$tn, $headers, $body);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();


text:
Q: Is there a `git` command commits all of add/modify/remove at once? As I know, I have to use
git add .
git commit -m "Test."

to add files.
And for update and delete,
git commit -a -m "Test."
However second command does not handle file addition.
Is there a command which does all of these at once?

A: No. Though, if you can guarantee that all un-ignored, un-versioned files want to be versioned, git add . is a doozy.

A: If you want to add and commit, you can create a shell script that does that.
git add .; git commit -a
This will open up the editor specified in your .gitconfig and you can enter the commit message.
You can even parameterize the path you want to add:
git add $1; git commit -a


text:
Q: Windows Server write access to Remote Desktop Local Resource from a different user I have connected to a server using Remote Desktop and mounted a drive as a "LocalResource". The drive is visible as \\tsclient\VpnFolder on the server. I can read and write files from the server to this share using Explorer, so the logged-in user does have write permission.
I am now trying to write to the drive as a different user (Exchange Server Shell) and I am getting Access Denied errors.
How can I modify the permissions on \\tsclient\VpnFolder so that another user (in this case the Exchange Client) can write to it? (I am attempting to export some PST files.)
I am using Remote Desktop on MacOS connecting to Windows Server 2008.

A: The \\tsclient resource exists only within the security context of the user that logged in via Remote Desktop. It does not support configuring permissions or access by users outside the specific RDP  session.
Your workarounds are:

*

*Run your commands on the local server using the same account you're using to log in via Remote Desktop.

*Establish an alternate connection method from the remote machine to your local device, such as through a SMB/CIFS share or FTP.

*Grant the user you're using to connect via RDP permission to the data generated by the command you're running in another user context.


text:
Q: How to set the field requried depends on condition? I am asking if it's possible to make the field required under condition like:
to set a text box required if the other field is not empty otherwise it will be optional.

A: You can use a CustomValidator for this, but there is something you need to know in order to get it working. The issue is that if you set the ControlToValidate property on the validator, then it will only fire if that control has a value. In your situation, you want to validate it specifically when it does not have a value.
To get around this, don't set the ControlToValidate property on the validator. Then, in your client and server validation handlers you will need to access both of the textboxes directly.
In your client validation function you could do something like this:
function OnCustomClientValidate(source, e) {
    e.IsValid = true;
    var otherTextBoxValue = $('#<%=OtherTxtBox.ClientID%>').val().trim();
    if (otherTextBoxValue == '') {
        return;
    }
    var controlToValidateValue = $('#<%=TextBoxToValidate.ClientID%>').val().trim();
    if (controlToValidateValue == '') {
        e.IsValid = false;
    }
}

Your server validation method could look like this:
protected void OnCustomServerValidate(object source, ServerValidateEventArgs e)
{
    e.IsValid = true;
    // Don't validate anything if `OtherTextBox` is empty
    if (OtherTxtBox.Text.Trim() == String.Empty)
    {
        return;
    }

    // If we got this far then we need to set IsValid to false if the ControlToValidate has no value
    if (TextBoxToValidate.Text.Trim() == String.Empty)
    {
        e.IsValid = false;
    }
}

and your aspx could be like this:
<asp:TextBox ID="OtherTextBox" runat="server"></asp:TextBox>
<asp:CustomValidator ID="MyCustomValidator" runat="server" ClientValidationFunction="OnCustomClientValidate" OnServerValidate="OnCustomServerValidate" Display="Dynamic" ErrorMessage="Please enter a value"></asp:CustomValidator>
<asp:TextBox ID="TextBoxToValidate" runat="server"></asp:TextBox>

Note that when using this approach, it won't validate when the (intended) control to be validated looses focus because we haven't specified that control. So the client side validation will fire when you submit the form, but the postback will be cancelled if the validation fails.


text:
Q: PHP: csv remodelling I'm a newbie trying code, and have an issue that i can not get my head around and would appreciate some help.
I have Csv's file looks something like this (always id,url but the amount of urls / id differ):
12345,wwwurl1
12345,wwwurl2
12345,wwwurl3
12346,wwwurl1
12347,wwwurl1
12347,wwwurl2
...,... and so on

How to make this look like this, easier to show than explain i think :)
12345,"wwwurl1,wwwurl2,wwwurl3"
12346,"wwwurl1"
12347,"wwwurl1,wwwurl2"
...,"...,..." and so on

Basically only one row per id, all urls added with comma separator.
All help is appreciated!

A: <?php

$file = fopen(__DIR__ . '\\' . 'test.csv', 'r+');//your file
$fileResult = fopen(__DIR__ . '\\' . 'result.csv', 'w+');//result file
$rowInfo = [];

while (($data = fgetcsv($file, 0, ",")) !== FALSE) {
    $rowInfo[$data[0]] .= $data[1] . ',';
}

foreach ($rowInfo as $key => $value) {
    fputcsv($fileResult,[$key,rtrim($value, ",")]);
}

fclose($file);
fclose($fileResult);


text:
Q: WiX 3 - Icon is always blank (white) i have installed the newest WiX (Installer) for my Visual Studio, and when i want to set the icon, it always ends blank. i'm trying to set the icon of the Entry in "All Windows Software"
in the following Picture you can see how the Icon looks like (Image is from the Internet, not from my example)
http://i.stack.imgur.com/smPKe.png
my code:
<Icon Id="Icon" SourceFile="logo_16.ico"/>
<Property Id="ARPPRODUCTICON" Value="Icon" />

allready tried different .ico-files. Anyone who knows why and how to solve the problem?

A: please make sure the file is located in the correct directory

< Icon Id="ATE_GUI.ico" SourceFile="..\src\ATE_GUI\res\ATE_GUI.ico"/><br>
 < Property Id="ARPPRODUCTICON" Value="ATE_GUI.ico" />

this is an example of usage:

< Feature Id='Complete' Title='ATE' Description='The complete installation' Display='expand' ConfigurableDirectory='INSTALLFOLDER' Level='1'>
      <ComponentRef Id='ProgramMenuDir' />
< /feature>

  <Component Id="comp_bin_debug_30" Guid="EB4650EB-75DC-4562-9DC3-8FFDD9B55468">
        <File Id="file_bin_30" Source="..\bin\Debug.x64\ATE.exe" KeyPath="yes" DiskId="1" />
        <Shortcut Id="startmenuATEDebug" Directory="ProgramMenuDir" Name="ATE (Debug.x64)"
      WorkingDirectory='INSTALLDIR' Icon="ATE_GUI.ico" IconIndex="0" Advertise="yes" />
 </Component>


text:
Q: Tying mandatory agreement in Shopify ../cart page to multiple products I've added a mandatory acknowledgment to my Shopify cart page that is displayed when I'm running pre-order sales for certain products.
{% for item in cart.items %}
  {% if item.product.tags contains 'DECEMBER' %}

  <input style="float:none; vertical-align:middle;" type="checkbox" id="agree" />

    I acknowledge that Company Name will charge my credit card at checkout, even though the {{item.product.title}} may not ship until December.

  {% endif %}
  {% endfor %}

The checkbox agreement will only show up if there is a product with a DECEMBER tag in the cart.
Everything works great for one product, but I would like to get it working for a cart that contains more than one product with the DECEMBER tag.
For example, if there were three different products with the DECEMBER tag, I would like the label text to read "I acknowledge that Company Name will charge my credit card at checkout, even though the Product and Product2 and Product3 may not ship until December.
What would be the best way to set this up?
Thanks!

A: I would approach the problem like this:
{% assign preorder = false %}
{% assign preorder_products = "" %}
{% for item in cart.items %}
  {% if item.product.tags contains 'DECEMBER' %}
    {% assign preorder = true %}
    {% capture preorder_products %}{{ preorder_products | append: item.product.title | append: "|" }}{% endcapture %}
  {% endif %}
{% endfor %}

{% if preorder %}
  {% assign preorder_products = preorder_products | split: "|" | join: ", " %}

      <input style="float:none; vertical-align:middle;" type="checkbox" id="agree" />

        I acknowledge that Company Name will charge my credit card at checkout, even though the following products may not ship until December: {{ preorder_products }}

{% endif %}

*

*Loop through all the items in the cart, and if the product has the tag 'DECEMBER' append it to a string with a separator (e.g. '|').

*Then if there is at least one pre-order product, use split and join to format the string for output. This is handy to get rid of the trailing separator and avoid output like "Product1, Product2, Product3, ".


text:
Q: Find all paths and sum the length of each path in the graph I have the following graph database:
edge(v1, v2, 3).
edge(v1, v3, 5).
edge(v1, v4, 13).
edge(v1, v6, 25).
edge(v1, v7, 5).
edge(v2, v7, 17).
edge(v3, v4, 15).
edge(v4, v2, 4).
edge(v4, v6, 2).
edge(v7, v6, 15).

And here is my code to understand the output as below:
path(A, B, [A, B], X) :- edge(A, B, X).
path(A, B, PathAB, Length) :-
    edge(A, C, X),
    path(C, B, PathCB, LengthCB),
    PathAB = [A | PathCB],
    Length is X + LengthCB.
find_paths(A, B) :-
    path(A, B, Path, Length),
    printPath(Path), nl,
    writef(' Total: %d', [Length]), nl,
    fail.
printPath([]).
printPath([X]) :- !, write(X).
printPath([X|T]) :- write(X), write(' -> '), printPath(T).

Desired results:
?-find_paths(v1, v4).
v1 -> v3 : 5
v3 -> v4 : 15
Total : 20
v1 -> v4 : 13
Total : 13

I'm having trouble not showing the desired results.

A: So it looks like your program runs as desired, only the output is "broken". Alter the ouput predicate and you are fine, for example:
printPath([_]).
printPath([X,Y|T]) :-
    edge(X,Y,V),
    write(X), write(' -> '), write(Y), write(" : "), writeln(V),
    printPath([Y|T]).

Now instead if single nodes of your path always a pair of nodes is printed together with their weight. To get a the exact order of your example you will have to re-write the search routine.
Tested with SWISH (removed one nl as well, not using writef/2):
?- find_paths(v1, v4).
v1 -> v4 : 13
Total: 13
v1 -> v3 : 5
v3 -> v4 : 15
Total: 20
false.


text:
Q: error -9999 when trying to write into int * on GTX 980 and OpenCL I get error -9999

Breakpoint 7, cl::detail::errHandler (err=-9999, errStr=0x43cc1f "clWaitForEvents") at /opt/AMDAPPSDK-3.0-0-Be
ta/include/CL/cl.hpp:321

at event.wait() because of the following line
valid[id] = 1;

where valid is __global int* valid.

The .cl code is
__kernel void validateRecords(__global const char* buffer, __global const struct RecordInfo* allRecords, __global int* valid, const unsigned int n)
{
    const int id=get_global_id(0);

    if (id < n)
    {
            char* record = buffer[allRecords[id].position];
            int size = allRecords[id].length;

            int updateTimeLen = findFixed(record, size, ',');
            if(updateTimeLen == -1 || updateTimeLen != UPDATE_TIME_LEN)
            {
               valid[id] = 1;
               return;
            }
    }

}

and I get error

code -9999 atvalid[id] = 1.

I just noticed that if I comment //valid[id] = 1; or //int updateTimeLen = findFixed(record, size, ','); all is fine, but when both are used I get the above error.
The device is GTX 980 with OpenCL 1.1. Can you help please?

A: I think I found the issue. First of all, I am using the AMD SDK on Nvidia card. This worked well for me in the past (with GTX 780 Ti). However this time I noticed a few problems. The first one is this line:
char* record = buffer[allRecords[id].position];

which I initially (correctly) wrote as
char* record = buffer + allRecords[id].position;

but it didn't compile and I mechanically changed it to the above and it did compile. That was the first problem, but it had nothing to do with the error.
The second was that passing a __private char* continued to throw error -9999 no matter what I do (perhaps because of the different SDK, but it might be something else), so I passed the __global char* buffer to the function and all worked fine.


text:
Q: How do I set up an AWS RDS instance for production so that I can regularly read in custom data from my personal computer I have built a REST API in Spring that I am ready to deploy as the back-end for my company's website.  It utilizes a mySQL RDS instance to store data.  I'm going to host it on AWS and am currently in the process of learning how to do that.  I connect to my database with Spring's jdbc template and make SQL queries to create and edit tables.
There is a big concern I have that has not been addressed by any of the tutorials I've read: Once everything is up and running on AWS, I will not have direct access to the database anymore as it will only be accessible from behind a my REST API which makes the necessary queries.  And the REST API will only be accessible by the front end server (which is also on AWS).  But I will regularly need to read in custom data in different formats.
Currently it is very easy to do that, because I can read in a random excel file and directly call the methods that actually make SQL queries on startup of the server.  But that is because my test RDS database is publicly accessible.  And I am pretty sure that is terrible practice.
So how can I set things up on AWS so that I can still connect to my database from my laptop and make custom SQL queries to my database?
I am following this tutorial (https://keyholesoftware.com/2017/09/26/using-docker-aws-to-build-deploy-and-scale-your-application/) to get my REST service up and running, and will have to set up the RDS instance separately.

A: Best choice I know of is to SSH into an EC2 then connect to RDS. If you're on Mac, Sequel Pro makes this easy since you can provide SSH settings along with your MySQL connection settings.
This can also be accomplished with an SSH port forwarding then you can use your local SQL client. Here's a link to an article that appears to have correct information MySQL SSH Tunnel
Only other secure option is to allow RDS connections from your IP. I can't verify that still works but my memory says I used to run my former companies RDS that way.


text:
Q: Selecting different item in multi column combobox doesn't update the value shown - Access 2016 I have a combobox with 3 columns. I have a Change() event listener on that combobox that fires every time I click a new item. The very first time I click that item, it retrieves the values and updates other textboxes accordingly like so:
Private Sub cb1_Change()
    If cb1.Value = "" Or IsNull(cb1.Value) Then
        tb1.Value = ""
        tb2.Value = ""
        tb3.Value = ""
    Else
        tb1.Value = cb1.Column(0)
        tb2.Value = cb1.Column(1)
        tb3.Value = cb1.Column(2)
    End If
End Sub

Lets say I select the item that contains this information: 1, 1, 2017. It would go and populate tb1, tb2, and tb3 with 1, 1, 2017 respectively. If I click a different item, say 2, 2, 2018, The change event fires, and goes into the Else statement. However, cb1.Column(0), cb1.Column(1), cb1.Column(2), still return the values 1, 1, 2017 and not 2, 2, 2018.
Why are these values not updating on every subsequent click?

A: Here goes ;-)
The change event fires for every keystroke, but the data isn't saved at that point so the underlying column data isn't updated to reflect the unsaved changed displayed value.
The AfterUpdate event only fires after the data is saved (dirtied is probably the correct technical term) and hence the column data you are using is also now updated reflecting the saved value.


text:
Q: Data Copy between ADLS Instances Copying data between various instances of ADLS using DISTCP
Hi All
Hope you are doing well.
We have a use case around using ADLS as different tiers of the ingestion process, just required you valuable opinions regarding the feasibility of the same.
INFRASTRUCTURE: There will two instances of ADLS named LAND & RAW. LAND instance will be getting the file directly from the source while RAW instance will be getting the file once validations are passed in LAND instance. We also have a Cloudera cluster hosted on Azure platform which will have connectivity established to both the ADLS instances.
PROCESS: We will have a set of data & control files landing in one of the ADLS instances (say landing). We need to run a spark code on Cloudera cluster to perform count validation between Data & control file present in Land ADLS instance. Once the validation is successful, we want distcp command to copy data from Land ADLS instance to Raw ADLS instance. We are assuming that Distcp utility will be already installed on the Cloudera cluster.
Can you guys suggest if above approach looks fine?
Primarily our question is whether DISTCP utility will support data movement between two different ADLS instances?
We also considered other options like ADLCopy but Distcp appeared better.
NOTE: We haven't considered use Azure Data Factory since it may has certain security challenges though we know Data Factory is best suited for above use case.

A: If your use case requires you to copy data between multiple storage accounts, distcp is the right way to execute this.
Note that even if you were to encapsulate this solution in data factory, the pipeline with copy activity will invoke distcp.


text:
Q: Mysql retrieve only specific values from n:n relation Say we have following Mysql tables:
user:
userID | user_name

classification:
classificationID | classification_name | classification_ponder

user_classification:
userId(PK) | classificationId(PK)

This is n:n relationship between user and classifiaction.
I am interested how to query for every user, ALL classifications with biggest ponder in one column, separated with ,?
E.g. let say we have user1 with ID=1 and following classifications:
 classificationId | classification_name | classification_ponder
---------------------------------------------------------------
        1                 class1                     5
        2                 class2                     5
        3                 class3                     4
        4                 class4                     2

user_classification table is(user have all classifications):
 userId | ClassificationId
---------------------------
    1            1
    1            2
    1            3
    1            4

What I want to get is:
userId | user_name | class1, class2

So only classification names with biggest ponder (in this case class1 and class2) displayed in one column, separated with ",".
I succeed to get all classifications for user with following mysql query:
select
  user.user_name,
  GROUP_CONCAT(DISTINCT Classification.classification_name) as Classification
from user
left join user_classification
  on (user_classification.userId=user.userID)
left join Classification
  on (Classification.classificationID=user_classification.classificationId)
GROUP BY user.userID</b>

What i want is do display only classifications with biggest ponder.

A: SELECT
    u.user_name,
    GROUP_CONCAT(DISTINCT c.classification_name) as Classification
FROM `user` u
INNER JOIN
(
    SELECT
        user_classification.userId as uid,
        MAX(classification.classification_ponder as max_ponder
    FROM user_classification
    INNER JOIN classification ON user_classification.classificationId = classification.classificationID
    GROUP BY user_classification.userId
) as user_max ON u.userID = user_max.uid
LEFT JOIN user_classification uc ON u.userID = uc.userId
LEFT JOIN classification c ON uc.classificationId = c.classificationID AND user_max.max_ponder = c.classification_ponder
GROUP BY u.userID

Something like this should do the trick (can have some syntax errors)


text:
Q: Prestashop 1.7 images not showing after add Im importing products with images:
if (count($d->images)) {
    foreach ($d->images as $img) {
        $url = $img->url;
        $cover = boolval($img->cover);
        $position = intval($img->position);

        $image = new Image();
        $image->id_product = $pid;
        $image->position = $position;
        $image->legend = $img->legend;
        $image->cover = $cover;

        if (($image->validateFields(false, true)) === true &&
            ($image->validateFieldsLang(false, true)) === true && $image->add())
        {
            $image->associateTo(1);
            if (!AdminImportController::copyImg($pid, $image->id, $url, 'products', true))
            {
                $image->delete();
            }
        }

    }
} else {
    file_put_contents('no_images.txt',$d->name." \n", FILE_APPEND);
}

but images not showing on page. On admin backend images existst and showing but on page frontend they not display. I have to open manually edit product and click Save to "refresh" images and make it possible to load display on page. How to do it in php code? Is there any way to refresh all images in prostashop products or refresh in php code images for product id?


text:
Q: Firefox CSS and/or D3 difference So I've got a page on a site that displays exactly like it should in both IE and Chrome, but not Firefox. The link is http://www.jakerevans.com/?page_id=61. In both IE and Chrome, the spinning animation (written with D3.js) displays fully through the padding-left and padding-top, but not in Firefox. Anyone have any idea how I can make this padding in Firefox transparent? Any other possible solutions? I'd really like to resolve this through CSS if possible, and not go back to the drawing board with the D3 code. Obviously I will if I have to though.
Thanks a lot for the help!!!

A: You need to explicitly set overflow: visible on your <svg> element.
The SVG specifications state that all SVG elements that create viewports should have overflow: hidden in the browser's default stylesheet.  However, browsers disagree over whether this should include the padding area or not: if you follow the description in the SVG specs, as Firefox does, padding would not be included.  However, general CSS/HTML layout does not consider content in the padding to be overflow, so Webkit/Blink/IE browsers do not clip it with overflow:hidden.

A: it doesn't seem to be the issue of the padding, it's like to be the firefox transform origin thing, see this Setting transform-origin on SVG group not working in FireFox


text:
Q: Не переключается класс на jQuery Пытался написать на чистом JS переключения класса, но ничего не вышло.
Решил уж и на JQuery, но это не работает также.
Я наблюдал за изменениями через Просмотр кода, но класс не поменялся.
Буду очень благодарен, если найдёте ошибку, особенно, если можно сделать это на чистом JS.
HTML:

        <button class="navbar-toggler" id="toggle">

        </button>

                    About us

                    Our blog

jQuery:
$("#toggle").click(function(){
    $("n").toggleClass("active");
})

Мы можете наблюдать здесь Bootstrap классы, знаю, можно было и через Bootstrap сделать, но это требует bootstrap.css, bootstrap.min.css, bootstrap.js и также bootstrap.min.js. Выгоднее написать на чистом JS.

A: Если Вы хотели добавлять/удалять класс active у элемента с ID равным n, то Вы просто не дописали решетку вначале:
$("#toggle").on("click", function() {
  $("#n").toggleClass("active")
})

На JS:

const handleClick = () => {
  document.querySelector("#n").classList.toggle("active")
}

document.querySelector("#toggle").addEventListener("click", handleClick)
.active {
  background-color: red;
}

  <button class="navbar-toggler" id="toggle">
            click me
        </button>

        About us

        Our blog


text:
Q: TdsParserStateObject - disposing ? Entity Framework I'm using EF and have problem with TdsParserStateObject.
I'm calling this method many times :
 public void SaveDataFromERP(string synchronizationType, string xml,int errorsHandlingPercentagePartition)
    {
        var param1 = new SqlParameter("XML", SqlDbType.Xml);
        param1.Value = xml;
        var param2 = new SqlParameter("PartitionedPackagePercentage", SqlDbType.Int);
        param2.Value = errorsHandlingPercentagePartition;
        ((IObjectContextAdapter)this).ObjectContext.ExecuteStoreQuery<dynamic>(
            $"exec [Synchronization].[Import{synchronizationType}] @XML,  @PartitionedPackagePercentage", param1 , param2 );
}

My repository consists of
SynchronizationRepository : ISynchronizationRepository
{
  private readonly POSDBContext _context = new POSDBContext();
  public void SaveData(string typeName, string xmlFile, int errorsHandlingPartitionPercentage)
    {
        _context.SaveData(typeName, xmlFile,errorsHandlingPartitionPercentage);
    }
 }

When I call ExecuteStoreQuery I can see new object in memory TdsParserStateObject.
Unfortunately I must call this method in sequence many times(a lot of data). The result is about 60 TdsParserStateObject and it take a lot of memory.
Moreover these objects do not disappear after some time.
Is it possible to dispose them ?

A: Resolved my own issue to some degree by removing:
"MultipleActiveResultSets=True"

From my connection string. My connections were being made on background threads so this goes someway to explaining why I was seeing the increase:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets


text:
Q: Anyway to input next string from a file in python Ok I'm new to python and Im trying to input a file and my question is that is there only the .read() function to read in a file? Or is there anyway you can take in the next string up to the next whitespace? Would the best way be to read in the line with .readline() then split the line? Any help is welcome
if loop == "do":
            outfile.write(" label 1; label 2;\n")
            ch = infile.read(1)
            count = 0

            while ch != "":
                var += ch
                ch = infile.read(1)

            varList[count] = var
            count++

This is an example of the program, the question is where the infile.read(1) is. Right now that only takes in the next character I was wondering if there was anyway to get the next set of characters until the next whitespace.

A: There is no built-in method on file objects to read up to the next whitespace, or up to a certain character.
Reading a character at a time does of course work, and if you've opened the file with the default settings it will be buffered reasonably (either in C's stdio for Python 2.x, or in Python's io module for 3.1+)… but it still may be pretty slow just because of all that looping.
You can definitely use readline and then split, as you suggest. That just means you need somewhere to store the other words on the line between reads. The cleanest way to do that is probably with a wrapper around the file. For example:
def words(f):
    for line in f:
        yield from line.split()

Or, in Python 3.2 and earlier:
def words(f):
    for line in f:
        for word in line.split():
            yield word

Then you can do this:
with open(filename) as f:
    for word in words(f):
        do_stuff(word)

In particular, your whole code could be written as:
if loop == "do":
    outfile.write(" label 1; label 2;\n")
    for count, word in enumerate(words(infile)):
        varList[count] = var

If you actually want to wrap this in a complete file-like object with an extra method instead of just a generator of words:
In 3.1+, you can look at how io.TextIOWrapper works and add a readword method that interacts with its buffering the same way readline does, which is pretty simple.
But in 2.x that isn't possible. Unless you want to dup the file descriptor and create an io object out of it instead of a traditional file object, the best option is to create a custom io.BufferedIOBase subclass that delegates to a real file object, which is a lot more work.
Fortunately, most apps aren't going to need a complete file-like object, so this isn't a big deal.


text:
Q: Displaying the result of a promise in React right away I'm trying to display a value from a promise right after mounting/while mounting, but having some issues. In particular, I'm trying to change the state of a component using a promise. Here was my initial try:

constructor(props) {
  super(props);

  this.state = {
    version: -1
  }

  fetchModel('http://localhost:3000/test/info')
    .then(result => this.setState({version: result.__v}));
}

This gave me the behavior I wanted, letting me get and display the version in the component, but I got the warning "Can't perform a React state update on an unmounted component". I updated it to this after seeing suggestions online:

constructor(props) {
  super(props);

  this.state = {
    version: -1
  }

  this.mounted = false;
}

componentDidMount() {
  this.mounted = true;

  fetchModel('http://localhost:3000/test/info')
    .then(function(result) {
      if (this.mounted) {
        this.setState({version: result.__v})
      }
    });
}

componentWillUnmount() {
  this.mounted = false;
}

but it no longer displays the correct version number. Inside the promise, after this.setState, I tried console.log(this.state.version), which did not print anything to the console, and a random console.log statement right afterwards did not print either. Is there anything I can do to get around this issue? Are there better ways to display information from a promise while mounting?


text:
Q: How does `do_new_mount_fc()` mount real file systems like ext4? In relatively old Linux kernel source codes, the do_new_mount() will call vfs_kern_mount(), which will finally do mount_fs(). And this function will call the real file system's function like below

struct dentry *
mount_fs(struct file_system_type *type, int flags, const char *name, void *data)
{
    struct dentry *root;
    struct super_block *sb;
......
    root = type->mount(type, flags, name, data);
......
    sb = root->d_sb;
......
}

But in relatively new Linux kernel source code, the do_new_mount() will call do_new_mount_fc() instead, and I can not find how this function call the real file system's mount function like above.
Can you tell me how it works now?

A: You don't find the "usual" function calls because of the recent transition to the new Filesystem Mount API through "filesystem context". You can find more info in the relevant (quite massive) patchwork.
I'm not going to explain the whole thing as the kernel documentation that I linked above should already give a pretty good explanation (and I also am no Linux FS internals expert).
The "filesystem context" is basically a structure containing useful information that is passed around and updated incrementally as needed. So what happens now is that the vfs_get_tree() function is responsible for creating the mountable root of the filesystem, and saving it in the fs_context structure that is then passed to do_new_mount_fc() and used to do the actual mount.
(*) int vfs_get_tree(struct fs_context *fc);

     Get or create the mountable root and superblock, using the parameters in
     the filesystem context to select/configure the superblock.  This invokes
     the ->get_tree() method.

So now in do_new_mount() you see that function being called right before do_new_mount_fc():
    fc = fs_context_for_mount(type, sb_flags);
    put_filesystem(type);
    if (IS_ERR(fc))
        return PTR_ERR(fc);

    if (subtype)
        err = vfs_parse_fs_string(fc, "subtype",
                      subtype, strlen(subtype));
    if (!err && name)
        err = vfs_parse_fs_string(fc, "source", name, strlen(name));
    if (!err)
        err = parse_monolithic_mount_data(fc, data);
    if (!err && !mount_capable(fc))
        err = -EPERM;
    if (!err)
        err = vfs_get_tree(fc); // <<<<<<<<<<<<<<<<<<<<<<< HERE
    if (!err)
        err = do_new_mount_fc(fc, path, mnt_flags);

    put_fs_context(fc);
    return err;
}

The vfs_get_tree() function calls fc->ops->get_tree() which is the method responsible for creating root (if it doesn't already exist) and assigning it to fc->root.
    error = fc->ops->get_tree(fc); // Here fc->root gets assigned.
    if (error < 0)
        return error;

The transition to this new API is still not complete for all filesystems. For the filesystems that still use the old API (for example ext4), the fs_context_for_mount() function (called at the beginning in do_new_mount()) creates the filesystem context through alloc_fs_context(), which checks whether or not the filesystem supports the new API, and if not it uses a default legacy version of the filesystem context operations (in fact, you can also see the comment in this last link which says "TODO: Make all filesystems support this unconditionally").
For get_tree(), the legacy version is legacy_get_tree(), which indeed does exacly what you would expect calling fc->fs_type->mount(...).
/*
 * Get a mountable root with the legacy mount command.
 */
static int legacy_get_tree(struct fs_context *fc)
{
    struct legacy_fs_context *ctx = fc->fs_private;
    struct super_block *sb;
    struct dentry *root;

    root = fc->fs_type->mount(fc->fs_type, fc->sb_flags,
                      fc->source, ctx->legacy_data);
    if (IS_ERR(root))
        return PTR_ERR(root);

    sb = root->d_sb;
    BUG_ON(!sb);

    fc->root = root;
    return 0;
}

Sooner or later, all filesystems will be updated to use the new API with filesystem context, those legacy_* functions will be removed completely and we will see a init_fs_context method in the ext4 file_system_type.


text:
Q: why does "try" "exception" does not work? The aim of the code is to make up a list, add all the dates that do not exist in the original list.
The code is as follows:
    for i in allDate:

        try:
            dict = next(item for item in list if item["date"] == int(i.strftime('%Y%m%d')))
            dict.update({"date": i})
            print(dict)
            list3.append(dict)
        except:
            dict = list3[-1]
            dict.update({"date": i})
            print(dict)
            list3.append(dict)

    for j in list3:
        print(j)

"allDate" is all the date in a time period :
[...
 Timestamp('2020-05-26 00:00:00', freq='D'),
 Timestamp('2020-05-27 00:00:00', freq='D'),
 Timestamp('2020-05-28 00:00:00', freq='D'), ...]

"list" is :
[{'date': 20200301, 'score_positive': 0}, {'date': 20200303, 'score_positive': 0.04884412481139103}, {'date': 20200305, 'score_positive': 0.026178522035479546}, {'date': 20200309, 'score_positive': 0.042888802476227283}, ...]

Then something strange happens.
If I print all the "dict" before list3 append them, it is:
{'date': Timestamp('2020-03-01 00:00:00', freq='D'), 'score_positive': 0}
{'date': Timestamp('2020-03-02 00:00:00', freq='D'), 'score_positive': 0}
{'date': Timestamp('2020-03-03 00:00:00', freq='D'), 'score_positive': 0.04884412481139103}
{'date': Timestamp('2020-03-04 00:00:00', freq='D'), 'score_positive': 0.04884412481139103}
{'date': Timestamp('2020-03-05 00:00:00', freq='D'), 'score_positive': 0.026178522035479546}
...

But if I print all the items in list3, it is:
{'date': Timestamp('2020-03-02 00:00:00', freq='D'), 'score_positive': 0}
{'date': Timestamp('2020-03-02 00:00:00', freq='D'), 'score_positive': 0}
{'date': Timestamp('2020-03-04 00:00:00', freq='D'), 'score_positive': 0.04884412481139103}
{'date': Timestamp('2020-03-04 00:00:00', freq='D'), 'score_positive': 0.04884412481139103}
{'date': Timestamp('2020-03-08 00:00:00', freq='D'), 'score_positive': 0.026178522035479546}
{'date': Timestamp('2020-03-08 00:00:00', freq='D'), 'score_positive': 0.026178522035479546}
{'date': Timestamp('2020-03-08 00:00:00', freq='D'), 'score_positive': 0.026178522035479546}
{'date': Timestamp('2020-03-08 00:00:00', freq='D'), 'score_positive': 0.026178522035479546}
{'date': Timestamp('2020-03-11 00:00:00', freq='D'), 'score_positive': 0.042888802476227283}

Does someone know why is that?
The aim of the code is to make up a list, add all the dates that do not exist in the original list.


text:
Q: Some additional characters appended after the URL My client website created using php code.
However, when I click on any link on any web page, the url bar append some characters as below "VzFqJRV95E4". It is different from another computer and different browsers showing different characters.
I copy the website to my localhost also display different characters.

http://localhost/newbridge/Frequently-Asked-Questions.php#.VzFqJRV95E4

Screenshot from chrome
How can I remove the codes? I think it is session tracking. It's so annoying and I think I should remove it to protect user privacy.

A: I got the answer from rocky!
https://drupal.stackexchange.com/questions/37467/strange-characters-after-url-uafabbty-ie
The URL is actually generated by AddThis plugin's Address Bar Sharing Analytics.
Info can refer to this URL http://www.addthis.com/academy/what-is-address-bar-sharing-analytics/

How it Works
Address bar share tracking works by appending a special tag to your URL once your page has loaded. Your URLs will start to look like this:
http://example.com/blog#AHb4gs1hwck
In this case, "#AHb4gs1hwck" is a semi-random value which identifies each page view. When a user clicks on an URL like this we'll know that they were the recipient of an address bar share and we'll count a share and a click for your site. This tag contains the time that the page was viewed by the sharer so we can properly attribute the share. If that recipient subsequently shares your page to someone else, we'll be able to measure it separately as a "reshare", taking into account the various generations of your viral sharing.
Note: these types of tags (called URL fragments) will not affect your SEO because they are discarded by search engines during web crawling.


text:
Q: How to edit CSV data in C# like 1234567 to 123-4567? Im trying to edit a postcode data which comes as for example 1234567 and i want to put a dash between 123 and 4567 (e.g 123-4567) is it possible to do this within C# without editing the csv file itself?
Im using a generic for loop to read through the csv file but i want to edit it like i asked above.
                foreach(string line in csvData_){
                string[] col = line.Split(',');
                deliveryAddress.Text = col[0];
                deliveryPostcode.Text = col[1];

deliveryPostcode contains 1234567 for e.g.

A: To solve your problem, you can use the method Insert() of the string object.
For example:
deliveryPostcode.Text = col[1].Length == 7 ? col[1].Insert(3, "-") : col[1];

You have to fit it for your needs, but this is the way I would use.
Here is the MSDN page of the String.Insert().


text:
Q: replacing several characters using javascript replace I want to replace all the occurrences of accented characters À, Á, Â, Ã, Ä, Å with "A" using javascript replace ( For example, "ÀNÁPIÂLÃZÄ" would be rendered to "ANAPIALAZA").
I tried:
var re = /À||Á||À||Á||Â||Ã||Ä||Å/g;
name =  name.replace(re,"A");

and
var  re = /(ÀÁÂÃÄÅ)/g;
name =  name.replace(re,"A");

I not sure how to express the desired rule in regex pattern.
Thanks

A: Square [ ] brackets will solve your problem.
var  re = /[ÀÁÂÃÄÅ]/g;
name =  name.replace(re,"A");

Example: http://jsfiddle.net/y2a6x/

A: Use [] square brackets, like this:
/[ÀÁÀÁÂÃÄÅ]/g

The problem with your first || example, by the way, is that you should only use one | in regexes.


text:
Q: how would show value on screen form
Hi i want to create a comments section so when i input some text and click send then it will show what has been inputted down below. i wanted to know how i would implement. i'm new to this stuff.
customeVue.js
   $('#sendbutton').click(function() {
    var name = $('#comments').val();
 });

index.html

     <input type="text" id="comments" autocomplete="off">
     <button id ="sendbutton">send</button>

A: you just need to set the innerHTML where you want to place the comment to the input.value

var text="";
$('#sendbutton').click(function() {
    var name = $('#comments').val();

        text = text + name + "
";
        document.getElementById('text').innerHTML = text;

        $('#comments').val("");

 });

     <input type="text" id="comments" autocomplete="off" />
     <button id ="sendbutton">send</button>


text:
Q: Which property features the most Firefly actors? The actors in Firefly have since appeared in numerous other sci-fi tv shows and movies.
Which show/movie has the most Firefly actors? Does any property have all of the main cast members?
Note: The actors need not have recurring roles. A cameo is enough to qualify.

A: Assuming you want to discount anything that's Firefly-related, the winner is Con Man, Wash [ahem, sorry] Alan Tudyk's pet project. It has six of the main actors, although not all in the same episodes.

*

*Alan Tudyk

*Nathan Fillion

*Sean Maher

*Jewel Staite

*Summer Glau

*Gina Torres

As of May 2016, second place goes to Castle, with 5 veterans:

*

*Nathan Fillion

*Adam Baldwin

*Gina Torres

*Summer Glau

*Jewel Staite

Third place is a tie between CSI (oddly enough) and Justice League.
CSI: Crime Scene Investigation has had the following main Firefly actors, although definitely not in the same episodes. (Which means that the show doesn't come up if you do a "credited with" search on IMDB.)

*

*Ron Glass

*Summer Glau

*Alan Tudyk

*Gina Torres

The Justice League animated TV series has also had four of our actors doing voices:

*

*Adam Baldwin

*Morena Baccarin

*Gina Torres

*Nathan Fillion

Honorable mention: Buffy-verse has had four actors, but not in the same series. Nathan was in Buffy itself, and Summer, Adam, and Gina all appeared in the spin-off Angel.
5th place is a three-way tie between the aforementioned Angel and the video games Halo 3 and Halo 3: ODST, which both had Adam, Alan, and Nathan.
Looking at it from the actor's perspective, Adam Baldwin has shared the screen most often with his erstwhile co-stars, with 19 of his shows having at least one other Firefly alum. The person who has worked on the same shows as her co-stars the least is Jewel, with only 4 shows: Con Man, The X Files (Adam),  Warehouse 13 (Sean), and Castle. The numbers are:

*

*Adam 19

*Alan 18

*Gina 13

*Jewel 4

*Morena 8

*Nathan 16

*Ron 5

*Sean 9

*Summer 11

A: The Firefly mobile RPG features all of the original cast along with several of the supporting characters such as Niska (who will provide the players with a continuous stream of jobs and missions).

At the Firefly panel Thursday night of Comic-Con, the cast members
  announced they would be providing voices for Firefly Online, an
  upcoming mobile role playing game set in the 'verse of the series.
  Fillion, Gina Torres, Adam Baldwin, and the rest of the main cast will
  lend their voices to the game, while Alan Tudyk will provide "multiple
  voices" for different characters. Given Tudyk's experience voice
  acting in animated films — Wreck-It Ralph, Frozen, and Big Hero 6 —
  it's no wonder why he'll be providing more voices aside from that of
  his original character, Wash.

You may wish to note that the beta was launched a while ago, but the full game seems to be stuck in development hell.


text:
Q: Проблема с LeaderBoard в unity android, до набора очков все работает, после нет, как исправить? Суть в том, что в начале не заходила в акаунт, после удалось это решить,
теперь проблема с LeaderBoard, до набора очков он спокойно туда заходит, но стоит хоть одно очко набрать, выдает ошибку: Произошла неизвестная ошибка.
Использую CloudOnce.
Сталкивался ли кто с подобным? Если да, то как вы решали?

Вот код. Вроде весь что взаимодействет с LeaderBoard
   void Start()
    {
        Screen.sleepTimeout = SleepTimeout.NeverSleep;

        Cloud.OnInitializeComplete += CloudOnceInitializeComplete; ///
        Cloud.Initialize(false, true);
    }

    public void CloudOnceInitializeComplete()
    {
        Cloud.OnInitializeComplete -= CloudOnceInitializeComplete;
    //Debug.LogWarning("Initialized");
    }

    public void Save()
    {
        FileStream file = null;

        try
        {
            BinaryFormatter bf = new BinaryFormatter();
            file = File.Create(Application.persistentDataPath + "/GameData.dat");
            if (data != null)
            {
                data.setHiScore(hiScore);
                data.setIsMusicOn(isMusicOn);
                data.setIsGameStartedFirstTime(isGameStartedFirstTime);

                bf.Serialize(file, data);

                ////////////
                Leaderboards.SCORE.SubmitScore(hiScore);

                ////////////
            }
        }
        catch (Exception e)
        {
        }
        finally
        {
            if (file != null)
            {
                file.Close();
            }
        }
    }


text:
Q: python : how to implement nested for loop using list comprehension? My code is
montly_ratio = [0.046644865594960915, 0.060708276768318435, 0.07706787106693493, 0.09332535512669753, 0.10693770921153412, 0.11542007554770539, 0.11681104031351618, 0.11013791562902592, 0.09588202154576116, 0.07644396803642538, 0.056608936984611016, 0.044011964174509026]
len = 12

production_by_yr = [12129.0, 24197.0, 36205.0, 48152.0, 60038.0, 71863.0, 83628.0, 95331.0, 106974.0, 118556.0, 130077.0, 141538.0, 152938.0, 164277.0, 175555.0, 186772.0, 197929.0, 209024.0]
len = 18

I want to do
for yr in production_by_yr:
    for month in montly_ratio:
        print yr * month,

Which will give me 216 values
I did the same by list comprehension as following:
[yr * month for yr in production_by_yr for month in montly_ratio]

This gives me 216 values like
565.7555748012809, 736.3306889229343, 934.7562081708537, 1131.9432323317144, 1297.0474750266974, 1399.9300963181188, 1416.8011079626376, 1335.8627786644554, 1162.953039328537, 927.1888883138034, 686.6097966863471, 533.82111347262, 1128.6658128012693, 1468.9581729630013, 1864.8112762066244, 2258.1936180007, 2587.571749791491, 2792.8195680278272, 2826.476742466151, 2665.00714447554, 2320.0572753427828, 1849.7146945773848, 1369.7664482166329, 1064.957497130595, 1688.77735886556, 2197.943160396969, 2790.242271978379, 3378.844482362084, 3871.6797620035927, 4178.783835204674, 4229.1437145508535, 3987.543235348883, 3471.4085900642826, 2767.6538627587806, 2049.526563527842, 1593.4531629380992, 2246.043568128558, 2923.2249429480694, 3710.9721276150503, 4493.8025000607395, 5149.264573953791, 5557.70747777311, 5624.685213176431, 5303.360913368856, 4616.911101471491, 3680.9299488899546, 2725.8335336829896, 2119.2640989309584, 2800.464440590263, 3644.803520616302, 4627.000843116639, 5603.067671096666, 6420.326185642085, 6929.590495733136, 7013.101238342884, 6612.460178535458, 5756.564809564408, 4589.542952970907, 3398.687358682076, 2642.390305109173, 3352.0399762506763, 4362.678893401668, 5538.328418483145, 6706.6399954698645, 7684.8645970684765, 8294.432889084752, 8394.391790050213, 7914.841030848689, 6890.369714343034, 5493.492875001637, 4068.0880385251016, 3162.831781472742, 3900.8168199753914, 5076.911769580934, 6445.031921585634, 7804.612798535461, 8942.986745942175, 9652.350077903506, 9768.67367933873, 9210.61360822418, 8018.421697828914, 6392.856158950181, 4734.09218214905, 3680.6325399858406, 4446.701682033219, 5787.380732600564, 7346.9572166819735, 8896.799429583201, 10194.47875684476, 11003.111222038302, 11135.71328412781, 10499.55763483067, 9140.528995978957, 7287.4799168804675, 5396.586571679953, 4195.70455672012, 4989.787852155348, 6494.207199014097, 8244.258439514297, 9983.386539323341, 11439.55450519465, 12346.947161640237, 12495.74422649808, 11781.893386499418, 10256.883372836253, 8177.517036728568, 6055.6844249917785, 4708.135855603929, 5530.028685476186, 7197.33046054476, 9136.858522211536, 11064.280802400752, 12678.107053282638, 13683.74247663376, 13848.649695409224, 13057.510725314796, 11367.38894637926, 9062.891074526447, 6711.329133147544, 5217.882424673092, 6067.424181995731, 7896.750517192557, 10024.757464773695, 12139.482218815434, 13910.136401108723, 15013.497167018873, 15194.429690861243, 14326.409651276805, 12472.045716607974, 9943.602030274104, 7363.520696147247, 5724.94426392761, 6602.020986579578, 8592.528077234254, 10908.032335071835, 13209.084113922514, 15135.749486382116, 16336.326652871126, 16533.201023894453, 15588.700302301071, 13570.949565543942, 10819.726347939575, 8012.315722927874, 6229.365385331658, 7133.7724543621325, 9284.602432393085, 11786.606065234893, 14272.993162366865, 16354.839371393604, 17652.11551411497, 17864.846883468537, 16844.272540471964, 14664.00461116562, 11691.187583554824, 8657.65760455244, 6731.101776921061, 7662.678585343394, 9972.973582669048, 12660.478655262868, 15331.20936414849, 17567.40605614319, 18960.8637507504, 19189.367269583498, 18093.126365789492, 15751.210853473005, 12557.985737119852, 9299.546341020943, 7230.153438695819, 8188.739379523363, 10657.641528062142, 13529.65010515576, 16383.732719267384, 18773.44954063087, 20262.57136277742, 20506.762182239334, 19335.261778253644, 16832.5682924661, 13420.120808634658, 9937.981932333387, 7726.520370655932, 8711.95483690204, 11338.60626857237, 14394.12041491357, 17430.56322772355, 19972.96982485665, 21557.238350196032, 21817.031621436043, 20570.67877786443, 17908.076928144903, 14277.59279809924, 10572.964378489769, 8220.2025728014, 9232.37160234502, 12015.9285124765, 15253.966652407364, 18471.794214872116, 21166.073846529736, 22844.98013308178, 23120.292398213944, 21799.48750253747, 18977.83264253096, 15130.478149481638, 11204.550288427074, 8711.244057096397, 9749.89638612111, 12689.486843220993, 16109.034681895006, 19507.239030002824, 22352.54773023171, 24125.565871283572, 24416.310890492405, 23021.467676441513, 20041.64367158118, 15978.623974845777, 11832.626444271333, 9199.556799612574]

so I thought to validate the last 12 numbers which is
production_yr = 209024.0 and ratio being same and I did

[20924.0 * r for r in montly_ratio]
      [975.9971677089621, 1270.259983100295, 1612.5681342045464, 1952.739730671019,
      2237.56462754214, 2415.0496607601876, 2444.1542075200123, 2304.525746621738, 2006.2354188235065, 1599.5135871941645, 1184.485397466001, 920.9063383874269]

and then I realized that the numbers I achieved with nested for loop are quite big and might not be right
9749.89638612111, 12689.486843220993, 16109.034681895006, 19507.239030002824, 22352.54773023171, 24125.565871283572, 24416.310890492405, 23021.467676441513, 20041.64367158118, 15978.623974845777, 11832.626444271333, 9199.556799612574

What is that I am not doing right here?

A: Err, but your code for validation is wrong:
209024.0 is the correct value, and you used:
[20924.0 * r for r in montly_ratio]
 ^^^^^


text:
Q: How to include a single quote / apostrophe in an ArcGIS Server REST API query string This is similar to How do I query a string in Arcobjects that has a single quote in it? but in my case the apostrophe is actually in the word I'm searching for: &where=locality = 'O'CONNELL'
This fails in an ArcGIS Server query:

A: As with the ArcObjects question above, the answer is to include a second single quote:
&where=locality = 'O''CONNELL'


text:
Q: Android layout strange TextView behaviour in editor I have an xml layout file that is used to show a ListView item. Here is xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:id="@+id/task_item_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_item_background"
    android:orientation="horizontal"
    android:weightSum="1">

    <RelativeLayout
        android:id="@+id/task_item_icon_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2">

        <ImageView
            android:id="@+id/item_icon"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            app:srcCompat="@android:drawable/stat_notify_sync" />

    </RelativeLayout>

    <TextView
        android:id="@+id/item_text"
        android:layout_width="0dp"
        android:layout_height="75dp"
        android:layout_weight="0.6"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:text="appName"
        android:textAlignment="textStart"
        android:textSize="20sp" />

    <RelativeLayout
        android:id="@+id/additional_info_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.19">

        <TextView
            android:id="@+id/price"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="5dp"
            android:text="0,1 $"
            android:textSize="20sp" />
    </RelativeLayout>
</LinearLayout>

I want TextView with id price to have gravity value set to center. But when I do it, item_text somewhy jumps to the center. This behaviour can be seen only in editor, everything is fine on my device.
Layout when price gravity value is not set:

Layout when price gravity value is set to center:

Why is this happening and how do I fix this?
UPD: Do not edit my question: I change gravity of price TextView, and item_text is the one that changes. This is the strange behaviour I am asking about.

A: In your TextView with id item_text add
android:layout_gravity="center"

It happens because there is an inconsistent specification between text_alignment and gravity. Older phones ignore text_alignment, which explains why it works on your device.

A: Make the following changes
<RelativeLayout
            android:id="@+id/additional_info_container"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.19">
            <TextView
                android:id="@+id/price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" //here
                android:layout_margin="5dp"
                android:text="0,1 $"
                android:layout_centerVertical="true" //add this
                android:textSize="20sp" />
        </RelativeLayout>


text:
Q: Regex in Perl messed up by bracket I am new to perl and having the following problem recently.
I have a string with format " $num1 $num2 $num3 $num4", that $num1, $num2, $num3, $num4 are real numbers can be a scientific number or in regular format.
Now I want to extract the 4 numbers from the string using regular expression.
$real_num = '\s*([+-]?[0-9]+\.?[0-9]*([eE][+-]?[0-9]+)?)'
while (<FP>) {
    if (/$real_num$real_num$real_num$real_num/) {
        print $1; print $2; print$3; print$4;
    }
}

How can I get $num1, $num2, $num3, $num4 from $1, $2, $3, $4? As there is a necessary bracket in the $real_num regular expression so $1, $2, $3, $4 are not what I am expecting now.
Thanks for all warm replies, non-capturing group is the answer I need!

A: Just use non-capturing groups in your $real_num regex and make the regex itself a captured group:
$real_num = '\s*([+-]?[0-9]+\.?[0-9]*(?:[eE][+-]?[0-9]+)?)'

Now, the problem is: /$real_num$real_num$real_num$real_num/ will easily fail, if there are more than 4 numbers out there. May be this is not the case now. But, you should take care of that also. A split would be a better option.

A: If you are sure that your lines contains numbers, you can avoid that regexp, using split function:
while (<FP>) {
    my @numbers = split /\s+/; #<-- an array with the parsed numbers
}

If you need tho check if the extracted strings are really numbers, use the Scalar::Util looks_like_number. Example:
use strict;
use warnings;
use Scalar::Util qw/looks_like_number/;

while(<DATA>) {
    my @numbers = split /\s+/;
    @numbers = map { looks_like_number($_) ? $_ : undef } @numbers;
    say "@numbers";
}

__DATA__
1 2 NaN 4 -1.23
5 6 f 8 1.32e12

Prints:
1 2 NaN 4 -1.23
5 6  8 1.32e12

A: The answers to two important questions will affect whether you even need to use a regular expression to match the various number formats, or if you can do something much simpler:

*

*Are you certain that your lines contain numbers only or do they also contain other data (or possibly some lines have no numbers at all and only other data)?

*Are you certain that all numbers are separated from each other and/or other data by at least one space? If not, how are they separated? (For example, output from portsnap fetch generates lots of numbers like this 3690....3700.... with decimal points and no spaces at all used to separate them.

If your lines contain only numbers and no other data, and numbers are separated by spaces, then you do not even need to check if the results are numbers, but only split the line apart:
my @numbers = split /\s+/;

If you are not sure that your lines contain numbers, but you are sure that there is at least one space between each number and other numbers or other data, then the next line of code is a quite good way of extracting numbers properly with a clever way of allowing Perl itself to recognize all the many different legal formats of numbers. (This assumes that you do not want to convert other data values to NaN.) The result in @numbers will be proper recognition of all numbers within the current line of input.
my @numbers = grep { 1*$_ eq $_ } m/(\S*\d\S*)/g;
# we could do simply a split, but this is more efficient because when
# non-numeric data is present, it will only perform the number
# validation on data pieces that actually do contain at least one digit

You can determine if at least one number was present by checking the truth value of the expression @numbers > 1 and if exactly four were present by using the condition @numbers == 4, etc.
If your numbers are bumped up against each other, for instance, 5.17e+7-4.0e-1 then you will have a more difficult time. That is the only time you will need complicated regular expressions.
Note: Updated code to be even faster/better.
Note 2: There is a problem with the most up-voted answer due to a subtlety of how map works when storing the value of undef. This can be illustrated by the output from that program when using it to extract numbers from the first line of data such as an HTTP log file. The output looks correct, but the array actually has many empty elements and one would not find the first number stored in $numbers[0] as expected. In fact, this is the full output:
$ head -1 http | perl prog1.pl
Use of uninitialized value $numbers[0] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[1] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[2] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[3] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[4] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[5] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[6] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[7] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[10] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[11] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[12] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[13] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[14] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[15] in join or string at prog1.pl line 8, <> line 1.
Use of uninitialized value $numbers[16] in join or string at prog1.pl line 8, <> line 1.
        200 2206

(Note that the indentation of these numbers shows how many empty array elements are present in @numbers and have been joined together by spaces before the actual numbers when the array has been converted to a string.)
However, my solution produces the proper results both visually and in the actual array contents, i.e., $numbers[0], $number[1], etc., are actually the first and second numbers contained in the line of the data file.
while (<>) {
my @numbers = m/(\S*\d\S*)/g;
@numbers = grep { $_ eq 1*$_ } @numbers;
print "@numbers\n";
}

$ head -1 http | perl prog2.pl
200 2206

Also, using the slow library function makes the other solution run 50% slower. Output was otherwise identical when running the programs on 10,000 lines of data.

A: My previous answer did not address the issue of non-space separated numbers. This requires a separate answer in my opinion, since the output can be drastically different from the same data.
my $number = '([-+]?(?:\d+\.\d+|\.\d+|\d+)(?:[Ee][-+]\d+)?)';

my $type = shift;

if ($type eq 'all') {

while (<>) {
my @all_numbers = m/$number/g;
# finds legal numbers whether space separated or not
# this can be great, but it also means the string
# 120.120.120.120 (an IP address) will return
# 120.120, .120, and .120
print "@all_numbers\n";
}

} else {
while (<>) {
my @ss_numbers = grep { m/^$number$/ } split /\s+/;
# finds only space separated numbers
print "@ss_numbers\n";
}
}

Usage:
$ prog-jkm2.pl all < input # prints all numbers
$ prog-jkm2.pl < input # prints just space-separated numbers

The only code that the OP probably needs:
my $number = '(-?(?:\d+\.\d+|\.\d+|\d+)(?:[Ee][-+]\d+)?)';
my @numbers = grep { m/^$number$/ } split /\s+/;

At this point, $numbers[0] will be the first number, $numbers[1] is the second number, etc.
Examples of output:
  $ head -1 http | perl prog-jkm2.pl
200 2206
  $ head -1 http | perl prog-jkm2.pl all
67.195 .114 .38 19 2011 01 20 31 -0400 1 1 1.0 200 2206 5.0


text:
Q: I get the error "ORA-25351: transaction in use" when I access the Oracle database from a Java application running on a Tomee server I am writing a web service method which writes into a first schema 'IMMO' and then writes into another schema 'CSF'.
The writing into the first schema is running well, but the first try to write into the second schema leads to the following error :
ORA-25351: transaction in use
What I need is a unique distributed transaction starting at the begining of my web service method and ending at the return of this method.
My web service is implemented by a stateless EJB which calls other stateless EJBs, all these EJB using default transaction parameters :

*
*no transaction management specified, so CMT is assumed

*
*no transaction attribute specified, so REQUIRED is assumed
Despite all that, it seems that when I try to get a connection to the second datasource, it considers that I am in another session.
The server is tomee 7.0.3
I think I have missed something in tomee configuration, but I can't find anything ...
Here is the datasource definition, coming from tomee.xml :
<Resource id="ImmoDataSource" type="javax.sql.DataSource">
    DataSourceCreator   dbcp
    name            ImmoDataSource
    username        IMMO
    password        ****
    JdbcUrl         jdbc:oracle:thin:@srv-ora5:1521:IBOP
    JdbcDriver      oracle.jdbc.xa.client.OracleXADataSource
    validationQuery     select * from dual
    connectionProperties    useUnicode=false;characterEncoding=WE8MSWIN1252;
    maxTotal        30
    maxIdle         1
    minIdle         0
    maxWaitMillis   60000
    DefaultAutoCommit   false
    testOnBorrow        false
</Resource>

<Resource id="CSFDataSource" type="javax.sql.DataSource">
    DataSourceCreator   dbcp
    name            CSFDataSource
    username        CSF
    password        ***
    JdbcUrl         jdbc:oracle:thin:@srv-ora5:1521:IBOP
    JdbcDriver      oracle.jdbc.xa.client.OracleXADataSource
    validationQuery select * from dual
    connectionProperties    useUnicode=false;characterEncoding=WE8MSWIN1252;
    maxTotal        30
    maxIdle         1
    minIdle         0
    maxWaitMillis   60000
    DefaultAutoCommit   false
    testOnBorrow        false
</Resource>

I expect that the writing in the second schema CSFDataSource is executed in the same transaction as the writing into the first one.
I have writed a small web service, only one little class,  that uses the same tomee.xml, and that reproduces the problem :
package fr.csf.testxa;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.sql.DataSource;

@Stateless
@WebService
public class TestXa
{
    @Resource
    private DataSource CSFDataSource;

    @Resource
    private DataSource ImmoDataSource;

    @WebMethod
    public String test() throws SQLException
    {
        String ret = "?";

        // This first insert via ImmoDataSource goes well
        Connection cnx = this.ImmoDataSource.getConnection();
        Statement stm = cnx.createStatement();
        stm.executeUpdate( "insert into testxa( id) values ( sys_guid())");

        // The second access gets the ORA-25351 error
        cnx = this.CSFDataSource.getConnection();
        stm = cnx.createStatement();
        stm.executeUpdate( "insert into testxa( id) values ( sys_guid())");

        // We never arrive here because of the SQLException
        ret = "OK";

        return ret;
    }
}

After some search and many tries, I have found out that I get the ORA-25351 error only when the two datasources reference the same database. But I don't think it is illegal to reference different schema of the same database. That code had been written a long time ago for a Weblogic 8.1 server, and that worked perfectly well.

A: Ater much work, I have found an explanation :
The version of my Oracle JDBC driver (ojdbc7.jar) may not be compatible with the version of the Oracle database (Oracle 10gR2).
Here is a link to Oracle website :
https://docs.oracle.com/en/database/oracle/oracle-database/19/jjdbc/JDBC-getting-started.html#GUID-926E5324-D89A-4A00-B1AE-975C1089F0EA
where one can read this :
Oracle Database 12c Release 2 (12.2.0.1) JDBC drivers are certified with supported Oracle Database releases (11.x.0.x). However, they are not certified to work with older, unsupported database releases, such as 10.2.x, 10.1.x, 9.2.x, and 9.0.1.x.
So I replaced my ojdbc7.jar driver with an old ojdbc1.4.jar one. But now I
get an other error :
Unable to enlist connection in transaction: enlistResource returns 'false'.
But I think that is an other problem, and I will create an other question for it.


text:
Q: Can I change the image displayed on screen with a slider? I want to use the value output by this slider to change the image which is loaded into the img variable. The paint function is called whenever the slider is moved.
The slider's value is 0 - 2. The second if statement tests as correct when the slider is > 1, however, the image does not change. Without the if statements I can switch the image manually, otherwise it isn't doing what I expect.
 void ModelGUI::sliderValueChanged(Slider* slider)
{
  rotate.getValue();
  DBG(rotate.getValue());

}
void ModelGUI::paint (Graphics& g)
{
    DBG("PAINT");
    g.setColour(Colours::red);

    if(rotate.getValue() < 1)
    {
        img = ImageFileFormat::loadFrom(f);
    }
    if(rotate.getValue() > 1)
    {
        img = ImageFileFormat::loadFrom(f2);
    }
    g.drawImage(img, model);

    g.drawEllipse(225, 230, 2, 2, 2);
    g.drawEllipse(240, 240, 2, 2, 2);
    g.drawEllipse(245, 275, 2, 2, 2);
}

Why is this happening? Cheers

A: just a wild guess but shouldn't you force repainting in the sliderValueChanged event somehow?  I do not know juce but I would expect one of these:
g.Repaint();
g.Refresh();
g.Update();

as changing slider is probably just repainting the slider itself and not updating the rest of your GUI. The g should be your Graphics object of coarse.
If the repaint is really time consuming then I usually do something like this:
bool _redraw=false; // some global variable (or local but accessible to your GUI/Form/Canvas whatever)

void any_event()
 {
 // here event stuff code
 if (need_to_repaint) _redraw=true; // for example you change something hit a special key that changes something etc ...
 }

void timer() // any timer with target max fps interval
 {
 if (_redraw())
  {
  _redraw=false;
  // here force repaint or call the repaint directly
  }
 }

This way the repaint will not slow down other events too much. For example If I use zoom on wheel and I am rendering a lot of stuff the wheel could feel slagish if repainted on each change of wheel. This will repaint only with timer period which should be fine if set right.
The usual events that need such handling are zoom, mouse move/edit and window/view resize as they can create a lot of event calls per second ...

A: As @Spektre surmises -- in JUCE, your component needs to request that it be repainted when it knows that's necessary. In this case:
void ModelGUI::sliderValueChanged(Slider* slider)
{
   rotate.getValue();
   DBG(rotate.getValue());
   repaint();
}

...will cause your ModelGUI component (and all of its child components) to repaint at the next reasonable point in time.
See: https://docs.juce.com/master/classComponent.html#af3ab3eabec93dd60faf983370f3a1206


text:
Q: onTouchListener only works when pressed for second time I'm trying to make a method that acts as a ColorStateListor Selector when a View is pressed. When a view is passed into the method onClickColorSelector
it takes the view and sets a setOnTouchListener, so when the user press down on a view, the view gets a selector effect.
Now the problem is that onTouchListener is only called when a View is clicked for the second time. Why does it behave like that and how to solve it?
Note! Dont suggest me ColorStateList!
onClickColorSelector is in a class called ViewSelector
  public void onClickColorSelector(View view, final int onPressColor) {

    Log.d("TAG" , "1");
    view.setOnTouchListener(new View.OnTouchListener() {
        int defaultTextColor = 0;

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                Log.d("TAG" , "2");
                if (view instanceof TextView) {
                    Log.d("TAG" , "3");
                    defaultTextColor = ((TextView) view).getCurrentTextColor();
                    ((TextView) view).setTextColor(onPressColor);
                }
                Log.d("TAG" , "4");
                    view.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);
                return true;

            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                if (view instanceof TextView) {

                    ((TextView) view).setTextColor(defaultTextColor);
                }

                    view.getBackground().setColorFilter(null);

                return true;
            }

            return false;
        }
    });
}

This is how onClickColorSelector(); is called from a another class:
ViewSelector vs = new ViewSelector(this);

      loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            vs.onClickColorSelector(loginBtn, Color.RED);

        }
    });

A:
It's Activated on when you press the button ...
That is the reason it running 2nd time ....
So call this vs.onClickColorSelector(loginBtn, Color.RED); in your
  OnCreate() method


text:
Q: AS3 stage.addChild / stage.removeChild << Must be child of caller If im usin function to add a mc to the stage like so:
var myChild:MC= new MC();

function somefunc()
{
   stage.addChild(myMC)
}

but when I try to remove the mc by:
stage.removeChild(myMC)

I get The supplied DisplayObject must be a child of the caller error...
any suggestions or work arounds?

A: Your code should work if the item is on the stage.  Perhaps qualifying it with a conditional statement like so:
if (myMC.stage != null)
   stage.removeChild(myMC);

Alternatively you could use the following code but it is probably not best practice.
if (myMC.parent != null)
   myMC.parent.removeChild(myMC);

A: The problem is not with removeChild. It's with the displaylist. If you check the parent property of the displayobject, when you call "removeChild" it will be null.
Why does it become null could be because of lots of reasons:

*

*Parent is nulled before the child.

*The child or parent have event listeners that won't let them die.

*The Display Object is really not the instance you're trying to remove. THIS one can be very tricky to find out. Look at the "name and parent properties" of the variable you're trying to remove while calling removeChild.

A: You could try hiding and showing the movieClip, if possible.
I think its a bit faster than removing and adding consistantly, code permitting.
Keep in mind this is just a suggestion, someone smarter than me outta be able to help you out..

A: You could also use this fail safe:

if(myMC.parent) myMC.parent.removeChild(myMC);

A: I could fix this problem by simply removing every EventListeners I added to that object before removing it.


text:
Q: No refresh token or refresh handler callback is set in nodejs authentification system I am trying to send Email using Nodemailer and OAuth2 in nodejs but i am getting an weird error :

concerning accesstoken method in sendmail file

Here is sendmail.js file:
    oauth2Client.setCredentials({
        refresh_token: MAILING_SERVICE_REFRESH_TOKEN
    })

    const accessToken = oauth2Client.getAccessToken()
    const smtpTransport = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            type: 'OAuth2',
            user: SENDER_EMAIL_ADDRESS,
            clientId: MAILING_SERVICE_CLIENT_ID,
            clientSecret: MAILING_SERVICE_CLIENT_SECRET,
            refreshToken: MAILING_SERVICE_REFRESH_TOKEN,
            accessToken
        }
    })

I am getting the following error:

No refresh token or refresh handler callback is set.
at OAuth2Client.getAccessTokenAsync (C:\Users\DELL\Desktop\events\api\node_modules\google-auth-library\build\src\auth\oauth2client.js:224:27)
at OAuth2Client.getAccessToken (C:\Users\DELL\Desktop\events\api\node_modules\google-auth-library\build\src\auth\oauth2client.js:209:25)
at sendEmail (C:\Users\DELL\Desktop\events\api\routes\sendmail.js:26:38)
at C:\Users\DELL\Desktop\events\api\routes\auth.js:41:7 [nodemon] app crashed - waiting for file changes before starting...

It returns a success response in postman but the server crashes and the mail is not send.
Hope you can help and thanks in advance


text:
Q: Why do I have to specify the type for "const" variables but not for "let" variables? To create a variable in Rust you'd use:
let var_name = 10;

This would also be valid:
let var_name: i32 = 10;

Constant variables are created like this:
const VAR_NAME: i32 = 10;

But if you tried to create a constant variable like this:
const VAR_NAME = 10;

You'd get an error that looks like this:
error: expected `:`, found `=`
 --> src/main.rs:5:11
  |
4 |   const VAR_NAME = 10;
  |                 ^ expected `:`

Having come from languages like JavaScript, Python & PHP this is kind of confusing to me.
Why is it that I have to specify a type definition when using const but not when I use let?

A: Currently, there is a rule "Constants must be explicitly typed." (for static: "A static item is similar to a constant").
But, you are right: the compiler could infer it. There is an open discussion about that: #1349, TL;DR:

*

*We could technically infer the type of const and static variable

*We do not use them very often so it's not very annoying to annotate the types

*We should maybe limit type inference for constants/statics to only literal value

*This could make error messages less accurate

*Maybe limit type inference for constants/statics to local scopes like function bodies

*For integers, const FOO = 22 would infer to i32 so probably not the type one would expect. So we'd end up writing const FOO = 22usize.

*When the variable is initialized with a const-fn, the type should be inferred

*When the variable is initialized with another variable typed explicitly

*For arrays, the explicit type is very redundant

*For variables which are only exported, we can end up not being able to infer their types (so it would be a compile-time error "type needs to be specified")

It may be worth mentioning that one of the guiding principle of type inference in Rust is that type inference should be local. This is the reason why, unlike in Haskell, function signatures always need to be fully specified. There are multiple reasons for this, notably it means easier reasoning for human readers and better error messages. This puts module level const in a tough spot, inference-wise. Matthieu M.

So far, there is still not a proposed RFC, so this issue stays open.
See also:

*

*Why does Rust not permit type inference for local constants?


text:
Q: Java. Util.ConcurrentModification Exception solution I have two list and I am Retrieving data from them.
for(String s:alist) {
for(String s1:bList) {
My code
}
}

I am getting Java. Util.ConcurrentModification Exception when searched for it and found some solutions on stackoverflow but still I am not able to resolve it. Please help.  I am getting exception on second for each loop and I followed one of the solution from stackoverflow that take a temporary list and do addAll when added all data to actual list but still not able to resolve it.  After this I have my code which is working fine.  I am getting exception in Retrieving through for each loop


text:
Q: After creating a JSON string, how do I retrieve data from it? I'm having trouble getting data that I've put into a JSON string in javascript. I first add my values to a JSON object and then I stringify it. I'm not sure I understand why I can't get a value from it. All I see is 'undefined' in the alert.
http://codepen.io/jimmykup/pen/wjJst
var jsonObj = [];

var name = "1stname";
var url = "firsturl";

item = {}
item ["name"] = name;
item ["url"] = url;

jsonObj.push(item);

var jsonString = JSON.stringify(jsonObj);

alert (jsonString.url);

I am converting my object to a string because I will be transferring that text somewhere and only THEN do I need to access the values.

A: You need to use JSON.parse() to convert a JSON string back into an object. Also, since your object is an array, you need to index it before accessing the url property.
var newObj = JSON.parse(jsonString);
alert (newObj[0].url);


text:
Q: Removing Duplicate Tuple Pairs by Condition How do you remove duplicate tuples from a list based on the condition that if (Y, Z) and (Z, Y) are part of the list, then we only keep the match where Y < Z?
For example, if we start with the following list of Car ID pairs:
CarID1 = [(100, 500), (100, 600), (100, 700), (500, 100), (500, 200)],

then we should remove the (500, 100 entry and end up with:
CarID2 = [(100, 500), (100, 600), (100, 700), (500, 200)]

I tried the following code to grab unique tuples, but it did not do what I described.
y = np.unique(x, axis=0)
z = []
for i in y:
   z.append(tuple(i))

A: Using a dictionary you can do it in linear time.
Note that for each tuple (u,v) I first check if (v,u) already exists and in that case I keep the one with u < v, otherwise it is inserted in the dictionary.
CarID1 = [(100, 500), (100, 600), (100, 700), (500, 100), (500, 200)]

d ={}
for (u, v) in CarID1:
    if (v, u) in d:
        d[(v,u)] = (u,v) if u < v else (v,u)
    else:
        d[(u,v)]  = (u,v)

d.values()
#dict_values([(100, 500), (100, 600), (100, 700), (500, 200)])

A: You can use list comprehension:
[(y, z) for y, z in CarID1 if (z, y) not in CarID1 or y < z]

And if an O(n) runtime is important, then use a set, which will take care of duplicates as well but may not guarantee the same order:
CarID1_distinct = set(CarID1)
[(y, z) for y, z in CarID1 if (z, y) not in CarID1_distinct or y < z]

A: z = [(a, b) for a, b in carID1 if not ( (b, a) in CarID1 and b > a) ]

This is a list comprehension that considers all pairs (a, b) in your original list.  It keeps them all except where the reversed pair is also in the list, and the elements are in the order you don't want.
Output:
>>> z
[(100, 600), (100, 700), (500, 100), (500, 200)]


text:
Q: How to get current PowerPoint slide number I am trying to access the current PPT slide index in normal view so that I can add a shape to the slide. But the VBA code for this has no equivalent that I can find in C#. Does anyone have the required syntax for finding the current slide index in the active presentation in normal mode? Thank you.
VBA code for retrieving the slide index:
idx = ActiveWindow.View.slide.SlideIndex
Set slide = ActivePresentation.Slides(idx)

C# code that is supposed to work in SlideShow mode from another SO post.
PowerPoint.SlideShowWindow.Presentation.SlideShowWindow.View.CurrentShowPosition

C# COM code for Normal mode that does not work is shown below.
The only Intellisense options after .Slide are Equals, Hashcode, GetType, and ToString.

var idx = papp.ActiveWindow.View.Slide.?


text:
Q: Java class parser I am parsing all the class files in a jar via Objectweb asm (http://forge.ow2.org/projects/asm/). The idea is to parse and store (and use for something later) all the public/protected methods and fields in each class file. It is working as expected. What I dont get is the list of methods, declared by the  interface and those inherited from superclasses and superinterfaces. Is there a smart parser available that would give me the above list?
I could load the class file and then use java.lang.Class object to get what I need. But loading classes might fail because of dependencies. I would rather parse and get that info.

A: The data you want is simply not there. Inherited members are implicit: you only have the names of the class and interfaces where they can be looked for, and you need to parse the corresponding class files.

A: You can simply do this :
Class superclass = aClass.getSuperclass();
aClass.getClass().getInterfaces();
aClass.getClass().getMethods();


text:
Q: Ignoring Javascript, CSS and image files routing in ASP.net I've turned Stack Overflow up and down, but, unfortunately, none of the answers helped me.
I have a web app that works perfectly on my local PC using IIS provided by the Visual Studio, but when I deploy this app to the server only the CSS is displayed properly.
Folder structure for files is as follows:

*

*Root (this folder is named Knowledge Management on the server)

*

*CSS

*JS

*Media

*Uploads

*

*Documents

*Images

*Users

My code, at least for Master page head section looks like this:

    <link href="CSS/Style.css" rel="stylesheet" />

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>

However, browser generates it like this:

    <link href="../../CSS/Style.css" rel="stylesheet" />

The problem is that besides CSS neither none of the files in JS folder and none of the files in Media or Uploads folders and subfolder doesn't generate properly.
The thing is if I add "slash" in front of the image src attribute the image gets location http://localhost/Media/Discussion.png and if I don't add "slash" then the image location is http://localhost/Uploads/Users/HrvojeFadiga.jpg when it should be http://localhost/Knowledge%20Management/Uploads/Users/HrvojeFadiga.jpg
Here is a sample of code with images:

    <img src="/Uploads/Users/<%=article.User.PhotoLocation %>" />

        <%= GetArticleRating(article.idArticle) %>

        <%= GetArticleViews(article.idArticle) %>

        <%= GetArticleComments(article.idArticle) %>

FYI, Global.asax doesn't contain any rules for ignoring file routes except for .axd files which is added by default.

A: I was able to sort this by adding runat=server attribute and using the tilt(~) before defining the source of the file. For example:
<link href="~/CSS/Style.css" rel="stylesheet" runat="server" />
Same applies to javascript files.

A: For any URLs for scripts and styles you need to call ResolveUrl like this:
<link href="<%= ResolveUrl("~/CSS/Style.css") %>" rel="stylesheet" />

A: Try this. without "~" it can also work but you can add it just to refer the root directory which is always your project solution. So by using Tilde "~" you can properly specify where your css and js files are located.
<link href="~/CSS/styles.css" type="text/css" rel="stylesheet"/>

<link href="CSS/Style.css" rel="stylesheet" type="text/css"/>

A: First of all, thank you all for your replies. After couple of days of playing I've finally figured out what to do to make everything work.
JS problems
I've solved JS problems by adding ScriptManager control to the .aspx page and by adding JS files inside it.
<asp:ScriptManager ID="smScripts" runat="server">

</asp:ScriptManager>

For some reason CSS files were working "out of the box" so I left them unchanged.
Image problems
I've managed to sort images problems out by avoiding hardcoded links to the images and by adding <%: Page.ResolveUrl("~/Media/Image.png") %> to the src attribute of the  tag. I guess I should've done this for everything that I don't want to route. This can be done for CSS files, JS files, everything. However, (even though this should work perfectly) I've experienced some strange problems with JS files and that's the reason for using ScriptManager.
Page links problem
At first I didn't realize that none of my links was working so I figured that the problem were semi-hardcoded links that, for some reason, don't route properly even though I hardcoded route the same way as defined in Global.asax file. I'm still not sure why this isn't working.
The solution for this is to generate links by using <%: Page.GetRouteUrl("RouteName", new { routeParameter1 = routeParameter1Value, routeParameter2 = routeParameter2Value}) %> and everyhting will work fine.

A: The directories/virtual-directory setup is the likely culprit.
View your page in Google Chrome then "Inspect Element".  Scroll to the top and you include your .JS files.  You can click on them to see what URL they are trying to link to.  More than likely the path is slightly different on the server than your local copy.


text:
Q: Existe alguma forma de pesquisar (FULLTEXT) em um campo específico no MongoDB? Eu tenho um índice full-text no MongoDB e preciso pesquisar apenas em cima de um campo, ao invés de todos. Alguém sabe se isso é possível?

A: Conforme a documentação do MongoDB, o mesmo suporta a indexação e busca de texto a partir da versão 2.4, se ativada. A partir da versão 2.6, este recurso está disponível por padrão.
Para criar um índice texto, faça:
db.reviews.ensureIndex( { comments: "text" } )

A engine de indexação de texto suporta várias linguagens, listadas aqui.
Para realizar a busca, use o operador $text, cuja sintaxes é:
{ $text: { $search: <string>, $language: <string> } }

A: Não tenho bons conhecimentos em MongoDB, mas este link irá lhe ajudar detalhadamente.
Full text search in MongoDB


text:
Q: AutoMapper: Mapping child member from complex type to string[] I have a destination type with a string[] property.
Animal
  string[] Barks;

My source object is:
  AnimalDTO
     List<BarkTypes> Barks;

How do I map BarkTypes.NameOfBark to the string[] Barks?
Something like this:?
Mapper.CreateMap<AnimalDTO, Animal>()
   .ForMember(dest => dest.Barks, y => y.MapFrom(x=>x.??????))

A: You want ResolveUsing:
Mapper.CreateMap<AnimalDTO, Animal>()
      .ForMember(dest => dest.Barks,
                    y => y.ResolveUsing(x=>x.Barks
                                            .Select(b=>b.NameOfBark)
                                            .ToArray())
              )

A: Completely untested, but:
Mapper.CreateMap<AnimalDTO, Animal>()
   .ForMember(dest => dest.Barks,
              y => y.MapFrom(x=>x.Barks
                                 .Select(z => z.NameOfBark)
                                 .ToArray());


text:
Q: How can I select the count of rows as a subquery of results from main query I am trying to gather the amount of items at a place only if the WHERE places.x < 5 is true. The reason for this, is that both the at_places and places tables contains tens of thousands of rows.
This is a general idea of what I'm trying to do; but I am unable to test it as it takes quite a long time to finish. I figure that being able to contain both the grabbing of count and the places in one query would be quite a bit faster than running a subsequent query grabbing the count for each place returned.
SELECT  `places`.`id`,
        `places`.`name`,
        (SELECT COUNT(*) FROM `at_places` WHERE places_id=places.id) AS count
FROM `places`
WHERE places.x < 5

A: You might find that an explicit join works better:
select p.id, p.name, ap.cnt
from places p join
     (select ap.places_id, count(*) as cnt from at_places ap group by ap.places_id) ap
     on p.id = ap.places_id
where p.x < 5

I believe your performance problem is due to the fact that the subquery is executed once for each row in the outer query.  An index on at_places.places_id should also speed up the query.


text:
Q: Automatically add newly generated component into entryComponents from command line When creating a new dialog with
ng generate component dialog/admin/item/edit-item-dialog

is there any way to have it automatically added to the entryComponents array inside app.module.ts?
It's quite inconvenient to have to open the file every time, scroll through it and place the component inside the array.

Specs:

*

*Angular CLI: 8.0.2

*Node: 10.15.0

*OS: win32 x64

*Angular: 8.0.0

A: Never mind, just read the docs:
ng generate component dialog/admin/item/edit-item-dialog --entryComponent=true

will automatically place the component inside the entryComponents array.


text:
Q: Git repo vanishes in integrated bash terminal in PyCharm when switching to virtual environment When I start a new terminal by click on the "+"-sign, a new git-bash terminal is started.
As I am in the root-folder of the currently selected PyCharm project, it recognizes automatically the .git - folder and checks on which branch I currently am. Here, I was recently on 'release/dev' (as visible in what follows).
Since the pip-virtual-env was not recognized automatically, I had to source the activation-script manually, even though I'd checked the box in the PyCharm-settings:

username@hd1pcms0347 MINGW64 ~/Projects/proj (release/dev)
$ source ../proj-venv/Scripts/activate

Next, something unexpected happens:
(proj-venv)
username@hd1pcms0347 MINGW64 ~/Projects/proj
$

The virtual-env called 'proj-venv' was indeed activated, but the git-repo 'release/dev' vanished.
Moreover, when using the git ... command, it states

bash: git: command not found

Yet, when opening a new bash terminal, the venv is gone but the git repo is present, and of course all git - commands are working.
Why do the git repo and the venv seem to exclude eachother and how can I resolve this issue?

System parameters:
OS: Windows 10
PyCharm 2021.2.2 (Community Edition)

Build #PC-212.5284.44, built on September 14, 2021 Runtime version:
11.0.12+7-b1504.28 amd64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. Windows 10 10.0 GC: G1 Young Generation, G1 Old Generation
Memory: 2004M Cores: 8 Registry:
debugger.valueTooltipAutoShowOnSelection=true

A: Virtual environments, in Python, work by modifying your shell's PATH and PYTHONPATH environment settings.1  This is why you have to source whatever/activate, rather than just running it.  Running it would create a sub-shell; the script would modify the sub-shell's settings; and then the sub-shell would exit, erasing all the modifications.
Depending on what's in the activation script, and what's currently in your own shell's environment, this can break things.  Python's venv-builder tries to build careful scripts, but there are an infinite number of ways to break things.
In this case, it seems that wherever Git is installed, that was in your $PATH before activating the environment, and not in $PATH afterward.  You can view $PATH before-and-after to see what has changed.  Ideally, the activate script merely added the location of the correct Python binary (see footnote 1), but apparently in this case it also removed the location of the correct Git installation.

1Unix-style shells find programs using $PATH.  That is, at the command line, you might type:
$ python test.py

Rather than somehow magically "knowing" where python is to be found, your shell simply breaks up the command-line words into an "argument vector" (sys.argv in Python).  The one in argv[0] in this case is just "python".  This isn't a full path like /c/whatever/python.exe, so the shell now takes the value of $PATH, which will be something like /c/bin1:/c/bin2:/c/addons or /usr/local/bin:/bin:/usr/bin or whatever, and attempt to run a python or python.exe within each of these path elements as separated by the colons.
Python, similarly, uses $PYTHONPATH to set up sys.path, which is where import looks.  So by setting $PATH so that python finds a particular Python version, and setting $PYTHONPATH so that this particular Python imports from some particular distribution, the virtual environment has sprung into existence.