text:
Q: NameError: name 'uuid_generate_v4' is not defined Getting this error while running insert query with uuid as primary key.

"NameError: name 'uuid_generate_v4' is not defined"

Note: extension 'uuid-ossp' is already created.
Is there any import statement I am missing?
This is the insert statement i am using
postgres_insert_query = "INSERT INTO users (UUID_ID,FULLNAME) VALUES (%s,%s)"

  record_to_insert =(uuid_generate_v4(),'name')

  cur.execute(postgres_insert_query, record_to_insert)

  connection.commit()

A: Try invoking the function call as part of the SQL statement instead of as a parameter. Something like:
postgres_insert_query = "INSERT INTO users (UUID_ID,FULLNAME) select uuid_generate_v4(),%s"

  record_to_insert =('name')

  cur.execute(postgres_insert_query, record_to_insert)

  connection.commit()


text:
Q: Pagination on group by I have a record in my MySQL table which is something like:
id                         Postcontent         postdate
1                                A                         2013-01-31
2                         B                         2013-01-31
3                         C                         2013-01-30
4                         D                         2013-01-30
5                         E                         2013-01-29
6                         F                         2013-01-29
and I would like to show it in something like
2013-01-31
A
B
2013-01-30
C
D
2013-01-29
E
F
i can able to show like above with group by, but not able to add pagination in group by
if anyone can help me on how to add pagination in group by.

A: You could do it like this :
while( $row = $query_prepared->fetch( PDO::FETCH_ASSOC ) )
{
    if( $date <> $row['postdate'] )
    {
        echo '
' ,$row['postdate'];
    }

    $date = $row['postdate'];

    echo '
' ,$row['Postcontent'];
}

And no don't put GROUP BY in your SQL but use ORDER BY postdate DESC or ASC .
Here is an example just for understanding :
$testData = array
(
    array('1','A','2013-01-31'),
    array('2','B','2013-01-31'),
    array('3','C','2013-01-30'),
    array('4','D','2013-01-30'),
    array('5','E','2013-01-29'),
    array('6','F','2013-01-29')
);

$date = '';
foreach( $testData as $data )
{
    $row = array();
    list( $row['d'] ,$row['Postcontent'] ,$row['postdate'] ) = $data;

    if( $date <> $row['postdate'] )
    {
        echo '
' ,$row['postdate'];
    }

    $date = $row['postdate'];

    echo '
' ,$row['Postcontent'];
}

This will output :
2013-01-31
A
B
2013-01-30
C
D
2013-01-29
E
F

A: What about this?
Make sure to have indexed postdate or even an index on (postdata, Postcontent) to get an covering index
Note some people will see this as wrong because you format (HTML) with SQL now but you get much cleaner client code with this approach
Run this query..
SELECT
   postdate
 , GROUP_CONCAT(Postcontent SEPARATOR '
') 'postcontent_formatted'

FROM
 your_table

GROUP BY
  postdate DESC

PHP code
<?php

     while( $row = $query_prepared->fetch( PDO::FETCH_ASSOC ) ) {
        echo $row['postdate'] . '
';
        echo $row['postcontent_html_formatted'] . '
';
     }

?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asp.net MVC 5 can't get user roles I'm trying to get user roles and modify it.
I've tried many ways to get user roles but nothing works.
Is there anything missing?
I can get right User entity but Roles is always null.
Is there any way to do it correctly?
Thanks
var user = UserManager.Users.Single(u=>u.Id==id);
var roles = user.Roles;
roles.Add(....)

var user = UserManager.Users.Single(u=>u.Id==id);
user.IsinRole("rolename");

A: You can get them via claims:
var roles = ((ClaimsIdentity)User.Identity).Claims
            .Where(c => c.Type == ClaimTypes.Role)
            .Select(c => c.Value);

To add a user to a role, you can do (Make sure the role exists in the database though):
var roleresult = UserManager.AddToRole(currentUser.Id, "RoleName");


text:
Q: vue-i18n: Is there a way to set a locale manually inside $t method? I am working on a project using Firestore and vue-18n. What I want to is to save a translated message into Firestore and I want to set a locale manually inside $t method. My code is like this.
methods: {
    doSomething() {
        ...
        db.collection('messages').add({
            body: this.$t('componentName.hello'), // I want to set a locale here
        })
    }
}

Is there a way to set a locale inside $t method?

A: ...
 body: this.$t('componentName.hello', locale), //for example "en"
...

source: https://github.com/kazupon/vue-i18n/blob/5.x/gitbook/api.md#tkeypath-lang-arguments


text:
Q: Can't get Jquery value on php side I have an array, it is filled in javascript code. I need to reach the values of this array on php side when confirm button clicked. So, I am using ajax post method as below.It is running successfully, I know because all of the alerts are working successfully. This is js part of my code.
$('#firstConfirmButton').click(function(){

    var my_json_val = JSON.stringify(ordersArray, null);
    alert(my_json_val.toString());

    $.ajax({
        type: "POST",
        url: "test.php",
        data: my_json_val,
        cache: false,
        contentType: false,
        async: false,
        processData: false,
        success:  function(response){
            //alert("---"+data);
        alert("Settings has been updated successfully.");
        alert(my_json_val);
        alert(response);

        window.location.reload(true);
        }
    });

});

On the other side, I have a test.php page and also it contains "confirm" button that use the js code above. When this button clicked, I want to echo values of the array that I posted with ajax. But I can not get the values on php side. Here is my php code;
<?php

    require("includes/db.php");
    require("includes/functions.php");

    session_start();

    if (isset($_POST['firstConfirmButton'])) {

        echo 'I am here'; //I can see only this row on php page

        $my_json_encoded = $_POST['data'];
        $my_json_val = json_decode($my_json_encoded);
        echo $my_json_val;  //nothing happens

    }

and here is my html code for confirm button;
<form role="form" method="post" action="starbucks.php">
                    <div id="firstConfirmButton">
                        <button type="submit" name="firstConfirmButton"   id="firstConfirmButton" class="btn btn-primary btn-lg">Onayla</button>
                    </div>

So where is my fault, please help!

A: Don't cast the array to Json, the ajax post will cast it itself, so replace my_json_val by ordersArray.

A: Do you really want to redirect to your php file or do you just need data from it? Because action="file.php" redirects to this file. If you just need data, try to use jquerys .submit method and do an ajax call, otherwise use it to remaster your action attribute (for simplicity i would use an id on the form if you have multiple forms on your site):
$('#yourform').submit(function(){
   var my_json_val = JSON.stringify(ordersArray, null);
   var elem = {
       firstConfirmButton: true,
       data: my_json_val
   }
   $.ajax({
        type: "POST",
        url: "test.php",
        data: elem,
        cache: false,
        contentType: false,
        async: false,
        processData: false,
        success:  function(response){
            //alert("---"+data);
            alert("Settings has been updated successfully.");
            alert(my_json_val);
            alert(response);
        }
    });
    return false;
});

if you actually want to redirect, try using this:
$('#yourform').submit(function(ev){
    var my_json_val = JSON.stringify(ordersArray, null);
    $(this).attr('action', ev.target.action+'?data="'+my_json_val+'"');
});


text:
Q: Parallels - Disk Access I have a MacBook Pro. I'm interested in running Windows. I've considered using Bootcamp, but it doesn't meet my needs. This lead me to consider Parallels.
My question is, is Parallels a Virtual Machine? Or, does it setup a separate disk partition? If I run Parallels from Mac OSX, can my Windows environment access my Mac OS X hard drive? I'm trying to understand how to Parallels runs Windows within Mac OS X. The reason I need to know if because I have a variety of technical needs that I'm trying to weigh in my decision.
Thank you for your help.

A: Parallels Desktop for Mac is a hardware emulation virtualization software.
Typically an hypervisor allows access to predefined shared folders between the host and the guest (Virtual Machine). Limitations may apply depending on the guest OS.
Depending on the actual "technical needs", undisclosed in your question, virtualization may not be what you're looking for.
A sophisticated boot manager like rEFInd is often recommended for multibooting in an Apple desktop.


text:
Q: Proof of $f=0$ a.e. in $[a,b]$ then $f$ is gauge integrable and $\int_a^bf=0$ Let $f:[a,b]\to \mathbb{R}$ so that $f(x)=0$ almost everywhere in $[a,b]$. Prove that $f$ is gauge integrable and $\int_a^bf=0$.
How can this be proven using the following definition of measure: $\mu(A)=\int_{-\infty}^{\infty}\chi_A$ when of course $\chi_A$ is integrable or the integral is infinite? I have established the basic properties of measures (countable additivity etc.) and can use the MCT, Fatou's Lemma, DCT for the gauge integral. Almost all proofs I have seen either use measurability of $f$ or the characterisation of measure $0$ via open interval covers. I would like to see an alternate approach


text:
Q: Google `drive.files.list` doesn't list files I'm having issues with the Google drive API. I am passing in the folder ID and it's not showing any files. How do I traverse within the sub folders to check for folders and files there?
const path = require('path')
const { JWT } = require('google-auth-library')
const { google } = require('googleapis')
const axios = require('axios')

// Get auth token
const getAuth = ({ email, key }) => {
  const scopes = ['https://www.googleapis.com/auth/drive']
  return new JWT({
    email,
    key,
    scopes,
  })
}

async function loadDrive(options) {
  const { folderId, key, service_email } = options
  const auth = await getAuth({ email: service_email, key })

  const drive = google.drive({
    version: 'v3',
    auth: auth,
  })

  try {
    const res = await drive.files.list({
      pageSize: 10,
      fields: 'nextPageToken, files(id, name)',
      q: `'${folderId}' in parents`,
      spaces: 'drive',
    })

    const files = res.data.files
    if (files.length === 0) {
      console.log('No files found.')
    } else {
      console.log('Files:')
      for (const file of files) {
        console.log(`${file.name} (${file.id})`)
      }
    }
  } catch (e) {
    console.log(e)
  }
}

A: [Update 01/04/22]: I shared my service account email under https://console.cloud.google.com/iam-admin/serviceaccounts with the folder in Google drive and was able access the Drive data.


text:
Q: How to create Docker run-time argument to copy a host file at runtime into the container? I'm trying to create a Docker image for Squid3 which when run will accept a command-line parameter representing the file on the host to copy over /etc/squid/squid.conf within the container. I don't think this is possible, because the argument would be processed by the container itself and therefore have no access to the host. However, I thought I'd ask in case there's some magic I haven't found yet.
In the absence of this, I'd just use the kotaimen/squid3 image (https://github.com/Kotaimen/docker-squid3) which has you mount a volume to map to /etc/squid.
Anyway, I think it'd be really nice to be able to do something like so:
docker pull squid3
docker run squid3 ~/squid.conf

I'm still early in the process of creating this so any suggestions are welcome. I'm looking at the Squid3 images on DockerHub for reference.

A: As you already understood all arguments passed on the command line are processed by the program within the container - which of course has no direct access to the host filesystem.
In order to place a file from the host filesystem into the container I only see 2 reasonable ways (and 1 unreasonable):

*

*Volume-mount the respective file - similar to the kotaimen/squid3 image:

*

*no need for a custom image

*file is mounted/changed at run-time

docker run -v ~/squid.conf:/etc/squid/squid.conf:ro squid3

*Create your own image which includes your custom config into the base image:

*

*config is included in the image

*can only be changed at build-time

# Dockerfile
FROM squid3
COPY squid.conf /etc/squid/squid.conf

*The hacky way: use a custom script as entrypoint which ready the config from stdin. Then you can pass the file at start-up:

docker run --entrypoint 'sh -c "cat > /etc/squid/squid.conf; ./entrypoint.sh"' squid3 < ~/squid.conf

But this has some serious drawbacks:

*

*you need to write a custom entrypoint and include it in a custom image or use a hacky --entrypoint one the command line each time (see above)

*the container can't use stdin for anything else like especially interactive input anymore

*the entrypoint is run on every container re-/start even if no stdin is connected then, i.e. this would result in an empty config after the container restart:

docker run --name squid3 --entrypoint 'sh -c "cat > /etc/squid/squid.conf; ./entrypoint.sh"' squid3 < ~/squid.conf
docker restart squid3


text:
Q: Can i create multiple global style sheet for user change? I'm the beginner of react-native.
I'm going to provide change global font size function in my app.
User could change the font size in setting page, them the whole app font size will be adjusted.
After doing some research, it seems can't do it. So my idea now is create multiple global style sheet and apply it base on the user setting saved in storage.
But I found that it seems not work, because after create global style sheet, it need to import at the beginning of the app page.
How can I apply change the app global style or font size in react-native?

A: You might want take a look at useContext hook, it will give you a good way to handle app global style, suck as light or dark theme, your case, font is also not a problem.
Another way is using react-redux, create a global state for your font, and all your component will listen to the font value stored in the store.

A: Let's keep it abstract. How I would do it: create and assign a theme for your app where you define classes with different font-sizes etc. Save the preferences as classes in the async storage. After loading the up retrieve saved preferences from async storage and set those to your components as classes. Job done.


text:
Q: Auto refresh & click & alert Hello im working in javascript script with extension tampermonkey to refresh and check if there is available dates in appointement website if true then alert , my script work till click in input to show calendar and if i don't click the script doesn't work
this is my script
var gun=setInterval(function(){
if (document.getElementsByClassName('day activeClass').length !==0) {
  new Audio('https://www.soundjay.com/mechanical/sounds/smoke-detector-1.mp3').play();
  clearInterval(gun);
    }
   }, 1000)

i want to add a click in calendar input to detect changes or if there is alternative ways to check even hidden class or in source code of webpage
calendar html code
<input type="text" readonly="" class="form-control-input app_date validate" style="width: 260px;" id="app_date" name="app_date" placeholder="YYYY-MM-DD" onchange="this.form.submit();showLoader();" value="" autocomplete="off">

before click calendar
after click calendar

A: The problem must be that the classes "day activeClass" won't be assigned to the elements unless you click on the input.
It'd have been better if you had also shared the HTML code of an example of appointments.
But I think you could have a global variable such as "x" and have it include the innerHTML of the calendar and alert if the new data wasn't the same as x


text:
Q: How to add expiration header into my site I've created my website http://www.thecabinetdepot.com, using volutions CMS.
I am facing issue of browser leverage caching during w3c validation.
How can I add expiration header into my site?

A: I suggest you to use the .htacces file (if you're able to do it) as it is the Google recomendation you can see here
If you also want to get better score of google ranks, just follow any other steps that same page tells you. I can tell it's very usefull...


text:
Q: Python, website request login not working Im trying to login to a website via a script but when I print the websites html content, but I cant see any of the data available after login...
Can someone tell what I am missing? Thank you!
def main():
headers = {
    "User-Agent":
        "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36",
}

s = requests.session()
s.headers.update(headers)
s.get('https://www.e-ams.at/eams-sfa-account/p/index.jsf')

# Generate the post data
data = {
    'url': 'https://www.e-ams.at/eams-sfa-account/p/index.jsf',
    'j_username': 'username',
    'j_password': 'password'
}

# Perform the post request
r = s.post('https://www.e-ams.at/eams-sfa-account/p/index.jsf', data=data)

# Try to get data only available after login
r = s.get('https://www.e-ams.at/eams-sfa-account/p/EsaSBasisdaten.jsf?eamsTrack=1524234335254')
print(r.url)
print(r.text)
print(r.status_code)

A: If it is not part of the html form inputs, specifying the url in data dict is not correct.
Your request must be as follows:
data = {
    'j_username': 'username',
    'j_password': 'password'
}
r = s.post('https://www.e-ams.at/eams-sfa-account/p/index.jsf', data=data)

Generally speaking all the input tags of the form (both visible and hidden) must be included in the data dict


text:
Q: Download images from a CSV / XLS catalog EDIT:
I found this code to download images from an xls file.
Source: GET pictures from a url and then rename the picture
Code:
Option Explicit

Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Dim Ret As Long

'~~> This is where the images will be saved. Change as applicable
Const FolderName As String = "C:\Temp\"

Sub Sample()
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String

    '~~> Name of the sheet which has the list
    Set ws = Sheets("Sheet1")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRow '<~~ 2 because row 1 has headers
        strPath = FolderName & ws.Range("A" & i).Value & ".jpg"

        Ret = URLDownloadToFile(0, ws.Range("B" & i).Value, strPath, 0, 0)

        If Ret = 0 Then
            ws.Range("C" & i).Value = "File successfully downloaded"
        Else
            ws.Range("C" & i).Value = "Unable to download the file"
        End If
    Next i
End Sub

It works fine with xls files, where "PIC NAME" and "URL" are in two separate columns. I have a csv file and, unlike xls, csv has it's values in one column separated by "|" (PIC NAME|URL). So - being a noob at coding - as a workaround, I used "Text to columns" in Excel to divide the lines into 2 separate columns right down the delimiter "|", that way I can use the original code.
QUESTION: is there a way to make the code work with a csv file? This would make it much faster and easier to extract images from big csv files with thousands of lines.

A: Since VBA provides automation for Excel everything that you can do manually also can be automated by VBA. Excel even has a macro recorder integrated that automatically converts all user action into VBA code. This answer explains how it works: Excel's Macro-Recorder usage
This can be used to see what kind of VBA code the Text to columns function generates. If you clean up the code a bit you end up with this VBA command:
Selection.TextToColumns Destination:=Range("A1") _
                      , DataType:=xlDelimited _
                      , Other:=True _
                      , OtherChar:="|"

Make sure that you replace Selection by the whole range that you imported to Excel or that you select the whole range before you execute the code. Also replace Range("A1") by the range where you want the result to be written to.
It should be noted though that it is not very efficient to write stuff into excel cells just to parse those cells afterwards. A cleaner solution to your problem would be to read the downloaded file line by line and parse each line to your needs.
Luckily there is already a solution for that: Read lines from a text file but skip the first two lines


text:
Q: Apache version in XAMPP I'm trying to figure out which version of Apache is on the latests XAMPP builds ( 1.8.2-5 and 1.8.3-4 ).
I've checked the XAMPP website, tried googling the question and browsed through the folders on my XAMPP install to try to find a readme or something.

A: Run in command line
<xampp_dir>\apache\bin\httpd -v

It prints Apache version.
For example I had installed XAMPP to C:\Aplikace\xampp directory and type into Command Line
C:\Aplikace\xampp\apache\bin\httpd -v

that responsed

A: *

*Go to xampp folder where you installed xampp

*Find apache?

*xampp->apache->bin->httpd->right click->properties->details->version
find php version in xampp

*xampp control panel which, after the complete installation, contains start, stop, config, etc.

*There you find shell-> click->type php-v

*mariaDB version in xampp?

*Type localhost/phpmyadmin after installation on url

*Find sql

*Type select version(); and hit enter


text:
Q: Python: concat rows of two dataframes where not all columns are the same I have two dataframes:
EDIT:
df1 = pd.DataFrame(index = [0,1,2], columns=['timestamp', 'order_id', 'account_id', 'USD', 'CAD'])
df1['timestamp']=['2022-01-01','2022-01-02','2022-01-03']
df1['account_id']=['usdcad','usdcad','usdcad']
df1['order_id']=['11233123','12313213','12341242']
df1['USD'] = [1,2,3]
df1['CAD'] = [4,5,6]
df1:
    timestamp   account_id order_id  USD CAD
0   2022-01-01  usdcad     11233123  1   4
1   2022-01-02  usdcad     12313213  2   5
2   2022-01-03  usdcad     12341242  3   6

df2 = pd.DataFrame(index = [0,1], columns = ['timestamp','account_id', 'currency','balance'])
df2['timestamp']=['2021-12-21','2021-12-21']
df2['account_id']=['usdcad','usdcad']
df2['currency'] = ['USD', 'CAD']
df2['balance'] = [2,3]
df2:
    timestamp  account_id currency  balance
0   2021-12-21 usdcad     USD       2
1   2021-12-21 usdcad     CAD       3

I would like to add a row to df1 at index 0, and fill that row with the balance of df2 based on currency. So the final df should look like this:
df:
    timestamp   account_id order_id  USD CAD
0   0           0          0         2   3
1   2022-01-01  usdcad     11233123  1   4
2   2022-01-02  usdcad     12313213  2   5
3   2022-01-03  usdcad     12341242  3   6

How can I do this in a pythonic way? Thank you

A: Set the index of df2 to currency then transpose the index to columns, then append this dataframe with df1
df_out = df2.set_index('currency').T.append(df1, ignore_index=True).fillna(0)

print(df_out)

   USD  CAD  order_id
0    2    3         0
1    1    4  11233123
2    2    5  12313213
3    3    6  12341242


text:
Q: How to make the following SQL code faster I am trying to write an Oracle SQL Developer code, which will summarize selected clinical events of each patient, which occurred at the day of admission, by the date of their admission (beg_effective_dt_tm) for certain services and nursing units. It requires many, many hours to run...
Wanted to reach out if anyone has any ideas, on how to speed-up the code. Thank you in advance
SELECT ENCNTR_ID, ROUND(BEG_EFFECTIVE_DT_TM,'DDD'), max(ventilator), max(O2FLOW), max(FIO2), min(PAO2), min(SPO2) FROM (
SELECT UNIQUE
EN.ENCNTR_ID,
ELH.BEG_EFFECTIVE_DT_TM,
max (CASE WHEN ce.event_cd = '43504571' THEN '1' ELSE '0' END) OVER (PARTITION BY elh.encntr_id, round(performed_dt_tm,'DDD')) AS ventilator,
max (case when ce.event_cd = '111123182' then ce.result_val else '' end) over (partition by elh.encntr_id, round(performed_dt_tm,'DDD'))  as O2FLOW,
max (case when ce.event_cd = '14611845' then ce.result_val else '' end) over (partition by elh.encntr_id, round(performed_dt_tm,'DDD'))  as FIO2,
min (case when ce.event_cd = '6758629' then ce.result_val else '' end) over (partition by elh.encntr_id, round(performed_dt_tm,'DDD'))  as PAO2,
MIN (Case When Ce.Event_cd = '51517102' Then Ce.Result_val Else '' End) OVER (PARTITION BY elh.ENCNTR_ID, ROUND(PERFORMED_DT_TM,'DDD'))  As SPO2

FROM
ENCOUNTER EN
join CLINICAL_EVENT CE on EN.ENCNTR_ID = CE.ENCNTR_ID
right JOIN ENCNTR_LOC_HIST ELH ON EN.ENCNTR_ID = EN.ENCNTR_ID

WHERE
CE.EVENT_CD IN ()

AND elh.MED_SERVICE_CD IN (29279,29280, 32177, 32182, 29243, 32187, 32201, 32202, 10795466, 32209)
AND elh.LOC_NURSE_UNIT_CD IN (95785229, 95785312, 95785470, 95785577, 95780475, 95780595, 95781786 ,95782289, 95784755, 95784860, 95785057, 95785139,95785789, 95785888, 95786353, 95786453)
AND CE.PERFORMED_DT_TM >= '01-JAN-2011'
AND CE.PERFORMED_DT_TM < '01-JAN-2012'
AND ROUND(CE.PERFORMED_DT_TM, 'DDD') = ROUND(ELH.BEG_EFFECTIVE_DT_TM, 'DDD')

)
GROUP BY ENCNTR_ID, ROUND(BEG_EFFECTIVE_DT_TM,'DDD')
ORDER BY ENCNTR_ID, ROUND(BEG_EFFECTIVE_DT_TM,'DDD')

A: Using distinct with group by is always suspicious.  As is doing analytic functions and then aggregating.  I think you intend something like this:
SELECT EN.ENCNTR_ID, ROUND(ELH.BEG_EFFECTIVE_DT_TM, 'DDD') as BEG_EFFECTIVE_DT_TM,
       max(CASE WHEN ce.event_cd = '43504571' THEN 1 ELSE 0 END) AS ventilator,
       max(case when ce.event_cd = '111123182' then ce.result_val end) as O2FLOW,
       max(case when ce.event_cd = '14611845' then ce.result_val end) as FIO2,
       min(case when ce.event_cd = '6758629' then ce.result_val end)  as PAO2,
       MIN(Case When Ce.Event_cd = '51517102' Then Ce.Result_val As SPO2
FROM ENCOUNTER EN join
     CLINICAL_EVENT CE
     on EN.ENCNTR_ID = CE.ENCNTR_ID JOIN
     ENCNTR_LOC_HIST ELH
     ON EN.ENCNTR_ID = EN.ENCNTR_ID
WHERE CE.EVENT_CD IN () AND
      elh.MED_SERVICE_CD IN (29279,29280, 32177, 32182, 29243, 32187, 32201, 32202, 10795466, 32209) AND
      elh.LOC_NURSE_UNIT_CD IN (95785229, 95785312, 95785470, 95785577, 95780475, 95780595, 95781786 ,95782289, 95784755, 95784860, 95785057, 95785139,95785789, 95785888, 95786353, 95786453) AND
      CE.PERFORMED_DT_TM >= '01-JAN-2011' AND
      CE.PERFORMED_DT_TM < '01-JAN-2012' AND
      ROUND(CE.PERFORMED_DT_TM, 'DDD') = ROUND(ELH.BEG_EFFECTIVE_DT_TM, 'DDD')
GROUP BY ENCNTR_ID, BEG_EFFECTIVE_DT_TM
ORDER BY ENCNTR_ID, BEG_EFFECTIVE_DT_TM;

Some notes:

*

*The RIGHT JOIN is unnecessary because the WHERE clause turns it into an inner join.

*The analytic functions are all turned into simple aggregation.

*The last condition in the WHERE clause should go in an ON clause.

*The ELSE for the CASE statement is unnecessary, because aggregation functions automatically ignore NULL values.


text:
Q: undefined method `comments' Ruby on rails Итак у меня вылазит ошибка, при создании комментария к посту
Comments Controller
class CommentsController < ApplicationController

   def create
      @post = Post.find(params[:post_id])
      @comment = Post.comments.create(comment_params)
      redirect_to post_path(@post)
   end

   private def comment_params
      params.require(:comment).permit(:username, :body)
   end
end

Post rb
class Post < ApplicationRecord
   has_many :comments
   validates :title, presence: true, length: {minimum: 5}
end

Миграцию сделал, но всё-равно выводит ошибку

A: У Вас ошибка в коде, Вы пытаетесь вызвать comments у класса Post, нужно вызывать у инстанса, который лежит в @post


text:
Q: Add mp3 encoded data to an existing mp3 file using Javascript I have an existing mp3 encoded audio blob(1) and a newly recodred mp3 audio data(2), I want to concatenate (1) and (2) resulting in a new mp3 blob(3) of which I will use as a source for the audio tag in my html5 player/recorder.
I'm using the ConcatenateBlobs function to concatenate an array of blobs which the resulting blob is (3).
(3) has  correct audio duration; because it has the duration of (1)+(2).
 Although (3) is playable but stops when the (2) part starts.
 //////Concatenate blobs////////////////
 (function() {
  window.ConcatenateBlobs = function(blobs, type, callback) {
    var buffers = [];

    var index = 0;

    function readAsArrayBuffer() {
        if (!blobs[index]) {
            return concatenateBuffers();
        }
        var reader = new FileReader();
        reader.onload = function(event) {
            buffers.push(event.target.result);
            index++;
            readAsArrayBuffer();
        };
        reader.readAsArrayBuffer(blobs[index]);
    }

    readAsArrayBuffer();

    function concatenateBuffers() {
        var byteLength = 0;
        buffers.forEach(function(buffer) {
            byteLength += buffer.byteLength;
        });

        var tmp = new Uint8Array(byteLength);
        var lastOffset = 0;
        buffers.forEach(function(buffer) {
            // BYTES_PER_ELEMENT == 2 for Uint16Array
            var reusableByteLength = buffer.byteLength;
            if (reusableByteLength % 2 !== 0) {
                buffer = buffer.slice(0, reusableByteLength - 1);
            }
            tmp.set(new Uint8Array(buffer), lastOffset);
            lastOffset += reusableByteLength;
        });

        var blob = new Blob([tmp.buffer], {
            type: type
        });

        callback(blob);
    }
};
})();
/////////////////where i use ConcatenateBlobs function////////////////

var old_blob;
var xhr = new XMLHttpRequest();
xhr.open('GET', $('.player audio source').attr("src"), true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
    if (this.status === 200) {

        console.log("THE NEW RECORDED TRACK = " + blob.size);
        old_blob = this.response;
        console.log("THE LOADED TRACK = " + old_blob.size);
        ConcatenateBlobs([old_blob, blob], 'audio/mp3', function(resultingBlob) {
            console.log("THE RESULTING BLOB = " + resultingBlob.size);
            var url = URL.createObjectURL(resultingBlob);
             console.log("THE RESULTING BLOB = " + resultingBlob.size);
            $('.player audio source').attr("src", url);
            audio.load();
        });
    }
};
xhr.send();

I want to know what's the correct way of doing this.


text:
Q: Exception: Unexpected end of ZLIB input stream There is something wrong with GZIPInputStream or GZIPOutputStream. Just please read the following code (or run it and see what happens):
def main(a: Array[String]) {
    val name = "test.dat"
    new GZIPOutputStream(new FileOutputStream(name)).write(10)
    println(new GZIPInputStream(new FileInputStream(name)).read())
}

It creates a file test.dat, writes a single byte 10 formatting by GZIP, and read the byte in the same file with the same format.
And this is what I got running it:
Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at nbt.Test$.main(Test.scala:13)
    at nbt.Test.main(Test.scala)

The reading line seems going the wrong way for some reason.
I googled the error Unexpected end of ZLIB input stream and found some bug reports to Oracle, which were issued around 2007-2010. So I guess the bug still remains in some way, but I'm not sure if my code is right, so let me post this here and listen to your advice. Thank you!

A: You have to call close() on the GZIPOutputStream before you attempt to read it.  The final bytes of the file will only be written when the stream object is actually closed.
(This is irrespective of any explicit buffering in the output stack.  The stream only knows to compress and write the last bytes when you tell it to close.  A flush() won't help ... though calling finish() instead of close() should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code.  Don't treat this as an example of "good code".)


text:
Q: Create external table hive, location contains multiple files inside CREATE EXTERNAL TABLE IF NOT EXISTS LOGS (LGACT STRING,NTNAME STRING)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
LOCATION '/user/hive/warehouse/LOGS/test';

under 'test' folder I am writing files daily. for eg:
/user/hive/warehouse/LOGS/test/20170420
/user/hive/warehouse/LOGS/test/20170421
/user/hive/warehouse/LOGS/test/20170422

I cannot see any data inside LOGS table that i have created.
But, I create the table using
LOCATION '/user/hive/warehouse/LOGS/test/20170422';

I can see that days records.
I want to see all the data under /test directory in my HIVE table, also the /test directory is populated daily with new files.

A: Option 1
In order to support sub-directories
set mapred.input.dir.recursive=true;

and if you Hive version is lower than 2.0.0 then also
set hive.mapred.supports.subdirectories=false;

Option 2
Create a partitioned table
CREATE EXTERNAL TABLE IF NOT EXISTS LOGS (LGACT STRING,NTNAME STRING)
partitioned by (dt date)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
LOCATION '/user/hive/warehouse/LOGS/test';

alter table LOGS add if not exists partition (dt=date '2017-04-20') LOCATION '/user/hive/warehouse/LOGS/test/20170420';
alter table LOGS add if not exists partition (dt=date '2017-04-21') LOCATION '/user/hive/warehouse/LOGS/test/20170421';
alter table LOGS add if not exists partition (dt=date '2017-04-22') LOCATION '/user/hive/warehouse/LOGS/test/20170422';

It would be easier to manage if you keep your directories using the standard convention, e.g. dt=2017-04-20 instead of 20170420

A: By default hive reads only the files (not directories) inside the specified location in external table. If you want to enable adding the directories, then set the below parameter:
set mapred.input.dir.recursive=true;


text:
Q: Papaparse/vfile doesnt work- Garbled output I posted a question regarding parsing large csv files Jquery crashes while parsing large csv file. It involves reading a csv file and tablifying it. I tried using the code given in one of the responses but it doesn't work..
Here's my entire code:
<!DOCTYPE html>
 <meta http-equiv="content-type" content="text/html;charset=utf-8" />

<input type="file" id="fUpload" />

I have Papaparse-4.1.0 and virtual-list-master folders within my current working directory. But when I open this in a browser and upload a csv file, no table is printed below. There seems to be no defects in the upload function since the answerer showed a fiddle demo of the same; I'm just reusing it here. You can see the fiddle here:http://jsfiddle.net/8e99j5v9/5/
Can someone please tell me why my code doesn't work?
EDIT
I thank Sergiu for proposing a working solution but the resultant table that is delivered is thoroughly garbled.. Rows and columns are overlapping like this

Can someone help?

A: JavaScript code is interpreted/executed in the order it appears in the HTML structure. It will also only "have access" to HTML before it. So $("#fUpload") will try and find an element with id #fUpload in body, but taking into account what I said before (the order in which stuff is "loaded/executed") it won't find anything, because <input type="file" id="fUpload" /> is after this script tag.
Solutions:
1) Move the


text:
Q: MySql configuration for Django I am getting error when try to run
python manage.py migrate
django.db.utils.OperationalError: (1045, "Access denied for user 'someuser'@'localhost' (using password: NO)")

This is my database setting inside setting.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/config/mysql.cnf',
        },
    }
}

config/mysql.cnf

[client] database = dbname user =
  root password = passwt host = localhost
  default-character-set = utf8

A: The MySql configs can be provided in settings.py file, as like below
DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB_NAME',
    'USER': 'DB_USER',
    'PASSWORD': 'DB_PASSWORD',
    'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
    'PORT': '3306',
    'OPTIONS': {
        'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        'charset': 'utf8mb4',
    }
} }

If need to configure with external file, below may be helpful
DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'OPTIONS': {
        'read_default_file': os.path.join(BASE_DIR, 'mysql.cnf'),
    }
} }

The mysql.cnf file should be in project dir


text:
Q: Find greater row between two dataframes of same shape I have two dataframes of the same shape and am trying to find all the rows in df A where every value is greater than the corresponding row in df B.
Mini-example:
df_A = pd.DataFrame({'one':[20,7,2],'two':[11,9,1]})
df_B = pd.DataFrame({'one':[1,8,12],'two':[10,5,3]})

I'd like to return only row 0.
    one     two
0   20      11

I realise that df_A > df_B gets me most of the way, but I just can't figure out how to return only those rows where everything is True.
(I tried merging the two, but that didn't seem to make it simpler.)

A: IIUIC, you can use all
In [633]: m = (df_A > df_B).all(1)

In [634]: m
Out[634]:
0     True
1    False
2    False
dtype: bool

In [635]: df_A[m]
Out[635]:
   one  two
0   20   11

In [636]: df_B[m]
Out[636]:
   one  two
0    1   10

In [637]: pd.concat([df_A[m], df_B[m]])
Out[637]:
   one  two
0   20   11
0    1   10

Or, if you just need row indices.
In [642]: m.index[m]
Out[642]: Int64Index([0], dtype='int64')

A: import pandas as pd

df_A = pd.DataFrame({"one": [20, 7, 2], "two": [11, 9, 1]})
df_B = pd.DataFrame({"one": [1, 8, 12], "two": [10, 5, 3]})

row_indices = (df_A > df_B).apply(min, axis=1)

print(df_A[row_indices])
print()
print(df_B[row_indices])

Output is:
   one  two
0   20   11

   one  two
0    1   10

Explanation:
df_A > df_B compares element wise, this is the result:
     one    two
0   True   True
1  False   True
2  False  False

Pythons max interprets True > False, so applying min row wise (this is why I used axis=1) only computes True if both values in a row are True:
0     True
1    False
2    False

This is now a boolean index to extract rows from  df_A resp. df_B.

A: df_A.loc[(df_A > df_B).all(axis=1)]

A: It can be done in one line code if you are interested.
df_A[(df_A > df_B)].dropna(axis=0, how='any')

Here df_A[(df_A > df_B)] gives the output after matching true false either the value or na.
    one   two
0  20.0  11.0
1   NaN   9.0
2   NaN   NaN

Then we can drop the na values along the the 0 axis if there is at least anynot a number value.


text:
Q: Recursive patching values cutting some data I'm gonna build function which could help me to patch original values.
I will throw example to present idea more clarify.
This is my real object
let a = {
    a: 'a',
    b: 'b',
    c: [1,2,3],
    d: {
        e: 'e',
        f: 'f'
    }
};

But i want to change a.d to {e: 'e', f: 'ff'}
Therefore i created function and it partially works. I mean
when i run
saveValues({f: 'ff'}, a.d);

everything is fine. But this line doesn't work
saveValues({d: {f: 'ff'}}, a);

Of course it change f to ff, but also deleting e
let saveValues = (values: {[key: string]: any}, obj: any) => {
    Object.keys(values).forEach((key: any) => {
        if((obj as Object).hasOwnProperty(key)){
            if(typeof obj[key] == 'object')
            {
                saveValues(values[key], obj[key]);
            }
            obj[key] = values[key];
        }
    })
};

Live code: click

A:  if(typeof obj[key] == 'object') {
   saveValues(values[key], obj[key]);
 } else {
   obj[key] = values[key];
 }

if the value is an object, dont assign it the value but only proceed recursively.


text:
Q: For loop on 2 lists and add to an object Im looping over two lists and want to add the objects to a custom object. So Im getting an Employee a list of Projects and a list of Doubles from Thymeleaf and save them to a database. I want to save them to the object EmployeeProject which takes an Employee, a Project and a double (employeeBookedMonths). My problem is I either get the multiple projects saved to the EmployeeProject but all the project months are the same (the last double value one in the list) or I save the multiple projects to the employeeProject with correct employeeBookedMonths but there is dupicates, for example if I save 3 projects with 3 employeeBookedMonths, I get 3 times each saved (so 9 saved). I've tried moving the employeeProjectService.saveEmployeeProject but can't make it work plus many other variations but I need some help.
Question: how can I loop through the 2 lists and add and them to the EmployeeProject object? Without getting multiples or only getting the last employeeBookedMonths.
Thanks in advance.
Also the System.println prints the wanted values, they just don't save.
    public String saveEmployee(@ModelAttribute("employee") Employee employee,
                               @RequestParam("projectId") List<Project> projectIds,
                               @RequestParam("employeeProjectMonths") List<Double> months) {
        List<Double> monthList = new ArrayList<>();
        for (Double month : months) {
            if (month != null) {
                monthList.add(month);
                System.out.println("Month:" + month);
            }
        }
        employeeService.saveEmployee(employee);
        if (projectIds != null) {
            EmployeeProject employeeProject = new EmployeeProject(employee);
            for (Project ids : projectIds) {
                for (Double month : monthList) {
                    employeeProject.setEmployeeBookedMonths(month);
                    System.out.println("Months: " + employeeProject.getEmployeeBookedMonths());
                    employeeProjectService.saveEmployeeProject(employee, ids, month);
                }
            }
        }
        return "redirect:/ines/employees";
    }

New Employee form
<form action="#" th:action="@{/ines/saveEmployeeMeeting}" th:object="${employee}"
            method="POST" enctype="multipart/form-data">

                Email:
                <input type="text" th:field="*{name}"
                       placeholder="Employee Name" class="form-control mb-4 col-4">

                    Start Time:

                        <input type="text" class="form-control datetimepicker-input"
                               th:field="*{meetingStartDateTime}" id="meetingStartDateTime"/>

                    End Time:

                        <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"
                               th:field="*{meetingEndDateTime}" id="meetingEndDateTime" placeholder="Date"/>

                <input type="text" th:field="*{message}"
                       placeholder="Message" class="form-control mb-4 col-4">

            <button type="submit" class="btn btn-info col-2">Save Employee/Meeting</button>
        </form>

Employee
@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @Column(name = "employee_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
    @Column(name = "contracted_from")
    private String contractedFrom;

    @JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
    @Column(name = "contracted_to")
    private String contractedTo;

    @OneToMany(mappedBy = "employee",
            cascade = CascadeType.ALL
//          fetch=FetchType.EAGER
    )
    private Set<EmployeeProject> employeeProjects = new HashSet<>();
// constructores getters and setters

Project
@Entity
@Table(name = "projects")
public class Project implements Serializable {
    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long projectNumber;

    @Column(nullable = false, length = 45)
    private String name;

    @JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
    @Column(name = "start_date", nullable = false)
    private String startDate;

    @JsonFormat(pattern = "yyyy-MM-dd", shape = JsonFormat.Shape.STRING)
    @Column(name = "end_date", nullable = false)
    private String endDate;

    @Column(name = "project_length_months")
    private double projectLengthInMonths;

    @Column(name = "project_booked_months")
    private double currentBookedMonths;

    @Column(name = "remaining_booked_months")
    private double remainingBookedMonths;

    private int numberOfEmployees;

    @OneToMany(mappedBy = "project", cascade = CascadeType.ALL)
    private Set<EmployeeProject> employeeProjects = new HashSet<>();
// constructores getters and setters

EmployeeProject
@Entity
@Table(name = "employee_projects")
public class EmployeeProject implements Serializable {

    @Id
    @Column(name = "employee_project_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;

    @Column(name = "employee_booked_months")
    private double employeeBookedMonths;
// constructores getters and setters

A: Its not the prettiest but it works, I feel a bit dumb after this one but if anyone has a more elegant approach I'm happy to see it.
@PostMapping("/saveEmployee")
    public String saveEmployee(@ModelAttribute("employee") Employee employee,
                               @RequestParam("projectId") List<Project> projectIds,
                               @RequestParam("employeeProjectMonths") List<Double> months) {

        List<Double> monthList = new ArrayList<>();
        for (Double month : months) {
            if (month != null) {
                monthList.add(month);
                System.out.println("Month:" + month);
            }
        }

        List<Project> projectList = new ArrayList<>();
        for (Project project : projectIds) {
            if (project != null) {
                projectList.add(project);
                System.out.println("Project:" + project);
            }
        }

        employeeService.saveEmployee(employee);
        for (int i=0; i<= monthList.size(); i++) {
            EmployeeProject employeeProject = new EmployeeProject(employee);
            employeeProject.setEmployeeBookedMonths(monthList.get(i));
            employeeProject.setProject(new Project(projectList.get(i).getId()));
            employeeProjectService.saveEmployeeProjectEmployeeOnly(employeeProject);
        }
        return "redirect:/ines/employees";
    }

The problem was I was getting the list of projectIds which also had the null values (not selected ones), so I had to create a list of the projects then use the i loop to set each Project and employeeProjectMonths.

A: In this line:
employeeProjectService.saveEmployeeProject(employee, ids, month);

it was supposed to save employee or employeeProject?
Because in the code you didn't use the variable employeeProject explicitly. Where it was supposed to be saved?

A: Did you consider that you're declaring  EmployeeProject employeeProject = new EmployeeProject(employee); inside   if (projectIds != null) { scope, so if you do println in the employeeProject, right above return "redirect:/ines/employees"; (outside the scope) you won't see it? In order to don't loose the data you need to declare employeeProject at the beginning of the method.
The follow code could correct this:
    public String saveEmployee(@ModelAttribute("employee") Employee employee,
                               @RequestParam("projectId") List<Project> projectIds,
                               @RequestParam("employeeProjectMonths") List<Double> months) {
        List<EmployeeProject> listOfEmployeeProjects = ArrayList<>();
        List<Double> monthList = new ArrayList<>();
        for (Double month : months) {
            if (month != null) {
                monthList.add(month);
                System.out.println("Month:" + month);
            }
        }
        employeeService.saveEmployee(employee);
        if (projectIds != null) {
            EmployeeProject employeeProject = new EmployeeProject(employee);
            for (Project ids : projectIds) {
                for (Double month : monthList) {
                    employeeProject.setEmployeeBookedMonths(month);
                    System.out.println("Months: " + employeeProject.getEmployeeBookedMonths());
                    employeeProjectService.saveEmployeeProject(employee, ids, month);
                }
            }
        listOfEmployeeProjects.add(employeeProject);
        }
    //Here you might see the data inside listOfEmployeeProjects, once it was declared in a outter scope
   //Maybe do a assign of your data to other field, for example:
   // mainData.setAllOfTheEmployeeProjects(listOfEmployeeProjects);
        return "redirect:/ines/employees";
    }

Did it help? If didn't please post the rest of your code.


text:
Q: Remove Background Color From Pasted Text WYSIWYG I'm currently working on a WYSIWYG text editor but having a little trouble with one element. Whenever I copy and paste text from a site it will paste with the background color too. I want it so that when it pastes the text, the background color is removed.
Currently I've got a div that can be edited:

and then using jQuery I am trying to remove the background color of all children within the div as when I paste text it adds a span to the div:
$('#editor').on('paste', function(e) {
    $(this).children().attr('background-color', 'transparent');
});

But this seems to set the background color of the previous pasted text to transparent but still it doesn't actually remove the background.

A: Similar to the second solution from here: JavaScript get clipboard data on paste event (Cross browser)

$('#editor').on('paste', function(e) {
    let  pastedData, text;
    // Stop data actually being pasted into div
    e.stopPropagation();
    e.preventDefault();
    // Get pasted data via clipboard API
    pastedData = e.originalEvent.clipboardData || window.clipboardData;
    pastedData = pastedData.getData('Text');
    text = $(this).text();
    console.log(text, pastedData);
    $(this).text(text+pastedData);
});


text:
Q: Linq caculate time difference and choose closest one I have list of object like this one:
+-------------+------------+---------------------+
| ID          | Value      | Time                |
+-------------+------------+---------------------+
| 1           | 1          | 2019-03-07 20:05:35 |
| 2           | 2          | 2019-03-07 20:06:09 |
| 5           | 5          | 2019-03-07 20:11:27 |
| 7           | 1          | 2019-03-07 20:13:30 |
| 8           | 0          | 2019-03-07 20:13:41 |
| 7           | 1          | 2019-03-07 20:17:00 |
| 8           | 0          | 2019-03-07 20:22:20 |
| 7           | 1          | 2019-03-07 20:23:05 |
| 8           | 0          | 2019-03-07 20:27:35 |
| 7           | 1          | 2019-03-07 20:27:37 |
| 8           | 0          | 2019-03-07 20:28:01 |
| 7           | 1          | 2019-03-07 20:37:19 |
| 8           | 0          | 2019-03-07 20:37:27 |
| 7           | 1          | 2019-03-07 20:37:54 |
| 8           | 0          | 2019-03-07 20:40:11 |
| 7           | 1          | 2019-03-07 20:44:00 |
| 8           | 0          | 2019-03-07 20:45:00 |
| 7           | 1          | 2019-03-07 20:47:41 |
| 7           | 1          | 2019-03-07 20:48:43 |
| 7           | 1          | 2019-03-07 20:48:51 |
| 8           | 0          | 2019-03-07 20:51:11 |
| 8           | 0          | 2019-03-07 20:54:46 |
| 8           | 0          | 2019-03-07 20:55:36 |
+-------------+------------+---------------------+

How to select records 15 minutes apart but records that are more close to the next time?
The result should be something like this:
+-------------+------------+---------------------+
| ID          | Value      | Time                |
+-------------+------------+---------------------+
| 1           | 1          | 2019-03-07 20:05:35 |
| 8           | 0          | 2019-03-07 20:22:20 |
| 7           | 1          | 2019-03-07 20:37:19 |
| 8           | 0          | 2019-03-07 20:51:11 |
+-------------+------------+---------------------+

If the first time is 20:05:35 and next apart 15 min is 20:22:20. The closest time to that is 20:22:20 because difference between them is  00:02:14 and between 20:17:35 is difference 00:02:25. Is there any way to calculate difference and make decision which one is closer to choose?

A: Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication132
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Dates> dates = Dates.GetDates();

            var results = dates.GroupBy(x => new DateTime(x.Time.Year, x.Time.Month, x.Time.Day, x.Time.Hour, 15 * (x.Time.Minute / 15), 0).AddMinutes(15))
                .Select(x => x.OrderBy(y => x.Key.Subtract(y.Time)).First())
                .ToList();
        }
    }
    public class Dates
    {
        public int ID { get;set;}
        public int Value { get;set;}
        public DateTime Time { get;set;}

        public static List<Dates> GetDates()
        {
            string input =
                "| 1           | 1          | 2019-03-07 20:05:35 |\n" +
                "| 2           | 2          | 2019-03-07 20:06:09 |\n" +
                "| 5           | 5          | 2019-03-07 20:11:27 |\n" +
                "| 7           | 1          | 2019-03-07 20:13:30 |\n" +
                "| 8           | 0          | 2019-03-07 20:13:41 |\n" +
                "| 7           | 1          | 2019-03-07 20:17:00 |\n" +
                "| 8           | 0          | 2019-03-07 20:22:20 |\n" +
                "| 7           | 1          | 2019-03-07 20:23:05 |\n" +
                "| 8           | 0          | 2019-03-07 20:27:35 |\n" +
                "| 7           | 1          | 2019-03-07 20:27:37 |\n" +
                "| 8           | 0          | 2019-03-07 20:28:01 |\n" +
                "| 7           | 1          | 2019-03-07 20:37:19 |\n" +
                "| 8           | 0          | 2019-03-07 20:37:27 |\n" +
                "| 7           | 1          | 2019-03-07 20:37:54 |\n" +
                "| 8           | 0          | 2019-03-07 20:40:11 |\n" +
                "| 7           | 1          | 2019-03-07 20:44:00 |\n" +
                "| 8           | 0          | 2019-03-07 20:45:00 |\n" +
                "| 7           | 1          | 2019-03-07 20:47:41 |\n" +
                "| 7           | 1          | 2019-03-07 20:48:43 |\n" +
                "| 7           | 1          | 2019-03-07 20:48:51 |\n" +
                "| 8           | 0          | 2019-03-07 20:51:11 |\n" +
                "| 8           | 0          | 2019-03-07 20:54:46 |\n" +
                "| 8           | 0          | 2019-03-07 20:55:36";
            List<Dates> dates = new List<Dates>();

            string line = "";
            StringReader reader = new StringReader(input);

            while ((line = reader.ReadLine()) != null)
            {
                string[] lineArray = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                Dates newDate = new Dates()
                {
                    ID = int.Parse(lineArray[0]),
                    Value = int.Parse(lineArray[1]),
                    Time = DateTime.Parse(lineArray[2])
                };

                dates.Add(newDate);
            }
            return dates;
        }
    }

}

The code move the time exactly at the 15 minute interval to next interval.  The smallest resolution of time is 100ns (1 tick) so subtract 1 tick I believe is the correct solution
            var results = dates.GroupBy(x => new DateTime(x.Time.Year, x.Time.Month, x.Time.Day, x.Time.Hour, 15 * (x.Time.Minute / 15), 0).AddMinutes(15).AddTicks(-1))
                .Select(x => x.OrderBy(y => x.Key.Subtract(y.Time)).First())
                .ToList();

To group by 15 minutes from start time use this
            //tick is 100ns
            const long TICKS_PER_15_MINUTES = 15 * 60 * 10000000L; //minutes, seconds, ticks

            DateTime minTime = dates.OrderBy(x => x.Time).First().Time;

            List<Dates> results = dates.GroupBy(x => (TICKS_PER_15_MINUTES * ((x.Time.Ticks - minTime.Ticks) / TICKS_PER_15_MINUTES) + TICKS_PER_15_MINUTES - 1))
                .Select(x => x.OrderBy(y => x.Key - y.Time.Ticks).First())
                .ToList();

Finally if you want closest 15 minutes from  min time
            //tick is 100ns
            const long TICKS_PER_15_MINUTES = 15 * 60 * 10000000L; //minutes, seconds, ticks

            DateTime minTime = dates.OrderBy(x => x.Time).First().Time;

            List<Dates> results = dates.GroupBy(x => ((x.Time.Ticks - minTime.Ticks) % TICKS_PER_15_MINUTES) < (TICKS_PER_15_MINUTES / 2)
                ? TICKS_PER_15_MINUTES * ((x.Time.Ticks - minTime.Ticks) / TICKS_PER_15_MINUTES)
                : (TICKS_PER_15_MINUTES * ((x.Time.Ticks - minTime.Ticks) / TICKS_PER_15_MINUTES)) + TICKS_PER_15_MINUTES)
                .Select(x => x.OrderBy(y => Math.Abs( x.Key - y.Time.Ticks)).First())
                .ToList();


text:
Q: How to create a list of strings using a special char to understand where to split I have a text file that consist of the songs from all the albums of pink floyd, which looks like that:
#The Piper At The Gates Of Dawn::1967
*Lucifer Sam::Syd Barrett::03:07::Lucifer Sam, Siam cat
Always sitting by your side
Always by your side
... ( The lyrics of the song )
*Matilda mother::Syd Barrett::03:07::There was a king who ruled the land
His majesty was in command
With silver eyes the scarlet eagle
... ( The lyrics of the song )
#Another album
*another song
song's lyrics

I would like to create a list of strings out of it, using the albums ( indicated using # ) as one string, and all the songs in it as another string after that and so on, like this:
["album\n", "*song's name\nlyrics\n*song's name\nlyrics ..."]

Thanks a lot! :D
Edit: so I noticed that my explanation is a bit clumsy, So i will rephrase it.
What i want to do is to convert the given text into a list, which has each album and it's data in separated variables, so i would have something like that:
["album's name, "(Everything between the album's name and the next one)", "album's name", ...]

and so on.
The albums have # before them, and i need to use it somehow to separate it from it's songs.
I tried to do a for which finds each # and the first \n after that to create the list, but it went into ashes :(
IMPORTANT! CLEAR EXPLANATION: consider you have a string that looks like that:
#Hello
Whatever
#Hello
More Whatever

I want to separate each #Hello with it's Whatever. so i would have something like that:
["hello", "Whatever", "Hello", "Whatever]

I'm really sorry for my bad explanation abilities. this is the easiest way i can think of to explain it to you :D

A: Not super efficient, but works:
f = "filepath"

txt = "".join([line + "#" if line.startswith("#") else line for line in open(f)])
data = [x for x in txt.split("#")][1:]
data

['The Piper At The Gates Of Dawn::1967\n',
 '*Lucifer Sam::Syd Barrett::03:07::Lucifer Sam, Siam cat\nAlways sitting by your side\nAlways by your side\n... ( The lyrics of the song )\n*Matilda mother::Syd Barrett::03:07::There was a king who ruled the land\nHis majesty was in command\nWith silver eyes the scarlet eagle\n... ( The lyrics of the song )\n',
 'Another album\n',
 "*another song\nsong's lyrics\n"]

A: You could do it using regular expressions (re module), consider following example, lets say that you have file songs.txt as follows:
#Song 1
First line
Second line
#Song 2
First line of second
Last line

You could do:
import re
with open('songs.txt','r') as f:
    data = f.read()
songs = re.findall(r'(#.+?\n)([^#]+)',data)
#now songs is list of 2-tuples with song name and "song body"
songs = list(sum(songs,())) #here I am doing so called flattening
print(songs) #['#Song 1\n', 'First line\nSecond line\n', '#Song 2\n', 'First line of second\nLast line\n']

pattern (1st argument of re.findall) contains two groups denoted by brackets (()), first is for title and second for lyrics. First group need to be in form of: # followed by 1 or more not newlines (\n) and ending in newline (\n). Second group mean simply 1 or more characters which are not #.


text:
Q: I have create admin grid in magento 1.9 .It was not working getCollection error how to solve please help me my config.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Epage_Developer>
      <version>1.6.0</version>
    </Epage_Developer>
  </modules>
  <frontend>
    <routers>
      <developer>
        <use>standard</use>
        <args>
          <module>Epage_Developer</module>
          <frontName>developer</frontName>
        </args>
      </developer>
    </routers>
    <layout>
      <updates>
        <developer>
          <file>developer.xml</file>
        </developer>
      </updates>
    </layout>
  </frontend>
  <admin>
    <routers>
      <developer>
        <use>admin</use>
        <args>
          <module>Epage_Developer</module>
          <frontName>admin_developer</frontName>
        </args>
      </developer>
      <adminhtml>
        <args>
          <modules>
            <developer before="Mage_Adminhtml">Epage_Developer_Adminhtml</developer>
          </modules>
        </args>
      </adminhtml>
    </routers>
  </admin>
  <global>
    <models>
      <developer>
        <class>Epage_Developer_Model</class>
        <resourceModel>developer_resource</resourceModel>
      </developer>
      <developer_resource>
        <class>Epage_Developer_Model_Resource</class>
        <entities>
          <developer>

developer

          </developer>
        </entities>
      </developer_resource>
    </models>
    <resources>
      <developer_setup>
        <setup>
          <module>Epage_Developer</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </developer_setup>
      <developer_write>
        <connection>
          <use>core_write</use>
        </connection>
      </developer_write>
      <developer_read>
        <connection>
          <use>core_read</use>
        </connection>
      </developer_read>
    </resources>
    <blocks>
      <developer>
        <class>Epage_Developer_Block</class>
      </developer>
    </blocks>
    <helpers>
      <developer>
        <class>Epage_Developer_Helper</class>
      </developer>
    </helpers>
  </global>
  <adminhtml>
    <menu>
      <developer module="developer">
        <title>developer</title>
        <sort_order>100</sort_order>
        <children>
          <developer module="developer">
            <title>Manage Developer</title>
            <sort_order>0</sort_order>
            <action>admin_developer/adminhtml_developer</action>
          </developer>
        </children>
      </developer>
    </menu>
    <acl>
      <resources>
        <all>
          <title>Alloe Everything</title>
        </all>
        <admin>
          <children>
            <developer translate="title" module="developer">
              <title>developer</title>
              <sort_order>1000</sort_order>
              <children>
                <developer translate="title">
                  <title>Manage Developer</title>
                  <sort_order>0</sort_order>
                </developer>
              </children>
            </developer>
          </children>
        </admin>
      </resources>
    </acl>
    <layout>
      <updates>
        <developer>
          <file>developer.xml</file>
        </developer>
      </updates>
    </layout>
  </adminhtml>
</config>

Local/Epage/Developer/Model/Developer.php

class Epage_Developer_Model_Developer extends Mage_Core_Model_Abstract {

  protected function _construct() {
    parent::_construct ();
    $this->_init('developer/developer');
  }

  public function savedeveloper($developer){
    $enquireCollection = Mage::getModel('developer/developer');
    $enquireCollection->settitle($developer['title']);
    $enquireCollection->setcontent($developer['content']);
    $enquireCollection->setstatus($developer['status']);
    return $enquireCollection->save();
  }

}

Model/Resource/Developer.php

class Epage_Developer_Model_Resource_Developer extends Mage_Core_Model_Resource_Db_Abstract{

  protected function _construct() {
    $this->_init('developer/developer', 'developer_id');
  }

}

Model/Resource/Developer/Collection.php

 class Epage_Developer_Model_Resource_Developer_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract {
  protected function _construct() {
    //parent::_construct ();
    $this->_init('developer/developer');
  }

}

Block/Adminhtml/Developer/Grid.php

<?php
class Epage_Developer_Block_Adminhtml_Developer_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId('developer_Grid');
        $this->setDefaultSort('developer_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);

    }/*
    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('developer/developer_collection')
                      ->addAttributeToSelect('title')
                      ->addAttributeToSelect('content')
                      ->addAttributeToSelect('status');

             $this->setCollection($collection);
             return parent::_prepareCollection();
    }*/

    protected function _prepareCollection()
    {
        // Instantiate the collection of data to be display on the grid
        $collection = Mage::getResourceModel('developer/developer_collection')->getCollection()->addAttributeToSelect('*');
        var_dump($collection);
        foreach($collections as $collection) {
            echo $collection->getId();
        }
        $this->setCollection($collection);
        parent::_prepareCollection();
        return $this;
    }
    protected function _prepareColumns()
    {
        $this->addColumn('developer_id',
                array(
                        'header' => Mage::helper('developer')->__('ID'),
                        'align' => 'right',
                        'width' => '50px',
                        'index' => 'ID',
                ));
        $this->addColumn('title',
                array(
                        'header' => Mage::helper('developer')->__('title'),
                        'align' => 'left',
                        'index' => 'title',
                ));
        $this->addColumn('content',
                array(
                        'header' => Mage::helper('developer')->__('content'),
                        'align' => 'left',
                        'index' => 'content',
                ));
        $this->addColumn('status', array(
                        'header'    => Mage::helper('developer')->__('Status'),
                        'width'     => '120',
                        'align'     => 'left',
                        'index'     => 'status',
                        'type'      => 'options',
                        'options'   => array(0 => $this->__('Disabled'), 1 => $this->__('Enabled')),
                        'frame_callback' => array($this, 'decorateStatus')
        ));
        $this->addExportType('*/*/exportCsv', Mage::helper('developer')->__('CSV'));
        $this->addExportType('*/*/exportXml', Mage::helper('developer')->__('XML'));
        return parent::_prepareColumns();
    }
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('developer_id');
        $this->getMassactionBlock()->setFormFieldName('developer');

        $this->getMassactionBlock()->addItem('delete', array(
                'label'    => Mage::helper('developer')->__('Delete'),
                'url'      => $this->getUrl('*/*/massDelete'),
                'confirm'  => Mage::helper('developer')->__('Are you sure?')
        ));

        $statuses = Mage::getSingleton('developer/developer')->getOptionArray();

        array_unshift($statuses, array('label'=>'', 'value'=>''));
        $this->getMassactionBlock()->addItem('status', array(
                'label'=> Mage::helper('developer')->__('Change status'),
                'url'  => $this->getUrl('*/*/massStatus', array('_current'=>true)),
                'additional' => array(
                        'visibility' => array(
                                'name' => 'status',
                                'type' => 'select',
                                'class' => 'required-entry',
                                'label' => Mage::helper('developer')->__('Status'),
                                'values' => $statuses
                        )
                )
        ));
        return $this;
    }
    protected function _preparePage()
    {
        $this->getCollection()->setPageSize($this->getParam($this->getVarNameLimit(), $this->_defaultLimit));
        $this->getCollection()->setCurPage($this->getParam($this->getVarNamePage(), $this->_defaultPage));
    }
    public function getRowUrl($row)
    {

        return $this->getUrl('*/*/edit', array('id' => $row->getId()));
    }
    public function getGridUrl() {
        return $this->getUrl('*/*/developer_grid', array('developer_id'=> Mage::registry('developer_data')->getId(), '_current' => true));
    }
}
?>

which place is error please let know.
My error was this

Fatal error: Call to undefined method
  Epage_Developer_Model_Resource_Developer_Collection::getCollection()
  in
  C:\xampp\htdocs\magentos\app\code\local\Epage\Developer\Block\Adminhtml\Developer\Grid.php
  on line 27

A: try this code

$collection = Mage::getModel('developer/developer')->getCollection();

A:
Block/Adminhtml/Developer/Grid.php

in your Grid.php Try changing below code
From
$collection = Mage::getResourceModel('developer/developer_collection')->getCollection()->addAttributeToSelect('*');

To
$collection = Mage::getResourceModel('developer/developer_collection')->addAttributeToSelect('*');


text:
Q: Capture groups in Python regex issue I'm searching for a string Number of copies: in a text file and once it's found, I want to print the digits associated with it, so I'm searching for, (\sNumber of copies: (\d{1,2})) and I want to return (\d{1,2}). I've been researching nested groups in REGEX, but I don't have the syntax down for it in Python. Any help would be appreciated.
zDiscs = re.search(r'(\sNumber of copies: (\d{1,2}))', fi2Content, re.M|re.I)
print(zDiscs.group(1))

Here what the line I'm looking for in a text file looks like:
12/13/2013 08:11:25  Number of Discs in Set: 2 - Number of copies: 2

My desired output would just be 2 and 2 because I'm looking for the number that follows the text.
fi2Content represent a whole text file read by Python.
I can print(zDiscs) but I can't print(zDiscs.group(2)). Why?
I get the following error:
AttributeError: 'NoneType' object has no attribute 'group'

when I try to print(zDiscs.group(2))
Here's my whole script if that helps troubleshooting
fo = open('outputFile', 'w')
fo.write("Col1|Col2|Col3\n")
# 1.walk around directory and find lastjob.txt file in one of folders
rootDir = "C:\\Users\bob\Desktop\Path Parsing Project"
for path, dirs, files in os.walk(rootDir):
for filename in files:
    fullpath = os.path.join(path, filename)
    if filename=="text.txt":
        print(fullpath)
        # 2.open file. read from file
        fi2 = open(fullpath, 'r')
        fi2Content = fi2.read()
        zDiscs = re.search(r'(\sNumber of copies: (\d{1,2}))', fi2Content, re.M|re.I)
        print(zDiscs.group(2)) #This is where the error occurs!!!!!!!!!!!!!

A: You must be looking for:
import re
zDiscs = re.search(r'(\sNumber of copies: (\d{1,2}))', " 12/13/2013 08:11:25  Number of Discs in Set: 2 - Number of copies: 2", re.I)
print(zDiscs.group(2))

See IDEONE demo
Output: 54
Mind that re.M is redundant in your regex as you do not have anchors ^ and $ in your pattern (only their behavior is impacted by that option).
If you use (\sNumber of copies: (\d{1,2})), there are 2 capturing groups, and the number will be in group 2.
If the file you search for the expression does not contain that text, and you want to skip it, check if you obtained a match object:
zDiscs = re.search(r'(\sNumber of copies: (\d{1,2}))', fi2Content, re.I)
if zDiscs:
    print(zDiscs.group(2))


text:
Q: How to create columns based on date in DataFrame in Python Pandas? I have DataFrame like below:
rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({"ID" : ["1", "2", "1", "1", "2"],
                   "Date" : rng,
                   "kind" : ["active", "not_active", "active", "active", "not_active"],
                   "status" : ["b2", "b2", "g8", "g8", "v10"]})

And i need to create DataFrame which will show what was the status of the last active and the last not active agreement. Below I upload example of result:

A: If datetimes are sorted you can use DataFrame.pivot_table:
df = (df.pivot_table(index='ID', columns='kind', values='status', aggfunc='last')
        .reset_index()
        .rename_axis(None, axis=1))

If not sure if sorted add DataFrame.sort_values:
df = (df.sort_values(['ID','Date'])
        .pivot_table(index='ID', columns='kind', values='status', aggfunc='last')
        .reset_index()
        .rename_axis(None, axis=1))
print (df)
  ID active not_active
0  1     g8        NaN
1  2    NaN        v10


text:
Q: PHP Fatal error: Can't use function return value in write context I am connecting my site to PayPal using this excellent guide.
I've done this before without any problems, however I am getting the following error:
PHP Fatal error:  Can't use function return value in write context

It appears to be caused by this line of code:
if(!empty(_SESSION('ppl_products'))&&!empty(_SESSION('ppl_charges'))){

What does this error mean? I didn't get it when I connected the paypal API on seperate hosting.  Is it a server issue?

A: empty() is a language construct.  It consumes a variable name.  As such, you can not write to it.  The return of a function writes out to a variable.
Your best bet is to ommit the empty and just check the truthiness of the return:
if(_SESSION('ppl_products') && _SESSION('ppl_charges')){
Then again, if _SESSION is not a function, and you are attempting to access the global session variable, then you are doing it a few kinds of wrong, and you must do it like this:
if(!empty($_SESSION['ppl_products'])&&!empty($_SESSION['ppl_charges'])){

A: This error looks familiar to me, because I had the same Problem when using a function return value with isset (As in: isset(myFunction())). Because, as kunststube.net points out, you can't do that with empty or isset.
While I don't see an obvious function call here (maybe there's one happening offstage?), you could try substituting the !empty($something) for $something == true, which is equivalent, but might give you more hints as to where the error lies.


text:
Q: Buttons are not working using tabulator in VueJs Here, I have setup a table using tabulator in my VueJs project. I have followed the instructions for tabulator setup in VueJs from: http://tabulator.info/docs/4.1/frameworks#vue .I have added button like adding row and updating row but for some reason it is not working. I can see my button but it is not functioning.
Here is my code:
 <template>

    <v-btn color="green" @click="addRow">Add Row</v-btn>

</template>

A: It's not a great idea to use jQuery and Vue.js in the same UI. Don't do it if you can avoid it.
Your buttons are not attached to any functions or actions in the Vue way.
Just use an event bind on the buttons, attaching it to one of your methods, to control what it does, like:
<v-btn color="green" @click="addRow">Add Row</v-btn>

and then on your component methods:
methods: {
    addRow() {
        // add your row here
        this.location.addRow({})
    }
}


text:
Q: LibGDX Problems with textures in 1st launch after installing I have a problem with my android app created with LibGDX. After 1st launch part of textures in game just disappear and only after relaunch (not hide and reopen) all works fine. It happens only 1 time currently after 1st launch after installing. If installing on installed app, all works fine.
I use atlas for textures, it is 2048x2048. In project I use AssetLoader class with static objects. I saw some tips, that problem may be with static, but then why part of textures normally load?
If somebody had this kind of problem give an advice.

A: This is called context loss. Textures you load and create are unloaded automatically when you hide, and some of the context are lost between hide and reopen. Relaunching or killing active app after hide will destroy current JVM and when you open again it will be fresh launch and everything works fine.
To avoid this you can manually manage this situation by overriding pause() and resume() methods on ApplicationListener class (which is your main class extending ApplicationListener). You should unload/dispose assets on pause() and reload/create them on resume().
It's not the best but to give an idea you can see an implementation here in question's "EDIT:" part: LIBGDX White textures in the first run on android
But I strongly recommend to avoid static fields and use AssetManager class to load and get Textures, TextureAtlases and such other assets. And let it manage textures for you.
Take a look at: https://github.com/libgdx/libgdx/wiki/Managing-your-assets

A: I found the problem. It is not in AssetLoader ot Textures. When i load game objects, I also recreate data in phone resources, so when this data exists, all loads fine, but if it is 1st time and it needs to create this data on phone, it causes problems with loading resources. I just move "recreating data" to own function and now all work fine.


text:
Q: Passing user input data from html to php page and showing the content back to html page without reloading I have a text box which takes URL as a input from user and on submission I want this URL to pass onto PHP page where I can make use of this URL. After all the processing in the php page, I want to show data on the same html page where user entered the URL.

A: You can access user-provided variables through the $_REQUEST array in PHP.
Depending on how you passed the variable (POST or GET request), you can use also $_GET and $_POST variables.
To show what's inside them you can use print_r function.
Note that $_REQUEST will also read user cookies, if there are any.

A: HTML:
<form method="POST" action="yourPHPPage.php">
<input type="text" name="url"/>
<input type="submit" value="send"/>
</form>

PHP :
<?php
$url=$_POST['url'];
echo $url;
?>

Hope it will help you.

A: You could have found this out with little efforts. But here's the basic version:
your form:
<form action="action.php" method="post">

Link: <input type="text" name="link" />

<input type="submit" />

</form>

action.php:
<?php
$link = $_POST['link'];
echo $link;
?>

Check the documentation on creating forms here.
Hope this helps!

A: To pass variable to php site you need to use one of 2 solutions.

*

*Ajax I'd recommend Jquery - this solution passes variable without page reload.

*The other solution is to use form tag.
Code:
<form method="POST" action="test.php">
    <input type="text" value="value of variable" name="testname" />
    <input type="submit" value="submit me" />
</form>

This will pass variable via POST method and it can be accessed in test.php
<?php echo $_POST['testname']; ?>
<form method="GET" action="test.php">
   <input type="text" value="value of variable" name="testname" />
   <input type="submit" value="submit me" />
</form>

This will pass variable via POST method and it can be accessed in test.php
<?php echo $_GET['testname']; ?>
with get variable may be also passed via url
test.php?testname=valueofvariable it can be accessed with
<?php echo $_GET['testname']; ?>
I don't recommend $_REQUEST because it handles 3 types of requests which is get, post and cookie and it may cause hard to find errors unless you check what type of request you have via $_SERVER['REQUEST_METHOD']


text:
Q: How to pass parameter to javascript function that contains web service results? I use this function in javascript to call web service (WCF):
function Do(caller)
{
   MyService.GetClient(some_id, CallBackGetClient);
}

function CallBackGetClient(WebServiceResult)
{
   var result = WebServiceResult;
   etc.
}

Now I want to pass parameter (caller) to CallBackGetClient function so I can make dictinction who called Do() function. How to pass a parameter?

A: You can put put it inside an anonymous function, for which you use the same function signature as the expected callback.
function Do(caller)
{
   MyService.GetClient(some_id, function(webServiceResult) {
       CallBackGetClient(webServiceResult, caller);
   });
}

Here you are passing an anonymous function to GetClient as the callback. That function will take the expected web service result as its argument, but inside that function, you're turning around and invoking the real CallBackGetClient, adding caller as a second argument. This works because caller gets "trapped" inside the scope of the anonymous function so it'a still usable.
And this right here is the best thing about Javascript.


text:
Q: What is the best way to display the currency symbol locale-dependent? I would like to display the currency symbol ($, €) dependent on the current browser locale.
What is the best approach to do so?
I tried:
locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
System.out.println(locale); //gives: "en"
Currency.getInstance(locale).getSymbol(); //java.lang.IllegalArgumentException
Currency.getInstance(locale.GERMANY).getSymbol(); //gives €

How can I get the symbol based on locale dependent browser setting (which is "en" here)?
Update
locale.getLanguage() > "de"
locale.getDefault() > "de_DE"

Nevertheless, Currency.getInstance(locale).getSymbol(); fails.

A: Currency depends on the Country-Part of Locale. Since en does not contain a country part it is an illegal argument for creating a Currency instance.
In other words: Would you expect $, US$, AU$ or £ for Locale "en"? Or something else? There is no currency for "English". There are currencies for the US, GB, Australia and so on but not for English.
Edit
If the user configured his browser properly then you'll get indeed a Locale with both: Country and Language Part (e.g. en-US). These locales you can use the way you've done it in your question.
BUT you should consider using Geotargeting based on IP-Address. There exist databases like GEO-IP and MaxMind. Be aware that there are differences - an US student on semester abroad in Germany surfing with his laptop. His browser may return en-US but a GEO-IP database will target most probably to Germany. But maybe this is exactly what you want?!
Finally you can use one of these approaches as primary targeting factor and the second as backup. When both fail then switch to a default (e.g. US$)


text:
Q: Error in comparing two std::chrono::time_point instances I have two std::chrono::time_point instances in variables exp and time. exp has a time in the future and time is the current time. But when I compare them as in this snippet:
std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

I get output:
Sat Apr 26 01:39:43 4758
Fri May 29 18:11:59 2020
1

Which is wrong because exp is in the year 4758 and time is in the year 2020.
Where am I going wrong?

A:
t_exp is -4243023785

This value of time_t corresponds to 1835-07-18 22:16:55 (assuming the Unix epoch and a precision of seconds, neither of which are specified by the standard, but are common).
Apparently the implementation of ctime on your platform can't handle dates this far in the past, which is a little surprising as 1835 is not very far in the past.
The value of exp is -4243023785 times a million or a billion (depending on the precision of system_clock on your platform) and is stored with a signed 64 bit integer (there is no overflow).  Thus time > exp == 1 is correct (time is 1590775919s converted to the precision of system_clock).
Sat Apr 26 01:39:43 4758 corresponds to a time_t of 87990716383.
I see nothing wrong with your use of the chrono library in the above code.
Update

The value 87990716383 is being converted to a time_point using from_time_t()

Ah, this combined with the knowledge that on your platform the precision of system_clock is nanoseconds tells me that you are experiencing overflow on the construction of exp.
This is not the code you have:
std::time_t t_exp = std::chrono::system_clock::to_time_t(exp);
std::time_t t_time = std::chrono::system_clock::to_time_t(time);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

The code you have looks something like:
// ...
std::time_t t_exp = 87990716383;
auto exp = std::chrono::system_clock::from_time_t(t_exp);
std::cout << std::ctime(&t_exp) << std::ctime(&t_time) << (time > exp) << std::endl;

On your platform, system_clock stores nanoseconds since 1970-01-01 00:00:00 UTC in a signed 64 bit integer.  The maximum storable date (system_clock::time_point::max()) on your platform is:
2262-04-11 23:47:16.854775807

Beyond this, the underlying storage of nanoseconds overflows.
When 87990716383 (seconds) is converted in from_time_t, it is multiplied by a billion which overflows.  The overflowed value is -4243003985547758080 which corresponds to the date 1835-07-19 03:46:54.452241920.
You can get a larger range by using a coarser precision, for example:
std::time_t t_exp = 87990716383;
time_point<system_clock, microseconds> exp{seconds{t_exp}};
// exp == 4758-04-26 01:39:43.000000


text:
Q: How to show progress for submodule fetching? I know I can tell Git to show progress like
Resolving deltas:  98% (123/125)

when passing the command line parameter --progress to, e.g. the fetch command. But we have a couple of large submodules and there no progress is shown. How to tell Git to also show progress for cloning submodules (e.g. as part of the fetch command)?

A: Starting with Git v2.11.0, the git submodule interface accepts the --progress option which you can use. It does exactly what you expect.
See: https://github.com/git/git/commit/72c5f88311dab7149fcca1f6029414ccb776fee8
--progress wasn't announced in the help text (git submodule --help) in earlier versions but now it is (tested with Git version 2.27.0)

A: The closest I came was to use this command:
git fetch --recurse-submodules=yes --jobs=10

This is not giving you a progress bar. But it speeds up the fetching of the repositories. This helped me a whole lot on a microservice project with ~30 submodules.
Of course, you can combine this with other commands afterwards, for example, update all repositories without potential conflicts:
# run all subprojects updates: Pull on currently selected branches

#git submodule foreach 'git rebase origin/master; true'
git submodule foreach '
  export BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
  git status -bs
  if [[ "master" == $BRANCH_NAME ]]
  then
    git merge FETCH_HEAD --ff-only
  else
    echo \"NOTE this branch is $BRANCH_NAME. You must merge/rebase yourself!\"
  fi
'


text:
Q: problem in use of $.each? Values the database row units for values salam & salavat : [this values inserted by json_encode()]
salam:

[{"name_units":"salam","price_units":"74,554","checkbox_units":["minibar","mobleman"]},{"name_units":"mokhles","price_units":"4,851,269","checkbox_units":["mobleman","tv"]},{"name_units":"fadat","price_units":"85,642","checkbox_units":["minibar","mobleman","tv"]}]

salavat:

[{"name_units":"chaker","price_units":"5,452","checkbox_units":null},{"name_units":"khobe","price_units":"5,452,545","checkbox_units":["minibar","mobleman"]}]

In the example, do the following works:
EXAMPLE: DEMO1- in here work my code & DEMO2-in here just is for show all codes
First. please inserted value: sala in input => this have "tow" result, please clicked on each a of results: salam or salavat -> you see that get five output after click => salam & mokhles & fadat | chaker & khobe(In case must have three values, since we clicked on the word salam => salam & mokhles & fadat)
second. please inserted value: salam => this have one result, please clicked on result (salam) -> you see that get "three" output after click => salam & mokhles & fadat
I want in any case that is result search "five" or "three" value or "Etc.", get values name_units related with word that is click.
$('.auto_complete').keyup(function () {
    var dataObj = $(this).closest('form').serialize();
    $.ajax({
        type: "POST",
        dataType: 'json',
        //url: 'http://binboy.gigfa.com/admin/tour_foreign/auto_complete',
        url: 'auto_complete',
        data: dataObj,
        cache: false,
        success: function (data) {
            var id_name = $('.list_autobox_hotel').attr('id');
            $('.list_autobox_hotel').show().html('');
            if (data == 0) {
                $('.list_autobox_hotel').show().html('
there is no
');
            } else {
                $.each(data, function (index, value) {
                    $('
' + value.name + '
').appendTo('.list_autobox_hotel');
                });
                //////////////////////*HERE//////////////////////
                $('.list_autobox_hotel p').click(function (e) {
                    e.preventDefault();
                    var ac = $(this).attr('id');
                    $.each(data, function (index, value) {
                        $.each(value.units, function (bu, key) {
                            alert(key.name_units);
                        });
                    });
                    $(this).remove();
                    return false;
                });
                //////////////////////HERE*//////////////////////

                $('body').click(function () {
                    $(".list_autobox_hotel p").hide().remove();
                    $('.auto_complete').val('');
                    $('.list_autobox_hotel').show().html('');
                    $('.list_autobox_hotel').css('display', 'none');
                });

            }
        },
        "error": function (x, y, z) {
            // callback to run if an error occurs
            alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
        }
    });
});

UPDATE:
for bin i done it as: (but this don't work and there is still the same problem)
$('.list_autobox_hotel p').bind("click", function (e) {
    e.preventDefault();
    var ac = $(this).attr('id');
    $.each(data, function (index, value) {
        $.each(value.units, function (bu, key) {
            alert(key.name_units);
        });
    });
    $(this).remove();
    return false;
});

i don't understand "filter the data depending on what item you click on" and not know how is it!?
UPDATE 2
Did this is true? (but this don't work and there is alert: undefined)
$('.list_autobox_hotel p').bind("click", function (e) {
    e.preventDefault();
    var ac = $(this).attr('id');
    var ok = $.grep(data, function (e) {
        return e.name == ac;
    }).units;
    alert(ok);
    $(this).remove();
    return false;
});

A: That is because your code doesn't care which item you click on, it always shows all the data anyway.
You should either bind the click event inside the loop where you add the items, so that you can use the specific data for each item, or filter the data depending on what item you click on.