Q: Rename all files in a folder I'm on a linux, and a download a lot of funny pictures. Unfortunately, I'm left with a bunch of duplicate names like download (1) and image.jpeg. I would like to change them all to something a bit more helpful.
Is there a way to (preferably using bash) to rename all files to sequential 4 digit numbers with leading zeroes?
Eg:
0001
0002
0003
0004
....

A: The code snippet provided in the previous answer, is an elegant way of doing it but a typo or a shell incompatibility may cause it not to function properly.
please try the code below instead. It does the same thing but every shortcut has been explicitly written with debugging echo commands in the loop.
counter=1
cd /my/image/directory
for f in $(ls -1)
do
  new_filename=$(printf "%04d" ${counter})
  echo "renaming ${f} ..to.. ${new_filename}"
  mv ${f} ${new_filename}
  (( counter=${counter}+1 ))
done

the screen output will be a little chatty. if you have too many files, you might want to add | tee screen.out to the end of the line with done command. So that you can go back and see what happened to which file recorded in the screen.out.

A: I created my own tool to do this. It also maintains file extensions, which I did not mention, but should probably be included. Here is the code:
#!/bin/sh

dir=$1
cd $dir
echo "Renaming all files in $dir."
COUNTER=1
for i in `ls -1`
do
  extension=${i##*.}
  mv "$i" "$COUNTER.$extension"
  echo "$i ==> $COUNTER.$extension"
  COUNTER=$(expr $COUNTER + 1 )
done

It does not (at the time of writing) include the leading zeroes, but it gets the job done.

A: As long as you don't care which file is renamed to what, it's easy :)
counter=1
for f in *; do
    mv "$f" "$( printf "%04d" $((counter++)) )"
done

A: Trying to rename all files with suffix .bash to suffix .sh in a folder is easily done with
rename .bash .sh *.bash


Q: runtime error for leetcode problem 154 : reorder list https://leetcode.com/problems/reorder-list/

this is my codes
  logic

 1) taking care of edge cases when 0,1,2 elements in list
 2) storing node addresses in vector addr
 3) inserting last nodes after 1st nodes one by one i.e 1-2-3 should become 1-3-2

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#define Node ListNode
class Solution {
public:
    void reorderList(ListNode* head)
    {
        if(head == nullptr || head->next == nullptr || head->next->next == nullptr)
        {
            return;
        }

        // copy to vector
        vector <Node*> addr;
        Node *temp = head;
        while(temp != nullptr)
        {
            addr.push_back(temp);
            temp = temp->next;
        }
        int n = addr.size();
        Node *ins = addr[--n];
        temp = head;

        while(temp != ins)
        {
            // insert after temp
            ins->next = temp->next;
            temp->next = ins;
            if((--n) != 0)
                ins = addr[n];
            temp = temp->next->next;
        }
        temp->next = nullptr;
    }
};

this is my output

Line 924: Char 34: runtime error: addition of unsigned offset to 0x603000000010 overflowed to 0x603000000008 (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:34

random edits made and code worked altho i still dunno why the above code is not working!

class Solution {
public:
        void reorderList(Node* head)
    {
        if(head == nullptr || head->next == nullptr || head->next->next == nullptr)
        {
            return;
        }

        // copy to vector
        vector <Node*> addr;
        Node *temp = head;
        while(temp != nullptr)
        {
            addr.push_back(temp);
            temp = temp->next;
        }
        int n = addr.size();
        Node *ins = addr[--n];
        temp = head;

        while(temp != ins && temp->next != ins)
        {
            // insert after temp
            ins->next = temp->next;
            temp->next = ins;
            ins = addr[--n];
            temp = temp->next->next;
        }
        if(temp->next == ins)
        {
            ins->next = nullptr;
        }
        else
        {
            temp->next = nullptr;
        }
    }
};


Q: I'm trying to upload an array of images using Alamofire but getting error I'm trying to upload an array of images to the server using Alamofire 4.8.2
Here is the function:
func uploadMultiplePhotos(centreId: Int, imagesArray: [UIImage]) {

    let parameters = ["ec_id": centreId, "uploaded_image": imagesArray] as [String : Any]
    Alamofire.upload(multipartFormData: { (multipartFormData : MultipartFormData) in

        let count = imagesArray.count

        for i in 0..<count{

            multipartFormData.append(imagesArray[i], withName: "photo[\(i)]", fileName: "photo\(i).jpeg", mimeType: "image/jpeg")

        }
        for (key, value) in parameters {

            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
        print(multipartFormData)
    }, to: storeCentreImageURL) { (result) in

        switch result {
        case .success(let upload, _ , _):

            upload.uploadProgress(closure: { (progress) in

                print("uploding: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in

                print(response.result.value!)

            }

        case .failure(let encodingError):
            print("failed")
            print(encodingError)

        }
    }

}

getting error in the line below:
multipartFormData.append(imagesArray[i], withName: "photo[\(i)]", fileName: "photo\(i).jpeg", mimeType: "image/jpeg")

Cannot invoke 'append' with an argument list of type '(UIImage, withName: String, fileName: String, mimeType: String)'

A: You need to convert the image to data
imagesArray.indices.forEach {
  multipartFormData.append(imagesArray[$0].jpegData(compressionQuality:0.8)!, withName: "photo[\($0)]", fileName: "photo\($0).jpeg", mimeType: "image/jpeg")
}


Q: Renaming input file before uploading with jquery and laravel I want to rename input file to be uploaded before sending to laravel.
Basically, i found an another way to rename the file in laravel but in this question I want to rename the file before sending to laravel.
In my case, I'm using jquery upload file, and now I want the input file to be renamed before uploading it. I want to get the new file name that I used to insert in the hidden input text.
Is there any solution to solve this kind of matter?
By the way, thank you in advance! ^_^

A: Did you check this: File Docs
as per this doc you can do this as follow:
$request->file('photo')->move($destinationPath, $fileName);

where $fileName is an optional parameter that renames the file.
so you can use this like:
$fileName = str_random(30);    // any random string

then pass this as above.


Q: joomla 2.5 module retrieve data from database i want to retrieve data from database in my module page.for that my helloworld.php put the code
// Get a database object
$db = JFactory::getDbo();

$query = $db->getQuery(true);
$query->select('id, description');
$query->from('#__banners');

// sets up a database query for later execution
$db->setQuery($query);

// fetch result as an object list
$result = $db->loadObjectList();

now i want to show the results in default.php. but when echo $result in default.php it dose not show anything. how to i show the result? how to i get data from #__banners table?

A: $db->loadObjectList() returns an array which you can't echo. You can create a foreach loop like so:
foreach ( $result as $row ) {
    echo $row->description;
}

A: You have to load the results from the model method in view.html.php.
In view.html.php
function display($tpl = null) {
  $model = JModelLegacy::getInstance('ModelName', 'FrontendModel'); //(or BackendModel)
  $variable = $model->getNameOfModelMethod();

  $this->assignRef('variable', $variable);
 }

And in default.php just call $this->variable.


Q: Como obterner el tamaño de memoria que utiliza mi sistema operativo android xamarin? Como obterner el tamaño de memoria que utiliza mi sistema operativo android o xamarin?
Este es mi código que tengo hasta el momento:
protected StorageInfo GetStorageInformation(string path)
    {
        StorageInfo storageInfo = new StorageInfo();

        StatFs stat = new StatFs(path); //"/storage/sdcard1"
        long totalSpaceBytes = 0;
        long freeSpaceBytes = 0;
        long availableSpaceBytes = 0;

        /*
          We have to do the check for the Android version, because the OS calls being made have been deprecated for older versions.
          The ‘old style’, pre Android level 18 didn’t use the Long suffixes, so if you try and call use those on
          anything below Android 4.3, it’ll crash on you, telling you that that those methods are unavailable.
          http://blog.wislon.io/posts/2014/09/28/xamarin-and-android-how-to-use-your-external-removable-sd-card/
         */
        if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2)
        {
            long blockSize = stat.BlockSizeLong;
            totalSpaceBytes = stat.BlockCountLong * stat.BlockSizeLong;
            availableSpaceBytes = stat.AvailableBlocksLong * stat.BlockSizeLong;
            freeSpaceBytes = stat.FreeBlocksLong * stat.BlockSizeLong;
        }
        else
        {

            totalSpaceBytes = (long)stat.BlockCount * (long)stat.BlockSize;
            availableSpaceBytes = (long)stat.AvailableBlocks * (long)stat.BlockSize;
            freeSpaceBytes = (long)stat.FreeBlocks * (long)stat.BlockSize;
        }

        storageInfo.TotalSpace = totalSpaceBytes;
        storageInfo.AvailableSpace = availableSpaceBytes;
        storageInfo.FreeSpace = freeSpaceBytes;
        return storageInfo;

    }


Q: How to cache stored procedure results to retrieve the results faster? I have a stored procedure which takes a lot of time (around 5 minutes) to execute. This stored procedure fills up a table. Now I am retrieving the data from that table. I have created a job to execute this stored procedure every 15 minutes. But while the stored procedure is in execution, my table is empty and the front end shows no results at that time. My requirement is to show data at the front end side all the time.
Is there a way to cache the stored procedure results and use that result while the stored procedure executes?
Here is my stored procedure,
BEGIN
declare @day datetime
declare @maxdate datetime
set @maxdate = getdate()
set @day = Convert(Varchar(10),DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0),110)
truncate table tblOpenTicketsPerDay
while  @day <= @maxdate
begin
insert into tblOpenTicketsPerDay
select convert(varchar(20),datename(dw,@day)) day_name, count(*) Open_Tickets from
(select [status], createdate, closedate
FROM OPENROWSET('MSDASQL','DSN=SQLite','Select * from tickets') AS a
where createdate <= @day
except
select [status], createdate, closedate
FROM OPENROWSET('MSDASQL','DSN=SQLite','Select * from tickets') AS a
where closedate <= @day and [status] = 'closed') x
set @day = @day + 1
end
END

Any ideas will be helpful.
Thanks.

A: If I have understood correct then your main concern is: your stored procedure empties the table and then fills it up and since it takes time, your application have no data show.
In that case, you can have a secondary/auxiliary clone table; say tblOpenTicketsPerDay_clone and have your stored procedure fill that table instead like
insert into tblOpenTicketsPerDay_clone
select convert(varchar(20),datename(dw,@day)) day_name,
count(*) Open_Tickets from

That way your application will always have data to display since main table has the data. Once, the clone table is done filling up then transfer the same data to main table saying
delete from tblOpenTicketsPerDay;

insert into tblOpenTicketsPerDay
select * from tblOpenTicketsPerDay_clone;

A: No, but the problem is not caching, it isa totally bad approach to generate the data.
Generate new data into a temporary table, then MERGE The results (using the merge keyword) into the original table.
No sense in deleting the data first. That is a terrible design approach.


Q: If the GCM server receives a message to be sent to an Android phone, is the message going to survive on the server until it reaches the client? I mean, once the message has reached the server, can I rely on GCM for that message to arrive to the phone whenever the phone is online? Can the message be lost in the middle of the way to the phone? Is there a confirmation (message arrvied) between server and phone?
I read in the documentation that "GCM makes no guarantees about delivery or the order of messages" but I don't understand if this means that the message can be lost while trying to reach the phone or that if the phone is off the message will never arrive to the phone.

A: If the phone is off and you turn it on you will then get the GCM message, its the same as you would an email that you got if you had your phone off. When it says there is no guarantee you will receive the message that means there is no guarantee the server will send it out. I remember reading there is a time to live on the message but its not one that expires for a while


Q: Is the limit of approximate eigenvectors an eigenvector? Suppose $\mathcal{H}$ is a Hilbert space $H:\mathcal{H}\to\mathcal{H}$ is a self-adjoint operator. If $\lambda\in\sigma(H)$, then we have a sequence of vectors $\{\phi_n\}\subset\mathcal{H}$ with unit norm, $\|\phi_n\|=1$, such that
$$\lim_{n\to\infty}\|(H-\lambda)\phi_n\| = 0\, .$$
If we suppose that $\phi_n$ converges to $\phi\in\mathcal{H}$ (i.e. $\phi_n\to\phi$) will $\phi$ be an eigenvector of $H$?
This is true if $H$ is bounded as
$$\begin{align}\|(H-\lambda)\phi \| &\leq \|(H-\lambda)(\phi-\phi_n)\| +\| (H-\lambda)\phi_n\|\\
&\leq \|H-\lambda\|\|\phi-\phi_n\| + \|(H-\lambda)\phi_n\|\to 0
\end{align}\, ,$$
by the assumption that $H$ (and hence $H-\lambda$) is bounded and that $\phi_n$ is a sequence of approximate eigenvectors.

*

*If it is not true for unbounded $H$, can someone provide an example?

*Are there extra criteria one can impose on unbounded $H$ to make the statement true?

A: If $H$ is self-adjoint, then $\sigma(H) \subseteq \Bbb{R}$, so we have $\lambda \in \Bbb{R}$, which means $H-\lambda I$ is also self-adjoint. (You can prove this by first observing that $H-\lambda I$ is symmetric, then check the domains of $H^*=H$ and $(H-\lambda I)^*$.)
Thus, $H-\lambda I$ is closed. As a consequence, $(\phi_n \rightarrow \phi) \; \wedge \; ((H-\lambda I)\phi_n \rightarrow 0) \implies (H-\lambda I)\phi = 0$, which means $\phi$ is an eigenvector of $H$ w.r.t. $\lambda$, as long as $\phi \ne 0$.
In fact, the sum of a closed and a continuous linear operator (denote by $A,T$ respectively) is always closed: we have both $$\lVert x \rVert + \lVert Ax \rVert = \lVert x \rVert + \lVert (A+T)x-Tx \rVert \le \lVert x \rVert + \lVert (A+T)x \rVert + \lVert Tx \rVert \le (1 + \lVert T \rVert)(\lVert x \rVert + \lVert (A+T)x \rVert)$$ and $$\lVert x \rVert + \lVert (A+T)x \rVert=\lVert x \rVert + \lVert Ax+Tx \rVert \le \lVert x \rVert + \lVert Ax \rVert + \lVert Tx \rVert \le (1 + \lVert T \rVert)(\lVert x \rVert + \lVert Ax \rVert)$$ which means the graph norms w.r.t $A$ and $A+T$ are equivalent on $D(A)=D(A+T) \subseteq H$, so their closedness are also equivalent.


Q: What happens if you cancel a job with multiple statements? If I have a SQL script with multiple Update statements in series. What happens if query device goes offline after completing half the Update Statements?
Does it rollback the currently executed Update statement only? Or all the Update statements you ran before it disconnected?
Does this behavior change if you click cancel vs just losing your connection?
Thanks in advance!

A: On basis of how ACID is generally implemented you have multiple possible outcomes, depending on how the statements were started/executed and depending on your client connection settings and/or client application settings.
1. Standard Batch of Statements
If you had a batch of statements like this:
UPDATE [TABLE1] SET [COLUMN1] = '[VALUE1]' WHERE [PREDICATE];
UPDATE [TABLE2] SET [COLUMN3] = '[VALUE3]' WHERE [PREDICATE];
UPDATE [TABLE3] SET [COLUMN4] = '[VALUE4]' WHERE [PREDICATE];
UPDATE [TABLE4] SET [COLUMN7] = '[VALUE2]' WHERE [PREDICATE];

Then the overall outcome may vary slightly, depending on the client application settings and/or your connection settings.
One of those settings is SET IMPLICIT_TRANSACTIONS. If this setting was turned ON before the UPDATES started, then you would have to issue a COMMIT TRAN to write the data to the tables. In case of a session timeout or broken connection, the UPDATE statements will be rolled back, because no COMMIT was issued.
An explanation is given in the article SET IMPLICIT_TRANSACTIONS (Transact-SQL)

When ON, the system is in implicit transaction mode. This means that if @@TRANCOUNT = 0, any of the following Transact-SQL statements begins a new transaction. It is equivalent to an unseen BEGIN TRANSACTION being executed first:
...
UPDATE
...

The default for some client connections is described further down in the article:

The SQL Server Native Client OLE DB Provider for SQL Server, and the SQL Server Native Client ODBC driver, automatically set IMPLICIT_TRANSACTIONS to OFF when connecting. SET IMPLICIT_TRANSACTIONS defaults to OFF for connections with the SQLClient managed provider, and for SOAP requests received through HTTP endpoints.

1.1 Outcome with IMPLICIT_TRANSACTIONS OFF (default)
All DML statements that were successful before the disconnect / session timeout are written to the tables as explained in the article:

When OFF, each of the preceding T-SQL statements is bounded by an unseen BEGIN TRANSACTION and an unseen COMMIT TRANSACTION statement. When OFF, we say the transaction mode is autocommit.

1.2 Outcome with IMPLICIT_TRANSACIONS ON
When a session times out or you are disconnected, then all the UPDATE statements should be rolled back. There is no autocommit turned on.
2. Batch of Statements with BEGIN TRAN
BEGIN TRAN
UPDATE [TABLE1] SET [COLUMN1] = '[VALUE1]' WHERE [PREDICATE];
UPDATE [TABLE2] SET [COLUMN3] = '[VALUE3]' WHERE [PREDICATE];
UPDATE [TABLE3] SET [COLUMN4] = '[VALUE4]' WHERE [PREDICATE];
UPDATE [TABLE4] SET [COLUMN7] = '[VALUE2]' WHERE [PREDICATE];
-- COMMMIT TRAN
-- ROLLBACK TRAN

2.1 Outcome with IMPLILCIT_TRANSACTIONS OFF (default)

*

*If no issues occur, then all UPDATES are committed, when you issue the COMMIT TRAN statement.

*If no issues occur, then all UPDATES are rolled back, if you decide to issue the ROLLBACK TRAN statement.

*If a session timeout / disconnect occurs during the third UPDATE, then all UPDATES are rolled back, because neither the ROLLBACK nor the COMMIT could be issued. This is because you explicitly issued a BEGIN TRAN and did not issue either a COMMIT TRAN or ROLLBACK TRAN, because your session was closed and/or timed out.

2.1 Outcome with IMPLILCIT_TRANSACTIONS ON

*

*If no issues occur, then all UPDATES are committed, when you issue the COMMIT TRAN statement multiple times, depending on the @TRANCOUNT level as explained in the article.

When your INSERT statements and anything else in your unit of work is finished, you must issue COMMIT TRANSACTION statements until @@TRANCOUNT is decremented back down to 0....

*If no issues occur, then all UPDATES are rolled back, if you decide to issue the ROLLBACK TRAN statement as explained in the article.

...Or you can issue one ROLLBACK TRANSACTION.

*If a session timeout / disconnect occurs during the third UPDATE, then all UPDATES are rolled back, because neither the ROLLBACK nor the COMMIT could be issued. Additionaly you had explicitly issued a BEGIN TRAN and that was never COMMITed or ROLLedBACK, because your session was closed and/or timed out.
Answering Your Questions

Does it rollback the currently executed Update statement only?

Normally, yes. But it depends. See the given explanations.

Or all the Update statements you ran before it disconnected?

Normally, not. But it depends. See the given explanations.

Does this behavior change if you click cancel vs just losing your connection?

Normally, not. There is no difference between cancelling the (currently) running statement vs. losing your connection during the (currently) running statement. However, the outcome may vary depending on your connection settings and/or your client's application settings.

Disclaimer
This is by no means a complete summary of all possible settings which may or may not affect how the DBMS handles "Cancel Query"/"Timeouts"/"Disconnects". But in general you can apply the ACID principles to modern DBMS.


Q: Custom Context Menu on everything except "input" in jQuery I want to add custom context menu with jQuery for the whole body of the page, except the textfields. How can I do that?
I have tried that code:
$('body:not(input)').bind('contextmenu', function(){
    /*code*/
});

A: Check the srcElement before plugin executions. If it's not an input element, do trigger the contextmenu plugin:
$(document).on("contextmenu", function(e) {
    if (!$(e.srcElement).is(":input")) { // if it's not an input element...
        $(this).triggerTheContextMenuPlugin();
    }
});

A: Use an event listener on the document and check if it was initiated by an input element.
$(document).on("contextmenu", function (e) {
    if (e.target.tagName.toUpperCase() === "INPUT") {
        console.log("context menu triggered");
    }
});

Demo here

A: Inspired by Salman's solution.
You can stop the event propagation in all input elements, with the e.stopPropagation() function. In doing so, you keep the default behavior of the inputs elements:
$(function() {
    $(document).on("contextmenu", function(e) {
        alert("Context menu triggered, preventing default");
        e.preventDefault();
    });
    $("input").on("contextmenu", function(e) {
        e.stopPropagation();
    });
});

JSFiddle Demo


Q: How to use Purchase Status API I'm developing an app which has several non-consumable inApp products in it and i need to get the purchase status of those by directly sending requests to Google server and receiving the result. As i understood "Purchase  Status API" gives that possibility but it's not working for me. I made all the needed settings in "Google API Console":
     Switched on "Google Play Android Developer API".
     Created a client ID for my App.
I tried to use the methods described over here: http://developer.android.com/google/play-services/auth.html
But the methods GoogleAuthUtil.getToken(); and GoogleAuthUtil.getTokenWithNotification(); are throwing me an "Unknown exception".
However i managed to get the access token by using this code:
AccountManager acountM=AccountManager.get(Utils.curentActivity);
        Account[] acount=acountM.getAccountsByType("com.google");
        String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/androidpublisher";
        AccountManagerFuture<Bundle> future=acountM.getAuthToken(acount[0], AUTH_TOKEN_TYPE, null, Utils.curentActivity, null, null);
        try{
            String token=future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
        }catch(Exception e){e.printStackTrace();}

But after this, i have no idea what to do with this token. If i try to Authenticate like this:
URL url=new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+token);
            URLConnection conection=url.openConnection();
            conection.setDoInput(true);
            conection.connect();
            InputStream is=conection.getInputStream();

It throws me a "File not found exception".
If i try to get the purchase status of a product:
String packageName=MainActivity.this.getPackageName();
            String productId="SKU_KEY_1";
            HttpClient client=new DefaultHttpClient();
            HttpGet get=new HttpGet("https://www.googleapis.com/androidpublisher/v1.1/applications/"+packageName+"/inapp/"+productId+"/purchases/"+token);
            HttpResponse response=client.execute(get);
            InputStream is=response.getEntity().getContent();
            String result=Utils.readInputStream(is);
            is.close();

The result is a JSON which looks like this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}

I'm desperately looking for a solution for several days. I'll will be glad if somebody will provide me a solution or an up to date documentation on this point.

A: So looking over your code and information I would try a couple things, first verifying your access token.  I have used this as a reference.  Using a browser and a simple html page (see below) I am able to acquire the token and verify it. You will need to need to fill out the values as specified on that page.
Make sure that your token is correct first.  I did this by using that userinfo address in a browser.
Next you inapp purchase html location needs ?access_token={access_token} at the end after the
If you notice the section "Accessing the API" in the above page about authorization, you need to add this.
Here is the webpage that I have used to help get the token for testing.  NOTE that this is for testing and will not work as final solution because the authorization token is only good for a short time.  You will need to make sure that the code that gets that access token functions correctly.
In addition again refer to the page above to fill this out for your product.  The only thing that is dynamic in this is the "code" value which comes from the instructions on that page.
Hope some of this can help you...
<form action=" https://accounts.google.com/o/oauth2/token" method="post">
            <input name="grant_type" type="hidden" value="authorization_code" />
            <input name="code" type="hidden"  value="the code from the previous step"/>
            <input name="client_id" type="hidden"  value="the client ID token created in the APIs Console"/>
            <input name="client_secret" type="hidden"  value="the client secret corresponding to the client ID"/>
            <input name="redirect_uri" type="hidden"  value="the URI registered with the client ID"/>
            <input type="submit" />
        </form>


Q: REST Relationships Besides Parent/Child This would seem to be a pretty basic question, but I can't seem to find appropraite guidelines for it. What is the "restful" way of POSTing a relationship between two entities that are not necessarily parent/child. As an example, consider customers and orders.
One could create a customer with a POST to /customer. However, what is the best way to create the order? One example would be a POST to /customer/123/order, but what if the order isn't assigned to a customer directly, and could exist on its own (in the case of a web-cart that allows for "anonymous" checkout)? Is the right way, then, to do POST /order?customerId=123
Further, consider the case that an order can be submitted separately from payments (let's say we are invoicing a customer). You could create the order (per either of the methods above), but how would we make the payment? POST /order/123/payment or POST /payment?orderId=123 (if we assume that a payment can be made for something other than an order, and one might want to get information about an order/payment without knowing the specific customer).

A: I would say that if an order is a first class object, use /order. If it needs to be associated with one or more customers, the customer ids should be an attribute of the order object.


Q: Ansible string concatenation into config file I have a list of variables ("/dev/sda", "/dev/sdb") which I would like to to dynamically update a config file.
The config file is finally expected to look like
filter = [ "a|/dev/sda[145]|", "a|/dev/sdb[145]|", "a|/dev/mapper/3500.*part1|", "r|.*|" ]

Currently, the config file looks like this.
filter = [ "a|/dev/mapper/3500.*part1|", "r|.*|" ]

A: I have the answer to my own question. I am not sure if this is the "jinja" way of doing things.
{% set ldsk = [] %}
{% for disk in ldisks  %}
        {{ ldsk.append( "\"|a"+ disk +"[145]|\"") }}
{% endfor %}
filter = [ {{ ldsk | join(", ") }}, "a|/dev/mapper/3500.*part1|", "r|.*|" ]


Q: docker postfix - missing logs I created docker container like this:
FROM debian

RUN export DEBIAN_FRONTEND=noninteractive
RUN apt-get update
RUN apt-get install -y syslog-ng syslog-ng-core
RUN apt-get install -y postfix vim \
&& rm -rf /var/lib/apt/lists/*

CMD /etc/init.d/postfix start && /bin/bash

And start it like this:
docker run --name testmailsrv -p 25:25 -p 143:143 -p 993:993 -v mailsrvpostfixetc:/etc/postfix -v mailsrvdovecotetc:/etc/dovecot -it mailsrv/mailsrv-0.6:latest

My postrix is not working properly, but I can't find any logs to diagnose it. No file /var/log/mail.log, no output from journalclt, nothing interesting from "docker logs" command.
How can I see any log from postfix in docker?

A: This image suggests:
# Use syslog-ng to get Postfix logs (rsyslog uses upstart which does not seem
# to run within Docker).
run apt-get install -q -y syslog-ng

expose 25
cmd ["sh", "-c", "service syslog-ng start ; service postfix start ; tail -F /var/log/mail.log"]

That might be easier in order to produce and see those logs (as output of the main thread)

Also, satnhak suggests in the comments (in 2021):

You probably also need this: syslog-ng/syslog-ng issue 2407

That refers to syslog-ng/syslog-ng PR 2408: "system-source: check if /proc/kmsg can be opened".
Or you would need in your configuration:
    source s_local {
        system(
            exclude-kmsg(yes)
        );
        internal();
    };

satnhak adds:

adding this to the Dockerfile does the trick:
RUN sed -i 's/system()/system(exclude-kmsg(yes))/g' \
    /etc/syslog-ng/syslog-ng.conf

A: *

*Install rsyslog
apt-get install ryslog

*Start rsyslog
service rsyslog start

*Restart postfix
service postfix restart

*You will find /var/log/mail.log


Q: How do I design a data warehouse model that allows me to dynamically query for total action count, unique user count, and a count of total users Currently facing a problem where I am trying to create a login utilization report for a web application. To describe the report a bit, users in our system are tagged with different metadata about the user. For example, I could be tagged with "New York City" and "Software Engineer", while other users may be tagged with different locations and job titles. The utilization report is essentially the following:

*

*Time period (quarterly)

*Total number of logins

*Unique logins

*Total users

*"Engagement percentage" (Unique logins / Total users)

The catch is, the report needs to be a bit dynamic. I need to be able to be apply any combination of job titles and locations and have each of the numbers reflect the applied metadata. The time period also needs to be able to be easily adjusted to support weekly, monthly, and yearly as well. Ideally, I can create a view in Redshift that allows our BI software users to run this report whenever they see fit.
My question is, what is an ideal strategy to design a data model to support this report? I currently have an atomic fact table that contains all logins with this schema:

*

*User ID

*Login ID

*Login Timestamp

*Job Title Group ID (MD5 hash of job titles to support multi valued)

*Location Group ID (MD5 hash of locations to support multi valued)

The fact table allows me to easily write a query to aggregate on total (count of login id) and unique (distinct count of user id).
How can I supplement the data I have to include a count of total users? Is what I currently have the best approach?

A: Hierarchical, fixed-depth many-to-one (M:1) relationships between attributes are typically denormalized or collapsed into a flattened dimension table. If you’ve spent most of your career designing entity-relationship models for transaction processing systems, you’ll need to resist your instinctive tendency to normalize or snowflake a M:1 relationship into smaller subdimensions; dimension denormalization is the name of the game in dimensional modeling.
It is relatively common to have multiple M:1 relationships represented in a single dimension table. One-to-one relationships, like a unique product description associated with a product code, are also handled in a dimension table. Occasionally many-to-one relationships are resolved in the fact table, such as the case when the detailed dimension table has millions of rows and its roll-up attributes are frequently changing. However, using the fact table to resolve M:1 relationships should be done sparingly.
In your case I recommend you to have this following design as a solution :


Q: How to find number of specific column in csv using pandas? This is my csv file.

Iam uploading this data to db using python pandas.How to find the number of fee columns are there(fee_1,fee_2,fee_3)?. Because the start,end,fee columns are dynamic. I need to upload based on the number of fee columns.
If number of fee columns is 2 means i need to upload this,
"slot_fee":[{"start": i['Start_1'],"end": i['End_1'],"fee": i['Fee_1']},{"start": i['Start_2'],"end": i['End_2'],"fee": i['Fee_2']}]
If it is 3 means i need to upload this,and so on.
"slot_fee":[{"start": i['Start_1'],"end": i['End_1'],"fee": i['Fee_1']},{"start": i['Start_2'],"end": i['End_2'],"fee": i['Fee_2']},{"start": i['Start_3'],"end": i['End_3']]
Can anyone help me with the python pandas code for this?

A: If I understand your question correctly this might help :
df.columns[df.columns.str.startswith('Fee_')]

it gives you the list of columns that start with Fee_, if you want the last one you can add
df.columns[df.columns.str.startswith('Fee_')][-1]


Q: shift operation in linked list name
played games
score
Deep
5
540 (head)
Peter
34
455
Avijit
2
430
Pekka
4
310 (tail)
For the above linked list of player list, I want to sort list in ascending order when Avijit gets higher score than Peter. So its a shift operation in linked list. Can anyone help me to find out the problem in code below to do this operation. And any solution?
Thanks.
void Player::update_statistics(int last_game_point)
{
    player_ptr currPtr = head; // Moving pointer
    player_ptr prevPtr = NULL; // Pointer to node before *currPtr
    //player_ptr head;                //  class variable in Player class
    //player_ptr selected_player;     //  class variable in Player class
    //player_ptr previous_player;     //  class variable in Player class

    // update selected player's data
    cout<<++(selected_player->played_games);  // increase by 1 for last game
    selected_player->total_point=(selected_player->total_point)+last_game_point;

    if ((selected_player!=head) && (previous_player->total_point < selected_player->total_point)){
        previous_player->link = selected_player->link;

        // search for appropriate position
        while (currPtr->total_point > selected_player->total_point){
            prevPtr = currPtr;
            currPtr = currPtr->link;
        }

        if (currPtr==head)
            selected_player->link=head;
            head=selected_player->link;
        }
        else {
            previous_player->link=selected_player;
            selected_player->link=currPtr;
        }
}

A: I think you want
else {
        previous_player->link=selected_player;
        selected_player->link=currPtr;
    }

to be
else {
        prevPtr->link=selected_player;
        selected_player->link=currPtr;
    }

A: If this is not a homework and you are not trying to learn the intrinsics of algorithms on a linked list then you should

*

*use the standard library

*avoid using pointers when you don't need pointers

That said, to answer your question:
struct record {
    std::string name;
    int games_played;
    int score;
};

bool lower_score(const record& a, const record& b)
{
    return a.score < b.score;
}

// ...
std::vector<record> records = the_records();
std::sort(records.begin(), records.end(), lower_score);

I'm not sure why you want to use a list; if you have no specific concrete reason then you should probably use a vector. Otherwise, std::list has a sort() member:
std::list<record> records = no_no_i_meant_those_records();
records.sort(lower_score);


Q: Special characters in Request URL in SoapUI I use SoapUI to send HTTP and SOAP requests. There is an URL like this: https://mydomain/response? , where a HTTP request should be posted. URL in raw request view it appears without question mark. I tried to provide it in URL encoded(%3F) form too, but it is not resolved, it points to a different URL.

A: This is an example of a GET string.
Anything after the "?" will be the parameters.
You don't have anything after the "?". Thus no parameters.
For some reason, this makes soapui remove it. But it really should be without any consequence. Both https://mydomain/response? and https://mydomain/response will reach the same endpoint with no parameters.


Q: Open folder vs create new project from existing files, located under shared network drive in PhpStorm It's not clear to my why I should use the option in PhpStorm to create a new project from existing files instead of just opening a folder and declaring the project directory.
I have a web server installed and I can access it's root by a shared network drive. Now I can just open the a folder in PhpStorm and declare it's root. It will generate a PhpStorm project at the given directory.
But there is also an option to open a new project from existing files (located under shared network drive). My best guess is that this option is the way to go. Is this true and if so, why? Or if it doesn't matter, why doesn't it?
There will be several people using the same shared drive to work in different projects in the webroot.

A: You can, of course, create a project on mounted network drive via File/Open, but note that this is not officially supported. All IDE functionality is based on the index of the project files which PHPStorm builds when the project is loaded and updates on the fly as you edit your code. To provide efficient coding assistance, PHPStorm needs to re-index code fast, which requires fast access to project files and caches storage. The latter can be ensured only for local files, that is, files that are stored on you hard disk and are accessible through the file system. Sure, mounts are typically in the fast network, but one day some hiccup happen and a user sends a stacktrace and all we see in it is blocking I/O call.
So, the suggested approach is downloading files to your local drive and use deployment configuiration to synchronize local files with remote. See https://confluence.jetbrains.com/display/PhpStorm/Sync+changes+and+automatic+upload+to+a+deployment+server+in+PhpStorm


Q: Inequality involving closure and intersection Let the closure of a set $A$ be $\bar A$. On Page 62, Introduction to Boolean Algebras,Steven Givant,Paul Halmos(2000), an exercise goes like,

Show that $P \cap \bar Q \subseteq \overline{(P \cap Q)}$, whenever $P$ is open.

I felt muddled in face of this sort of exercises. Is there some way to deal with these problems and be assured about the result?

A: Suppose $x \in P \cap \overline{Q}$.  To show that $x \in \overline{ P \cap Q }$ we will show that every open neighbourhood of $x$ meets $P \cap Q$.
If $U$ is any open neighbourhood of $x$, then as $x \in P$ it follows that $U \cap P$ is also an open neighbourhood of $x$.  As $x \in \overline{Q}$, then $U \cap P$ meets $Q$, or, $U \cap ( P \cap Q ) = ( U \cap P ) \cap Q \neq \emptyset$.  Therefore $x \in \overline{ P \cap Q }$.

A: Let $x$ in $P\cap\bar Q$. Since $x$ is in $\bar Q$, there exists a sequence $(x_n)_n$ in $Q$ such that $x_n\to x$. Since $x$ is in $P$ and $P$ is open, $x_n$ is in $P$ for every $n$ large enough, say, $n\geqslant n_0$. Hence, for every $n\geqslant n_0$, $x_n$ is in $P\cap Q$. Thus, $x$ is in $\overline{P\cap Q}$ as limit of $(x_n)_{n\geqslant n_0}$.


Q: Adding scrolling programmatically when needed I have a screen set up in my app with all the constraints and everything, and so don't want to set up a scroll view for this view in the interface builder if it means that I will lose the constraints.
The content size varies, so I only want to make the view scrollable if it goes off the screen.
Is there a way to make this view scrollable without the constraints being deleted? (If it can be done in the interface builder without changing constraints, then please say)

A: 1- Drag a scrollView behind it and hook it's leading , trailing , top and bottom to superView
2- Copy that view you want to make it scroll-bale , paste it inside the scrollview with L,T,T,B constraints to the scrollView and Equal width to top outer view
BTW: You can also use embed from

Editor -> EmbedIn -> scrollView

Note: this won't break inner constraints of the view , but you will lose only the constraints of the view itself


Q: IPN not receiving from paypal sandbox I had developed a website with online transaction using paypal as payment option.
Checkout and the shopping cart calculations on paypal side are working, but i'm not receiving any IPN messages from paypal sandbox.
<form name="paypal_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="rm" value="2" />
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="upload" value="1" />
<input type="hidden" name="invoice" value="1234" />
<input type="hidden" name="business" value="merchant@domain.com" />
<input type="hidden" name="return" value="http://domain.com/success" />
<input type="hidden" name="cancel_return" value="http://domain.com/cancel" />
<input type="hidden" name="notify_url" value="http://domain.com/notify">
<input type="hidden" name="item_name_1" value="First item"/>
<input type="hidden" name="amount_1" value="6.00"/>
<input type="hidden" name="quantity_1" value="1"/>
<input type="hidden" name="shipping_1" value="5.00"/>
<input type="hidden" name="currency_code" value="EUR"/>
</form>

The overview page in merchant paypal account shows the transactions are completed. When i click on transaction details it shows error 3004 .
Also the IPN history page does not displaying any IPN records. It says "no records found in last 24 hours" .
How can i solve this?
Thanks & Regards.

A: It can be PayPal error - see: https://www.x.com/developers/paypal/forums/instant-payment-notifications-ipn-payment-data-transfer-pdt/ipn-failing-hasn-t-been-changed?page=0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1
The most iportant messages from the link above are PayPal responses:
July 18:
"I have found that the problem you are experiencing with IPN in the Sandbox is being caused by some technical issues with the PayPal system. Our engineers are currently working diligently on a solution to this problem."
and July 19:
"We are aware of this issue and our engineers are currently working on a solution. Unfortunately, i can't give you an exact timeframe when this will be done, however this should be resolved within the next days."

A: Make sure that your ipn is actually world-accessible (and not under localhost or a private network)

A: If you are trying this on localhost, it wont work. IPN just works on live. And you are saying you are not getting message from paypal sandbox ? If you are working on sandbox, why are you keeping the action url for actual paypal form ?


Q: CSS based 50% Transparent border without using transparent image I need to make the border of fancy box transparent after i have made some modifications to it. For some reason i cant make it work with transparent.
I have create a sample example which is somewhat & i want to make the borders of the inner DIV transparent. i tried few thing but did not work. I would appreciate a pure CSS solution without using any transparent images
Example: JSFiddle
Is their a way we can add Opacity to border

A: Just use color as transparent like this for making it fully transparent
border:10px solid transparent;

My fiddle
And if you want to add opacity, than this approach of your's is correct, it does make the border opaque
border-color:rgba(17,17,17,0.7);

You can use this too border-color:rgba(244,244,244,0.4); My fiddle


Q: for loop/list-comprehensions to apply zip_longest for list of lists combinations to get (l1[0]:l2[0]) without getting l1[0]:l2[1]) I have been working on combining lists of lists...testing answers to various questions on zip, zip_longest, lists, list comprehensions, iteration through lists of unequal lengths lists of lists, but I have been unable to find one that fixes my issue.  I am now defeated.
This may very well be a result of my inexperience, but I've run out of places to look.
I have two lists of lists with the internal lists having various lengths.
I want to zip_longest each internal list with the following type of result:
[('1', '1. A method'),
('2', '2. The method'),
('Description', '3.Description'), etc.]
The attempts shown below get me results I like but the code generats cross combining of list_1[0] with list_2[1].  I want only combining of lists at the same index (list_1[0] with list_2[0]) then 1:1, 2:2.
from itertools import zip_longest
claim_text = [['1. A method', '2. The method', '3. Description'],
              ['1. A method', '2. The method', '3. The method', '5. The method']];
claim_num =  [['1', '2'], ['1', '2', '3']]

combined = []
for i in claim_text:
   for x in claim_num:
       combined.append(list(itertools.zip_longest(x,i, fillvalue='Description')))
print(combined)

another approach:
[(list(itertools.zip_longest(a,b, fillvalue='Description'))) for a in claim_num for b in claim_text]

Any help is appreciated.

A: Do you want to zip_longest the first num with the first text, second null with second text, etc.?
Then start by combining the sublists of the two inputs with zip:
[list(zip_longest(a, b, fillvalue='Description'))
 for a, b in zip(claim_num, claim_text)]

Output:
[[('1', '1. A method'),
  ('2', '2. The method'),
  ('Description', '3. Description')],
 [('1', '1. A method'),
  ('2', '2. The method'),
  ('3', '3. The method'),
  ('Description', '5. The method')]]


Q: Merging a decrypted search of items within a LINQ query I have the following search query:
IQueryable<File> files = GetFiles(f => f.Clients.Any(fc => fc.Contacts.Any(c => c.Companies.Any(x => x.Name.Contains(searchText)))));

Unfortunately the search for Companies.Name will never work because the Name is encrypted.
So I have the following list of decrypted Companies. It's a Stored Procedure and it uses SQL CLR to decrypt the Name field:
List<Company> companies = GetSearchCompanies(searchText).Query.ToList();

This list is working fine, it returns a list of companies based on the searchText.
My question is whether I can replace the original files list of companies in order to be able to search against decrypted Company names as well as the other searches against Contacts, Clients, etc.
Any help would be appreciated and thanks in advance.

A: How about something like:
var newFiles = from f in files
               join c in companies on f.CompanyId equals c.CompanyId
               select new File
               {
                   prop1 = f.prop1,
                   //Assign all your other properties
                   Company = c
               };


Q: Mount user-specific folder on logon There is a small network with an active directory, and there is one machine with RAID-1 storage. How can I mount a user-specific shared folder, for example:
\\NetworkStorage\Storage\%USERNAME%

when %USERNAME% performs logon?

A: you can use the NET command to mount a drive:
NET USE F: \\NetworkStorage\Storage\%USERNAME%

(Note that you need to use back slashes, not forward slashes)
This could be added to your logon script.
ALSO, you can specify a "home" drive for each user in his or her active directory profile.  This can be mounted automatically, or with the following command:
NET USE F: /HOME


Q: Перестановка столбцов/строк в матрице по ключу C# Возникли трудности во время перестановок столбцов/строк в матрице по ключу. Данные в матрицу заносятся с клавиатуры. Ключ задается списком. Код перестановки есть, но он немного неверно сортирует. Если ввести ключ {0, 1, 2, 3, 4, 5, 6, 7}, то выводится сначала 7-й столбец, а потом с 0 по 6.
string[,] ct1 = new string[6, 8];
List<int> columnsCypherKey = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7 };
public void ColumnsPermutation()        //Перестановка столбцов
    {
        foreach (int t in columnsCypherKey)
        {
            for (int i = 0; i < ct1.GetLength(0); i++)
            {
                string tmp = ct1[i, 0];
                ct1[i, 0] = ct1[i, t];
                ct1[i, t] = tmp;
            }
        }
    }


Q: How to create an association class in draw.io? I've started using the website draw.io, I want to create a class diagram but I couldn't find how to create an association class, any help would be useful. Thanks.

A: draw.io is a drawing tool, not a UML tool.
As such you can simply draw two class shapes, connect them with an association shape, then draw a third class as you association class and then use an association shape to connect you association class to the association.
Then go into the properties of the last association shape and change the line style to dashed.
Now it looks like a valid UML Association class, but I think you should really opt for a real UML tool instead of a drawing tool when you want to do anything with UML. Using this tool is similar to writing Java with MS Word.

A: The accepted answer is far to be perfect. In Draw.io (now called Diagrams.net), you can connect two shapes (here classes) with a connector but you cannot connect two connectors together.
Consequently, with the given solution, it will look like an association class but the dashes will not be really adjusted :

And really worste, if you need to re-arrange your diagram, the association link will not move and you will have to re-adjust it manually :

So, as it is sadly not possible to have a 100% satisfying solution for an association class, another solution is to turn the association class as a regular class. Here in the example, the OrderLine class is associated with both Order and Product classes. It is worth to note the migration of the multiplicities. Refactoring a class association as such an association will ALWAYS lead to have a 1 multiplicity for the non-association classes (here Order and Product), and the original multiplicities will be moved to the association class (here OrderLine).


Q: Proper way to handle Query Cursor in Google Firestore? (Vue/Nuxt.js) I run a chat application with Firebase Firestore and it works all super well, however I'm running into the following issue:
For paginating my conversations & chats I use query cursors for my listeners. I save these query cursors into my state (vuex) so I can access them later when needed. That works and I can paginate my chat messages and conversations.
I create query cursors like so:
const query = await ref.get()
const cursor = query.docs[query.docs.length - 1]
commit('SET_CONVERSATIONS_QUERY_CURSOR', cursor)

And later use them in the next query like so:
.startAfter(state.conversations.queryCursor)

Everything actually works perfect.
My issue now is that that cursor saved in my state seem to be updated regularly (...why Firebase?) & especially directly. This gives me the following error messages when using vuex strict-mode (-> not allowed to access the state directly):

app.js:506 Error: [vuex] Do not mutate vuex store state outside
  mutation handlers.

Now I of course want to use strict mode to avoid mutation state directly, but I can't due to the query cursors in my state.
I tried to clone the cursor before saving in to the store, but shallow clones did no good and deep clones did not work because of Converting circular structure to JSON.
So...

*

*Is there a recommended way on how to store query cursors for later use?

*Are there options to just store the id of a document and later "recreate" a query cursor?

Thanks!

A: You can prevent javascript object from getting modified by using Object.freeze(obj).
So in your case it should be const cursor = Object.freeze(query.docs[query.docs.length - 1])


Q: Converting enums to symbols in Julia I have a definition of an enum as below. I would like to map each instance of the enum into the corresponding symbol. I can do this by manually constructing an array symbols and indexing into it. Is there a way of accomplishing this without specifying the array of symbols by hand?
@enum MyEnum A=1 B=2 C=3

symbols = [:A, :B, :C]

function enumToSymbol(x::MyEnum) :: Symbol
    return symbols[Int(x)]
end

@assert enumToSymbol(A) == :A

A: Just use Symbol:
julia> @enum MyEnum A=1 B=2 C=3

julia> Symbol(A)
:A

julia> x = A
A::MyEnum = 1

julia> Symbol(x)
:A

as it is defined as follows:
Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol

in particular you have an un-exported:
julia> Base.Enums.namemap(typeof(x))
Dict{Int32,Symbol} with 3 entries:
  2 => :B
  3 => :C
  1 => :A


Q: Magento 2 : How to Write Conditional Query in Collection Method How to write this query in magento2 collection method ?
SELECT o.increment_id, o.base_grand_total, h.status,o.created_at , h.created_at
FROM sales_order AS o
RIGHT JOIN sales_order_status_history AS h ON h.parent_id = o.entity_id

WHERE h.status = 'processing_closed'
AND CONVERT(o.created_at, DATE) <= CONVERT('2018-04-10', DATE)
AND CONVERT(h.created_at, DATE) = CONVERT('2018-04-10', DATE)

A: You can get your goal by this code
<?php
use Magento\Framework\App\Bootstrap;

include 'app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$factoryCollection = $objectManager->get('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$collection = $factoryCollection->create();
$date = date('Y-m-d H:i:s', strtotime("2018-04-10"));

$collection->addAttributeToSelect("increment_id");
$collection->addAttributeToSelect("base_grand_total");
$collection->addAttributeToSelect("created_at");
$collection->getSelect()->joinRight( array('order_history'=> sales_order_status_history), 'order_history.parent_id = main_table.entity_id', array('order_history.status','order_history.created_at'));

$collection->addFieldToFilter("order_history.status","processing_closed");
$collection->addFieldToFilter('main_table.created_at',array('lteq' => $date));
$collection->addFieldToFilter('order_history.created_at',array('ew' => $date));
echo $collection->getSelect();

If you want to use your custom table alias you need to use this
<?php
use Magento\Framework\App\Bootstrap;

include 'app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$factoryCollection = $objectManager->get('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$collection = $factoryCollection->create();
$date = date('Y-m-d H:i:s', strtotime("2018-04-10"));

$collection->getSelect()
    ->reset(\Zend_Db_Select::FROM)
    ->reset(\Zend_Db_Select::COLUMNS)
    ->from(array('o' => $collection->getMainTable()), array('increment_id','base_grand_total','created_at'));
$collection->getSelect()->joinRight( array('h'=> sales_order_status_history), 'h.parent_id = o.entity_id', array('h.status','h.created_at'));
$collection->addFieldToFilter("h.status","processing_closed");
$collection->addFieldToFilter('o.created_at',array('lteq' => $date));
$collection->addFieldToFilter('h.created_at',array('ew' => $date));

echo $collection->getSelect();

Please note that this code can be run in the root of Magento directory.


Q: HTML,PHP issues I am creating a website at school for a pretend client. At this stage it is a mobile repair/shop with services and products. My aim is to get all the products on my edit page so that if an item was out of stock my (client) could login as an admin and edit the page without having to go through the database and manually do it, or change the code.
I am getting this error every time and I am out of ideas on why this might not be working. I am totally new to this.
Parse error: syntax error, unexpected end of file in /Applications/XAMPP/xamppfiles/htdocs/matthew/edit.php on line 108
Here is my code:
<?php
// Start the session
session_start();
?>

<!DOCTYPE html>
<title>Matts Mobile</title>
    <link rel="stylesheet" href="css/style.css">

    <?php

$pagenum=$_GET["pagenum"];
      include 'setup.php';

    if(isset($_SESSION['username'])){
        if($_SESSION["username"] ==$user)
      {$message= "Welcome admin"; }
    } else {
      header('Location: login.php');
    }

//---//

$sql = "SELECT * FROM pages where pagenum = $pagenum";
$result = $conn->query($sql);

$row = mysqli_fetch_all($result,MYSQLI_ASSOC) ;
   #print_r($row);
if(!$row){echo "0 results";}
 else
 { $pagenum = $row[0]["pagenum"];
  $pagetitle = $row[0]["pagetitle"];
  $pagetext = $row[0]["pagetext"];
   //print "$pagetext";}

//---//

  $sql = "SELECT * FROM pages where product_id = $product_id";
$result = $conn->query($sql);

$row = mysqli_fetch_all($result,MYSQLI_ASSOC) ;
   #print_r($row);
if(!$row){echo "0 results";}
 else
 { $product_id = $row[0]["product_id"];
  $name = $row[0]["name"];
  $price = $row[0]["price"];
  $image = $row[0]["image"];
   //print "$name";}

//---//

$conn->close();
?>

<form action="update.php" method="post">
    Page Number: <input type="text" name="pagenum" value="<?php echo $pagenum; ?>" >

    Page Title: <input type="text" name="pagetitle" value="<?php echo $pagetitle; ?>" >

    Products:
    1<input type="checkbox" name="stock" value="<?php echo $product_id=1; ?>" >
    2<input type="checkbox" name="stock" value="<?php echo $product_id=2; ?>" >

    <textarea name="pagetext" rows="5" cols="40"><?php echo $pagetext;?></textarea>
<input type="submit">
</form>

A: The last lines of your PHP code are if (...) { ... } else { ... Note that there is no closing brace for the else. That's what it's upset about.


Q: Python dictionary, how can I create a key with a string and the actual key combined? I hope this is a quite easy question, but for me without a lot of python background I can't find an answer.
df = pd.DataFrame(
    {'Messung': ['10bar','10bar','10bar','20bar','20bar'],
     'Zahl': [1, 2, 3, 4, 5],
     'Buchstabe': ['a','b','c','d','e']})

There is a DataFrame (made a simplier Test DF for this post) where I loop through one column and compare the first 2 numbers of a string. The whole column has in the end like 20 Keys. Everytime the key is found, append the whole row to this key.
d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    if key not in d:
        d[key] = []
    d[key].append(df.iloc[row])

This code works, but my first attempt to this was different.
I wanted to have dictionaries where I have keys named as 'RP_10', 'RP_20'.
d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    if key not in d:
        d['RP_'+key] = []
    d['RP_'+key].append(df.iloc[row])

Can someone explain to me, why this doesn't work and how could I write the code so that I get 'RP_10', 'RP_20' and so on?

A: Can you please try below code. You do small mistake in if condition.
d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    key = "RP_"+key
    if key not in d:
        d[key] = []
    d[key].append(df.iloc[row])

ALso you can use setdefault() of python.Then your code looks like as below:
d={}
for row, item in enumerate(df['Messung']):
    key=item[0:2]
    key = "RP_"+key
    d.setdefault(key, []).append(df.iloc[row])

A: While trying your solution I noticed, I can even delete the line with key=item[0:2] and directly build my key with 'RP_' and the item[0:2]
d={}
for row, item in enumerate(df['Messung']):
    key = "RP_"+item[0:2]
    d.setdefault(key, []).append(df.iloc[row])


Q: android sort integers from database from big to small I made an quiz android app where the user get score every time he finish the quiz and after that the score will be saved in the database and after that the user can display the saved score. and my question is how I can display or sort these score on the page score from the biggest score to the smallest.
this is my code where I get the score and name of the user and set it on a textview:
    TextView tv1 = (TextView) findViewById(R.id.TextView1);
    DbHelper info = new DbHelper(this);
    userInfo.open();
    String data = userInfo.getData();
    userInfo.close();
    tv1.setText(data);

my getData method:
    // TODO Auto-generated method stub
        String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_SCORE};
        Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, null);
        String result ="";

        int TheRow = c.getColumnIndex(KEY_ID);
        int TheName = c.getColumnIndex(KEY_NAME);
        int TheScore = c.getColumnIndex(KEY_SCORE);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
            result = result + c.getString(TheRow ) + " " + c.getString(TheName ) + " " + c.getString(TheScore ) + "\n";
        }

        return result;
    }

A: You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this:
Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC");

Good Luck!


Q: Parse SGML using beautiful soup Below is the sample content :-
<WKEXT-META-ATTRS>
<WKEXT-META-ATTR NAME="uri" VALUE="http://sample.com/ceres/wk-us/Concept/i8148" DATA-TYPE="OTHER"></WKEXT-META-ATTR></WKEXT-META-ATTRS></WKEXT-META-OBJECT>
<WKEXT-META-OBJECT NAME="UNIONREPINFO" ID="ext-met-0005" PUBLISHER-URI="http://wk-us.com/meta/publishers/#CCH">
<WKEXT-META-ATTRS>
<WKEXT-META-ATTR NAME="UnionRep" VALUE="Jim Gookins" DATA-TYPE="OTHER"></WKEXT-META-ATTR></WKEXT-META-ATTRS></WKEXT-META-OBJECT>
<WKEXT-META-OBJECT NAME="TOPICALSUBJECTINFO" ID="ext-met-0006" PUBLISHER-URI="http://sample.com/meta/publishers/#CCH">
<WKEXT-META-ATTRS>
<WKEXT-META-ATTR NAME="uri" VALUE="http://sample.com/ceres/sample/Concept/i8173" DATA-TYPE="OTHER"></WKEXT-META-ATTR></WKEXT-META-ATTRS></WKEXT-META-OBJECT>
<WKEXT-META-OBJECT NAME="TOPICALSUBJECTINFO" ID="ext-met-0007" PUBLISHER-URI="http:/sample/meta/publishers/#CCH">

I want to extract the VALUE of uri -- "http://sample.com/ceres/wk-us/Concept/i8141
I am currently trying out with below code:-
with open ("sample.sgm","r")as f:
    contents =f.read()
    soup = BeautifulSoup(contents, 'lxml')
    s = soup.find('wkext-meta-attr').attrs
    #for a in s:
    #    t = a.attrs
    #    for key,value in t.items():
    #        alias_text.append(t['normval'])
    #print(alias_text)
    #df = DataFrame(alias_text, columns=['arbitratorname'])
    #s_topic=soup.find('WKEXT-META-ATTRS'=
    print(s)

I am not able to figure out how to obtain the exact value .
Any help will be much appreciated!!!

A: If you want to retrieve the value of each wkext-meta-attr, You can use the`.findAll() method and then loop through each element. Check whether the below code fulfills your task:
from bs4 import BeautifulSoup

with open ("sample.sgm","r")as f:
    contents =f.read()
    soup = BeautifulSoup(contents, 'html.parser')
    meta_attrs = soup.findAll('wkext-meta-attr')

for meta_attr in meta_attrs:
    print(meta_attr['value'])


Q: Netty doesn't complain if port is already used Following problem:
I expect an exception if a port is already used.
So I tried to start my server twice in a thread
    public void start() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            EventLoopGroup bossGroup = new EpollEventLoopGroup();
            EventLoopGroup workerGroup = new EpollEventLoopGroup();

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(final SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("decoder", new Decoder(Server.this));
                            socketChannel.pipeline().addLast("encoder", new Encoder(Server.this));
                        }
                    });

            serverBootstrap.bind(port).channel().closeFuture().syncUninterruptibly();
        }
    }).start();
}

But got no exception. I also tried to add an channel handler and catch a exception there, no luck :/
Surrounding the line with bind(port) to catch an exception has also no effect. But I noticed when I added a ChannelListener to the ChannelFuture, that one of the started instances never reached that point.
Anyone an idea?

A: After binding you are directly taking the channel from the future, but it probably hasn’t finished at that point.
Try to wait for your bind to complete with bind(port).sync().
See for reference https://www.baeldung.com/netty#6-server-bootstrap and https://netty.io/4.1/api/io/netty/channel/ChannelFuture.html


Q: How to write CLLocation's GPS information into UIImage using PHPhotoKit? Is there any method to write GPS info into one image?
for example, I want to develop a camera app that can take photos with location information.
Can I use PhotoKit related methods or some other methods such as ImageIO?
Thanks.

A: You can add location information to your image like this
let locationCordinate = CLLocationCoordinate2DMake(lat, long)
let currentDate = NSDate()
let imageLocation = CLLocation(coordinate: locationCordinate, altitude: 0.0, horizontalAccuracy: 0.0, verticalAccuracy: 0.0, timestamp: currentDate)

After this you can add this location to your image like this
PHPhotoLibrary.sharedPhotoLibrary().performChanges({

      let assetLocationChangeRequest = PHAssetChangeRequest(forAsset: lastImageAsset)
      assetLocationChangeRequest.location = imageLocation

      }, completionHandler: {
            (success:Bool, error:NSError?) -> Void in

            if (success) {
                print("Succesfully saved location to image")
            } else {
                print("Failed to save with Error : \(error!)")
                }
        })


Q: Добавление сборки в GAC Несколько вопросов по теме. При добавлении сборки в GAC, происходит ли копирование сборки в Windows\assembly? Если происходит, то как ее потом найти? Через командную строку сборка добавляется, но в папке assembly она не появляется. Правильно ли я понимаю, что в Visual Studio при добавлении ссылки показывается список сборок в GAC? Если это так, то почему я не вижу там своей сборки?
Добавлял так: gacutil /i mydll.dll
Пишет: сборка успешно добавлена в кэш
A: *

*Внутренняя структура каталогов GAC:
C:\WINDOWS\assembly\GAC\
C:\WINDOWS\assembly\GAC_32\
C:\WINDOWS\assembly\GAC_64\
C:\WINDOWS\assembly\GAC_MSIL\
само собой, это для 64битных машин. смысл вопроса я не очень понял.

*либо gacutil -l, либо просмотром в файл-менеджерах.

*здесь и здесь

A: Сборки, управляемые .NET 4.0 и выше находятся по адресу C:\Windows\Microsoft.NET\assembly\GAC_MSIL


Q: google chart PHP y Mysql Buen dia, estoy haciendo una aplicacion en PHP y  Mysql para gestionar los reportes atendidos en una oficina de atencion al cliente de una empresa de servicios de agua y saneamiento. En estos momentos estoy tratando de generar reportes estadisticos graficos utilizando Google Chart y tengo problemas al generar un grafico de barras.
Necesito un grafico como este:

pero el codigo utilizado me esta arrojando el siguiente grafico:

el codigo utilizado es el siguiente:
PHP
    query("SELECT servicio, estatus, count(estatus) as   SUBTOTAL FROM reporte GROUP by servicio, estatus");
    ?>
HTML
<!DOCTYPE html>

Agradecido por cualquier ayuda que me pueda brindar

A: Solución:

<?php
// Database credentials
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'redes';

//guarda los resultados
$rows = array();

// Create connection and select db
$db = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);

//QUERY
$query = "SELECT servicio, estatus, count(estatus) as SUBTOTAL
          FROM reporte, estatus,servicio where
            idestatus=estatus.id AND
            idservicio=servicio.id AND MONTH(fecha_recibido) = month(curdate())
            GROUP by servicio, estatus";

// Get data from database
$result = mysqli_query($db,$query);
?>

<!DOCTYPE html>

La funcion del código es que quede dinámico el chart con referencia al resultado de la consulta.


Q: merge sort merge run time anaylsis I have some confusion of the run time analysis of the merge function in merge sort.
Merg(A,p,q,r)
1 n1=q-p+1
2 n2=r-q
3 let L[1..n1+1] and R[1..n2+1] be new arrays
4 for i=1 to n1
5     L[i] = A[p+i-1]
6 for j =1 to n2
7    R[j] = A[q+j]
8  L[n1+1] = infinity
9 R[n2+1] = infinity
10 i =0
11 j=0
12 for k=p to r
13   if L[i]<=R[j]
14       A[k]=L[i]
15       i=i+1
16    else A[k] = R[j]
17       j=j+1

In my book it says the following: to see that the merge procedure runs in O(n) time, where n=r-p+1, observe that each of lines 1-3 and 8-11 takes constant time, the for loops of lines 4-7 take O(n1+n2) = O(n)time, and there are n iterations of the for oop of lines 12-17, each of which takes constant time
My question is why do lines 12-17 take constant time per iteration and not affect the run time but
lines 4-7 don't take constant time. to me, it seems like both loops are doing the same thing. can someone help clarify this for me? Thanks!

A: Lines 1 through 9 are just splitting the input (A) into two pieces (L and R). Lines 10 and 11 are doing a bit of initializing to get ready for merging. The merge itself is from lines 12-17.
IOW, everything before line 12 (or arguably 10, not that it really matters) is irrelevant to analyzing the merge because none of it is really part of the merge at all.
Edit: Ultimately, however, a single iteration from 1 to 27 is linear: in lines 4-7, you walk exactly once through the input array, assigning each input exactly once to either L or R. In lines 12-27, you then walk through those two pieces, and copy them back to the original input. Ignoring a few other minor details like initializing i and j, the total number of operations is exactly 2N. For big-O notation, constant factors are ignored, so it's O(N).

A: It's confusingly written. Both loops (4-7 and 12-17) have the same length (n) and the inside of both loops are constant time (no nested loops). So they're each O(n), for a total of O(n) for the whole routine.
Regarding Jerry's answer, lines 4-7 matter because they're still O(n). If you could magically remove lines 12-17 you'd still have an O(n) routine.


Q: Create multi-page document from a single page template using doc4j I am planning to use doc4j for search and replace in a template. I'do like to create the page for each member in the list.  Basically, I need to replicate the same page from the template.  I have done simple search and replace. However, this little complex one for which I need some sample examples. Here is my requirement:

*

*I have a docx template which has the content with place holders.

*There is a table with  3 columns in it and I need to replace with different values for each column like first name, last name and etc. The number of rows may vary anywhere from one to 200. So technically this may go beyond one page. If it exceeds more than one page, then I need the table header to repeat in the next page too.

*I want to copy the same template on every page and replace the place holder. Basically create a single document with multiple pages each page for one member.
Please provide me with the example.
Appreciate the help.
Thanks.


Q: Как сделать запрос в базу данных 1С-битрикс правильно Есть сайт на 1С-битрикс.. Нужно сделать запрос в базу данных на все товары .. Чтобы запрос выдал: наименование товара, количество по складам для определенного клиента , цену для определенной группы клиентов..
Запрос должен делаться по айди клиента.. Как это сделать я просто не представляю..
Есть класс https://dev.1c-bitrix.ru/api_help/catalog/classes/ccatalogstoreproduct/index.php но как им пользоваться я чет до конца не пойму..

A: //Формируем массив данных
$products = array();
$StoreArray = array();

$arGroups = CUser::GetUserGroup($USER->GetID());//Группа покупателя
$userID = $USER->GetID();//Айди клиента
$rsUser = CUser::GetByID($userID);//Массив с данными клиента
$arUser = $rsUser->Fetch(); // Выборка данных с массива о клиенте
$arrayStoreUser = $arUser["UF_STORE"]; // Массив доп поля

//Выобрка товаров

$arSelect = Array("ID", "NAME", "DATE_ACTIVE_FROM", "SECTION_ID", 'IBLOCK_ID');
$arFilter = Array(
    "IBLOCK_ID"=>10,
    "SECTION_ID"=>array(305,329,350,351,363,378,410,417,437), /// Это массив для разделов
    "INCLUDE_SUBSECTIONS"=>"Y" // тут указали выбор подразделов
);

$res = CIBlockElement::GetList(Array(), $arFilter, false, Array(), $arSelect);
$var = 0;
while($ob = $res->GetNextElement())
{
    $arFields = $ob->GetFields();

    $rsStore = CCatalogStoreProduct::GetList(array(), array('PRODUCT_ID' => $arFields['ID'], 'STORE_ID' => $arrayStoreUser), false, false, array('AMOUNT'));

    //Количество товара по складу
    $rsStoreProduct = \Bitrix\Catalog\StoreProductTable::getList(array(

        'filter' => array('=PRODUCT_ID'=>$arFields['ID'],'STORE_ID'=>$arrayStoreUser),
        'select' => array('AMOUNT','STORE_TITLE' => 'STORE.TITLE','STORE_ID','PRODUCT_NAME' => 'PRODUCT.IBLOCK_ELEMENT.NAME')

    ));
    //Группа товара
    $groupProduct = CIBlockElement::GetByID($arFields['ID']);

    //Выборка цен для группы
    $db_res = CPrice::GetList(
        array(),
        array(
            "PRODUCT_ID" => $arFields['ID'],
            "CATALOG_GROUP_ID" => max($arGroups)
        )
    );

    if ($arStore = $rsStore->Fetch()) {
        $products[$arFields['ID']]["product_title"] =  $arFields['NAME'];
        if ($ar_res = $db_res->Fetch())
        {
            $products[$arFields['ID']]["PRICE"] = $ar_res['PRICE'];
        }
        else
        {
            $products[$arFields['ID']]["PRICE"] =  "Цена не найдена!";
        }
        //Выборка группы товара
        if($obRes = $groupProduct->GetNextElement())
        {
            $array_Group = $obRes->GetGroups();
            $nameGroup = $array_Group->Fetch();
            $products[$arFields['ID']]['Group'] = $nameGroup['NAME'];

        }
    }

    while($arStoreProduct = $rsStoreProduct->fetch())
    {
//        $products[$arFields['NAME']]['STORE_TITLE'. $var++] = $arStoreProduct['STORE_TITLE'];
        $products[$arFields['ID']]['AMOUNT' . $var++] = $arStoreProduct['AMOUNT'];

        $StoreArray[]= $arStoreProduct['STORE_TITLE'];

    }

    $resultArray = array_unique($StoreArray);
};


Q: search the product by tag or category not working I am working on a search. I am trying to search the product by tag or category. I tried the below code but it's not working. I am getting

Nothing Found

Also, the Below code is working only with title and content.
Would you help me out with this?
<?php
/**
 * The template for displaying search results pages
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
 *
 * @package CoolPickings
 */

get_header();
?>

        <?php

                    if ( have_posts() ) :
                    ?>

            <?php

       while (have_posts()){the_post();?>

                <?php the_post_thumbnail();?>

<?php echo get_the_date('F j, Y'); ?>

                            <?php $cat = get_the_category();
                            ?>

                            <a href="<?php echo esc_url( get_category_link( $cat[0]->term_id ) );?>"><?php echo $cat[0]->cat_name?><?php //the_category('');

                            ?>

<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php echo wp_trim_words(get_the_title(), 12, '...'); ?>

<?php echo wp_trim_words(get_the_excerpt(), 25, '...'); ?>

             <?php } ?>

            <?php //endwhile;

            //the_posts_navigation();

        else :

            get_template_part( 'template-parts/content', 'none' );

        endif;
        ?>

<?php
get_sidebar();
get_footer();

A: Try the following code below. The only difference is using terms as an array.
$getSearch=get_search_query();
$args = array(
    'tax_query' => array(
       'relation' => 'OR',
        array(
            'taxonomy' => 'product_tag',
            'field' => 'slug',
            'terms' => array($getSearch) // Using the terms as an array
        ),
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array($getSearch) // Using the terms as an array
        )
    ),
    'post_type' => 'product'
);
$the_query = new WP_Query( $args );

// ... functions.php
add_action( 'pre_get_posts', 'my_search_exclude' );

function my_search_exclude( $query )
{
    if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
        $query->set( 's', '' );
    }
}

You can find more info here: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters


Q: Unable to load dataset from "" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader I wrote a demo of Spring Boot + JPA, and here I met a question that confused me couple of days when I try to do some tests on repository.
The error is
**java.lang.IllegalArgumentException: Unable to load dataset from"dbunit/studentTestSample" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoaderava.lang.IllegalArgumentException: Unable to load dataset from "/data/dbunit/studentTestSample.xml" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader
at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.12.jar:5.3.12]
    at com.github.springtestdbunit.DbUnitRunner.loadDataset(DbUnitRunner.java:211) ~[spring-test-dbunit-1.3.0.jar:na]
    at com.github.springtestdbunit.DbUnitRunner.loadDataSets(DbUnitRunner.java:192) ~[spring-test-dbunit-1.3.0.jar:na]
    at com.github.springtestdbunit.DbUnitRunner.setupOrTeardown(DbUnitRunner.java:173) ~[spring-test-dbunit-1.3.0.jar:na]
    at com.github.springtestdbunit.DbUnitRunner.beforeTestMethod(DbUnitRunner.java:75) ~[spring-test-dbunit-1.3.0.jar:na]
    at com.github.springtestdbunit.DbUnitTestExecutionListener.beforeTestMethod(DbUnitTestExecutionListener.java:185) ~[spring-test-dbunit-1.3.0.jar:na]**

*

*Firstly, here is my test file

    package com.meds.infrastructure.student;

import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
    import com.github.springtestdbunit.annotation.DatabaseSetup;
    import com.meds.domain.student.entity.StudentInfoDo;
    import com.meds.infrastructure.repository.StudentRepository;
    import static org.assertj.core.api.Assertions.assertThat;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.TestExecutionListeners;
    import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
    import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
    import org.springframework.transaction.annotation.Transactional;

    @AutoConfigureMockMvc
    @SpringBootTest
    @ContextConfiguration
    @TestExecutionListeners({
            DependencyInjectionTestExecutionListener.class,
            DirtiesContextTestExecutionListener.class,
            TransactionDbUnitTestExecutionListener.class,
            MockitoTestExecutionListener.class
    })
    public class StudentRepositoryTest {

        @Autowired
        private StudentRepository studentRepository;

        @Test
        @Transactional
        @DatabaseSetup("dbunit/studentTestSample")
        public void should_get_student_info_id() {

            StudentInfoDo studentInfoDo = studentRepository.findStudentById(1l);

            assertThat(studentInfoDo.getId()).isEqualTo(1l);
            assertThat(studentInfoDo.getStudentId()).isEqualTo("studentId");
            assertThat(studentInfoDo.getName()).isEqualTo("studentName1");
            assertThat(studentInfoDo.getGender()).isEqualTo("MALE");
        }
    }

and here is my gradle.build
    dependencies {
        implementation 'junit:junit:4.13.1'
        annotationProcessor 'org.mapstruct:mapstruct-processor:1.2.0.Final'
        annotationProcessor 'org.projectlombok:lombok:1.18.10'
        compileOnly 'org.projectlombok:lombok:1.18.10'
        compileOnly 'org.mapstruct:mapstruct-processor:1.2.0.Final'

        implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
        implementation 'org.springframework.boot:spring-boot-starter-web'
        implementation 'org.hibernate:hibernate-core'
        implementation 'javax.xml.bind:jaxb-api:2.3.0'
        implementation 'javax.xml.soap:saaj-api:1.3.5'
        implementation 'jakarta.validation:jakarta.validation-api:2.0.2'
        implementation 'org.flywaydb:flyway-core'
        implementation 'org.mapstruct:mapstruct-jdk8:1.2.0.Final'
        implementation 'org.mapstruct:mapstruct:1.3.1.Final'
        implementation 'io.springfox:springfox-swagger2:2.8.0'
        implementation 'io.springfox:springfox-swagger-ui:2.8.0'
        implementation 'org.springframework.boot:spring-boot-starter-security'

        runtimeOnly 'mysql:mysql-connector-java'

        testImplementation("org.dbunit:dbunit:2.5.2")
        testImplementation("com.github.springtestdbunit:spring-test-dbunit:1.3.0")
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
    }

Here is my studentTestSample.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <student_info id="1" student_id="studentId1" student_name="studentName1" gender="MALE" grouped="0" />
</dataset>

*What I have tried

*

*add classpath at @DatabaseSetup

*add "" at XML file

*add version at XML file

*remove jupiter and use junit.Test

*Check the location of XML

I guess the reason is cannot find the XML file(because I change the file name randomly it still has this error), maybe it's about my Spring Boot version and JUnit version does not support DbUnit?

A: Try something like this
@DatabaseSetup("/data/.../studentTestSample.xml")

Careful with your file path will help you resolve problem.
Reference document https://springtestdbunit.github.io/spring-test-dbunit/apidocs/com/github/springtestdbunit/annotation/DatabaseSetup.html section parameter value.

A: I finally found the issue. It was because the format of xml was not right!
Here is my xml name:
studentTestSample
It should be written like is:
studentTestSample.xml
I do remember I wrote "studentTestSample.xml" when I created this file. It looks like I have to emphasize the type of my xml file.
Finally, make sure you can jump to the location of file when you are typing command+B.


Q: Uri Segment When Using Ajax In my codeigniter application i want to display the uri segments.Iam using ajax to call controller.
This is my html code
function add_store(){
            var path="<?php echo base_url()?>images/loader.gif";
            $("#add_store").html("

").show();
            $.ajax({
                type: "POST",
                url: "<?php echo base_url();?>index.php/Admin/add_store/",
                success: function(msg){
                $("#add_store").html('');
                $("#add_store").html(msg).show();
                }
            });
}

This is my controller code
public function add_store()
    {
        echo $this->uri->segment(3);
    }

nothing will be displayed.How can i get uri segments?
If i use
echo $this->uri->segment(1);

Then it displays Admin but after 1 nothing will be displayed.

A: Looks like your controller 'Admin' is calling a method 'add_store', but there are no further segments, that's why your 3rd one isn't passed.

1st segment: "Admin"
2nd segment: "add_store"

I don't know what you want to achieve, but if you have an url like:
admin/add_store/someparam/someotherparam

you would just do
public function add_store($param1, $param2)
{
    echo $param1; // 'someparam'
    echo $param2; // 'someotherparam'
}

without the need to call directly the uri segment.


Q: Asymmetric S-shaped function mapping interval $[0, 1]$ to interval $[0, 1]$ In the literature, is there any asymmetric $S$-shaped function that maps the interval $[0, 1]$ to interval $[0, 1]$?
Unfortunately I can't post figure so I just describe what I mean in text. The function I want should be monotonic increasing. In the meanwhile, for a real number $c < 0.5$, the function
$$0 \mapsto 0, \quad c \mapsto 0.5, \quad 1 \mapsto 1.$$
Moreover, the function is smooth on its domain, concave on interval $[0, c]$ and convex on interval $[c, 1]$.
By the way, can it be seen as a sort of link-function?

A: Yes.
And here is how you go about finding one.
For our purposes, convex means $F''(x)\ge 0$ and concave means $F''(x)\le 0$.
Ok, so let $F$ be such a function. If we also assume monotonicity, we have $F'(x)\ge 0$, and $F$ is a cumulative distribution function. Therefore, the convex and concave conditions are $f'(x)\ge 0$ for $x\le c$ and $f'(x) \le 0$ for $x\ge c$ (where $f=F'$ is the pdf of $F$).
In other words, now we are looking for density function on $[0,1]$ that is increasing on $[0,c]$ and decreasing on $[c,1]$. We go to a table of probability distributions on $[0,1]$ (e.g., Wikipedia's list) and see that the cumulative distribution function of the Beta distribution fits the bill.
Another approach would be to explicitly construct such a function (I believe a quartic would do the job).

A: I would comment instead, but I don't have the score yet, so here's my two cents:
The only thing I could think of is an asymmetric tangent function, yet I couldn't find anything about them except for this part of the Proceedings of the Estonian Academy of Sciences, Engineering. See if it helps...?


Q: Counting number of records in database: Django I'm trying to output the count of the number of "subscribers" in my database in Django, I've found count in my view and then I think I'm using it correctly in the html, but it always just outputs "there are subscribers" without the number, when I use "|length" in the html it always outputs 0, so I'm not sure what my error is.
views.py
def list_todo_items(request):
    context = {'todo_list' : Todo.objects.all()}
    count = Todo.objects.count()
    context2 = {'count': count}
    # context = {'count': Todo.objects.count()}
    # count = Todo.objects.count()
    return render(request, 'index.html',context,context2)

def insert_todo_item(request: HttpRequest):
    todo = Todo(content=request.POST['content'])
    try:
        todo.full_clean()

    except ValidationError:
        # pymsgbox.alert('ValidationError! Phone number must be entered in the format: +999999999. Up to 15 digits allowed.', 'Title')
        return redirect('/main/list/')

    todo.save()
    return redirect('/main/list/')

def delete_todo_item(request,todo_id):
    todo_to_delete = Todo.objects.get(id=todo_id)
    todo_to_delete.delete()
    return redirect('/main/list/')

index.html
{% for todo in todo_list %}

 {{todo.content}}

    <form action="{% url 'delete_todo_item' todo.id %}" method="post" class="float-right d-inline">
        {% csrf_token %}
        {{form.as_p}}
        <button type="submit" class="btn">

        </button>
    </form>

    There are {{ count }} subscribers.

{% empty %}

     No current subscribers.

{% endfor %}

A: You can pass multiple items to the same context. A dictionary allows to add multiple key-value pairs (as long as the keys are hashable, and unique):
def list_todo_items(request):
    context = {
        'todo_list': Todo.objects.all(),
        'count': Todo.objects.count()
    }
    return render(request, 'index.html', context)


Q: How to bind a String to a TexBlock Property ? WPF c# I have this :
TextBlock MyText = new TextBlock();
String SomeWords;

I want to bind those two properties but I dont know how to do it with a string :
Binding binding = new Binding();
binding.Path = new PropertyPath(MyText.Text);
BindingOperations.SetBinding(SomeWords, ???????, binding);

What am I suppose to put at the emplacement of the question marks ?
Ty !!!

A: TextBlock MyText = new TextBlock();

Binding binding = new Binding();
binding.Path = new PropertyPath("Name"); //Name of the property in Datacontext
BindingOperations.SetBinding(MyText,TextBlock.TextProperty , binding);

If you want to bind to property of some other object you will need to set binding.Source to that object.

A: The other answers are technically more correct to this particular question given you are trying to create the binding in code, but usually people perform these simple bindings through xaml.
Xaml View:
<TextBox Text="{Binding MyTextPropertyFromViewModel}" />

C# ViewModel:
public String MyTextPropertyFromViewModel
{ get; set; }

A: That should be the target property of the binding, ie your TextBlock.TextProperty
See:
http://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.setbinding.aspx


Q: Tag synonym: indent->indentation indent and indentation not only both exist and are in active use, their tag wikis differ by a single word (probably because the system rejected identical wikis).  They should be merged.


Q: How does Thorns work? I'm trying to figure out how thorns works so I can start deciding how to approach making a viable thorns build. Stacking some thorns on my Crusader has led me to believe that it's not as simple as it sounded at first.
I have around 7,000 thorns right now, but when enemies attack me, they take over 90,000 damage. I've also seen the thorns damage crit, and I've also seen enemies take upwards of 2 million damage from a single activation of thorns.
With Vo'Toyias Spiker equipped and using Iron Skin with Reflective Skin and Provoke with Charged Up, I've just utterly melted enemies, seeing crits of over 8 million. None of my active attacks can deal even 2 million damage, so these massive numbers must be from some combination of these skills.
Is thorns return damage somehow a function of how much damage I sustain? What if I block or dodge? What is the approximate formula for damage return based on my current thorns?

A: After doing some math, I arrived at the following formulas for thorns damage:
Regular Attack

*

*((S / 100 / 4) + 1) * T

Reflective Skin Attack

*

*((S / 100) + 1) * 2T * (P / 100 + 1)

where

*

*S is Strength (or mainstat)

*T is your thorns damage

*P is your Physical Damage bonus (as a percent)

It does not appear that regular thorns damage can crit, nor is it based off your weapon damage or the damage done to you. It did not to appear to be affected by any damage reduction modifiers nor is it improved by bonuses to Physical Damage Skills. It is scaled according to your mainstat by 1/4
Reflective Skin does indeed double your base thorns damage. However, because it is a skill doing the damage and not the thorns mechanic, it scales off your mainstat like all other skills (not at a 1/4 ratio). It is also then eligible to crit and receive your "+X% Damage to Physical Skills" bonuses. This is the reason for the (more than 2x) large spike in damage when using Reflective Skin.
An example:
For a crusader with 5000 Strength and 10000 Thorns and 20% Bonus to Physical Skills:

*

*A regular attack would deal 135,000 damage.

*An attack while Reflective Skin is active would deal 1,224,000 damage
(with the option to crit).

A: After doing some research, I have reached a few conclusions, plus found how the approximate damage works.
Thorns return damage does not depend on how much damage the attack against you does. It's calculated by your base thorns times a multiplier based on your primary stat. The multiplier is one quarter of the bonus provided to your attacking damage. For example, if you have 20,000 thorns, and 6,000 strength, then you'll get 1500% bonus thorns damage (6000 / 4 as a percentage), which amounts to 320,000 thorns damage to enemies when they attack you (20,000 base plus 300,000 bonus from primary stat). This can then crit based on your normal crit chance and crit damage.
All of the insanely high damage numbers occur using the Iron Skin skill with the Reflective Skin rune, which appears to be bugged currently and do lots of wonky stuff (including killing allied Crusaders).

A: I did some testing because I was wondering the same question and came to the conclusion that only your main stat and dmg taken debuffs on the target affect thorns damage (dmg buffs on yourself do not increase thorns dmg, atleast not the ones I tested with), dmg taken debuff affects thorns dmg by 75% the normal amount and main stat increases thorns dmg about 25% of the normal dmg increase.

A: In the 2.0.5 patch notes, they mention changing the item Sanguinary Vambraces. Inside this change they mention the modifier.

The Thorns damage dealt by these bracers will now benefit from your
  main stat damage increase at a 25% rate, as normal Thorns damage does

Therefore, it is modified by 25% of your primary attribute. Confirmed.

A: Here's a thorns crusader damage calculator:
http://www.ring.lt/crusader/

A: I have analyzed the source code of the crusader thorns DPS calculator mentioned in user77988's answer. The important lines are
var damage = Math.round(((parseInt(strength)/400)+1)*parseInt(thorns));
var rsdamage = Math.round(((parseInt(strength)/100)+1)*2*parseInt(thorns)*(phy/100+1));

Where damage is regular Thorns damage, rsdamage is Reflective Skin Damage. Converting from Javascript to regular Math, that is
D  = (S/400+1)*T
RS = (S/100+1)*2*T*(P/100+1)

where S is strength, T is thorns and P is the bonus damage to physical skills in %
This is identical to the formulas in TheCheeseGod's answer.


Q: Create an Angular 2 app inside no Angular project I've created an Angular 2 app inside a normal javascript project and I need to use some files (.CSS, .JS, etc) outside the Angular app, but if I use the CLI with command ng serve it creates the app in the http://localhost:4200/, and the app works, but these files outside the angular app they won't be loaded. So I have to deploy the app with ng build --prod to get these files and see the real result. But I think this is not the best way as I have to deploy the app for every change in the code.
So, is there any way to manage this situation?
Thanks!


Q: Top Contributors Plugin with Custom Post Type I am using the plugin Top Contributors. That's very helpful for all blogs. But the problem with this plugin is: it is not integrated with custom post types.
How could I extend the plugin to do that?

A: This plugin hasn't been updated in almost two years, so you should consider finding a new one.
That said, in this cases you have to open1 the plugin files and search for some string related to your issue, e.g., post_type.
You'll find that in the file functions.inc.php, it has two occurrences of:
AND a.post_type = 'post'

Change that to:
AND ( a.post_type = 'post' OR a.post_type = 'YOUR_CPT_SLUG' )

Not sure if that's the only thing that needs to be changed, but now you should be able to further inspect it and locate other parts that need modification.
 1: Software for WordPress Theme and Plugin Development?

A: Best Solution is Top Authors
Its support CPT now. http://wordpress.org/support/topic/custom-post-type-support-2?replies=3#post-3967338