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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: Python Decorator for printing every line executed by a function I want to, for debugging purposes, print out something pertaining to each and every line executed in a python method.
For example if there was some assignment in the line, i want to print what value was assigned for that variable, and if there was a function call, i want to print out the value returned by the function, etc.
So, for example if i were to use a decorator, applied on function/method such as :
@some_decorator
def testing() :
    a = 10
    b = 20
    c = a + b
    e = test_function()

the function testing when called, should print the following :
a = 10
b = 20
c = 30
e = some_value

Is there some way to achieve this? More fundamentally, i want to know whether i can write a code that can go through some other code line by line, check what type of an instruction it is, etc. Or maybe like we can get a dictionary for finding out all the variables in a class, can i get a dictionary like datastructure for getting every instruction in a function, which is as good a metaprogram can get.
Hence, I am particularly looking a solution using decorators, as I am curious if one can have a decorator that can go through an entire function line by line, and decorate it line by line,
but any and all solutions are welcome.
Thanks in advance.

A: How about something like this? Would this work for you?
Debug Context:
import sys

class debug_context():
    """ Debug context to trace any function calls inside the context """

    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print('Entering Debug Decorated func')
        # Set the trace function to the trace_calls function
        # So all events are now traced
        sys.settrace(self.trace_calls)

    def __exit__(self, *args, **kwargs):
        # Stop tracing all events
        sys.settrace = None

    def trace_calls(self, frame, event, arg):
        # We want to only trace our call to the decorated function
        if event != 'call':
            return
        elif frame.f_code.co_name != self.name:
            return
        # return the trace function to use when you go into that
        # function call
        return self.trace_lines

    def trace_lines(self, frame, event, arg):
        # If you want to print local variables each line
        # keep the check for the event 'line'
        # If you want to print local variables only on return
        # check only for the 'return' event
        if event not in ['line', 'return']:
            return
        co = frame.f_code
        func_name = co.co_name
        line_no = frame.f_lineno
        filename = co.co_filename
        local_vars = frame.f_locals
        print ('  {0} {1} {2} locals: {3}'.format(func_name,
                                                  event,
                                                  line_no,
                                                  local_vars))

Debug Decorator:
def debug_decorator(func):
    """ Debug decorator to call the function within the debug context """
    def decorated_func(*args, **kwargs):
        with debug_context(func.__name__):
            return_value = func(*args, **kwargs)
        return return_value
    return decorated_func

Usage
@debug_decorator
def testing() :
    a = 10
    b = 20
    c = a + b

testing()

Output
###########################################################
#output:
#   Entering Debug Decorated func
#     testing line 44 locals: {}
#     testing line 45 locals: {'a': 10}
#     testing line 46 locals: {'a': 10, 'b': 20}
#     testing return 46 locals: {'a': 10, 'b': 20, 'c': 30}
###########################################################


Q: IF-statement depending on notebook.page.label (gtk#) I am realtively new to C# and am trying to have an action in my toolbar that will act depending on which page in a notebook that I am currently "viewing".
Here is what I am trying to do:
protected void OnRefreshActionActivated (object sender, EventArgs e)
{

    if (mynotebook.CurrentPage.Equals == pgMyNotebookPage)
    {
        lblMsg.Text = "You are viewing the first page";
    }
    else
    {
        lblMsg.Text = "You are viewing the second page";
    }

}

However I can't seem to get this to work. Any pointers?
Regards,
Christian

A: I solved this by creating a messagedialog that showed me the output of mynotebook.CurrentPage. It turned out that each page was assigned a number starting with 0.
This is the working code:
protected void OnRefreshActionActivated (object sender, EventArgs e)
{
    if (nbMain.CurrentPage == 0)
    {
            lblMsg.Text = "You are viewing the first page.";

    }
    else
    {
           lblMsg.Text = "You are viewing the first page.";

    }

}


Q: WebKit gradient from an image Does anyone know if there is a tool that will take an image (.png, .gif, etc) and output the gradient that the image contains?
I really want to recreate this image  in css. Looks like a mix of linear and radial gradients and is beyond my css skills

A: Getting the gradient from a random image is going to be tough for any image processor.  You would probably have better luck by getting the pixel data for the image, finding the top and bottom pixel, pulling the color data out of them, then using these values to create your gradient.

A: Get started with this tool
http://gradients.glrzad.com/ and then read about radial gradients here to make it radial http://hacks.mozilla.org/2009/11/css-gradients-firefox-36/
You can get this far with that tool:
-webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0, rgb(68,214,254)),
    color-stop(0.49, rgb(53,150,230)),
    color-stop(0.51, rgb(123,180,236)),
    color-stop(1, rgb(255,255,255))
)
-moz-linear-gradient(
    center bottom,
    rgb(68,214,254) 0%,
    rgb(53,150,230) 49%,
    rgb(123,180,236) 51%,
    rgb(255,255,255) 100%
)

Then make it radial, mozilla only here
-moz-radial-gradient(right bottom,
   ellipse,
   #44D6FE 0%,
   #3596E6 49%,
   #7BB4EC 51%,
   #FFFFFF 100%) repeat scroll 0 0 transparent

and here is an image of what it looks like

A: Your example is an overlap of two radial gradients. There is a white to mid-blue stop to opaque radial gradient centered above the button with a mid-opacity; on top of simple blue to white radial gradient centered to the bottom right.


Q: Replace input field error message text based on input field label name So I have this account creation form for a company. Here's what it looks like:

I am going to explain first how a feature in this system works.

*

*After company creation, a table will be shown, listing all the companies I created.

*In the Action column of this table, there's an action button that once I click it, I will be logged in into a specific company I chose, acting as the user logged inside that company.

*Inside, there's more like the same layout and I can create a sub-company called "Operator".

*So there's a "Create Operator" button and once clicked, I will be redirected to the same form layout above (except that the "Company Name" label is changed to "Operator Name").

*Alright, so I am using Yii2 php framework and basically, each input field is an attribute in a db table and in my model, there's a function called public function attributeLabels() where each of these attributes are assigned to a specific label.

*For example, first input field's db table attribute name is company_name so inside this function it is assigned as company_name => "Company Name" and this label is passed to the view which is this form. So whenever there are error messages, this label is used.

*Regardless if I am creating a company or operator, the error message is always "Company Name should not be blank". What I need to accomplish is when I create an operator, the error message should be "Operator Name should not be blank."
I hope you get my problem. So I tweaked some javascript/jQuery but I am still having problems.
// For changing Operator Name error message
var operatorNameLabel = $('.field-company-company_name label').attr('for','company-company_name').text();
var companyNameErrorDiv = $(".field-company-company_name p");
var operatorNameMsg = 'Operator Name should not be blank.';

$('#submit-button').click(function() {
    // Change Operator Name error message
    if (operatorNameLabel == "Operator Name") {
        companyNameErrorDiv.html("
Operator Name should not be blank
");
        //companyNameErrorDiv.text(operatorNameMsg);
    }
});

$('#content-offset').click(function () {
    if (operatorNameLabel == "Operator Name") {
        companyNameErrorDiv.html("
Operator Name should not be blank
");
        //companyNameErrorDiv.text(operatorNameMsg);
    }
});

My problem in my current code is that :

*

*when I leave the operator name input field blank then click into a blank space outside the input field, the error message is still "Company Name should not be blank."

*but then when I click back to the input field, that's the time the error message changes to "Operator Name should not be blank."

*What really happens is that when I click at the operator name input field, then single click outside or at any other input fields, the error message remains "Company Name should not be blank.",

*but when I do a second click, the the error message changes.

*There's a problem when I click back to the operator name input field for it keeps on getting back to the "Company Name should not be blank" error message, when clicked.
I hope you get my problem.
EDIT:
Yii2 generated html looks like this:

    Operator Name

        <input type="text" id="company-company_name" class="form-control" name="Company[company_name]" required="required">

Company Name cannot be blank.

A: Try adding required attribute to input element, data-* at label element; css :invalid, :after pseudo element, content property of label to display message when input is invalid.

input:invalid + label:after {
  content: " " attr(data-name) " should not be blank";
  color: red;
}
<input type="text" name="company_name" required />

<input type="text" name="login_name" required />

<input type="email" name="email" required />

<input type="password" name="password" required />

<input type="password" name="password_confirm" required />


Q: Python - Create a Bar Chart of Average Estimated Salary by c_rating, but do a facet_wrap by gender My data set is Churn_Modeling:
RowNumber     CustomerId     Surname    CreditScore     Geography   Gender  Age Tenure    Balance   NumOfProducts   HasCrCard   IsActiveMember  EstimatedSalary Exited
        1       15634602    Hargrave            619       France    Female  42       2          0               1           1                1        101348.88     1
        2       15647311        Hill            608       Spain     Female  41       1   83807.86               1           0                1        112542.58     0
        3       15619304        Onio            502       France    Female  42       8   159660.8               3           1                0        113931.57     1
        4       15701354        Boni            699       France    Female  39       1          0               2           0                0         93826.63     0
        5       15737888    Mitchell            850       Spain     Female  43       2  125510.82               1           1                1          79084.1     0
        6       15574012         Chu            645       Spain     Male    44       8  113755.78               2           1                0        149756.71     1

I created a column called c_rating with the following ranges: (<500 -="very poor",  500-600="poor",  601-660="fair", 661-780="good",  and >= 780 – "excellent") with code:
from plotnine import *
from dfply import *
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import datetime as dt

a_churn = pd.read_csv("Churn_Modeling.csv")

a_churn['c_rating'] = pd.cut(a_churn['CreditScore'], bins=[0,500,600,660,780,1000],labels = ['very poor', 'poor', 'fair', 'good', 'excellent'])

a_churn

I am trying to create a Bar Chart of Average Estimated Salary by c_rating, but do a facet_wrap by gender.
(a_churn >>
  group_by(X.c_rating) >>
  summarise(avg_est_salary = X.EstimatedSalary.mean()) >>
  ggplot(mapping=aes(x=avg_est_salary,y = 'c_rating')) +geom_bar(stat = "identity"))

However I get the error c_rating is not defined.

A: Is this what you are trying to do?
from plotnine import ggplot, aes, geom_bar, facet_wrap
import pandas as pd

a_churn = pd.read_csv('Churn_Modeling.csv')
a_churn['c_rating'] = pd.cut(a_churn['CreditScore'], bins=[0,500,600,660,780,1000],labels = ['very poor', 'poor', 'fair', 'good', 'excellent'])

p = ggplot(a_churn) + aes(x='c_rating', y='EstimatedSalary') + geom_bar(stat='identity', alpha=0.8) + facet_wrap('Gender')
print(p)


Q: Twig impossible to invoke a method on a string variable After updating "twig/twig" to "v2.4.4" I have an error when calling macro function.
Impossible to invoke a method ("widget_prototype") on a string variable (":ERP/timesheets:_form_part.html.twig").

My macro:
{% macro widget_prototype(widget, remove_text) %}
{% if widget.vars.prototype is defined %}
    {% set form = widget.vars.prototype %}
    {% set name = widget.vars.prototype.vars.name %}
{% else %}
    {% set form = widget %}
    {% set name = widget.vars.full_name %}
{% endif %}

Calling macro part:
{% include ':ERP/timesheets:_data_content_supply_from_widget.html.twig' with {form:form, name:name} %}

{% endmacro %}

            <div id="post_supplies"
             data-prototype="{{ _self.widget_prototype(form.supplies, 'remove'|trans({}, 'common'))|escape }}"
             style="margin-bottom: 5px">
            {% for widget in form.supplies.children %}
                {{ _self.widget_prototype(widget, 'remove'|trans({}, 'common')) }}
            {% endfor %}
        </div>

How to correctly call macro? Tried calling without _self and I have the error: Unknown "widget_prototype" function.

A: DarkBee's answer is good, but if your macro is in the same twig file that's calling it then you will still need to import it like so:
{% import _self as my_macros %}
{{ my_macros.widget_prototype(...) }}

Seems a bit counter-intuitive but that's how it is.

A: You need to import the macro, not include it
{% import "my_macro.twig" as my_macro %}
{{ my_macro.function(arg1) }}


Q: Specifying matplotlib scatter size in plot units I would like to specify my scatter dot size not using points or pixels but rather using plot units. Take for instance the following:
import matplotlib.pyplot as plt
x = [0]
y = [0]
plt.scatter(x,y)
plt.show()

This produces a plot as follows:

What if, say, I wanted my marker to have a radius of exactly 0.002 plot units? I understand the s parameter indicates the area of the marker size in points. Is there a way to directly provide it in plot units? If not what is the best way to convert from plot units to points so I can pass it into the s parameter?
I have also seen some other questions which propose using a PatchCollection and simply plotting a circle with a specified radius. I would prefer not to use this approach. I'd like to avoid extensively rewriting existing code and instead use the s parameter along with plt.scatter.
Edit
I tried using the code from this question which apparently allows you to control the marker size based on plot units. However I couldn't really get it to work for my basic case:
import matplotlib.pyplot as plt
import numpy as np

class scatter():
    def __init__(self,x,y,ax,size=1,**kwargs):
        self.n = len(x)
        self.ax = ax
        self.ax.figure.canvas.draw()
        self.size_data=size
        self.size = size
        self.sc = ax.scatter(x,y,s=self.size,**kwargs)
        self._resize()
        self.cid = ax.figure.canvas.mpl_connect('draw_event', self._resize)

    def _resize(self,event=None):
        ppd=72./self.ax.figure.dpi
        trans = self.ax.transData.transform
        s =  ((trans((1,self.size_data))-trans((0,0)))*ppd)[1]
        if s != self.size:
            self.sc.set_sizes(s**2*np.ones(self.n))
            self.size = s
            self._redraw_later()

    def _redraw_later(self):
        self.timer = self.ax.figure.canvas.new_timer(interval=10)
        self.timer.single_shot = True
        self.timer.add_callback(lambda : self.ax.figure.canvas.draw_idle())
        self.timer.start()

x = [0]
y = [0]
fig = plt.figure()
ax = fig.gca()
size = 3.14*0.002**2
scatter(x, y, ax, size = 0.002, edgecolors = 'black')
ax.set_ylim(-0.004, 0.004)
ax.set_xlim(-0.004, 0.004)
ax.scatter(x,y)
ax.grid()
plt.show()

The above outputs the following figure:

Which does not look like it has a size of 0.002 as I indicated in scatter(x, y, ax, size = 0.002, edgecolors = 'black'). I'm not sure what I'm doing wrong here.


Q: Details of socket using socket ID This question may sound basic one . Are there any functions in c or Java where I can get the socket details like , port , address , buffer size using only socket identifier ?

A: Some minimal information available with me is posted below.
I don't know much of Java. But as far as 'C' is concerned, you can use the getsockopt function to get the buffer sizes (send buffer and recv buffer) of the socket.
It appears getsockname helps you in getting the ip & port to which the socket is bound to.

A: In c in the function accept:
csock = accept(sock, (struct sockaddr*)&csin, &recsize);

*

*sock is the socket server(int)

*csock is the socket client (int)

*recsize is the size

*csin is a struct with client's details

*

*csin.sin_addr is the client's address

*csin.sin_port is the client's port

From a socket ID try this:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>

f()
{
   int s;
   struct sockaddr_in sa;
   int sa_len;
   .
   .
   .
      /* We must put the length in a variable.              */
   sa_len = sizeof(sa);
      /* Ask getsockname to fill in this socket's local     */
      /* address.                                           */
   if (getsockname(s, &sa, &sa_len) == -1) {
      perror("getsockname() failed");
      return -1;
   }

  /* Print it. The IP address is often zero beacuase    */
  /* sockets are seldom bound to a specific local       */
  /* interface.                                         */
   printf("Local IP address is: %s\n", inet_ntoa(sa.sin_add r));
   printf("Local port is: %d\n", (int) ntohs(sa.sin_port));
   .
   .
   .
}


Q: How can I add additional columns during BULK INSERT without modifying source file I have a BULK INSERT into a table but I need to add data that is not in my csv for the last column in each row of the table.
For example, if my csv file contains 10 columns but the database table contains 11 columns, how can I add data for the last column? Modifying the csv file itself is not an option
Is this possible with BULK INSERT?
Here is my script:
BULK INSERT [Data_GPS].[dbo].[Data_z]
    FROM 'C:\TEMP\SQL\Bulk insert\dane.csv'
    WITH
    (
    FIRSTROW = 2,
    FIELDTERMINATOR = ';',
    ROWTERMINATOR = '\n',
    ERRORFILE = 'C:\TEMP\SQL\Bulk insert\errors.txt',
    TABLOCK
    )

A: Sure.  Just use OPENROWSET(BULK ...) instead of BULK INSERT and you can add whatever extra columns you want. EG
select *
from openrowset(bulk 'C:\TEMP\dane.csv', format='CSV')


Q: Get string between two sets of characters in shell I pipe the following string "version": "1.0.0", to sed and I'm trying to get 1.0.0 out of it. I want to get it by the rule: get string between : " and ",.
I've been trying the following:
sed -e '/:\ \"/,/\ ",/p'
sed -e 's/:\ \"\(.*\)\",/\1/'

The first one does nothing and the last one returns "version"1.0.0, which is close, but no cigar. What am I missing?

A: You need to match complete input by using .* on either side of your search pattern to be able to replace full line with just the captured group's back-reference.
This sed should work:
s='"version": "1.0.0",'

sed 's/.*: "\([^"]*\)",.*/\1/' <<< "$s"
1.0.0

Or even this one:
sed 's/.*: "\(.*\)",.*/\1/' <<< "$s"
1.0.0

A: Another approach, using grep with lookahead/lookbehind:
$ grep -oP '(?<=: ")[^"]*(?=")' <<< '"version": "1.0.0",'
1.0.0

or shorter, using \K to exclude : " from the matched string:
$ grep -oP ': "\K[^"]+' <<< '"version": "1.0.0",'
1.0.0


Q: Storing Documents on Azure with custom metadata i am trying to find the best way to implement a small site allowing the user to upload a file and then search on it.
i used azure search with blob storage.
the file is stored on the blob storage and is then gets indexed by azure search indexer - so far so good.
the problem is that i would like to add to each document some custom data like file id and other business data, this data is not part of the document. is there a way to achieve this?
some one, suggested i use cosmos db, though i am not sure its the best way to go when it comes to documents.
Thanks

A: If you would like to keep using blob storage, you can store metadata with the blobs - just add custom metadata to your blobs, add corresponding fields to the search index, and the blob indexer will pick up the metadata.


Q: How to enable SSL usage when using local XML autodiscover file? I use the Redemption library and I encountered a problem I can not solve by myself.
In my project, I use a local XML file to login to the Exchange server (Autodiscover service is disabled on the server and can not be enabled). For this purpose, I create an Outlook Autodiscover "PreferLocalXml" registry key value and a domain name value defining the path to the local XML file. Redemption works correctly, but for some reason it does not use SSL when sending requests to the server.
Is it possible to force SSL usage in this case? However, using Autodiscover (without local XML file) works fine (SSL is used). Thank you in advance for your help.
I tried setting RDOSession.ConnectEncryptData to true, but it did not work.

A: But PreferLocalXml is supposed to point to a local file, not a web server, so SSL would not apply - the file is accesses using the file API.


Q: Trigger to run TeamCity based on file existence I want to run TeamCity processes based on file existance.
I have two TeamCity processes (Dev and Prod):

*

*Dev should be run if there is DevParam file in repo (or in specified location).

*Prod should be run if there is ProdParam file.

I want to run exactly one process after each push to repository.
This files will be added and removed like:

*

*[0] Repository has DevParam file

*[1] Pushed, there is still DevParam file -> Dev process should be run

*[2] Pushed, removed DevParam file and added ProdParam -> Prod process should be run

*[3] Pushed, there is still ProdParam -> Prod should be run

I tried to create Trigger with rules, but I failed (rule like +:DevParam run also on file removal).
Git recognizes addind and removing this files as Moving with Rename, so it may be relevant.

A: file management is not a normal process. I strongly advise you to use the branch flow. For your example, use develop branch(DevParam) for an all your developers and master branch for a prod
Try to use the follows advice.
The developers are coding in the dev branch. Each developer working only this branch.
You should create the build configuration with the trigger to your dev branch. After each new commit, the configuration will be triggered.
If you decided that the code in the dev branch is ready to production, you just merged all to the master. And now you can also trigger the same configuration only for a master branch.
For more information about gitflow-workflow read this


Q: Intel Compiler /QxCORE-AVX2 switch and compatibility with AMD Excavator/RyZen For some unknown reason Intel decided to does not support AVX2 via typical /arch: option. /arch: recognizes only following instructions IA32,SSE,SSE2,SSE3,AVX. So if you want to compile for AVX2 you are basically forced to activate /QxCORE-AVX2 switch. The problem with this option is that it injects check code. That code at runtime checks if your cpu is compatible with selected intructions. If CPU is not compatible then this message pops-up.
Please verify that both the operating system and the processor support Intel(R)
MOVBE, F16C, FMA, BMI, LZCNT and AVX2 instructions.
Now I'm worried that the same message may pop-up on AMD Excavator and RyZen CPU due to not being GenuineIntel. Unfortunately I do not have access to any AMD cpu so I can't check that on real cpu. To make your life easier I've compiled this simple code with activated /QxCORE-AVX2 option.
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    double a, b, c;
    a = 3.0;
    b = 2.0;
    c = 1.0;

    a = a*b + c;

    printf("a=%1.1f",a);

    return 0;
}

and here is decompiled asm code: http://codepad.org/KL4Vq978
My question to people who understand asm code is do you see anything what may block execution of this code on latest AMD cpus? If yes will this http://www.softpedia.com/get/Programming/Patchers/Intel-Compiler-Patcher.shtml help?

A: It turns out that /arch:CORE-AVX2 is recognized and compiled executable contains FMA instructions! I really do not understand why this option is not listed in Visual Studio and in ICL /help ?!?
Dropbox menu in Visual Studio (NO AVX2!)
http://i.cubeupload.com/c1xidV.png
ICL /help
http://i.cubeupload.com/y2Cre6.png

A: The Ryzen supports these instruction sets, but the code will not run on AMD processors because it checks if the processor is "GenuineIntel". There has been a long discussion and legal battle about this issue. See http://www.agner.org/optimize/blog/read.php?i=49


Q: Is there a jQuery event that fires when all effects are done running The title explains the question, otherwise is there way to call a function when all the effects on a page are done running?

A: You could nest your animations like this
$('#Div1').slideDown('fast', function(){
   $('#Div2').slideUp('fast');
});

And do them sequentially...
You could also do something like this:
var animations = 0;
checkAnimation(1);
$('#Div1').slideDown('fast', function(){
   checkAnimation(-1);
});

checkAnimation(count){
   animations += count;
   if(count == 0)
      //animations complete
   }
   else {
       //still animating
   }
}

Hope this helps.

A: You might be able to make use of .queue to get the functionality you are after.  If the length of the queue was 0 you would know that all animations on the object are finished.
Documentation


Q: Angular + TypeScript + AMD = duplication? I've been developing in Angular for a few months and am now investigating whether it's worth moving to TypeScript for my development. One of the issues I'm having is the duplication when using external modules and injecting services. For example I have this (simplified) code:
///<reference path="../../../../typings/tsd.d.ts" />

// imports for strong typing
import audioModel = require('app/plugins/audio/audio.model');

export class AudioController {

    public model: audioModel;

    static $inject = ['$scope', '$q', 'AudioModel'];
    constructor(protected $scope, protected $q, protected AudioModel:audioModel) {
        this.model = new AudioModel();
    }

}

The AudioModel is an Angular factory defined in the external module 'audio.model.ts', so it seems to me that I'm injecting it twice - once using Angular, and again using the TypeScript import to get strong typing.
Is there a better way to both use Angular dependency injection and strong typing in an AMD project?

A:
Is there a better way to both use Angular dependency injection and strong typing in an AMD project

This was an issue with angular 1.x dependency injection. The Angular module system was independent of the traditional Browser module systems in existance (e.g. AMD).
So you do need to import it twice. Once the Type, next the DI.


Q: How to integrate a maven project with parent pom as module? I'd like to use a parent maven project/aggregator to build my project and a dependency which I have in my source root as git submodule, e.g.
aggregator pom.xml
 - dependency pom.xml
 - project pom.xml

I naively adapted this layout from GNU C/C++ projects, like coreutils which simply checkout dependencies as submodules and updated them to a compatible commit together with the project state/commit.
The thing with maven is that there's a parent directive in pom.xml of the dependency and removing it would definitely require to modify the dependency which is not the intention of this setup. So, the same question asked a very different way is: Is a parent directive in a pom definitely preventing a project from being used as a maven module?. Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored?
I'm aware about the fact that this isn't the intended workflow of maven (with the local cache in mind) and that it could be easily achieved by making dependency not a maven module, but just a git submodule and write a two-line build script invoking mvn in the source root and the dependency subdirectory.
I tried using the reactor plugin, but it simply doesn't build anything which isn't included in module declaration (both the make and the make-dependents target) (error Couldn't find project [dependency] in reactor; make sure you specified the correct group:artifactId).
I'm using maven 3.3.1.

A:
Is a parent directive in a pom definitely preventing a project from being used as a maven module

No. In the end a parent is simply used to inherit stuff and it can refer to any parent. In a multimodule project parents and children point to each other (child refers to a parent, parent defines child as a module).
On the other hand: you might wonder why it is a problem that any project is used as a module. The writer of the aggregator pom probably had a reason for it.

Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored?

It shouldn't be ignored, it must be set correctly, i.e. use <relativePath></relativePath> (empty String) in the parent.


Q: SQL Server queries xls file worked yesterday(I swear), now refuses to. 0.o Hey all, the following select statement used to correctly query an Excel spreadsheet on a 64bit SQL Server 2008 R2, and now provides me with an error.
SELECT
     MPNCode, Supplier, Stock , Price, Manufacturer, [Description]
FROM
     OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0 Xml;Database=C:\inetpub\wwwroot\nCompass\Products\Import\SupplierProducts.xls;HDR=YES',
                'SELECT * FROM [Sheet1$]') WHERE MPNCode IS NOT NULL

The error I get is.

OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked
  server "(null)" returned message
  "Unspecified error".
  Msg 7303, Level 16, State 1, Line 1
  Cannot initialize the data source object of OLE DB provider
  "Microsoft.ACE.OLEDB.12.0" for linked
  server "(null)".

I've tried restarting everything and googled the thing to death - somehow something has happened that is preventing this from working.
The file-path/file-name is correct because when I change the path I get a different error message.
Ad-hoc connections are enabled from the surface manager - after this I'm stumped at what the issue could be.
Any help will be very much appreciated.

A: Is the linked spreadsheet opened on the desktop?  What happens if you create a new sheet in the same folder and try to open it instead?

A: I think SQL Server needs to access to TEMP folders to copy or create some files.
If the folder does not exist or ther SQL Service account does not have enough permission to access the folders, you'll get the exception.
Run Procmon.exe on the server and execute the query again. You can see what's happening and where the SQL Server wants to access.


Q: package ‘RMySQL’ is available as a source package but not as a binary I am receiving the above error when I try to install this package. Reading this question install RMySQL for Mac I read the install guide.
Here's what is said:
During installation, RMySQL looks for the MySQL headers and libraries
in the system directories.  If these are not installed in system-wide
directories (or if you want to use an alternate MySQL distribution),
you may specify which MySQL directory(ies) to use through one of the
following:

   1. The shell variables PKG_CPPFLAGS and PKG_LIBS (using Bourne shell)

       export PKG_CPPFLAGS="-I<include-dir>"
       export PKG_LIBS="-L<library-dir> -lmysqlclient"

       For instance, on some 64 systems (e.g., Linux) you may need to set

       export PKG_CPPFALGS="-I/usr/include/mysql"
       export PKG_LIBS="-L/usr/lib64/mysql -lmysqlclient"

I have browsed my computer, I don't believe that those directories exist.
I have installed XAMPP previously on my Mac and wondered if the directories needed are in there somewhere since XAMPP uses MySQL?
Can I just download the directories somewhere?
How can I find if they are already on my computer?
export PKG_CPPFALGS="-I/usr/include/mysql"
export PKG_LIBS="-L/usr/lib64/mysql -lmysqlclient"

I'm at a loss for what to do next?

A: If you don't mind installing another MySQL server via Homebrew, I have posted the complete solution in another thread: Installing RMySQL in mavericks

But in your case, I do find those directories in XAMPP that contain the same necessary MySQL header and library files as those installed via Homebrew.
So you can set the environment variables and build in the Terminal way:
% export PKG_CPPFALGS="-I/Applications/XAMPP/xamppfiles/include"
% export PKG_LIBS="-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient"
## RMySQL_x.x-x.tar is the source package you have manually downloaded
% R CMD INSTALL RMySQL_x.x-x.tar

or in the RStudio way:
> Sys.setenv(PKG_CPPFLAGS = "-I/Applications/XAMPP/xamppfiles/include")
> Sys.setenv(PKG_LIBS = "-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient")
## It will automatically download the source package in the remote repo
> install.packages("RMySQL", type = "source")


Q: How to chain api calls with AngularJS I'm new to angualrJS and web development in general. I have a controller named FavoritesCtrl that makes an api call and returns an object.
My controller looks like this:
controllers.controller('FavoritesCtrl', function($scope, $http) {
  $http.jsonp('https://api...=JSON_CALLBACK').then(function (scooby){
    $scope.list=scooby.data;
  });
});

I access the returned data in my html with this:

product_id: {{ favorite.product_id }}

I need to send that {{ favorite.product.id  }} back as a parameter in another api call so I can generate an affiliate link, but I don't know the most angular way to do it.
Should I attempt to send the second call in the FavoritesCtrl or would it make sense to put it in a new controller?
I can get the proper affiliate link back with something like this:
controllers.controller('FavoritesCtrl', function($scope, $http) {
  $http.jsonp('https://api...=JSON_CALLBACK').then(function (scooby){
    $scope.list=scooby.data;

    var length = scooby.data.favorites.length;
    var i;

    for (i=0;i<length;i+=1){
      var getProductId = scooby.data.favorites[i].product_id;
      $http.jsonp('https://api...+getProductId+'&callback=JSON_CALLBACK').then(function (fred){
      console.log(fred.data.link);
    });
  });
});

But I can't figure out a good way to display this on my page with the associated item. Any suggestions will be greatly appreciated.
Thank You!

A: You're on the right track.  I think in your for loop in the controller, just put $scope.list.favorites[i].affiliateLink = [whatever the returned value of the specific affiliate link should be];
Then in the HTML, it would just interpolate as {{favorite.affiliateLink}}

A: You probably want to use ng-click and this will call another method in your controller:

{{favorite.product_id}}

in your controller :
$scope.doSomething = function (prodId) {
  // Do whatever you want here
};

A: You can accomplish this in a more elegant way using a tool that you already have - promises. Promises are there to help you chain events like this.
A simple example would be:
get('story.json').then(function(response) {
  return JSON.parse(response);
}).then(function(response) {
  console.log("Yey JSON!", response);
});

A very good introduction to promises can be found here [1].
[1] http://www.html5rocks.com/en/tutorials/es6/promises/