text:
Q: Heroku: deploy Spray based service I have a simple Scala project, that has several maven modules. It looks something like this:
Parent project
|- service1
|- service2
|-...
|- serviceN
 |- Procfile
 |- ...
 |- pom.xml

I was trying to deploy serviceN to heroku (right now, serviceN only, without the other services). In that service's directory, I have executed the following commands:
heroku create serviceN
git push heroku master

ServiceN is a Spray.io project, I'm trying to expose my web services on interface=0.0.0.0 and port=8080 (seen it on some example project).
When the push finishes, the we interface gives me :
An error occurred in the application and your page could not be served. Please try again in a few moments.

when I run heroku ps, there is no output. When I run heroku scale web=1 I get the error:
Scaling dynos... failed
 !    Couldn't find that formation.

My Procfile (no extension, capital P at the beginning) looks like this (I build with maven, so my app is recognized as a Java app):
web: java $JAVA_OPTS -cp target/serviceN.jar com.service.ObjectWithMain

When I look into the logs, I see this:
2015-11-22T20:11:11.886773+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="MY_WS_ENDPOINT" host=serviceN.herokuapp.com request_id=71fad213-66d5-4186-a9fd-20ef505908e9 fwd="91.104.133.218" dyno= connect= service= status=503 bytes=
2015-11-22T20:11:12.217106+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=static-data-service.herokuapp.com request_id=cabd051a-1e37-4edd-841b-4a0eb875baf6 fwd="91.104.133.218" dyno= connect= service= status=503 bytes=

Please hep me find out what I missed.

A: The Procfile must exist in the root directory of the Git repo. The commands in the Procfile must also be relative to the root dir (which will be the current working dir when heroku runs it).


text:
Q: Setup a MYSQL database on a Windows VPS for connecting outside network I have a question about configuring or setting up a MySQL database for connecting outside my Windows VPS.
How do I need to configure my VPS for it and how do I need to configure the MySQL database?
Thanks in advance for your reply!

A: If you are looking to connect to a MySQL server that is located on a VPS or other type of dedicated server then you most likely need to open the ports on the server.
The default MySQL port is 3306 and a guide to opening ports on a server can be found here: https://www.solvps.com/blog/how-to-open-ports-on-windows-server-vps-or-dedicated-server/

A: To access MySQL databases outside your Windows VPS, you'll need to allow Remote Connection to MySQL Server. Probably, this tutorial should help you.
https://manage.accuwebhosting.com/knowledgebase/2200/How-to-Allow-Remote-Connection-to-MySQL-Server-in-Windows.html
Once MySQL server is configured for Remote Connections, open MySQL port 3306 from Windows firewall.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mocha и Sinon. Как сделать идемпотентные тесты, без памяти состояния? Имею папку tests, в которой лежит чуть более 10 файлов с тестами.
Запускаю файлы по отдельности - все работает.
Когда запускаю как mocha * или mocha file1.js file2.js получаю ошибку.
Ошибка связана с тем, что у меня один экземпляр сервиса для базы данных, на который я ставлю заглушки.
Пример:
File1:
sinon.stub(database.__proto__, "findAll").returns(1);

File2:
sinon.stub(database.__proto__, "findAll").returns(2);

Как сделать их идемпотентными? Убрать эту "память" между тестами.

A: Решил используя флаг mocha --parallel


text:
Q: Converting object to float loses too much precision - pandas I'm trying to plot a DataFrame using pandas but it's not working (see this similar thread for details).  I think part of the problem might be that my DataFrame seems to be made of objects:
>>> df.dtypes
Field          object
Moment         object
Temperature    object

However, if I were to convert all the values to type float, I lose a lot of precision.  All the values in column Moment are of the form -132.2036E-06 and converting to float with df1 = df.astype(float) changes it to -0.000132.
Anyone know how I can preserve the precision?

A: You can do this to change the displayed precision
In [1]: df = DataFrame(np.random.randn(5,2))

In [2]: df
Out[2]:
          0         1
0  0.943371  0.171686
1  1.508525  0.005589
2 -0.764565  0.259490
3 -1.059662 -0.837602
4  0.561804 -0.592487

[5 rows x 2 columns]

In [3]: pd.set_option('display.precision',12)

In [4]: df
Out[4]:
               0              1
0  0.94337126946  0.17168604324
1  1.50852519105  0.00558907755
2 -0.76456509501  0.25948965731
3 -1.05966206139 -0.83760201886
4  0.56180449801 -0.59248656304

[5 rows x 2 columns]


text:
Q: Wordpress ... Forcing 3rd party plugins to use a theme font styling css? It seems to me that there should be Wordpress plugin or hack that forces 3rd party plugins to inherit css font styling values such as font-family, weight, color, line-height etc other than re-writing values to a child theme.
It is such a chore to dig through plugin css and js files Anyone know of anything that does this?

A: For the css you could try using the css editor in the Jetpack plugin.
If a plugin has a div with text called "textdiv" then you can enter
#textdiv{
color:#000}

etc into the jetpack css editor and it will override the plugins theme.


text:
Q: How can I have two view layouts to switch between? (Swift) So I have this timer app that I am developing, and there is a setting in it to change from minutes:seconds to hours:minutes:seconds. This means that I need to adjust the UI of the app once the setting is changed. Considering I have constraints on the UI already, how could I do this?
When it is set to minutes:seconds, it displays this:
minutes:seconds
and then when it is set to hours:minutes:seconds, I want the UI to look like this: hours:minutes:seconds
Basically I would like to know the most efficient way to change the UI of the app when an action occurs. Thank you so much in advance!

A: Create two custom classes -
MinutesView
HoursView

Both will be inheriting from UIView. For each ofttimes classes you need their content which is their subviews. You can do that either programatically or via XIBs. It  doesn't really matter.
Inside these subclasses implement the layout with two or three subviews.
Both classes will also have a time variable. Implement a property observer on both. Once a new time is set, update the labels that represent time digits.
Once you have both working. Put them both into your main scene, lay them out however you wish.
The only thing you will have to do when switching between two modes is set the .hidden property on both. Obviously when one is hidden the other one is not and vice versa.


text:
Q: how can I use jpcap library in my project? I am using Netbeans 7, and I have 32 bit JDK version 1.7.0.40. I want to use jpcap library to analyze incoming packets.
I do following to be able to use jpcap.
I added "jpcap.jar" into my project's library.
I copied "jpcap.dll" into my JRE/bin
I copied "jpcap.jar" into my JDK/jre/lib/ext
I copied "jpcap.jar" into my JRE/lib/ext

However, I  get the exception below:
Exception in thread "main" java.lang.UnsatisfiedLinkError: jpcap.JpcapCaptor.getDeviceList()[Ljpcap/NetworkInterface;
at jpcap.JpcapCaptor.getDeviceList(Native Method)
at src.JpcapAnalyzer.<init>(JpcapAnalyzer.java:19)
at src.Main.main(Main.java:31)

Java Result: 1
I appreciate for any recommendations.
Edit :
After 2 weeks posting this question, I received no answers. Then I want to share my experience with the community.
I tried another library,jnetpcap, which can be downloaded at https://sourceforge.net/projects/jnetpcap/. I easily implemented it. You can use this library both in 32 bit and 64 bit OS and JDK.


text:
Q: In Wordpress how to add a body class to all interior pages except the homepage I want to add a class to the body tag to all pages EXCEPT the homepage. Right now I have.
<?php body_class('interior'); ?>

But it adds 'interior' to ALL pages including the home page.
What is the best standard way of adding a class to the body tag to all interior pages except the 'home page'?

A: http://codex.wordpress.org/Function_Reference/is_home
<?php if (!is_home()) body_class('interior'); ?>

Unless you mean http://codex.wordpress.org/Function_Reference/is_front_page
<?php if (!is_front_page()) body_class('interior'); ?>

A: I think the best solution is write:
<body <?php if (!is_front_page()) body_class('interior'); ?> <?php body_class(); ?>>

In this way you add only class="interior" in all page except the front page, and you can save the class in the front page, otherwise in you use only the fist php code in the tag <body> in home you will not have class.


text:
Q: Working of 64 bit drivers I'm not a programmer, but learning some programming concepts.
My question is, on 32 and 64 bit systems, the HAL layer will be different as they are two different platform, how does the driver interact with HAL layer and in turn with CPU?
If we take an example of LAN driver, can anybody explain in high level what exactly happens in two different platform that is 32 and 64?
Any pointer will be great help...
Thanks,
Pramod.

A: You re-compile the drivers for each platform.   The APIs are the same but the code generated by the compiler will be different.


text:
Q: How to avoid the IF ELSE statements I have the following code, which does not look very nice. What methods could I use to make it look better?
Imagine that there are a lot of IF ELSE statements. As an example, I would like to distinguish whether the left is smaller or larger than the right. And more distances are added.
(It's about a robot that is supposed to detect obstacles in front of it.)
distance1 = left_LOX.distance();
distance2 = middle_LOX.distance();
distance3 = right_LOX.distance();

if (distance1 < 100 || distance2 < 100 || distance3 < 100)
  distance_case = 1;
else if (distance1 < 300 || distance2 < 300 || distance3 < 300)
  distance_case = 2;
else
  distance_case = 3;

// Abfragen für die Automatik
switch (distance_case)
{
case 1:
  target = 0;
  robot.Stop();
  delay(2000);
  break;
case 2:
  target = 4000;
  robot.Forward();
  break;
case 3:
  target = 6000;
  robot.Forward();
  break;
}

An idea on how to make it better would be nice.

A: you can use if ... else if ... else block directly if the distance_case does not have long term use. It unnecessarily introduces new variables which has no purpose. Or define an enum if you see, in long term, there will many such cases. Reader can also quickly make sense of the values.

A: If you have a lot of distances (hundreds, thousand), it's easier to group all the distances together in a container such as vector first, and then use standard algorithms.  E.g. something like this:
This is assuming you have the C++ std library available on the esp32 platform/compiler you are using - it should be possible at least up to C++11 - see e.g. https://medium.com/geekculture/modern-c-with-esp32-dcd3918dd978.
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    // Just an example vector initialisation - replace this with the required x_Lox.distance() calls.
    std::vector<int> distances = {300, 500, 500, 200, 100 };
    const auto min = *std::min_element(distances.begin(), distances.end());

    std::cout << "Min distance: " << min;

    return 0;
}

Once you have the minimum distance, you can run through the various cases for handling.  This is based on the assumption that you are only interested in the shortest distance to choose your robot's action.  If you have more complex logic, the code also gets more complex.

A: You can add if it looks better for you.
distance_case = (distance1 < 100 || distance2 < 100 || distance3 < 100) +
                (distance1 < 300 || distance2 < 300 || distance3 < 300) +
                (distance1 >= 300 || distance2 >= 300 || distance3 >= 300);


text:
Q: Fixing CA2122 with Process.Start In an application we can output a report as a csv file and load it up similar to the following code:
Process.Start("C:\MyReport.csv") ' Not real path

When running code analysis it produces the following error:

CA2122 Do not indirectly expose methods with link demands 'Form.Function(Definition)' calls into 'Process.Start(String)' which has a LinkDemand. By making this call, 'Process.Start(String)' is indirectly exposed to user code

I have seen somewhere to mark the assembly with the SecurityTransparentAttribute, does this just suppress the message? If so this is not what I would like. Is there another way of opening the file that would circumvent this message without suppressing it? I would ideally like to avoid Excel automation if I can as Excel is not used anywhere else at the moment.
Ideas?

A: I stumbled upon the same issue today and thought the following answer would be useful for others so thought to write it.
So basically, my code was to open up a given directory path in explorer, as shown below
public static void OpenDirectoryPath(string directoryPath)
{
    if (Directory.Exists(directoryPath))
    {
        Process.Start(directoryPath);
    }
}

The above code produced the following error

CA2122 : Microsoft.Security : 'Helper.OpenDirectoryPath(string)' calls into 'Process.Start(string)' which has a LinkDemand. By making this call, 'Process.Start(string)' is indirectly exposed to user code. Review the following call stack that might expose a way to circumvent security protection:

The question to ask is, do you really want this method to be public. In my case, the answer was "No". Changing the method to internal resolved the problem.
internal static void OpenDirectoryPath(string directoryPath)
{
    if (Directory.Exists(directoryPath))
    {
        Process.Start(directoryPath);
    }
}

A: Process.Start() is having [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust", Unrestricted = false)] attribute.
All the functions in the hierarchy must have this attribute set.
Example
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust", Unrestricted = false)]
Method1()
{
    Process.Start(...);
}

[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust", Unrestricted = false)]
Method2()
{
    Method1();
}

[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust", Unrestricted = false)]
Method3()
{
    Method2();
}

[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust", Unrestricted = false)]
Method4()
{
    Method3();
}

...
...

This fixes this issue. I did not test the security violation scenario, but I hope this must solve the issue.

A: You may do not care about it at all (suppress the message locally) or in global suppression. It depends on your security policy/requests.
What is means is:
Process.Start has some security attributes applied but it has specified that the check should be done only for it and for its caller (SecurityAction.LinkDemand). This implies that if you call it in a public method the code that use your method will skip this security check. Your code may be trusted to call Process.Start but their code not but if they call your method they'll gain that privilege.
If you need to fix this you may apply the same security attributes to your code, this will require your caller to have that privileges (SecurityAction.LinkDemand doesn't walk the full stack so it's faster).


text:
Q: Error: NoCredentialProviders: no valid providers in chain. Deprecated. error with dehydrated tool I am trying to update certs on my servers with dehydrated and dehydrated-route53-hook-script.
Here is the complete command and error:
./xsys renewcerts
Running: cd certificates && ./dehydrated --cron
# INFO: Using main config file ..config/certificates/config
Processing mydomain.org with alternative names: dev-mydomain.org
 + Checking domain name(s) of existing cert... unchanged.
 + Checking expire date of existing cert...
 + Valid till Apr 21 11:47:17 2019 GMT (Less than 30 days). Renewing!
 + Signing domains...
 + Generating private key...
 + Generating signing request...
 + Requesting new certificate order from CA...
 + Received 2 authorizations URLs from the CA
 + Handling authorization for dev-mydomain.org
 + Handling authorization for mydomain.org
 + 2 pending challenge(s)
 + Deploying challenge tokens...
Error: NoCredentialProviders: no valid providers in chain. Deprecated.
    For verbose messaging see aws.Config.CredentialsChainVerboseErrors
Could not find zone for dev-mydomain.org
Running: cd certificates && ./dehydrated --cleanup

Looks like the aws credentials are failing, but from everything I can tell those are OK. I last ran this ~60 days ago and it ran fine then and (as far as I know) nothing has changed.
Any ideas on where to look for a fix is appreciated.
Update
I found that this command is failing:
$cli53 list
Error: NoCredentialProviders: no valid providers in chain. Deprecated.
    For verbose messaging see aws.Config.CredentialsChainVerboseErrors

So the root issue seems to be cli53. I have credentials in  ~/.aws/credentials per docs.

A: This ended up being an issue with cli53. I had a symlink as follows...
ls -la .aws/
total 0
drwxr-xr-x    3 myuser  staff    96 Apr  5 15:33 .
drwxr-xr-x+ 143 myuser  staff  4576 Apr  8 12:30 ..
lrwxr-xr-x    1 myuser  staff    69 Apr  5 15:33 credentials -> /Users/myuser/ansible/myapp/_secrets/aws_credentials

...but I had recently changed this path to:
/Users/myuser/apps/myapp/_secrets/aws_credentials so it was simply a failure of cli53 being able to find the appropriate credentials.


text:
Q: Close main form when other form open How can i hide main form and open the second one.
      If My.Computer.Registry.GetValue("HKEY_CURRENT_USER\tFull", "tFull", Nothing) Is Nothing Then
        Me.Show()
    Else
        FrmPocetak.Show()
        Me.Hide()
    End If

It won't close the main form but it opens the FrmPocetak :( :(


text:
Q: How to post JSON but get XML response using Retrofit? I have a particular webservice that expects a JSON as post, and will spit back an XML. I'm using Retrofit for all my network calls. Here is how I set the Retrofit adapter with the XML converter:
mRestAdapter = new RestAdapter.Builder()
                    .setEndpoint(getBaseUrl())
                    .setConverter(new SimpleXMLConverter())
                    .build();

As you can see, I'm not using the Gson converter. How can I manage to post any JSON? Thanks!

A: Create custom Converter. That will use different converters for serialization and deserialization.
public class MixedConverter implements Converter {
      private Converter mSerializer;
      private Converter mDeserializer;

    public MixedConverter(Converter serializer, Converter deserializer) {
        mSerializer = serializer;
        mDeserializer = deserializer;
    }

    @Override
    public Object fromBody(TypedInput body, Type type) throws ConversionException {
        return mDeserializer.fromBody(body, type);
    }

    @Override
    public TypedOutput toBody(Object object) {
        return mSerializer.toBody(object);
    }
}

Usage:
.setConverter(new MixedConverter(new SimpleXMLConverter(), new GsonConverter(gson)));


text:
Q: .datepicker calendar selection not working 100% of the time This code seems to work normally except when a user selects a new date from the #startdate input field it only updates the #enddate field the first 2 times and on the 3rd it does nothing, not sure what exactly is causing the problem... if anyone would be able to spot the issue
I use the following imports, well thats what it says at the top of each one when I open them in notepad++
jquery-ui.css v1.11.2
jquery.js v1.10.2
jquery-ui.js v1.11.2
$(document).ready(function () {
    $("#enddate").datepicker({
        dateFormat: "dd-M-yy",
        onSelect: function (date){
            var dateliveend = $("#enddate").val();
            $('#dateliveend').html(dateliveend);
        }
    });

    $("#startdate").datepicker({
        dateFormat: "dd-M-yy",
        minDate: 0,
        maxDate: 365,
        onSelect: function (date) {
            var enddate = $('#startdate').datepicker('getDate');
            var startdate = $('#startdate').datepicker('getDate');

            startdate.setDate(startdate.getDate());
            enddate.setDate(enddate.getDate() + 28);
            $('#enddate').datepicker('setDate', enddate);

            $('#enddate').datepicker('option', 'maxDate', enddate);
            $('#enddate').datepicker('option', 'minDate', startdate);
        }
    });
});

    <input type="text" id="startdate" name="startdate"
           value=" <?php echo date('d-M-Y', strtotime('+0 day') + 36000); ?>" readonly />

    <input type="text" id="enddate" name="deadline"
           value=" <?php echo date('d-M-Y', strtotime('+28 day')  +36000); ?>" readonly />

I made a fiddle http://jsfiddle.net/RzD5Z/25/ which shows you the odd behaviour i'm experiencing

A: $('#enddate').datepicker({
    dateFormat: "dd-M-yy",
    minDate: 0,
    defaultDate: "+28d",
    maxDate: "+28d",

        });
$("#startdate").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 0,
    maxDate: 365,
    onClose: function () {

        var enddate = $('#startdate').datepicker('getDate');
        var startdate = new Date(enddate);

        enddate.setDate(enddate.getDate()+28);

        $('#enddate').datepicker('destroy');
        $('#enddate').datepicker();
        $('#enddate').datepicker('setDate', enddate);

$('#enddate').datepicker('option', {
                                    dateFormat: "dd-M-yy",
                                    minDate: startdate,
                                    maxDate: enddate
                                    });

    }
});

HTML
<input type="text" id="startdate" readonly />

<input type="text" id="enddate" readonly />

Here's the solution, I believe .datepicker had an issue with the initialisation so I destroy it before re-intialising. See fiddle - works great http://jsfiddle.net/RzD5Z/33/


text:
Q: GridView - Set focus to specific cell I've seen lots of posts out there for this question, however, they all suggest we use methods like:  dgv.CurrentCell   or  dgv.Rows[row].Cells[cellno].Selected.  Intellisense finds no such methods.  I have a textbox in a gridview, where I use the OnTextChanged method.  Then, in my C# code, I update this quantity, then the grid refreshes automatically, and goes back to the top row, even though we've scrolled down a couple of pages.  I've also tried putting in the MaintainScrollPositionOnPostback="true" in the 'Page' section of my .aspx page and that didn't seem to do anything.  We're on .Net Framework 4.0.
<asp:GridView ID="gvOrderDetails" runat="server" AlternatingRowStyle-BackColor="#FAFAFA" Width="940px" AutoGenerateColumns="False" AllowSorting="True" OnSorting="SortOrderDetails"
OnRowCommand="gvOrderDetails_RowCommand" EmptyDataText="No Data to Display"
DataKeyNames="STOREORDNUM" HeaderStyle-Height="22px"
onselectedindexchanged="gvOrderDetails_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" /><EditRowStyle BackColor="#2461BF"/>
<FooterStyle BackColor="LightGray" Font-Bold="False" ForeColor="Black" />
<HeaderStyle BackColor="LightGray" Font-Bold="False" ForeColor="Black" BorderWidth="1px" BorderColor="Gray"/><PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB"  Height="22px"/>
<Columns>
     <asp:BoundField DataField="ITMCD" HeaderText="Item Code" SortExpression="ItemCode" >
     </asp:BoundField>
     ....
     <asp:TemplateField HeaderText="Order Qty" SortExpression="OrderQty" >
         <ItemTemplate>
            <asp:TextBox ID="OrderQty" runat="server" Width="36" MaxLength="5" class="numberinput" AutoPostBack="true" OnTextChanged="buttonUpdateQty_Click" Text='<%# Bind("ORDERQTY") %>' ></asp:TextBox>
         </ItemTemplate>
     </asp:TemplateField>
  </Columns>
 </asp:GridView>

In the code behind, I've tried these two things:
gvOrderDetails.Rows[row.RowIndex].FindControl("OrderQty").Focus();
gvOrderDetails.Rows[row.RowIndex].Cells[7].Controls[0].Focus();

A: You need to cast the required cotrol cell into Textbox control and then call the Focus() method on it.
Try This:
TextBox txtOrderQty = (TextBox) gvOrderDetails.Rows[row.RowIndex].FindControl("OrderQty");
txtOrderQty.Focus();

A: Add a handler to SelectedindexChange Event of your grid view
Gridview1.SelectedRow.Focus();


text:
Q: Conditional day distribution probability Let $X$ be a random day of the week, coded so that Monday is 1, Tuesday is 2,
etc. (so $X$ takes values 1, 2,..., 7, with equal probabilities). Let $Y$ be the next day after $X$ (again represented as an integer between 1 and 7). Do $X$ and $Y$ have the same distribution? What is $P(X < Y )$?

A: They should have the same distribution
$P(X<Y) = P(X \not= 7) = \dfrac{6}{7}$

A: Well, you have:
$$\begin{align}
P(X=x) = & \begin{cases} 1/7 & : x\in \{1,2,3,4,5,6,7\} \\ 0 & : \text{else}\end{cases}
\\[2ex]
P(Y=y) = & \begin{cases} P(X=y-1) & : y\in\{2,3,4,5,6,7\} \\ P(X=7) & : y=1 \\ 0 & : \text{else}\end{cases}
\\[1ex] = & \begin{cases} 1/7 & : y\in \{1,2,3,4,5,6,7\} \\ 0 & : \text{else}\end{cases}\end{align}$$
So now, do these look like the same distribution? (Y/N)

Also, notice that $X<Y$ except when $X=7$, then $Y=1$, so $P(X<Y) = \ldots$ ?


text:
Q: After Installation of Visual studio 2013 on Windows 8 After the completion of visual studio 2013 it is taking too much time after first restart. I don't know what to do.Its like just stuck on window screen

A: Please try disabling the "Hardware Graphics Acceleration" in Visual Studio. Please follow the below steps and check the outcome.
Tools > Options > Environment > General > deselect the "Automatically adjust visual experience based on client performance", "Use hardware graphics acceleration if available" and "Enable rich client visual experience" options.
Hope this helps.


text:
Q: iphone to ipad, iphone 4 uialertview problems So I've upgraded the code to the ipad (i.e. converted to a universal app). However, the UIAlertview rendering seems to be off for IOS4. Instead of being positioned in the middle, it jumps up and is displayed on top, with half the box cut off. Same goes for landscape orientation.
It is my understanding that the UIalertview is always set in the middle? I looked through the code and I did not set up the frame/position anywhere in the code. This only happens for 4.0, on both the iphone 4 and the itouch running 4.0. Every other version is fine, including the ipad. Any thoughts?
Thanks.

A: Seems to be a bug. I also had the Problem on iPad with iOS 3.2.
Solution:
a) Check your app state:
In iOS 4 just use
[UIApplication sharedApplication].applicationState

Older iOS: Store your app state manually:
-(void)applicationWillResignActive:(UIApplication *)application
{
    self.appIsInBackground = YES;
}

-(void)applicationWillTerminate:(UIApplication *)application
{
    self.appIsInBackground = YES;
}

-(void)applicationDidBecomeActive:(UIApplication *)application
{
    // Open your UIAlert here if self.appIsInBackground == YES;

    self.appIsInBackground = NO;
}

b) open the UIAlert after the app did become active, as shown above in the comments.

A: Does your alert have any Textfields added ?
Because in 4.0+ iOS scrolls the alertview to visible part if you have a textfield in the alertview.

A: I have the same problem for iPad 3.2 when application resign active and in that time alert is shown that alert will be shown on top left corner. So i fixed using following code in the method -(void)applicationDidBecomeActive:(UIApplication *)application
//Check that key window is alert view
if ([[[UIApplication sharedApplication].keyWindow description] hasPrefix:@"<_UIAlertOverlayWindow"]) {
    //Yes then check for subviews tht are alertViews
    UIWindow *alertViewWindow = [UIApplication sharedApplication].keyWindow;
    NSArray *subViews = [alertViewWindow subviews];
    for (UIView *subview in subViews)
    {
        if ([subview isKindOfClass:[UIAlertView class]])
        {
            //Retain it
            UIAlertView *alertView = (UIAlertView *)[subview retain];
            //Now dismiss it and then show it again
            [alertView dismissWithClickedButtonIndex:0 animated:NO];//Here ClickedButtonIndex must be according to cancel button
            //Show the alert view again
            [alertView show];
            //Release previsous retained object
            [alertView release];

        }
    }
}


text:
Q: Xamarin.Forms How to disable Back Button In Nav Bar I am using Xamairn.Forms, How I can Disable Back Button In Navigation Bar when
ViewList Is Refreshing.
Actually, I am using the following code to disable Default Back Button, but right now I am trying to find away also to disable Navigation Bar back button
 protected override bool OnBackButtonPressed()
   {
     if (ListView.IsRefreshing)
         return true;
      return false;
   }

Any Idea how I Can Disable Back Button In Navigation bar?

A: Overall Android and iOS do not have normal APIs to prevent a navigation bar back button from being executed for one very good reason, the user expects to be able to go back and you should not prevent them from doing so.
You should instead change your design by only giving the user the options you want them to be able to make or hide the navigation bar entirely and create your own bar with your own buttons.
Adam's guide provides a great over view of the subject which I wish I would have found when faced with this issue.
He suggest the same things I just did but also provides VERY hacky ways to prevent navigating back if you refuse to change your design (code below is lifted mostly unchanged from the article linked above):
On Android you can attempt to find the back button and use the ContentPage's ViewModel method to find out if going back should be allowed or not. You would overwrite OnOptionsItemSelected within MainActivity:
public override bool OnOptionsItemSelected(IMenuItem item) {
    var app = Application.Current;

    if (item.ItemId == 16908332) { // This makes me feel dirty.
        var navPage = ((app.MainPage.Navigation.ModalStack[0] as MasterDetailPage).Detail as NavigationPage); // Notice this code assumes it is looking for a MasterDetailPage being shown as a modal

        if (app != null && navPage.Navigation.NavigationStack.Count > 0) {
            int index = navPage.Navigation.NavigationStack.Count - 1;

            var currentPage = navPage.Navigation.NavigationStack[index];

            var vm = currentPage.BindingContext as ViewModel; //You would want to cast this to a base ViewModel or a specific one so that OnBackButtonPressed() can be called

            if (vm != null) {
                var answer = vm.OnBackButtonPressed();
                if (answer) {
                    return true;
                }
            }
        }
    }

    return base.OnOptionsItemSelected(item);
}

On iOS you need a custom renderer to switch out the real back button for your own custom one:
[assembly: ExportRenderer(typeof(Page), typeof(CustomPageRenderer))]
namespace Mobile.iOS.CustomRenderer {
    public class CustomPageRenderer : PageRenderer {

        public override void ViewWillAppear(bool animated) {
            base.ViewWillAppear(animated);

            var page = Element as CorePage;

            if (page != null) {
                if ((page).OverrideBackButton) {
                    var root = this.NavigationController.TopViewController;
                    // NOTE: this doesn't look exactly right, you need to create an image to replicate the back arrow properly
                    root.NavigationItem.SetLeftBarButtonItem(new UIBarButtonItem("< Back", UIBarButtonItemStyle.Plain, (sender, args) => {
                        var navPage = page.Parent as NavigationPage;
                        var vm = page.BindingContext as ViewModel;

                        if (vm != null) {
                            var answer = vm.OnBackButtonPressed();

                            if (!answer)
                                navPage.PopAsync();
                        } else {
                            navPage.PopAsync();
                        }
                    }), true);
                }
            }
        }
    }
}

On Windows Phone... just override OnBackButtonPressed... working with WP is actually easy for once.

A: You can use the following code to disable the back button press in Xamarin Forms:
protected override bool OnBackButtonPressed()
{
    return false;
}

I hope it will help you.
Warning: This event is not raised on iOS. here

A: You can use this simple code to prevent user to navigate back
NOTE that you should have only one page
(root page) that the user can navigate back to it.
for example we have page named "Login", "Home" and "Cars" pages
and the root page is Login
=> inside Home page:
Home home= this;
Navigation.PushAsync(new Cars());
Navigation.RemovePage(home);

=> you should do this to the rest of the pages except root page!

A: Just do that. For me it works for Android
protected override bool OnBackButtonPressed(){
   return true;
}


text:
Q: What are the differences between the console version and PC release? This article on PC Gamers' website contains an interview with the lead designer for XCOM: Enemy Unknown, who speaks about there being differences such as higher resolution textures and a new user interface which displays "loads more data and allowing for a speed of interaction that changes how players approach tactical decisions" being available on the PC version in comparison to consoles.
Are there any other differences between the PC and console versions known at the moment, or any differences between individual console releases of the game?

A: There is still no definitive list, but there's a pretty comprehensive review here.
According to this guy,

*

*PC has better textures and allows to zoom in closer,

*PC loads faster,

*when playing with a mouse you have minor conveniences like hovering on top of aliens-in-view icons to see hit percentages (I'm playing with a mouse and I've never knew it).

*Important: multiplayer is not cross-platform, so you better follow your friends.

Reviewer explicitly states that he felt no tactical performance gain on any platform.
Tactical view grid should also be classified as a minor convenience - after some hours, you'll be easily telling distances at a glance.


text:
Q: How to get weights for PCA I am trying to find weights of PCA using skit-learn. However, none of the methods are working.
Codes:
import pandas as pd
import numpy as np
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
# load dataset into Pandas DataFrame
df = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])

from sklearn.preprocessing import StandardScaler
features = ['sepal length', 'sepal width', 'petal length', 'petal width']
# Separating out the features
x = df.loc[:, features].values
# Standardizing the features
x = StandardScaler().fit_transform(x)
from sklearn.decomposition import PCA
pca = PCA(n_components=1)
principalComponents = pca.fit_transform(x)

Finding weights
Method 1
weights = pca.components_*np.sqrt(pca.explained_variance_)
# recovering original data
pca_recovered = np.dot(weights, x)
### This output is not matching with PCA

Method 2
# Standardising the weights then recovering
weights1 = weights/np.sum(weights)
pca_recovered = np.dot(weights1, x)
### This output is not matching with PCA

Please help if I am doing anything wrong here. Or, something is missing in the package.

A: use
weight = pca.components_

but the output of
x.dot(pca.components_.T)

is different from
pca.fit_transform(x)

because pca output is standardized.
Use
tmp = x.dot(pca.components_.T)
tmp-tmp.mean(axis=0)

your will get the same output

A: Instead of
weights = pca.components_*np.sqrt(pca.explained_variance_)

If I use simply
weights = pca.components_

May be first time while I was trying, there was calculation error.


text:
Q: Sum row in Excel/Google Sheets based on Condition It seems like this question should exist somewhere, but I can't seem to find it...exactly.
The most similar solution I can find requires the use of SUMIFS or SUMIF, which only seems to add up numbers in a column, not spanning multiple columns. Here's an example sheet with 2 rows:
      A             B    C    D    E    F    G    H  ...
1     2015-01-01    0    1    6   12   45   12    5  ...
2     2016-01-01    256 43   13   35  134  135   12  ...

Now I'd like to have a cell somewhere that adds all of the cells in the row for 2015-01-01. My attempt looks like:
SUMIF(A1:A30,"2015-01-01", B1:BJ30)
But this only yields the sum of the column B, so 0 for the exact formula above or 256 if I were to do this for the year 2016.
When trying something with SUMIFS, I'm told that the criterion range's size should match the sum range size, which isn't the case because my criterion range is only the first column of dates.
How can I add all the values in a row if the first cell's date matches my criterion? It may be worthwhile to note that this is in Google Sheets, not Excel.

A: In both excel and googlesheets you can use a SUMPRODUCT, for example:
=SUMPRODUCT((A1:A30 = DATE(2015, 1, 1)) * B1:BJ30)

A: You can try either of these:
=if(A1=date(2015,1,1),sum(B1:F1),"")

=if(A1=A1,sum(B1:F1),"")


text:
Q: ASCII Vigenere cipher implementation in java This is about an assignment I got from my programming instructor.
We are to implement the vigenere cipher for all printable ASCII codes and run tests with it.
The vigenere cipher is a polyalphabetic cipher using multiple caesar ciphers with a shift of one. Also see Wikipedia
I implemented my vigenere as below, but the tests in my assignment do not produce the required output for my implementation.
I did a search, but it seems as if ASCII implementations of this are quite sparse.
Is there an obvious error in my code I'm not seeing?
public String encrypt(String plaintext) {

    String cipherText = "";
    for (int i = 0; i < plaintext.length();  i++) {
        char c = plaintext.charAt(i);

        // vigenere for the letters A-Z is defined as vigenere(m) = m[i] + k[i] % 26
        // where m[i] is the message and k[i] is the key.
        //
        // For ASCII support, as printable space starts at 32,
        // subtract 2*32 from the sum of keyChar and messageChar to get zero based.
        // Then calculate the modulo of this sum to be sure to stay in bounds.
        // Finally add 32 to the result of the modulo operation to place it in the 32 - 126 range.
        //
        // The key wrapping is implemented as i % _key.length() to restart
        // from the beginning if the end of the key is reached.
        cipherText += (char) ((c + _key.charAt(i % _key.length()) - 64) % 94 + 32);
    }

    return cipherText;
}

A: The only difference between your code and your comments is you're using % 94 when the range 32 to 126 includes 95 characters.
Changing your corresponding statement to use modulo 95, and breaking it up a bit:
int caesar = _key.charAt(i % _key.length()) - 32;
int sum = c - 32 + caesar;
cipherText += (char) (sum % 95 + 32);

Then your decryption algorithm can use all the same code, only replacing the second statement above with:
int sum = c - 32 + (95 - caesar);


text:
Q: How to get and use the the number of days since the last comment? How would I achieve this condition ...
    if lastest comment is < 7 days old
        echo 'New Comment';
    else ''

A: To get the latest comment use get_comments().
get_comment_date returns the date of a comment in any format for PHP's date().
Now it is easy. Let's put the logic into a function to keep the global namespace clean:
/**
 * Returns the number of days since the latest comment.
 *
 * @return int
 */
function get_days_since_last_comment( $post_id = 0 )
{
    $args = array (
            'number' => 1,
            'status' => 'approve'
        );
    0 !== $post_id and $args['post_id'] = (int) $post_id;
    // Array of comment objects.
    $latest_comment = get_comments( $args );

    // No comments found.
    if ( ! $latest_comment )
    {
        return -1;
    }

    $comment_unix = get_comment_date( 'U', $latest_comment[0]->comment_ID );
    return round( ( time() - $comment_unix ) / 86400 );
}

Add the function to your plugin or to your theme's functions.php.
To display a special message:
if ( get_days_since_last_comment() > 7 )
{
    print 'Looks like everything has been said.';
}

To get the days for a specific post (here ID 123) :
if ( get_days_since_last_comment( 123 ) > 7 )
{
    print 'Looks like everything has been said.';
}


text:
Q: ng-switch condition being evaluated every digest I have one of two directives being rendered as a result of a ng-switch condition.
Even though the condition rarely changes, the condition is being evaluated every digest.
Are there any idiomatic optimizations I can apply to avoid this check and improve performance?

A: I will suggest you two ways
First you can use one time binding this value won't change once it has been stabilized
e.g. :
One time binding: {{::name}}

Second way can be usage of debounce function i.e it will delay the digest cycle according to your requirement.
e.g
 <input ng-model="user.name" ng-model-options="{ debounce: 150 }" />

here time is given in milliseconds.
Other than this i don't think there is any direct way to solve this problem.


text:
Q: Sending mail using gmail and .net Getting the exception:

Failure sending mail.

While using System.Net.Mail.Smtp
in C#.NET on the line smtp.Send(message);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(sendto);
message.Subject = "CP1 Lab Password";
message.From = new System.Net.Mail.MailAddress("abc@gmail.com");
message.Body = mail_message;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");

smtp.Host = "smtp.gmail.com";
smtp.Port = 465; //(465 for SSL)587
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "mypassword");
smtp.Send(message);

Edit 1:
Here is the detail of the error:

A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond ...

The same error when using port 25.
Few months before this code used to work but today it is not working

A: As from your exception message (incomplete) and the code, it is very hard to say what went wrong in your case. Failure sending mail is thrown when the server is not found, port cannot be connected. It means that connection was not established, until now.
The exception message that gets raised if the connection was established but authentication was not performed correctly is, "The SMTP server requires an authenticated connection...". I would suggest that you check the PORT, SMTP server host (do not add http://) and then re-try. An SMTP connection (in most general cases) requires

*

*SMTP Server host: smtp.gmail.com is enough!

*PORT to connect at: I have always used default TCP port for SMTP, 25. It works.

*EnableSsl: most require it. I suggest you always use it. client.EnableSsl = true;

*Credentials are required by all: No server would allow bots sending emails. In this concern, if you create a new account. You may face trouble sending emails programmatically, I faced the problem with a new account not sending the emails whereas an old account (default account of mine) was sending the email without any trouble.

The following code template (if filled with accurate parameters) will definitely send the email, because I have tested and verified it bazillion times. :)
// You should use a using statement
using (SmtpClient client = new SmtpClient("<smtp-server-address>", 25))
{
   // Configure the client
   client.EnableSsl = true;
   client.Credentials = new NetworkCredential("<username>", "<password>");
   // client.UseDefaultCredentials = true;

   // A client has been created, now you need to create a MailMessage object
   MailMessage message = new MailMessage(
                            "from@example.com", // From field
                            "to@example.com", // Recipient field
                            "Hello", // Subject of the email message
                            "World!" // Email message body
                         );

   // Send the message
   client.Send(message);

   /*
    * Since I was using Console app, that is why I am able to use the Console
    * object, your framework would have different ones.
    * There is actually no need for these following lines, you can ignore them
    * if you want to. SMTP protocol would still send the email of yours. */

   // Print a notification message
   Console.WriteLine("Email has been sent.");
   // Just for the sake of pausing the application
   Console.Read();
}

Sending an email may be a headache sometimes, because it requires some basic understanding of networking also. I have written an article that covers sending emails in .NET framework and a few problems that beginners usually stumble upon such as this one. You may be interested in reading that article also.
http://www.codeproject.com/Articles/873250/Sending-emails-over-NET-framework-and-general-prob


text:
Q: jQuery не обрабатывает созданный элемент. Добрый день. Создаю Div с помощью jQuery:
$("#main").append("
Тест
");

Однако если вызвать функцию
 $('#one a').click(function() {
    alert('1');
 });

Алерт не срабатывает. Подскажите пожалуйста в чем ошибка?
A: Дело в том, что .click() навешывает обработчики только на существующие элементы DOM, чтобы навесить обработчик на тот элемент, которой возможно будет создан динамически, используйте .on() или ему подобные, делегирующие методы: .bind(), .delegate(), .live().
$("#one a").on("click", function(event){
    alert('1');
});

или
$(document).on("click", "#one a", function(event){
    alert('1');
});

A: Пример из вопроса не работает из-за синтаксической ошибки. Там неправильная
комбинация кавычек. Их нужно либо экранировать с помощью обратной косой черты
(\"), либо заменить на одинарные без ущерба для HTML.

$("#main").append("
Тест
");
$('#one a').click(function() {
    console.log('1');
});

В остальном код работоспособен. Вызов метода .click(c) абсолютно идентичен
вызову .on("click", c), и замена ни на что не влияет.
Если поменять последовательность создания тега со ссылкой и навешивание
обработчика щелчка, код, естественно, работать не будет т.к. $("#one a")
вернёт пустую коллекцию, и метод будет не к чему применять. Если логика работы
требует вначале создавать обработчик, а затем ссылки, можно его навешивать на
корневой элемент и перехватывать всплывающие события от ссылок,
отфильтровыывая их. Для такой фильтрации надо вызывать метод
.on("click", "#one a", c). Тогда каждое нажатие в пределах веб-страницы
будет обрабатываться, и если оно было по ссылке с родителем чей id="one",
вызовется c.
Подробности про обработку событий — в учебнике JavaScript, список методов
для обработки событий можно найти в документации jQuery.


text:
Q: List of Dictionaries Python3 lst = []

dct = {
    "key": "",
    "value": ""
}

for i in range(10):
    dct["key"] = i
    dct["value"] = i
    lst.append(dct)

lst
>>[{'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}, {'key': 9, 'value': 9}]

I am getting this output for this code. what is going on here! The output shouldn't be different? like
[{'key': 1, 'value': 1}, {'key': 2, 'value': 2}, {'key': 3, 'value': 3}]......

A: There is no need to create a dictionary like you did in the beginning. You could create dictionaries and append them to the list within the loop.
lst = []
for i in range(10):
    d = {'key':i+1, 'value':i+1}
    lst.append(d)
print(lst)

Output :
[{'key': 1, 'value': 1}, {'key': 2, 'value': 2}, {'key': 3, 'value': 3}, {'key': 4, 'value': 4}, {'key': 5, 'value': 5}, {'key': 6, 'value': 6}, {'key': 7, 'value': 7}, {'key': 8, 'value': 8}, {'key': 9, 'value': 9}, {'key': 10, 'value': 10}]


text:
Q: Mapper not initialized, When Use ProjectTo() I Use Automapper 5.2.0 In My Project. When I Use ProjectTo() In Code Get This Error:

Mapper not initialized. Call Initialize with Appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

Service Code
 public async Task<FreelancerProfileViewModel> GetFreelancerProfile()
    {
        var id = Guid.Parse(_identity.GetUserId());
        var model = await _freelancerProfiles
            .AsNoTracking()
            .Where(_ => _.User.Id == id)
            .ProjectTo<FreelancerProfileViewModel>()
            .FirstAsync();

     //  var viewmodel =  _mapper.Map<FreelancerProfileViewModel>(model);

        return model;
    }

Automapper Profile
   public class FreelancerDashbordProfile : Profile
{
    private readonly IIdentity _identity;
    public FreelancerDashbordProfile(IIdentity identity)
    {
        _identity = identity;
        var id = Guid.Parse(_identity.GetUserId());
        CreateMap<FreelancerProfile, FreelancerProfileViewModel>()
        .ForMember(_ => _.DoingProjectCount,
            __ => __.MapFrom(_ => _.Projects.Count(project => project.ProjectState == ProjectState.Doing)))

        .ForMember(_ => _.EndProjectCount,
            __ => __.MapFrom(_ => _.Projects.Count(project => project.ProjectState == ProjectState.End)))

        .ForMember(_ => _.ProjectCount, __ => __.MapFrom(_ => _.Projects.Count));

    }

}

Also I Use StructureMap For IoC
AutoMapperRegistery
   public AutoMapperRegistery()
    {

        this.Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.AssemblyContainingType<SkillProfile>(); // for other asms, if any.
            scan.WithDefaultConventions();

            scan.AddAllTypesOf<Profile>().NameBy(item => item.FullName);
        });

        this.For<MapperConfiguration>().Singleton().Use("MapperConfig", ctx =>
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMissingTypeMaps = true; // It will connect `Person` & `PersonViewModel` automatically.
                addAllCustomAutoMapperProfiles(ctx, cfg);
            });
            config.AssertConfigurationIsValid();

            return config;
        });

        this.For<IMapper>()
            .Singleton()
            .Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));

    }

I See Other Question and Issue but not solved my problem.

A: You need to pass the MappingConfiguration provider to the ProjectTo call.
public async Task<FreelancerProfileViewModel> GetFreelancerProfile()
{
    var id = Guid.Parse(_identity.GetUserId());
    var model = await _freelancerProfiles
        .AsNoTracking()
        .Where(_ => _.User.Id == id)
        .ProjectTo<FreelancerProfileViewModel>(_mapper.Configuration)
        .FirstAsync();

 //  var viewmodel =  _mapper.Map<FreelancerProfileViewModel>(model);

    return model;
}

A: In the .NET Core 3.1 (AutoMapper 9.0.0) new registration is:
services.AddAutoMapper(typeof(Startup));
In the .NET Core 2.1 (AutoMapper 7.0.1) version you have to pass the ConfigurationProvider.

*

*Register AutoMapper like described here

*Inject to the Controller:
private readonly IMapper  _mapper;
public SomeController(ApplicationDbContext dbContext, IMapper mapper)
{ _mapper = mapper; }

*Pass the ConfigurationProvider this way:
ApplicationDbContext.SomeEntities.ProjectTo(_mapper.ConfigurationProvider)


text:
Q: Avoid Terraform module to create duplicate resources? I have the following project structure to build Lambda functions on AWS using Terraform :
.
├── aws.tf
├── dev.tfvars
├── global_variables.tf -> ../shared/global_variables.tf
├── main.tf
├── module
│   ├── data_source.tf
│   ├── main.tf
│   ├── output.tf
│   ├── role.tf
│   ├── security_groups.tf
│   ├── sources
│   │   ├── function1.zip
│   │   └── function2.zip
│   └── variables.tf
└── vars.tf

In the .main.tf file i have this code that will create 2 different lambda functions :
module "function1" {
  source = "./module"

  function_name    = "function1"
  source_code      = "function1.zip"

  runtime          = "${var.runtime}"
  memory_size      = "${var.memory_size}"
  timeout          = "${var.timeout}"
  aws_region       = "${var.aws_region}"
  vpc_id           = "${var.vpc_id}"
}

module "function2" {
  source = "./module"

  function_name    = "function2"
  source_code      = "function2.zip"
  runtime          = "${var.runtime}"
  memory_size      = "${var.memory_size}"
  timeout          = "${var.timeout}"
  aws_region       = "${var.aws_region}"
  vpc_id           = "${var.vpc_id}"
}

The problem is that in deployment terraform create all resources twice. For Lambda it's Ok, that's the purpose, but for security groups and Roles that's not what i want.
For example this security group is create 2 times :
resource "aws_security_group" "lambda-sg" {
  vpc_id = "${data.aws_vpc.main_vpc.id}"
  name   = "sacem-${var.project}-sg-lambda-${var.function_name}-${var.environment}"

  egress {
    protocol    = "-1"
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    protocol        = "-1"
    from_port       = 0
    to_port         = 0
    cidr_blocks     = "${var.authorized_ip}"
  }
  # To solve dependcies error when updating the security groups
  lifecycle {
    create_before_destroy = true
    ignore_changes        = ["tags.DateTimeTag"]
  }

  tags = "${merge(var.resource_tagging, map("Name", "${var.project}-sg-lambda-${var.function_name}-${var.environment}"))}"

}

So that's clear that the problem is the structure of the project. Could you help to solve that ?
Thanks.

A: If you create the SecurityGroup within the module, it'll be created once per module inclusion.
I believe that some of the variable values for the sg name change when you include the module, right? Therefore, the sg name will be unique for both modules and can be created twice without errors.
If you'd choose a static name, Terraform would throw an error when trying to create the sg from module 2 as the resource already exists (as created by module 1).
You could thus define the sg resource outside of the module itself to create it only once.
You can then pass the id of the created sg as variable to the module inclusion and use it there for other resources.


text:
Q: Getting the wrong chinese string in search query result!! Magento 1 I have a store in chinese language. When I search for any product it works fine.
But when I sort the result page by sku, name or price it does not work. It seems that I've got the wrong url for sorting.
Please help me!!!! How can I get the proper string url for the sorting option?
Please see the screenshot!!

A: app/design/frontend/[Magento theme Folder]/template/catalog/product/list/toolbar.phtml
Goto: 82 Line or search getOrderUrl($_key, 'asc') ?>
from
<?php echo $this->__('Sort By') ?>
           <select onchange="setLocation(this.value)">
           <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
               <option value="<?php echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>
                   <?php echo $this->__($_order) ?>
               </option>
           <?php endforeach; ?>
           </select>

to
<?php echo $this->__('Sort By') ?>
           <select onchange="setLocation(this.value)">
           <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
               <option value="<?php echo urldecode($this->getOrderUrl($_key, 'asc')) ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>
                   <?php echo $this->__($_order) ?>
               </option>
           <?php endforeach; ?>
           </select>


text:
Q: javascript - new Date('1611065280155').getDate() returns NaN I am trying on the Google console.
new Date('1611065280155').getDate() which returns NaN and I was expecting 'yyyy/mm/dd' similar format.
How do I get the date from a milliseconds?
I was referring to https://www.codegrepper.com/code-examples/delphi/get+the+date+in+different+format+javascript but since there are many functions and got confused

A: You could use Date with a number as value for handing over epoch time.

console.log(new Date(1611065280155));


text:
Q: Operate on different kinds of Android widgets at once In my activity, the user performs a search, and there are ~10 filters for the search. Some of the filters are EditText and some filters are Spinner. I want to display a message if the user tries to perform an empty search(i.e search without any filters). For this I have this method:
 public boolean emptySearch(){

        if(!TextUtils.isEmpty(ticketID.getText().toString())){
            return false;
        }
        else if(productID.getSelectedItemId()!=0){
            return false;
        }
        else if(!TextUtils.isEmpty(desc_summary.getText().toString())){
            return false;
        }
        else if(severity.getSelectedItemId()!=0){
            return false;
        }
        else if(!TextUtils.isEmpty(customerID.getText().toString())){
            return false;
        }
        else if(!TextUtils.isEmpty(version_target.getText().toString())){
            return false;
        }
        else if(!TextUtils.isEmpty(created_by.getText().toString())){
            return false;
        }
        else if(!TextUtils.isEmpty(date_start.getText().toString())){
            return false;
        }
        else if(!TextUtils.isEmpty(date_end.getText().toString())){
            return false;
        }
        else
            return true;
    }

(The first option in the spinners is a default dummy option).
This code looks like a mess though, and I feel it is somewhat unnecessary.
I was wondering if it's possible to write some isViewEmpty method like:
 public boolean viewIsEmpty(EditText et){
        if(!TextUtils.isEmpty(et.getText().toString()))
            return false;
        else
            return true;
    }
 public boolean viewIsEmpty(Spinner sp){
        if(sp.getSelectedItemId()!=0)
            return false;
        else
            return true;
    }

And then store each of the views in an arraylist<View> and simply call viewIsEmpty() on each element of the Arraylist in a for(View v: views) loop. Then I could get rid of that huge cumbersome peice of code, but I am unclear how to proceed since I cannot call viewIsEmpty(v) on a View instead of a EditText or Spinner. How should I go about it?

A: You can create your own generic tester. you just have to write once the test for each type of View this tester can be really generic an you can use it every time you want to do the same kind of check.
public class ViewTester {

    private ArrayList<View> viewToTest;

    public ViewTester(){
        viewToTest = new ArrayList<View>();
    }

    public void add(View v){
        viewToTest.add(v);
    }

    public boolean isEmpty(){
        Iterator<View> it = viewToTest.iterator();
        while (it.hasNext()) {
            View v = (View) it.next();
            if(v instanceof EditText){
                String s = ((EditText)v).getText().toString();
                if(s != null && s.trim().length() > 0 )
                    return false;
            }else if(v instanceof Spinner){
                long i = ((Spinner)v).getSelectedItemId();
                if(i > 0)
                    return false;
            }else if(v instanceof DatePicker){
                // ...
            }
        }
        return true;
    }
}

Then in your activity you just have to register all view you want to test before checking their content
ViewTester tester = new ViewTester();
tester.add(ticketID);
tester.add(productID);
tester.add(desc_summary.getText());
//...

if(tester.isEmpty()){
    // Show message
}

Hope it helps...


text:
Q: Ajax concat post array This is my code:
var data = {};
data.uuid = uuid;
data.method = "addAddress";

//Other parameters
var par = {};
par.name = "test";
par.surname = "test";

data.concat(par); //doesn't work

var url = myURL;
var result = $.ajax({
    url: url,
    data: data,
    async: false
});

I want to merge two variables array. It is possible to merge this variables?

A: Variables data and par are objects and there is not concat method in Objects.. So you end up with a TypeError: "data.concat is not a function".
But you can merge the two Objects like this:

var data = {},
    par = {};

data.uuid = 1234;
data.method = 'addAddress';

par.name = 'test';
par.surname = 'test';

Object.keys(par).forEach(k => data[k] = par[k]);

console.log(data);

Note that properties of data that are also in par will be overwritten.

A: Check this code.
I have changed your var.surname = "test" code into par.surname = "test"

var data = {};
data.uuid = 1;
data.method = "addAddress";

var par = {};
par.name = "test";
par.surname = "test";

var obj = Object.assign({}, data, par);

console.log(obj);


text:
Q: Кривая кодировка в json_encode с русскими символами $json = array('name' => 'Руслан', 'last_name' => 'Садыхов');
return json_encode($json);

Возвращаются вместо имени и фамилии подобные символы: \u0420\u0443\u0441\u043b\u0430\u043d
Как это можно исправить?
A: Кириллица в json_encode

A: Не знаю на сколько старые посты, но может кому пригодится это : \u0420\u0443\u0441\u043b\u0430\u043d json кодировка, она должна быть такой, на jquery делаем var result= JSON.parse('\u0420\u0443\...'); получаем человекопонятный массив


text:
Q: Is there a way to turn a Button in GridView to a link text? The size of the button really kills the width of my GridView and so I am looking to just change the buttons into a link (like if you were to use AutoGenerateEditButton or AutoGenerateDeleteButton). Here's what I have:
<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="editButton" runat="server" CommandName="Edit"
            Text="Edit"  />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:Button ID="BtnUpdate" runat="server" CommandName="Update"
            Text="Edit" />
        <asp:Button ID="BtnCancel" runat="server" CommandName="Cancel"
            Text="Cancel" />
    </EditItemTemplate>
</asp:TemplateField>

How would I change what I have into just a text that is like a link (once again, like if it was from AutoGenerateEditButton). I can't set that to true because I need to conditionally hide it and I can't seem to do it if it's automatically generated. If you know a way to conditionally hide it when it's automatically generated, please let me know!
Take note that I'm using a SQLDataSource.

A: Use a LinkButton MSDN
<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="editButton" runat="server" CommandName="Edit">Edit</asp:LinkButton>
    </ItemTemplate>
    <EditItemTemplate>
        <div style="white-space: nowrap;">
            <asp:LinkButton ID="BtnUpdate" runat="server" CommandName="Update">Edit</asp:LinkButton>
            <asp:LinkButton ID="BtnCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
        </div>
    </EditItemTemplate>
</asp:TemplateField>


text:
Q: Out of the blue I can't start Rails server with rails -s Last night I installed ruby 3.0.0 and ruby on rails 6.1.1 on my Ubuntu system by following the instructions at this link http://railsapps.github.io/installrubyonrails-ubuntu.html and I was able to get rails running in my browser on port 3000 using command rails -s. Today I try to get it running again and I get this rails aborted error. I'm completely confounded by this issue as I did not change any settings from last night when it was working perfectly fine. I've seen other questions asked with similar issues but not with my specific error so I'm not sure how to proceed. I tried creating a separate directory and creating a new gemset for a separate project and I get the same error. Anyone have any ideas?
rails aborted!
LoadError: cannot load such file -- rexml/document
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:89:in `register'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:44:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `block in require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:299:in `load_dependency'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/selenium-webdriver-3.142.7/lib/selenium/webdriver/firefox.rb:22:in `<main>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `block in require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:299:in `load_dependency'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/webdrivers-4.5.0/lib/webdrivers/geckodriver.rb:72:in `<main>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `block in require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:299:in `load_dependency'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/webdrivers-4.5.0/lib/webdrivers.rb:4:in `<main>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/who/workspace/proj/config/application.rb:7:in `<main>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `block in require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:299:in `load_dependency'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:53:in `require_relative'
/home/who/workspace/proj/Rakefile:4:in `<main>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:326:in `block in load'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:299:in `load_dependency'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:326:in `load'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/railties-6.1.1/lib/rails/commands/rake/rake_command.rb:20:in `block in perform'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/railties-6.1.1/lib/rails/commands/rake/rake_command.rb:18:in `perform'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/railties-6.1.1/lib/rails/command.rb:52:in `invoke'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/railties-6.1.1/lib/rails/commands.rb:18:in `<main>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/bootsnap-1.6.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `block in require'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:299:in `load_dependency'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/activesupport-6.1.1/lib/active_support/dependencies.rb:332:in `require'
/home/who/workspace/proj/bin/rails:5:in `<top (required)>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `load'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `call'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/lib/spring/client/command.rb:7:in `call'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/lib/spring/client.rb:30:in `run'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/bin/spring:49:in `<top (required)>'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `load'
/home/who/.rvm/gems/ruby-3.0.0@proj/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
<internal:/home/who/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
<internal:/home/who/.rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
/home/who/workspace/proj/bin/spring:10:in `block in <top (required)>'
<internal:kernel>:90:in `tap'
/home/who/workspace/proj/bin/spring:7:in `<top (required)>'
bin/rails:2:in `load'
bin/rails:2:in `<main>'
(See full trace by running task with --trace)


text:
Q: Pontryagin Dual and Continuity involving w* topology For $G$, a locally compact group, we've defined $\hat{G}$ to be the group of all continuous homomorphisms from $G$ to the torus $\mathbb{T}$. With this definition, $\hat{G}\subseteq L^\infty(G)$ as the torus is a bounded space.
Separately, we can make the association that $L^\infty(G)\cong(L^1(G))^*$ where $X^*$ is the space of all bounded linear functionals on $X$, endowed with the weak$^*$ topology.
Finally, we define
$$\Psi:\hat{\mathbb{Z}}\to\mathbb{T}$$
$$\chi_\theta\mapsto\theta$$
where $\chi_{\theta}(m)=\theta^m$. With this set up, I've been tasked to show that $\Psi^{-1}$ is continuous.
I know, in words, what I need to demonstrate is that given a neighborhood of a function $\chi_{\theta}$ in $\hat{\mathbb{Z}}$ I need to provide a neighborhood of $\theta$ in $\mathbb{T}$ such that $\xi$ belonging to the latter neighborhood gives $\chi_\xi$ belongs to the former.
In the weak$^*$ topology, we can define (the simplest of) neighborhoods by choosing a point in the pre-dual space, and an $\varepsilon>0$. Applying this to our specific example, we would have for $g\in L^1(G)$
$$N_{\varepsilon, g}(\chi_\theta)=\left\{\chi_{\xi}\in \hat{\mathbb{Z}}: \left|\sum_{n=-\infty}^{\infty}\chi_{\xi}(n)g(n) -\sum_{n=-\infty}^{\infty}\chi_{\theta}(n)g(n)\right|<\varepsilon\right\}.$$
To prove the continuity of $\Psi^{-1}$, I need to provide some neighborhood of $\theta$ so that $\xi\in N_\delta(\theta)$ gives $\chi_\xi\in N_{\varepsilon, g}(\chi_\theta)$.
My Questions

*

*Am I correct in my understanding thus far?

*Given the sum in the $N_{\varepsilon, g}$, I can bound it above by $M=\sup{g}$, but that leaves me with $M\sum_{n=-\infty}^\infty|\xi^n-\theta^n|$. If this were a singular term of the sum, I could choose $\delta<\min(\frac{\varepsilon}{M},1)$, but I'm not sure how to handle the fact that we're dealing with an infinite number of summands.


text:
Q: Why this XPath selects zero nodes? I have this XML:
<?xml version="1.0" encoding="utf-8"?>
<!-- Report generated by xxx -->
<report AppKey="stuffs" AppId="123">
  <physician name="AAA BBB">
     ....
     <services>
       <service id="1" diagnostic="345" />
       <service id="2" diagnostic="253" />
       <service id="3" diagnostic="585" />
     ....
     </services>
  </physician>
</report>

and this c# code
XmlDocument doc = new XmlDocument();
doc.Load(file);
XmlNodeList xnList = doc.SelectNodes("/report/physician/services/*");

My problem is that the xnList is always empty, I tried with "/report/*" which return 0, tried with "/report/physician/*" which returns the same, only "*" returns the entire xml file. What I want to do is to select every <service> and then get their attributes. I cant seem to find a way to get every service element, because my queries always return nothing.

A: Can you use LINQtoXML? In that case it should be as simple as:
var doc = XDocument.Load(file);
XNamespace ns = "http://www.cnas.ro/siui/2.0";
var nodes = doc.Root.Element(ns + "physician")
                        .Element(ns + "services")
                            .Elements(ns + "service");

You can also use Descendants which will take the matching nodes regardless of their position in the tree, like this:
var nodes = doc.Root.Descendants(ns + "service");

Either way, you will get an IEnumerable<XElement> that you can easily map.
N.B. remember to add using System.Xml.Linq; in your directives.
UPDATE:
For mapping to the attributes, it is a matter of opinions... I would go like this:
var services = from n in nodes
               select new
                   {
                       Id = n.Attribute("id").Value,
                       Diagnostic = n.Attribute("diagnostic").Value
                   };

services will be an IEnumerable<AnonymousType> which you can then iterate on:
foreach (var service in services)
{
    Console.WriteLine(service.Id + " - " + service.Diagnostic);
}

A: Remove the asterisk;
XmlNodeList xnList = doc.SelectNodes("/report/physician/services/service");

foreach (XmlNode service in xnList)
    x = service.Attributes["id"].Value;

A: The below XPath should work for you.
XmlNodeList xnList = doc.SelectNodes("/report/physician/services/service");

A: This should select all service elements, no matter where they are in the file:
XmlNodeList xnList = doc.SelectNodes("//service");

Click here to find more XPath expressions


text:
Q: TweetSharp Library issues I've this code which is not working.
If i try to post in twitter with the generated access token and access token secret from the page, it works perfectly, but if i try to retrieve the access tokens it doesn't work, it goes to the page, i authorize the app and it doesn't retrieve the tokens, can anyone help me please?
var oauth_consumer_key = "******************************";
var oauth_consumer_secret = "**************************************";
var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);

OAuthRequestToken requestToken = service.GetRequestToken();
string authUrl = service.GetAuthorizationUri(requestToken).ToString();
Process.Start(authUrl);

TILL THIS POINT THE CODE IS WORKING.
START OF NOT WORKING CODE
OAuthAccessToken accessToken = service.GetAccessToken(requestToken);
string token = accessToken.Token.ToString();
string tokenSecret = accessToken.TokenSecret.ToString();
Console.WriteLine(accessToken.Token);
Console.WriteLine(accessToken.TokenSecret);
Console.ReadKey();
service.AuthenticateWith(accessToken.Token,accessToken.TokenSecret);

This part is working if i authenticate directly with the strings generated in the app page
//service.AuthenticateWith("*****************************", "***********************************");
service.SendTweet(new SendTweetOptions
                {
                    Status = "yayayayayayayayayayyayayay"
                });

I really dont understand why it doesn't work, can someone please help me?
Thank you so much guys


text:
Q: Filtering a dictionary + Tuple So i've load a pickle file an got these dictionaries here:
 {1536: {'origin': u'HW', 'department': u'Kunde', 'events': [(1411562482304633L, u'new'), (1421683468875977L, u'closed')]},

 {1537: {'origin': u'HW', 'department': u'Kunde', 'events': [(1411562809498852L, u'new'), (1414071035946802L, u'closed')]},

 {1538: {'origin': u'HW', 'department': u'Kunde', 'events': [(1411562928759247L, u'new')]}

as you can see there is a tuple called 'events' which can contain one or more events.
I want to display all of these dictionaries which contain an event named 'closed'.
i've tried it this way but it doesnt work
ticketdata = pickle.load(open("tickets.p", "rb"))

for i in ticketdata:
    for j in ticketdata[i]['events']:
        if 'closed' in ticketdata[i]['events']:
            print i, ticketdata[i]['events']

A: You're checking if 'closed' is in the list of tuples, but not in the tuple itself, so it will never match. You're already iterating over the list of tuples with j, so just check if closed is in j instead.
ticketdata = pickle.load(open("tickets.p", "rb"))

for i in ticketdata:
    for j in ticketdata[i]['events']:
        if 'closed' in j:
            print i, ticketdata[i]['events']

A: In a pythonic way, you can do this:
Put all your dic in a list named lst_dic and:
dic_closed = [dic for dic in lst_dic for evt in dic.get('events',[]) if 'closeed' in evt]

A: There is no need for two for loops:
ticketdata = pickle.load(open("tickets.p", "rb"))

for (i,j) in ticketdata.iteritems():
    if 'closed' in j['events']:
       print i,j['events']


text:
Q: Async queue how it works with this sample code I have written a sample code for getting deep into the threading concepts as below.
print("a")
DispatchQueue.global(qos: .default).async {
   print("b")
   DispatchQueue.global(qos: .default).async {
      print("c")
      DispatchQueue.global(qos: .default).async {
        print("d")
        DispatchQueue.global(qos: .default).async {
         print("e")
        }
        print("f")
      }
      print("g")
   }
   print("h")
}
print("i")

OUTPUT
a
i
b
h
c
g
d
f
e

How the output seems like this. What is actually happening inside?

A: There are two basic behaviors:

*

*As the name implies an asynchronously dispatched queue is always executed after the enclosing scope – {} – exits.
So i is printed before b, h is printed before c etc.

*A dispatch queue works serial by default, all tasks are executed one after another
So the consecutive order is i - b - h - c - g - d - f - e

A: The idea is any 2 lines 1 of them is
DispatchQueue.global(qos: .default).async

the second will run first , so this
print("a")
DispatchQueue.global(qos: .default).async {
 print("b")
}
print("i")

gives
a // comes first
i // printed first before queue as the queue dispatches the execution with some delay
b // printed second

Then go inside the async and apply the same rule
   DispatchQueue.global(qos: .default).async {
      print("c")
      DispatchQueue.global(qos: .default).async {
      print("d")
      }
      print("g")
   }
   print("h")

h

c

g

d

A: On each DispatchQueue.global context was splitting up, and cost of dispatching higher than simple print, that's all.


text:
Q: Android Lollipop Appcompat problems running with Robolectric I'm not able to run Robolectic test when using new Appcompat support library available since Android Lollipop came out. I've followed:

*

*https://github.com/robolectric/deckard-gradle

*https://chris.banes.me/2014/10/17/appcompat-v21/
My current progress is available here: https://github.com/fada21/android-tdd-bootstrap
My configuration (distilled) is:
android {
  compileSdkVersion 21
  buildToolsVersion "21.0.1"

defaultConfig {
  applicationId "com.fada21.android.bootstrap"
  minSdkVersion 15
  targetSdkVersion 21

...
dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  compile 'com.android.support:support-v4:21.0.0'
  compile 'com.android.support:appcompat-v7:21.0.0'

...
androidTestCompile('org.robolectric:robolectric:2.4-SNAPSHOT') {

I've raised an issue here: https://github.com/robolectric/robolectric/issues/1332 (look here for more details).
This is errors I'm getting:
java.lang.RuntimeException: Could not find any resource  from reference ResName{com.fada21.android.bootstrap:style/Theme_AppCompat_Light_NoActionBar} from style StyleData{name='AppTheme', parent='Theme_AppCompat_Light_NoActionBar'} with theme null
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getParent(ShadowAssetManager.java:456)
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getAttrValue(ShadowAssetManager.java:394)
at org.robolectric.shadows.ShadowResources.getOverlayedThemeValue(ShadowResources.java:297)
at org.robolectric.shadows.ShadowResources.findAttributeValue(ShadowResources.java:286)
at org.robolectric.shadows.ShadowResources.attrsToTypedArray(ShadowResources.java:189)
at org.robolectric.shadows.ShadowResources.access$000(ShadowResources.java:48)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:494)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:489)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:484)
at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java)
at android.content.Context.obtainStyledAttributes(Context.java:380)
at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:143)
at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:139)
at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
at com.fada21.android.bootstrap.HomeActivity.onCreate(HomeActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5133)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.util.ActivityController$1.run(ActivityController.java:113)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:265)
at org.robolectric.util.ActivityController.create(ActivityController.java:110)
at org.robolectric.util.ActivityController.create(ActivityController.java:120)
at com.fada21.android.bootstrap.HomeActivityTest.testActivityNotNull(HomeActivityTest.java:24)

A: Add a project.properties file at the same hierarki level as your manifest, with the following content:
android.library.reference.1=../../build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.0.0

Make sure the appcompat version is the same as in your gradle file.

A: NOTE: As of 7/7/15, Roboelectric 3.0 has been released. It solves the problem in question making this answer no longer necessary.
Old Answer:
Until Robolectric 3.0 comes out, here's a fix.
#/app/src/main/res/values/styles.xml
<resources>

    //<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        //<!-- Customize your theme here. -->
    </style>

    //<!-- Hack for Robolectric to run with appcompat.v7 -->
    <style name="RoboAppTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar">
        //<!-- Customize your theme here. -->
    </style>

</resources>

And then adjust your custom RobolectricRunner class
public class MyRobolectricTestRunner extends RobolectricTestRunner {
    private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18;

    public MyRobolectricTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    @Override
    protected AndroidManifest getAppManifest(Config config) {
        String manifestProperty = "../app/src/main/AndroidManifest.xml";
        String resProperty = "../app/src/main/res";
        return new AndroidManifest(Fs.fileFromPath(manifestProperty), Fs.fileFromPath(resProperty)) {
            @Override
            public int getTargetSdkVersion() {
                return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC;
            }

            @Override
            public String getThemeRef(Class<? extends Activity> activityClass) {
                return "@style/RoboAppTheme";
            }
        };
    }
}

Basically we are just telling the JVM to use a different app theme. Then use this TestRunner like you normally would with @RunWith(MyRobolectricTestRunner.class).
Note:
This addresses activities that only extend Activity, other issues of the same type occur for activities that extend ActionBarActivity
EDIT: As of 4/7/15, Robolectric 3.0-snapshot build is available which accounts for ActionBarActivity. More information is available in the links in the comments

A: Using this custom RobolectricTestRunner fixed a similar problem that I was having. This also means you don't need @Config(emulateSdk = 18) in every test.
Replace: @RunWith(RobolectricTestRunner.class)
with: @RunWith(MyRobolectricTestRunner.class)
in all your Robolectric tests
public class MyRobolectricTestRunner extends RobolectricTestRunner {

    public MyRobolectricTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    @Override
    protected AndroidManifest getAppManifest(Config config) {
        String manifestProperty = System.getProperty("android.manifest");
        if (config.manifest().equals(Config.DEFAULT) && manifestProperty != null) {
            String resProperty = System.getProperty("android.resources");
            String assetsProperty = System.getProperty("android.assets");
            CustomAndroidManifest androidManifest = new CustomAndroidManifest(
                    Fs.fileFromPath(manifestProperty),
                    Fs.fileFromPath(resProperty),
                    Fs.fileFromPath(assetsProperty));
            androidManifest.setPackageName("com.justyoyo");
            return androidManifest;
        }
        return super.getAppManifest(config);
    }

    private static class CustomAndroidManifest extends AndroidManifest {

        private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18;

        public CustomAndroidManifest(FsFile androidManifestFile, FsFile resDirectory, FsFile assetsDirectory) {
            super(androidManifestFile, resDirectory, assetsDirectory);
        }

        @Override
        public int getTargetSdkVersion() {
            return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC;
        }
    }
}

Credit to this: https://github.com/robolectric/robolectric/issues/1025

A: some solution could be:
add to the test:
@Config(emulateSdk = 18, reportSdk = 18)
and make it something like:
@RunWith(RobolectricTestRunner.class)
@Config(emulateSdk = 18, reportSdk = 18)
public class YourClassTestNameTest {…

A: @RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)

solved my issue.


text:
Q: Pug/jade not picking up a variable in Express js app I am trying to pass in a variable that checks the hostname and renders a different graphic based on the hostname.
on app.js
app.use(function (req, res, next) {

  app.use('/', indexRouter);
  app.use('/login', loginRouter);

 app.locals.subdomain = req.hostname;

}

in my pug/jade template I want to be able to do something like this.
if subdomain == "college.alumni.org"
  div(class="container" style="background-image: url(/images/alumni.png);")
else
  div(class="container" style="background-image: url(/images/admissions.jpg);")

Right now is not rendering either graphic.


text:
Q: Put one function to multiple widgets This is a scuffed version of aimlabs I'm working on right now. and I know there is a way to make this more elegant. I need to put one function to multiple widgets for Python GUI.
def clicked1():
    clicker1.place(x=randint(1, 900), y=randint(1, 600))
def clicked2():
    clicker2.place(x=randint(1, 900), y=randint(1, 600))
def clicked3():
    clicker3.place(x=randint(1, 900), y=randint(1, 600))
def clicked4():
    clicker4.place(x=randint(1, 900), y=randint(1, 600))
def clicked5():
    clicker5.place(x=randint(1, 900), y=randint(1, 600))

clicker1 = Button(root, text='CLICK!', width=10, height=5, command=clicked1)
clicker1.place(x=randint(1, 900), y=randint(1, 600))
clicker2 = Button(root, text='CLICK!', width=10, height=5, command=clicked2)
clicker2.place(x=randint(1, 900), y=randint(1, 600))
clicker3 = Button(root, text='CLICK!', width=10, height=5, command=clicked3)
clicker3.place(x=randint(1, 900), y=randint(1, 600))
clicker4 = Button(root, text='CLICK!', width=10, height=5, command=clicked4)
clicker4.place(x=randint(1, 900), y=randint(1, 600))
clicker5 = Button(root, text='CLICK!', width=10, height=5, command=clicked5)
clicker5.place(x=randint(1, 900), y=randint(1, 600))


text:
Q: How to say the period of time when you are not on vacation? Let say I jogged when I was on vacation, would you say that I jogged in that time when I was on vacation? And how to say when I am not on vacation? Would I say in times apart from vacation? They sound strange so please correct as many mistakes as possible.

A: Usually you would not use a qualifier for non-vacation time.

I like jogging
I go jogging every week
I often go jogging

I would automatically think this means non-vacation time.
If you jog on vacation, you would say:

I like jogging on vacation
When I go on vacation I often go jogging
While I was on vacation I went jogging every week.

If you wanted to be explicit that you only jog when you are not on holiday, you could say:

When I'm not on vacation, I go jogging.

But there is no specific word for time when you are not on vacation.