text:
Q: Not able to receive emails postfix Ubuntu I am Unable to receive email but sending them works fine
stuck on what to do next If anyone could point out the mistake or point me in the right direction it would be much appreciated.
Postfix main.cf file
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
append_dot_mydomain = no
readme_directory = no
smtpd_tls_cert_file=/etc/ssl/certs/dlcincluded.crt
smtpd_tls_key_file=/etc/ssl/private/dlcincluded.key
smtpd_use_tls=yes
smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
milter_default_action = accept
milter_protocol = 2
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, check_relay_domains
smtpd_data_restrictions = reject_unauth_pipelining
myhostname = dlcincluded.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
home_mailbox = Maildir/
virtual_alias_maps = hash:/etc/postfix/virtual

tail -f /var/log/mail.log
Aug 12 10:17:46 dlcincluded postfix/smtpd[3925]: connect from mail-pf0-f174.google.com[209.85.192.174]
Aug 12 10:17:46 dlcincluded postfix/smtpd[3925]: warning: connect to Milter service inet:localhost:8891: Connection refused
Aug 12 10:17:46 dlcincluded postfix/smtpd[3925]: NOQUEUE: reject: RCPT from mail-pf0-f174.google.com[209.85.192.174]: 454 4.7.1 <admin@dlcincluded.com>: Relay access denied; from=<chj1axr0@gmail.com> to=<admin@dlcincluded.com> proto=ESMTP helo=<mail-pf0-f174.google.com>
Aug 12 10:17:46 dlcincluded postfix/smtpd[3925]: disconnect from mail-pf0-f174.google.com[209.85.192.174] ehlo=2 starttls=1 mail=1 rcpt=0/1 data=0/1 quit=1 commands=5/7

A: The reason The problem accrued is because I didn't have the domain in  mydestination = localhost. It needed to be mydestination = dlcincluded.com, localhost

A: check_relay_domains has been removed in postfix for quite some time. It was replaced with reject_unauth_destination. Change this in your smtpd_recipient_restrictions.

It also looks like your milter demon (OpenDKIM?) isn't running, but that's likely a separate issue.


text:
Q: Xamarin.Forms - Android/iOS : Push notification not working if app is killed I have used https://github.com/CrossGeeks/PushNotificationPlugin for push notifications in my xamarin.forms application.
The major issue I am facing currently is Notifications not arriving in device once the app is closed. Here is how the push notifications working:

*

*it works if app is in foreground or background,

*if kill app and then send notification it not works

*if you again open app and it's again either in background or foreground notifications not works

So it works only first time when app is installed in device and it's in
either Foreground or background.

Anyone know how to handle this issue?

I have initialised plugin in both Android and iOS also setup all required things.
Version of packages I have used:

*

*Xamarin.Forms - 4.7.0.968

*Plugin.PushNotification - 1.3.0

1 Code in App.xaml.cs OnStartMethod
CrossPushNotification.Current.OnTokenRefresh += (s, p) =>
{
    if (Device.RuntimePlatform == Device.Android)
    {
        DeviceToken = p.Token;
    }
};

CrossPushNotification.Current.OnNotificationReceived += async (s, p) =>
{
    //Logic to handle arrived notification
};

CrossPushNotification.Current.OnNotificationOpened += async (s, p) =>
{
    //Notification tap handler code here
};

CrossPushNotification.Current.OnNotificationDeleted += (s, p) =>
{
    Debug.WriteLine("Dismissed");
};

2 Android Main Application class
[Application]
public class MainApplication : Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();

        //Set the default notification channel for your app when running Android Oreo
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            //Change for your default notification channel id here
            PushNotificationManager.DefaultNotificationChannelId = "DefaultChannel";

            //Change for your default notification channel name here
            PushNotificationManager.DefaultNotificationChannelName = "General";
        }

        //If debug you should reset the token each time.
#if DEBUG
        PushNotificationManager.Initialize(this, true);
#else

        PushNotificationManager.Initialize(this, false);
#endif

        //PushNotificationManager.IconResource = Resource.Drawable.icon;

        //Handle notification when app is closed here
        CrossPushNotification.Current.OnNotificationReceived += (s, p) =>
        {

        };
    }
}

3 Android: MainActivity class
protected async override void OnCreate(Bundle savedInstanceState)
{
    LoadApplication(new App());
    PushNotificationManager.ProcessIntent(this, Intent);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding CID and LRD of a business page on Google I want to know how to find the LRD and CID for an specific business page on Google.
The sample URL I'm trying to construct as follows
https://www.google.com/#q=takeout+banani&lucid="CID"&lrd=0x3755c7120ec9e20f:0x8889d4d79e711995,3

What I've found out so far is there isn't any direct way to find both CID and LRD.
I have to make two API calls to get CID which looks like as follows,
"url": "https://maps.google.com/?cid=4839020573042712727",

but is there any other way to or direct FIELD in api like the place_id below?
"place_id": "ChIJrQFQG6PHVTcRl6AErZKnJ0M"

Now comes to the LRD part, HOW CAN I FIND IT? In this details API
https://maps.googleapis.com/maps/api/place/details/json?reference="Referense key from place request api"&sensor=true&key="Your API Key"

There is no direct field also for LRD.
So how can i get or find LRD 0x[HEX_CODE1]:0x[HEX_CODE2] in these formate.
I'm linking the stackoverflow questions below as reference.
How to get the cid in the Google Place URL?
Google Places API - Find a company's CID and LRD

A: Read this answer to obtain the CID:
How to get the cid in the Google Place URL?
Two API requests and you'll have the CID of a business programmatically.
EDIT ----------
The LRD is CID in hexadecimal. You can use this function to:
function dec2hex($number)
{
    $hexvalues = array('0','1','2','3','4','5','6','7',
               '8','9','A','B','C','D','E','F');
    $hexval = '';
     while($number != '0')
     {
        $hexval = $hexvalues[bcmod($number,'16')].$hexval;
        $number = bcdiv($number,'16',0);
    }
    return $hexval;
}

So you can build the Google Review Url like this:
$business_url = "https://www.google.com/search?q=NAMEOFBUSINESS&ludocid=YOURCID#lrd=0x0:0xYOURHEXCID,1";


text:
Q: Как выбрать отмеченную кнопку RadioButton.Checked? Доброго времени суток. Помогите, пожалуйста, разобраться с синтаксисом С#. Имеется 4 radioButton, одна из них выбрана. Как выбрать эту выбранную кнопку? Что-то типа RadioButton.Checked. Вопрос нубский, ну и я пока нуб. Заранее спасибо.
A: Установка в позицию выбрана:
radioButton.Checked = true;

Проверка если выбрана:
if(radioButton.Checked){...}

RadioButton объединяются в группы - когда может быть выбран только один, тогда чтобы узнать какой именно выбрал пользователь, необходимо проверять каждый по очереди до тех пор пока не найдете выбранный.
A: for (int i = 0; i < radioButton.count; i++) {
    if (radioButton[i].Checked) {
        MessegeBox.Show("Нашлась красавица");
    }
}


text:
Q: Using static classes in Business Logic Layer I am aware that the answer to my question might involve choosing a specific approach, But I try to explain what I'm trying to find out with details:
Consider a simple 3-layer application (DAL, BLL, PL).
DAL uses EF 4.1 Code-First and access to data is wrapped up in a reposiory.
Right now, in BLL, I have Manager classes. (e.g. UserManager, ProductManager) which all derive from BaseManager. Almost each method in my Manager classes take their related entity as a parameter and perform the appropriate operations on it. e.g. in UserManager (Pseudo code):
public bool AddPermission(User user, PermissionItem permission)
{
    this.repository.Add(permission);
    this.save();
}

Question is: My manager classes do not need to get instantiated. they can be defined static.
But if I define them static, I should create my shared methods and members (like repository, and a couple of other members) in each class (I do not want to define members like repository as static).
So do you suggest I should change my Manager classes that are indeed meant to be static to static classes? or is it ok using them as they are?

A: imho static classes are nothing more than containers for functions (and not real objects). The difference is that non-static classes can be derived and get their dependencies through the constructor.
Try to write proper tests for a static class.
You might not have intended for them to be instances today, but what about tomorrow? If you change them to static, you'll have to refactor all your depending code to unmake them static.
I would rather start using an inversion of control container to manage their creation and instances.

A: I see no reason to make them static. As far as I can see, it would only complicate the API and the implementation. And where would your callers retrieve the repository from? Should they look it up for each call? That's wasteful. Far better to look it up once and store it within the manager. That's what instance variables are for.

A: I like to create a static "directory" (the correct name for this object is actually repository) that contains all my instances.  For example:
public static Class BusinessRepository
{
    private static Users users = new Users();

    public static Users Users
    {
        get
        {
            return users;
        }
    }
}

The BusinessRepository class is static, but Users is an instance object contained within it.  This can then be accessed like this:
BusinessRepository.Users.DoSomething();

This way you get to keep your object instances and all the benefits that they bring, with static like access to them.
A lot of people dont agree with these sort of "global variables" as they will call them, but that is your judgement call to make.  It seems like you've already made the decision that you're happy with this as you're already talking about static classes.


text:
Q: Efficient checking for Subset Given two bitset objects 'B1' and 'B2' of length 'n' respectively. Whats the efficient way to say whether all the bits that are set in 'B2' are also in 'B1'?
Example:
B1 = 110111
B2_bad = 011001
B2_good = 100001

So, 'B1' and 'B2_good' is good but not 'B1' and 'B2_bad'?

A: Well, I guess these two following methods might help. You might need to benchmark them as which is faster.
std::bitset<6> B1 (std::string("110111"));
std::bitset<6> B2_bad (std::string("011001"));
std::bitset<6> B2_good (std::string("100001"));
    //////////////One way/////////////////////////
    if ( (~B1 &= (B2_bad)).any()) std::cout << "No" << std::endl;
    else std::cout << "Yes" << std::endl;

    if ( (~B1 &= (B2_good)).any()) std::cout << "No" << std::endl;
    else std::cout << "Yes" << std::endl;

    ///////////////Second way//////////////////
    int i =0;
    for (i = 0; i < B1.size(); ++i) if (B2_bad[i] == 1 && B1[i] == 0) break;
    if (i == B1.size()) std::cout << "Yes" << std::endl;
    else std::cout << "No" << std::endl;

    for (i = 0; i < B1.size(); ++i) if (B2_good[i] == 1 && B1[i] == 0) break;
    if (i == B1.size()) std::cout << "Yes" << std::endl;
    else std::cout << "No" << std::endl;`

Probably, someone more proficient than me can comment on their performance. But my best guess is first method leverages the library functions which should give the best performance , however if most of your queries would have 'Result NO' and B1-B2 will not agree on one of the earlier bits then second method might have better runtime. As, library functions involved have a worst runtime complexity of O(n).


text:
Q: mysql search for duplicates by column A and delete by criteria on othe columns I have a mysql database, containing a table with following columns: PartCode, Price and Quantity. The goal is to write a query which would search for rows with duplicate 'PartCode', then compare them by Price and Quantity, and delete the row with higher 'Price' values, but if one of the 'Quantities' is 0, then to delete the one with 0 quantity.
A sample table would look like this:
PartCode  -  Price  -  Quantity
 ABCD     -    5    -     2
 CDEF     -    6    -     1
 CDEF     -    4    -     1
 VZXY     -    8    -     4
 VZXY     -    7    -     0
 ....     -   ...   -    ...

And for the results, I'd like to get this:
PartCode  -  Price  -  Quantity
 ABCD     -    5    -     2
 CDEF     -    4    -     1
 VZXY     -    8    -     4
 ....     -   ...   -    ...

I've found the solution to receive all duplicate PartCodes:
SELECT `PartCode` FROM `Table` GROUP BY `PartCode` HAVING COUNT(*) > 1

What I cannot figure out, is how to implement it to delete one of the duplicates, by other columns comparison.
Thanks in advance.

A: The following query will delete one record from each PartCode group having either the highest quantity, or if one record has a zero quantity then it would be deleted instead.
DELETE
FROM yourTable t1
WHERE (PartCode, Quantity) IN
(
    SELECT
        t.PartCode,
        t.qty
    FROM
    (
        SELECT
            PartCode,
            CASE WHEN MIN(Quantity) = 0 THEN MIN(Quantity) ELSE MAX(Quantity) END AS qty
        FROM yourTable
        GROUP BY PartCode
        HAVING COUNT(*) > 1
    ) t
)


text:
Q: WCF operation contract and list size I have an operation contract in my service contract that accepts a list of data contract objects as an input (void Foo(IList data)). How can I limit the number of data contract items in the collection so that f.ex. not more that 500 can't be sent?
t. Erki.

A: Depending on the binding you use, there are settings that allow you to define the max data size sent from the client or accepted by the service (MaxReceivedMessageSize for instance).
If you want a higher level of granularity than the byte level, you will need to code it in your service implementation and throw a fault if the client sends more than 500 items in the collection.


text:
Q: socket.io, server emit event before client set up listener for that event In the following code snippet(using node.js and socket.io library), sometimes (and sometimes not) server emit event something before client side set up socket listener for something event which will cause that associated anonymous function will not execute.
Client-side: index.html
<script src="socket.io/socket.io.js"></script>
<script>
   ...
   var socket = io.connect('http://localhost:8080/abc');
   ...
</script>
<script src="/somewhere/test.js"></script>

Content of test.js
...
console.log(new Date().getTime(), 'debugging');

socket.on('something', function(data) {
// will not execute
console.log(data);
});
...

Server-side:
io.of('/abc').on('connection', function(socket) {
   console.log(new Date().getTime(), 'EMIT SOMETHING');
   io.of('/abc').emit('something', 'b');
});

Result of console.log on the client side: 1439057954676 debugging
Result of console.log on the server side: 1439057954114 EMIT SOMETHING
Why server emit event before client set up listeners in the above example?

A: Try putting both var socket = io.connect('http://localhost:8080/abc'); and socket.on('something', function(data) in the same script tag.
(Essentially try making your whole script in one HTML element, instead of separating them.)


text:
Q: How to design a schema to store search keywords I am doing a database design that stores search keywords of a search form, used to generate the most popular search keyword reports by date, month and year. I have made a simple schema:
CREATE TABLE SearchTerm (
 ID             INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
 SearchTerm     VARCHAR( 255 )  NOT NULL,
 Date           DATE            NOT NULL
);

In this case, search term will be redundant in the table and make the database grow faster. I want to avoid data redundancy.
Also I am not sure if using the date data type or unix timestamp will make a difference in retrieving the data faster.
So, should I create a new table to store a date that links to master table by id? For example,
CREATE TABLE SearchTerm (
 ID             INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
 SearchTerm     VARCHAR( 255 )  NOT NULL,
 Hit           INTEGER         NOT NULL,
 DateID         INTEGER         NOT NULL
);

CREATE TABLE DateofSearchTerm (
 DateID         INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
 Date           DATE            NOT NULL
);

My concern is performance as the database grows. If the database is not designed properly , it would be leading to performance and bottleneck issues.
One of my friends has done an analytic site, but it is not going well. I figured out that there are 3 million records in the table and his query is taking more than 3 minutes to return results.
And only one table he created, then save "Event Name", "Start data"," End date" something like that. When generating monthly report, it could not show the report due to timeout issues (server time out, query time out, jquery response time out).
His SQL query is too expensive. He use group by date in sp to get how many users daily and monthly.  Then passes the result to populate flash based report. I fixed it to see report by increasing command time out. But I don't think it is a good idea. Data is continuing to grow, it would be 4 mill records in end of this year. At the end of the day , increasing command time out will not work. This issue is a result of weak database design. I don't want to follow it.
Please advise me and share your experience to avoid these issues. How should I design search term db schema?

A: First, let me address your concern about data redundancy. I agree with you that the second schema is more likely to reduce the redundancy, and is probably closer to what I would go with. One thing to be aware of, though, is this will be unique search terms. So unless you have some way of normalizing data, misspellings will get through and be viewed as different search terms.
Also, I would switch the way you link the searchTerm to the date searched, so that dateofSearchTerm links to the search term (not the other way around).
CREATE TABLE SearchTerm (
 ID             INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
 SearchTerm     VARCHAR( 255 )  NOT NULL,
 Hit           INTEGER         NOT NULL,
);

CREATE TABLE DateofSearchTerm (
 DateID         INTEGER         PRIMARY KEY AUTOINCREMENT NOT NULL,
 searchID       INTEGER         NOT NULL,
 Date           DATE            NOT NULL
);

It would also be a good idea to make searchID a foreign key that references searchTerm.ID to ensure there are no orphan rows (rows in DateofSearchTerm that do not have a matching parent in SearchTerm).
As for your anecdotal story about your friend, the biggest thing I see you missing in your designs are indexes. A table 3-million strong should have no problem running quickly with proper indexes.
Using your design, you would want an index on the searchTerm.searchTerm column, and on DateofSearchTerm.date.
I think if you follow the advice to make searchID a foreign key, that will also become a proper index. I don't use SQL Server, so I don't know if foreign keys require an index, so make sure that it does.

A: Do you have a reason to store the searches as individual events or are you only interested in recording which terms were used how many times on any given day?
If you just need to record how many times each search term is used on any particular day, then the most compact schema would be:
CREATE TABLE SearchTerm (
  ID            INTEGER       PRIMARY KEY AUTOINCREMENT NOT NULL,
  Words         VARCHAR(255)  NOT NULL
);

CREATE TABLE SearchStats (
  SearchDate    DATE          PRIMARY KEY NOT NULL,
  SearchTermID  INTEGER       PRIMARY KEY NOT NULL,
  Hits          INTEGER       NOT NULL,
  FOREIGN KEY SearchTermID REFERENCES SearchTerm(ID)
);

Using this schema, each use of a search term requires either an insert (if it's the first use of the term on any given date) or an update of a record in SearchStats.  If the search term has never been used before, then obviously you need to insert there too.


text:
Q: Using SQL Server Designers from .NET This is a duplicate question, but the other one didn't get any answers, so I'll have another go.
I have SQL Server 2008 Client Tools installed, and would like to use SQL Server's query designer(s) in my application, for working with queries, views, SPs and functions. I'm pretty sure Access ADP does this, can I?
I guess what I am hoping for is that these designers are COM objects which I can use via p/invoke.

A: I expect that you would have to implement the functionality yourself, but, it really shouldn't be that hard to do, technically, but will be a time-consuming project.


text:
Q: Respond to resize I have a sticky footer that needs to re-position when the site content grows. Currently when my textarea grows to a certain point, it simply underflows the footer, and that footer is staying as it is.
What is the best way to respond to an element resizing in height? I have seen some stuff using animation frames and such. But all that I want to do is re-calculate the position of my footer each time a resize event is fired.

A: Ryan Fait's sticky footer:

* {
    margin: 0;
}

html,
body {
    height: 100%;
}

main {
    min-height: 100%;
    height: auto !important;
    /* This line and the next line are not necessary unless you need IE6 support */
    height: 100%;
    margin: 0 auto -155px;
    /* the bottom margin is the negative value of the footer's height */
}

footer,
.push {
    height: 155px;
    /* .push must be the same height as .footer */
}

footer {
    height;
    155px;
    background: gray;
}

textarea {
    height: 100px;
    width: 200px;
}

    <textarea></textarea>


text:
Q: When comparing series, i'm having trouble understanding how my book determines which is greater than the other For example, by book says the series $$\sum_{n=2}^\infty \frac{1}{\sqrt{n} -1}$$ is greater than
$$\sum_{n=2}^\infty \frac{1}{\sqrt{n}}$$
Yet when I enter both An and Bn in my calculator, It seems to me that the value of Bn is always greater.

A: For any $n\in\mathbb{N},n\ge 2$ it is $$\frac{1}{\sqrt n-1}\ge \frac{1}{\sqrt n}.$$ So, $$\sum_{n=1}^N \frac{1}{\sqrt n-1}\ge \sum_{n=1}^N \frac{1}{\sqrt n}$$ for any $N\in\mathbb{N},N\ge 2.$

A: We have
$$
\sqrt{n}-1<\sqrt{n},\qquad n=1,2,3,\cdots,
$$ giving
$$
\frac1{\sqrt{n}-1}>\frac1{\sqrt{n}},\qquad n=2,3,\cdots,
$$ and by summing
$$
\sum_{n=2}^N \frac1{\sqrt{n}-1}>\sum_{n=2}^N \frac1{\sqrt{n}}
$$ but, as $N \to \infty$, both series are divergent:
$$
\lim_{N \to \infty}\sum_{n=2}^N \frac1{\sqrt{n}-1}=\lim_{N \to \infty}\sum_{n=2}^N \frac1{\sqrt{n}}=\infty.
$$

A: The basic point lies in the fact that, for any positive $n>1$
$$\sqrt{n}-1 \leq \sqrt{n}$$
$$\implies \frac{1}{\sqrt{n}-1} \geq \frac{1}{\sqrt{n}}$$
$$\implies \boxed{\sum_{n=2}^M \frac{1}{\sqrt{n}-1} \geq \sum_{n=2}^M \frac{1}{\sqrt{n}}} \,\,\,\,\,\,\, \text{for any finite positive integer M}$$
However, the inequality will have no meaning if $M \to \infty$. Since, then, both the summations become divergent.


text:
Q: jq with multiple select statements and an array I've got some JSON like the following (I've filtered the output here):
[
  {
    "Tags": [
      {
        "Key": "Name",
        "Value": "example1"
      },
     {
        "Key": "Irrelevant",
        "Value": "irrelevant"
      }
    ],

    "c7n:MatchedFilters": [
      "tag: example_tag_rule"
    ],
    "another_key": "another_value_I_dont_want"
  },
  {
    "Tags": [
      {
        "Key": "Name",
        "Value": "example2"
      }
    ],

    "c7n:MatchedFilters": [
      "tag:example_tag_rule",
      "tag: example_tag_rule2"
    ]
  }
]

I'd like to create a csv file with the value within the Name key and all of the "c7n:MatchedFilters" in the array. I've made a few attempts but still can't get quite the output I expect. There's some example code and the output below:
#Prints the key that I'm after.
cat new.jq | jq '.[] | [.Tags[], {"c7n:MatchedFilters"}] | .[] | select(.Key=="Name")|.Value'
"example1"
"example2"

#Prints all the filters in an array I'm after.
cat new.jq | jq -r '.[] | [.Tags[], {"c7n:MatchedFilters"}] | .[] | select(."c7n:MatchedFilters") | .[]'
[
  "tag: example_tag_rule"
]
[
  "tag:example_tag_rule",
  "tag: example_tag_rule2"
]

#Prints *all* the tags (including ones I don't want) and all the filters in the array I'm after.
cat new.jq | jq '.[] | [.Tags[], {"c7n:MatchedFilters"}] | select((.[].Key=="Name") and (.[]."c7n:MatchedFilters"))'
[
  {
    "Key": "Name",
    "Value": "example1"
  },
  {
    "Key": "Irrelevant",
    "Value": "irrelevant"
  },
  {
    "c7n:MatchedFilters": [
      "tag: example_tag_rule"
    ]
  }
]
[
  {
    "Key": "Name",
    "Value": "example2"
  },
  {
    "c7n:MatchedFilters": [
      "tag:example_tag_rule",
      "tag: example_tag_rule2"
    ]
  }
]

I hope this makes sense, let me know if I've missed anything.

A: Your attempts are not working because you start out with [.Tags[], {"c7n:MatchedFilters"}] to construct one array containing all the tags and an object containing the filters. You are then struggling to find a way to process this entire array at once because it jumbles together these unrelated things without any distinction. You will find it much easier if you don't combine them in the first place!
You want to find the single tag with a Key of "Name". Here's one way to find that:
first(
    .Tags[]|
    select(.Key=="Name")
).Value as $name

By using a variable binding we can save it for later and worry about constructing the array separately.
You say (in the comments) that you just want to concatenate the filters with spaces. You can do that easily enough:
(
    ."c7n:MatchedFilters"|
    join(" ")
) as $filters

You can combine all this together like follows. Note that each variable binding leaves the input stream unchanged, so it's easy to compose everything.
jq --raw-output '
    .[]|

    first(
        .Tags[]|
        select(.Key=="Name")
    ).Value as $name|

    (
        ."c7n:MatchedFilters"|
        join(" ")
    ) as $filters|

    [$name, $filters]|

    @csv

Hopefully that's easy enough to read and separates out each concept. We break up the array into a stream of objects. For each object, we find the name and bind it to $name, we concatenate the filters and bind them to $filters, then we construct an array containing both, then we convert the array to a CSV string.
We don't need to use variables. We could just have a big array constructor wrapped around the expression to find the name and the expression to find the filters. But I hope you can see the variables make things a bit flatter and easier to understand.


text:
Q: How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)? So here is my code:
test = {
    'a':1, 'b':2 , 'c':3 , 'd':4
}

x = raw_input("Type 'abcd' ")
y = len(x)
z = 1
while z < y+1:
    a = x[z-1]
    print test[a]
    z = z + 1

The point is to make a basic encoder, obviously this code is just to establish a quasi-code that I can build off of. My issue is this:
I can't make the result of the 'while' loop print into a single line, and with that, not only print into a single line, but to concatenate into a larger integer(or string for that matter, say the result of the code displayed letters instead of integers, to create a string from those letters). Although, in this code specifically, I want the result of the code to be the integer '1234'. Not:
1
2
3
4

Essentially, my question is this: How do I make the results of a while loop print in such a way that they concatenate integers(or letters) to create a larger number(or string)? I don't want the result
    1
    2
    3
    4
to become 10, but instead I want it to become the integer 1234. I've looked online, but I can't find anything that works for me. In fact I haven't found anything at all.

A: First of all, using a while loop here isn't optimal, instead, use a for loop, which is designed to loop over iterators like data structures (a string is just a sequence of characters):
for character in x:
    print(test[character])

Then instead of printing the characters, store them in a list.
characters = []
for character in x:
    characters.append(str(test[character]))

We can then join those into a single string (we made the numbers strings earlier to make this step easier), and make an int from that string:
int("".join(characters))

Python supports an easier way to do this kind of list construction - the list comprehension:
characters = [str(test[character]) for character in x]

This produces the same list as the for loop above, but faster and more concisely.
This means we can write your program as:
test = {'a': 1, 'b': 2 , 'c': 3 , 'd': 4}

user_input = raw_input("Type 'abcd':")

number = int("".join(str(test[character]) for character in user_input))

As an alternative to making the numbers strings to concatenate, then reverting back, we could also do it with maths:
number = sum((10 ** power) * test[character]
             for power, character in enumerate(reversed(user_input)))

What we do here is start from the right, take each number, multiply it up by the power of ten for the column it is in, and then sum the lot.

A: The easy answer is: don't print within the while loop, but concatenate up a string to print at the end:
result = ''
while z < y+1:
    a = x[z-1]
    result += str(test[a])
    z = z + 1
print result

If there are going to be a whole bunch of things, instead of concatenating strings on the fly, use a list and join at the end:
result = []
while z < y+1:
    a = x[z-1]
    result.append(str(test[a]))
    z = z + 1
print ''.join(result)

But you say you want to get an integer. Do you need that integer, for any reason other than to print it out? If so, you could build up a string and then convert it to an integer:
result = []
while z < y+1:
    a = x[z-1]
    result.append(str(test[a]))
    z = z + 1
val = int(''.join(result))

But this is silly. Why not just build up the value as an integer in the first place?
val = 0
while z < y+1:
    a = x[z-1]
    val = val * 10 + test[a]
    z = z + 1

Since you seem to be using Python 2, the only way to print without adding a newline, instead adds a space, which doesn't help. But Python 3—and Python 2 with from __future__ import print_function—has a more flexible alternative:
while z < y+1:
    a = x[z-1]
    print(test[a], end='')
    z = z + 1
print()

Or you can write directly to stdout:
while z < y+1:
    a = x[z-1]
    sys.stdout.write(str(test[a]))
    z = z + 1
sys.stdout.write('\n')


text:
Q: Generating strings from context free grammars The problem is implementing an algorithm, that generates all strings with length between l and r from given context free grammar G.
I have come up with simple approach: run BFS on grammar graph, remembering states.
But it fails on some recursive rules:
(1)   S -> 0 | SSS | λ

I can't simply limit maximum string length, because rules can contain λ (empty strings), so non-terminals can reduce final string length. (eg. running (1) with l = 1,  r = 2 will output only 0 in my implementation)
I also tried to limit maximum number of applied rules, but it is obviously wrong too.
How i can limit or change my algorithm, so it will never go in endless loop and will work correctly?

A: You can transform the grammer to Greibach normal form, and then each step1  in the creationis increasing the size of the produced word, and you will be able to limit the length of the word as initially explained in the question.

(1) except possibly the first, if the empty word is in the grammer


text:
Q: Как сделать неограниченное количество яндекс карт на одной странице? Стоит задача заверстать большое количество карт на одной странице, какое именно - неизвестно, но их может быть очень много.
Инициализировать ее нужно по клику, так как карты находятся в табах, ну и соотвественно при переходе на другой таб, скрывать предыдущую и показывать новую, то есть инициализировать новую карту, а старую убирать.
Насколько я понял, яндекс API позволяет вызывать ее тольео по id, Значит мне надо как-то параметром передавать этот id. В идеале контейнеру через data-attr надо передавать координаты еще.
До чего дошел сам на данный момент:
$(document).ready(function(){

    $('.carousel-flights-item').click(function(){
        showMap();
        initYaMap ();
        return false;
    });

});

function initYaMap () {

    ymaps.ready(init);
    var myMap;

    function init(){
        myMap = new ymaps.Map ("map", {
            center: [53.35, 83.73],
            zoom: 4
        });
    }

}

P.S. Если нужна доп информаци или рабочий код, пишите выложу на codepen.


text:
Q: Realm usage for non-ui thread I have made use of realm in the non-Ui and ui threads.
Different thread jobs are queued, ui thread jobs are managed from activity or fragments onCreate-onDestroy and using RealmManager.
Always given this error:

Exception! message:This Realm instance has already been closed, making
  it unusable.

Please help me!

Ui thread operations controller:

RealmManager:
public class RealmManager {

    private static String TAG = RealmManager.class.getSimpleName();
    private static final ThreadLocal<Realm> localRealms = new ThreadLocal<>();

    private static Monarchy monarchy;
    private static Monarchy.Builder monarchyBuilder;

    public static Monarchy getMonarchy() {

        checkDefaultConfiguration();

        if (monarchy == null) {

            monarchy = new Monarchy.Builder()
                    .setRealmConfiguration(Realm.getDefaultConfiguration())
                    .build();
        }
        return monarchy;
    }

    public static Monarchy.Builder getMonarchyBuilder() {

        checkDefaultConfiguration();

        if (monarchyBuilder == null) {
            monarchyBuilder = new Monarchy.Builder();
        }
        return monarchyBuilder;
    }

    public static Realm open() {

        checkDefaultConfiguration();

        Realm realm = Realm.getDefaultInstance();

        if (checkRealm(realm)) {
            localRealms.set(realm);
        }

        Mylog.i(TAG, " open Realm.getDefaultInstance() realm:" + realm + localRealms);

        return realm;
    }

    public static Realm getLocalInstance() {

        checkDefaultConfiguration();

        Realm realm = localRealms.get();

        Mylog.i(TAG, " getLocalInstance localRealms.get() realm:" + realm);

        if (!checkRealm(realm)) {
            return open();
        }
        return realm;
    }

    public static void close() {

        Realm realm = localRealms.get();
        Mylog.i(TAG, " close localRealms.get realm:" + realm);
        close(realm);
    }

    public static void close(Realm realm) {

        Mylog.i(TAG, " close realm:" + realm);
        checkDefaultConfiguration();

        if (!checkRealm(realm)) {
            return;
        }

        realm.close();
        controlLocalInstanceCount();
    }

    public static void checkDefaultConfiguration() {

        if (Realm.getDefaultConfiguration() == null) {
            new RealmEncryptionHelper().setDefaultConfiguration();
        }
    }

    public static boolean checkRealm(Realm realm) {
        return realm != null && !realm.isClosed();
    }

    private static void controlLocalInstanceCount() {

        // noinspection ConstantConditions
        Mylog.i(TAG, " controlLocalInstanceCount:" + Realm.getLocalInstanceCount(Realm.getDefaultConfiguration()));

        // noinspection ConstantConditions
        if (Realm.getLocalInstanceCount(Realm.getDefaultConfiguration()) <= 0) {
            localRealms.set(null);
        }
    }

}

Activity usage on main:

onCreate(){
realm = RealmManager.open();
}

onDestroy(){
RealmManager.close(realm);
}

Another thread usage:

RealmRunnable realmRunnable = new RealmRunnable() {
            @Override
            public void run() {

                Realm mRealm = getRealm();
                //realm operations for non-ui thread
            }
        };

        getRealmController().addRealmRunnable(realmRunnable);

A:
    private ConcurrentLinkedQueue<RealmRunnable> runnableConcurrentLinkedQueue = new ConcurrentLinkedQueue<>();
    private Thread realmThread;

            realmThread = new Thread(new Runnable() {

                Realm realm;

                @Override
                public void run() {

                    while (!realmThread.isInterrupted()) {

                        if (runnableConcurrentLinkedQueue.isEmpty()) {

                            synchronized (realmThreadLock) {

                                if (runnableConcurrentLinkedQueue.isEmpty()) {

Everything related to the management of serialized runnable execution can be done with one line:
Executor singleThreadedExecutor = Executors.newSingleThreadedPool();

However this would assume that whenever you post a runnable, you need to open/close Realm.
singleThreadedExecutor.post(new Runnable() {
    @Override public void run() {
        try {
            realmManager.openLocalInstance();
            // do whatever
        } finally {
            realmManager.closeLocalInstance();
        }
    }
});

With Realm out of the box, this would of course also work:
singleThreadedExecutor.post(new Runnable() {
    @Override public void run() {
        try(Realm realm = Realm.getDefaultInstance()) {
            // do whatever, but you have to pass Realm around instead of `getLocalInstance()`
        }
        // realm is closed here
    }
});

If you want the automatic lifecycle management per runnable so that Realm is open with realmManager.getLocalInstance() on the background thread WITHOUT manually opening it yourself, then you need to go much deeper. Note that I'm writing it for the very first time here, so it's kinda theoretical in that regard.
Anyways, you'd need to extend ThreadPoolExecutor and define protected void beforeExecute(Thread t, Runnable r) and protected void after(Thread t, Runnable r). It would look something like this:
 public class RealmThreadPoolExecutor extends ThreadPoolExecutor {
     private final RealmManager realmManager;

     public RealmThreadPoolExecutor(RealmManager realmManager) {
          super(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); // from newSingleThreadedPool
          this.realmManager = realmManager;
     }

     @Override protected void beforeExecute(Thread thread, Runnable runnable) {
         super.beforeExecute(thread, runnable);
         realmManager.openLocalInstance();
         realmManager.getLocalInstance().refresh();
     }

     @Override protected void afterExecute(Thread thread, Runnable runnable) {
         super.afterExecute(thread, runnable);
         realmManager.closeLocalInstance();
     }
}

Then instead of your personally managed runnable execution, you'd do:
private final Executor realmExecutor = new RealmThreadPoolExecutor(realmManager);

public void addRunnable(Runnable runnable) {
    realmExecutor.execute(runnable);
}

and it should be equivalent with what you did. Except instead of RealmRunnable and setRealm, you'd be calling realmManager.getLocalInstance().
BTW, get shouldn't open a Realm, if you need to open a Realm in there then that means the lifecycle management is wrong and you should have opened it previously, so it just hides bug.

Technically you also chose to use Monarchy instead of using your own manual thread-local cache (though personally I'm not sure if you need both at once...), which means you would be using Realm in a "singleton manner" just by executing your logic inside a monarchy.doWithRealm(new RealmBlock() {.
@Override public void run() {
    monarchy.doWithRealm((realm) -> {
        // realm is open here
    });
    // realm is closed here
}

Monarchy doesn't expose a open/close directly because people never close the Realm (I've been here for a while now, I know) so this block disallows them from doing so. Unless they manually call Realm.getDefaultInstance() somewhere, Monarchy will keep Realm closed when it's not needed. The benefit here is that if you want a transaction, you do:
monarchy.runTransactionSync((realm) -> {
    // do transaction. Realm is opened by config automatically.
});
// realm is closed here.

And most importantly, via Monarchy, the UI thread queries are all exposed via a LiveData, where having at least 1 subscriber opens the Realm, while having 0 subscribers closes the Realm -- therefore on UI thread, the Realm lifecycle is managed automatically by your subscriptions to Realm queries. If there are no observers, then Realm is closed.
LiveData<List<RealmDog>> dogs;
Observer<List<RealmDog>> observer = dogs -> {
    adapter.updateData(dogs);
};

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ButterKnife.bind(this, view);
    ...
    dogs = monarchy.findAllCopiedWithChanges(realm -> realm.where(RealmDog.class));
    dogs.observeForever(observer);
}

@Override
public void onDestroyView() {
    dogs.removeObserver(observer);
    super.onDestroyView();
}

Regardless of which path you choose, you should probably just delete that RealmController, you don't need it.


text:
Q: Error: the chosen directory does not contain the required product while installing STS While installing STS using installer, I was asked to select the JDK path:

I used the following command to get the jdk path:

However it shows the error:
The chosen directory does not contain the required product

Please advice.

A: Somebody solved selecting path up to JDK directory (removing final bin).
Otherwise try downloading zip file instead of installer and unzip it somewhere (not in Program Files).
Then you can configure it manually setting the "-vm c:\pathtojdk\bin\javaw.exe" argument in STS.ini.


text:
Q: Метасимволы \b и \B Текст:
cat catter scat scatter

nine-digit - nine - digit

Регулярные выражения:

*

*\bcat\b — результат,

*\Bcat\B — результат,

Всё, как в описании метасимволов: \b — соответствует границе слова, \B — не соответствует.
Однако если вместо cat использовать литерал -:

*\b-\b — результат,

*\B-\B — результат.

Получается наоборот. Шаблоном \b-\b находятся дефисы внутри слова, а \B-\B — окружённые пробелами. Почему так?

A: Всё дело в том, что символ - не является частью «слова» в терминологии PCRE.
В документации PHP к символьному классу \w есть следующие строки:

Символ, образующий "слово" - это произвольная цифра, буква или символ подчеркивания, проще говоря, любой символ, который может являться частью "слова" в Perl.

А в документации к PCRE есть вот такое определение «слова»:

A "word" character is an underscore or any character that is  a  letter or  digit.

A: "nine-digit" - это не одно слово, а два. Вот по их границами и происходит отсечение.
Символ "-" не относится к символам, из которых состоят слова.


text:
Q: website redirection to mobile site I need help in redirecting visitor to depending on device they use.
PC: http://example.com/filename
Mobile: http://mobile.example.com/filename
I tried with java script notice 1 issue when user enters url example .com/filename it is redirecting to mobile index page instead of page user wanted.
main issue i noticed is url entered by user is not captured.
Please help me how to do it

*

*If user is using PC he should remain on main website and if using mobile device he should redirect to mobile site.

*Url entered by user should be captured

A: I won't be specifically answering your question, but it's no longer that "good practice" to separate content for mobile and desktop devices.
In these days of CSS3, HTML5 there are lots of better ways to accomplish fully responsive webpage than deviding the content.
I understand that there might be reasons why you need to do it this way (finished project that would be hard to reconstruct, etc.) but if it's not too late, think about it.
This answer could be also useful for people who don't know all possibilities on responsive web pages field.


text:
Q: Batch splitting an array element in nested loop @echo off

set hosts[1]=192.168.1.1
set hosts[2]=192.168.1.2
set hosts[3]=192.168.1.3
set hosts[4]=192.168.1.4

set hostcreds[1]=root:pw1!
set hostcreds[2]=root:pw2!
set hostcreds[3]=root:pw3!
set hostcreds[4]=root:pw4!

for /L %%a in (1,1,4) do (

 CALL ECHO Host: %%hosts[%%a]%%>>file%%a.txt

  for /F "tokens=1,2 delims=: " %%A in ("%%hostcreds[%%a]%%") do (
   CALL ECHO User: %%A Pass: %%B>>file%%a.txt
  )

)

The output is 4 text files named file1 through 4.txt with the contents of "Host: [host IP]" (line return) "User: root:pw1 Pass:" but I would like the output to split "root:pw1" so the output looks like "User: root Pass: pw1".
Why is my for /F not splitting this array element into %%A and %%B? If I remove the array element and change it to just plain text it splits fine.

A: Inside the command for your inner FOR loop, use the CALL command to expand the array value before you process the results. This way the value is parsed before it is split by the FOR delimiters. By doing this, you no longer need the CALL statement when writing the credentials.
Here is the updated script:
@echo off

set hosts[1]=192.168.1.1
set hosts[2]=192.168.1.2
set hosts[3]=192.168.1.3
set hosts[4]=192.168.1.4

set hostcreds[1]=root:pw1!
set hostcreds[2]=root:pw2!
set hostcreds[3]=root:pw3!
set hostcreds[4]=root:pw4!

for /L %%a in (1,1,4) do (

 CALL ECHO Host: %%hosts[%%a]%%>>file%%a.txt

  for /F "tokens=1,2 delims=: " %%A in ('CALL ECHO %%hostcreds[%%a]%%') do (
   ECHO User: %%A Pass: %%B>>file%%a.txt
  )

)


text:
Q: Split list based on first character - Python I am new to Python and can't quite figure out a solution to my Problem. I would like to split a list into two lists, based on what the list item starts with. My list looks like this, each line represents an item (yes this is not the correct list notation, but for a better overview i'll leave it like this) :
***
**
.param
+foo = bar
+foofoo = barbar
+foofoofoo = barbarbar
.model
+spam = eggs
+spamspam = eggseggs
+spamspamspam = eggseggseggs

So I want a list that contains all lines starting with a '+' between .param and .model and another list that contains all lines starting with a '+' after model until the end.
I have looked at enumerate() and split(), but since I have a list and not a string and am not trying to match whole items in the list, I'm not sure how to implement them.
What I have is this:
paramList = []
for line in newContent:
    while line.startswith('+'):
        paramList.append(line)
        if line.startswith('.'):
            break

This is just my try to create the first list. The Problem is, the code reads the second block of '+'s as well because break just Exits the while Loop, not the for Loop.
I hope you can understand my question and thanks in advance for any pointers!

A: data = {}
for line in newContent:
    if line.startswith('.'):
        cur_dict = {}
        data[line[1:]] = cur_dict
    elif line.startswith('+'):
        key, value = line[1:].split(' = ', 1)
        cur_dict[key] = value

This creates a dict of dicts:
{'model': {'spam': 'eggs',
           'spamspam': 'eggseggs',
           'spamspamspam': 'eggseggseggs'},
 'param': {'foo': 'bar',
           'foofoo': 'barbar',
           'foofoofoo': 'barbarbar'}}

A: What you want is really a simple task that can be accomplish using list slices and list comprehension:
data = ['**','***','.param','+foo = bar','+foofoo = barbar','+foofoofoo = barbarbar',
     '.model','+spam = eggs','+spamspam = eggseggs','+spamspamspam = eggseggseggs']

# First get the interesting positions.
param_tag_pos = data.index('.param')
model_tag_pos = data.index('.model')
# Get all elements between tags.
params =  [param for param in data[param_tag_pos + 1: model_tag_pos] if param.startswith('+')]
models =  [model for model in data[model_tag_pos + 1: -1] if model.startswith('+')]

print(params)
print(models)

Output
>>> ['+foo = bar', '+foofoo = barbar', '+foofoofoo = barbarbar']
>>> ['+spam = eggs', '+spamspam = eggseggs']

Answer to comment:
Suppose you have a list containing numbers from 0 up to 5.
l = [0, 1, 2, 3, 4, 5]

Then using list slices you can select a subset of l:
another = l[2:5]   # another is [2, 3, 4]

That what we are doing here:
data[param_tag_pos + 1: model_tag_pos]

And for your last question: ...how does python know param are the lines in data it should iterate over and what exactly does the first paramin param for paramdo?
Python doesn't know, You have to tell him.
First param is a variable name I'm using here, it cuold be x,  list_items, whatever you want.
and I will translate the line of code to plain english for you:
# Pythonian
params =  [param for param in data[param_tag_pos + 1: model_tag_pos] if param.startswith('+')]

# English
params is a list of "things", for each "thing" we can see in the list `data`
from position `param_tag_pos + 1` to position `model_tag_pos`, just if that "thing" starts with the character '+'.

A:
I am new to Python

Whoops.  Don't bother with my answer then.

I want a list that contains all lines starting with a '+' between
  .param and .model and another list that contains all lines starting
  with a '+' after model until the end.

import itertools as it
import pprint

data = [
    '***',
    '**',
    '.param',
    '+foo = bar',
    '+foofoo = barbar',
    '+foofoofoo = barbarbar',
    '.model',
    '+spam = eggs',
    '+spamspam = eggseggs',
    '+spamspamspam = eggseggseggs',
]

results = [
    list(group) for key, group in it.groupby(data, lambda s: s.startswith('+'))
    if key
]

pprint.pprint(results)
print '-' * 20
print results[0]
print '-' * 20
pprint.pprint(results[1])

--output:--
[['+foo = bar', '+foofoo = barbar', '+foofoofoo = barbarbar'],
 ['+spam = eggs', '+spamspam = eggseggs', '+spamspamspam = eggseggseggs']]
--------------------
['+foo = bar', '+foofoo = barbar', '+foofoofoo = barbarbar']
--------------------
['+spam = eggs', '+spamspam = eggseggs', '+spamspamspam = eggseggseggs']

This thing here:
it.groupby(data, lambda x: x.startswith('+')

...tells python to create groups from the strings according to their first character.  If the first character is a '+', then the string gets put into a True group.  If the first character is not a '+', then the string gets put into a False group.  However, there are more than two groups because  consecutive False strings will form a group, and consecutive True strings will form a group.
Based on your data, the first three strings:
***
**
.param

will create one False group.  Then, the next strings:
+foo = bar
+foofoo = barbar
+foofoofoo = barbarbar

will create one True group.  Then the next string:
'.model'

will create another False group. Then the next strings:
'+spam = eggs'
'+spamspam = eggseggs'
'+spamspamspam = eggseggseggs'

will create another True group.  The result will be something like:
{
    False: [strs here],
    True:  [strs here],
    False: [strs here],
    True:  [strs here]
}

Then it's just a matter of picking out each True group: if key, and then converting the corresponding group to a list: list(group).
Response to comment:

where exactly does python go through data, like how does it know s is
  the data it's iterating over?

groupby() works like do_stuff() below:
def do_stuff(items, func):
    for item in items:
        print func(item)

#Create the arguments for do_stuff():

data = [1, 2, 3]

def my_func(x):
    return  x + 100

#Call do_stuff() with the proper argument types:

do_stuff(data, my_func) #Just like when calling groupby(), you provide some data
                        #and a function that you want applied to each item in data

--output:--
101
102
103

Which can also be written like this:
do_stuff(data, lambda x: x + 100)

lambda creates an anonymous function, which is convenient for simple functions which you don't need to refer to by name.
This list comprehension:
[
    list(group)
    for key, group in it.groupby(data, lambda s: s.startswith('+'))
    if key
]

is equivalent to this:
results = []

for key, group in it.groupby(data, lambda s: s.startswith('+') ):
   if key:
       results.append(list(group))

It's clearer to explicitly write a for loop, however list comprehensions execute much faster.  Here is some detail:
[
    list(group)  #The item you want to be in the results list for the current iteration of the loop here:
    for key, group in it.groupby(data, lambda s: s.startswith('+')) #A for loop
    if key #Only include the item for the current loop iteration in the results list if key is True
]

A: I would suggest doing things step by step.
1) Grab every word from the array separately.
2) Grab the first letter of the word.
3) Look if that is a '+' or '.'
Example code:
import re
class Dark():
    def __init__(self):
        # Array
        x = ['+Hello', '.World', '+Hobbits', '+Dwarves', '.Orcs']
        xPlus = []
        xDot = []
        # Values
        i = 0
        # Look through every word in the array one by one.
        while (i != len(x)):
            # Grab every word (s), and convert to string (y).
            s = x[i:i+1]
            y = '\n'.join(s)
            # Print word
            print(y)
            # Grab the first letter.
            letter = y[:1]
            if (letter == '+'):
                xPlus.append(y)
            elif (letter == '.'):
                xDot.append(y)
            else:
                pass
            # Add +1
            i = i + 1
        # Print lists
        print(xPlus)
        print(xDot)

#Run class
Dark()


text:
Q: How to assign environment variables in .env file to $_ENV variable php In laravel, the environment variables are stored in the .env file and later assigned to the $_ENV superglobal variable. What should I do if I want the same function (get the variables in the .env file). I tried researching but my efforts are in vain...

A: You can use this lib for that: https://github.com/vlucas/phpdotenv


text:
Q: How to properly escape hash in Android.mk? I am using -Werror flag to treat all warnings as errors in my code. However, I would like compile warnings issued from code to still be treated as warnings. A GCC option for this is -Wno-error=cpp which works correctly, however clang option is -Wno-error=#warnings which I don't know how to pass to clang from Android.mk.
I've tried this:
ifeq "$(findstring clang,$(NDK_TOOLCHAIN_VERSION))" "clang"
    LOCAL_CFLAGS += -Wno-error=#warnings
endif

and this (as suggested in this SO answer):
ifeq "$(findstring clang,$(NDK_TOOLCHAIN_VERSION))" "clang"
    LOCAL_CFLAGS += -Wno-error=\#warnings
endif

However, both versions treat # as beginning of comment and ndk-build passes -Wno-error= to compiler (i.e. everything after = is ignored) - I inspected that with ndk-build -n.
I even tried
ifeq "$(findstring clang,$(NDK_TOOLCHAIN_VERSION))" "clang"
    LOCAL_CFLAGS += -Wno-error=\\#warnings
endif

which produces -Wno-error=\ compiler flag.
How to properly pass this compiler flag to clang from Android.mk file?
I am using NDK r12b.
EDIT:
I even tried this:
ifeq "$(findstring clang,$(NDK_TOOLCHAIN_VERSION))" "clang"
    VAR=\#warnings
    $(info VAR is '$(VAR)')
    LOCAL_CFLAGS += -Wno-error=$(VAR)
endif

and ndk-build first outputs message VAR is '#warnings' yet compiler arguments contain -Wno-error=. This is obviously an NDK issue.

A: LOCAL_CFLAGS += -Wno-error=\#warnings

is almost there. But to get make to treat the \ as escaping the #
it needs to be in quoted context.
Makefile
CXX := clang++

CXXFLAGS += "-Wno-error=\#warnings"

hello: HelloWorld.o
    $(CXX) -o $@ $^

Build and run:
$ make && ./hello
clang++ "-Wno-error=#warnings"   -c -o HelloWorld.o HelloWorld.cpp
clang++ -o hello HelloWorld.o
Hello World


text:
Q: Core Image Filtered image jumps out of my UIImageView on iOS 10 I am having an issue applying certain Core Image Filters on iOS 10. Filters like CICrystallize, CIEdgeWork, CIHexagonalPixellate, CIPointillize jump out of my UIImageView when filter is applied.
Strange part one is the bigger the inputScale the more they shift away from center. Strange part two is that it happens only iOS 10; they were all working fine on iOS 9. Strange part three is that it happens only on real devices; on the iOS 10 simulator all works fine!

A: Found a solution. Replaced
filteredImage.image = UIImage(CIImage: filteredImageData)

With this:
let filteredImageRef = ciContext.createCGImage(filteredImageData, fromRect: filteredImageData.extent)
filteredImage.image = UIImage(CGImage: filteredImageRef!)


text:
Q: Where do electrons go after reaching GND in this Arduino Mega design? When examining the EAGLE file for the Arduino Mega that I downloaded from their official website, I noticed that the ground (GND) is not connected to anything other than the C4 component, which means electrons flows from +5V through the C4 component into the GND.
When I look at the actual board, I see that the GND is indeed only connected to the C4 component and has no path connected to anything else at all.
Does that mean when I plug in the Arduino board to a power source, the electrons from +5V just start piling up at where GND is, since there is not an outlet for it? Won't there come a point where there are so many electrons piling up at GND that electrons at GND start repelling the electrons flowing from +5V, and the circuit just stops working?

A: I downloaded the board files, opened in eagle, and ran the command "ratsnest" to repour all copper pours. Lo and behold, it's as suggested by both me and @WesleyLee in the comments - there is a copper ground pour on the board.

A: Assuming there is no connection, you would have an open chain. This means no current will flow and no voltage will be built up over the component.
Remember: \$ V = \int\frac{I}{C}dt \$
But the current will be zero.


text:
Q: How to make table to scroll with an Android device? I am using a jQuery Mobile script and datatables and I must say that I have successfully combined those two together.
But here is a problem that I have noticed. When I am testing my application with an Iphone I am able to perform an inner scroll of the table with 2 finger gestures sliding up/down, but when I tried on several Android devices inner scroll of the table is not working.
My table has a hide/show option so when I am in the last line where results are shown and when I press plus button an additional window is opened but I can't scroll down and with an Iphone I can. What could I do to achieve this?

A: You need to use a script for this as otherwise your phone OS do not know if you want to scroll the inner div or the whole page :
This is the one and only : http://cubiq.org/iscroll-4


text:
Q: What is difference between two strings?
*

*%EB%AA%A8%EB%85%B8%EA%B0%80%ED%83%80%EB%A6%AC

*%B8%F0%B3%EB%B0%A1%C5%B8%B8%AE

I decode them. and They are same as "모노가타리". But their encoded appearance are different. I think they have different encoding.
What is difference between two strings?

A: The first encoding is UTF-8. The second appears to be Unified Hangeul.
http://www.kreativekorp.com/charset/encoding.php?name=Unified+Hangeul&char=B8F0


text:
Q: Can I send a ctrl-C (SIGINT) to an application on Windows? I have (in the past) written cross-platform (Windows/Unix) applications which, when started from the command line, handled a user-typed Ctrl-C combination in the same way (i.e. to terminate the application cleanly).
Is it possible on Windows to send a Ctrl-C/SIGINT/equivalent to a process from another (unrelated) process to request that it terminate cleanly (giving it an opportunity to tidy up resources etc.)?

A: Somehow GenerateConsoleCtrlEvent() return error if you call it for another process, but you can attach to another console application and send event to all child processes.
void SendControlC(int pid)
{
    AttachConsole(pid); // attach to process console
    SetConsoleCtrlHandler(NULL, TRUE); // disable Control+C handling for our app
    GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // generate Control+C event
}

A: Edit:
For a GUI App, the "normal" way to handle this in Windows development would be to send a WM_CLOSE message to the process's main window.
For a console app, you need to use SetConsoleCtrlHandler to add a CTRL_C_EVENT.
If the application doesn't honor that, you could call TerminateProcess.

A: Here is the code I use in my C++ app.
Positive points :

*

*Works from console app

*Works from Windows service

*No delay required

*Does not close the current app

Negative points :

*

*The main console is lost and a new one is created (see FreeConsole)

*The console switching give strange results...

// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
    bool success = false;
    DWORD thisConsoleId = GetCurrentProcessId();
    // Leave current console if it exists
    // (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
    bool consoleDetached = (FreeConsole() != FALSE);

    if (AttachConsole(dwProcessId) != FALSE)
    {
        // Add a fake Ctrl-C handler for avoid instant kill is this console
        // WARNING: do not revert it or current program will be also killed
        SetConsoleCtrlHandler(nullptr, true);
        success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
        FreeConsole();
    }

    if (consoleDetached)
    {
        // Create a new console if previous was deleted by OS
        if (AttachConsole(thisConsoleId) == FALSE)
        {
            int errorCode = GetLastError();
            if (errorCode == 31) // 31=ERROR_GEN_FAILURE
            {
                AllocConsole();
            }
        }
    }
    return success;
}

Usage example :
DWORD dwProcessId = ...;
if (signalCtrl(dwProcessId, CTRL_C_EVENT))
{
    cout << "Signal sent" << endl;
}

A: A solution that I have found from here is pretty simple if you have python 3.x available in your command line.  First, save a file (ctrl_c.py) with the contents:
import ctypes
import sys

kernel = ctypes.windll.kernel32

pid = int(sys.argv[1])
kernel.FreeConsole()
kernel.AttachConsole(pid)
kernel.SetConsoleCtrlHandler(None, 1)
kernel.GenerateConsoleCtrlEvent(0, 0)
sys.exit(0)

Then call:
python ctrl_c.py 12345

If that doesn't work, I recommend trying out the windows-kill project:

*

*Choco: https://github.com/ElyDotDev/windows-kill

*Node: https://github.com/ElyDotDev/node-windows-kill

A: I have done some research around this topic, which turned out to be more popular than I anticipated. KindDragon's reply was one of the pivotal points.
I wrote a longer blog post on the topic and created a working demo program, which demonstrates using this type of system to close a command line application in a couple of nice fashions. That post also lists external links that I used in my research.
In short, those demo programs do the following:

*

*Start a program with a visible window using .Net, hide with pinvoke, run for 6 seconds, show with pinvoke, stop with .Net.

*Start a program without a window using .Net, run for 6 seconds, stop by attaching console and issuing ConsoleCtrlEvent
Edit: The amended solution from @KindDragon for those who are interested in the code here and now. If you plan to start other programs after stopping the first one, you should re-enable CTRL+C handling, otherwise the next process will inherit the parent's disabled state and will not respond to CTRL+C.
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(uint dwProcessId);

[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool FreeConsole();

[DllImport("kernel32.dll")]
static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);

delegate bool ConsoleCtrlDelegate(CtrlTypes CtrlType);

// Enumerated type for the control messages sent to the handler routine
enum CtrlTypes : uint
{
    CTRL_C_EVENT = 0,
    CTRL_BREAK_EVENT,
    CTRL_CLOSE_EVENT,
    CTRL_LOGOFF_EVENT = 5,
    CTRL_SHUTDOWN_EVENT
}

[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);

public void StopProgram(Process proc)
{
    //This does not require the console window to be visible.
    if (AttachConsole((uint)proc.Id))
    {
    // Disable Ctrl-C handling for our program
    SetConsoleCtrlHandler(null, true);
    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

    //Moved this command up on suggestion from Timothy Jannace (see comments below)
    FreeConsole();

    // Must wait here. If we don't and re-enable Ctrl-C
    // handling below too fast, we might terminate ourselves.
    proc.WaitForExit(2000);

    //Re-enable Ctrl-C handling or any subsequently started
    //programs will inherit the disabled state.
    SetConsoleCtrlHandler(null, false);
    }
}

Also, plan for a contingency solution if AttachConsole() or the sent signal should fail, for instance sleeping then this:
if (!proc.HasExited)
{
    try
    {
    proc.Kill();
    }
    catch (InvalidOperationException e){}
}

A:         void SendSIGINT( HANDLE hProcess )
        {
            DWORD pid = GetProcessId(hProcess);
            FreeConsole();
            if (AttachConsole(pid))
            {
                // Disable Ctrl-C handling for our program
                SetConsoleCtrlHandler(NULL, true);

                GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // SIGINT

                //Re-enable Ctrl-C handling or any subsequently started
                //programs will inherit the disabled state.
                SetConsoleCtrlHandler(NULL, false);

                WaitForSingleObject(hProcess, 10000);
            }
        }

A: Thanks to jimhark's answer and other answers here, I found a way to do it in PowerShell:
$ProcessID = 1234
$MemberDefinition = '
    [DllImport("kernel32.dll")]public static extern bool FreeConsole();
    [DllImport("kernel32.dll")]public static extern bool AttachConsole(uint p);
    [DllImport("kernel32.dll")]public static extern bool GenerateConsoleCtrlEvent(uint e, uint p);
    public static void SendCtrlC(uint p) {
        FreeConsole();
        if (AttachConsole(p)) {
            GenerateConsoleCtrlEvent(0, p);
            FreeConsole();
        }
        AttachConsole(uint.MaxValue);
    }'
Add-Type -Name 'dummyName' -Namespace 'dummyNamespace' -MemberDefinition $MemberDefinition
[dummyNamespace.dummyName]::SendCtrlC($ProcessID)

What made things work was sending the GenerateConsoleCtrlEvent to the desired process group instead of sending it to all processes that share the console of the calling process and then AttachConsole back to the current process' parent's console.

A: The closest that I've come to a solution is the SendSignal 3rd party app.  The author lists source code and an executable.  I've verified that it works under 64-bit windows (running as a 32-bit program, killing another 32-bit program), but I've not figured out how to embed the code into a windows program (either 32-bit or 64-bit).
How it works:

After much digging around in the debugger I discovered that the entry point that actually does the behavior associated with a signal like ctrl-break is kernel32!CtrlRoutine. The function had the same prototype as ThreadProc, so it can be used with CreateRemoteThread directly, without having to inject code. However, that's not an exported symbol! It's at different addresses (and even has different names) on different versions of Windows. What to do?
Here is the solution I finally came up with. I install a console ctrl handler for my app, then generate a ctrl-break signal for my app. When my handler gets called, I look back at the top of the stack to find out the parameters passed to kernel32!BaseThreadStart. I grab the first param, which is the desired start address of the thread, which is the address of kernel32!CtrlRoutine. Then I return from my handler, indicating that I have handled the signal and my app should not be terminated. Back in the main thread, I wait until the address of kernel32!CtrlRoutine has been retrieved. Once I've got it, I create a remote thread in the target process with the discovered start address. This causes the ctrl handlers in the target process to be evaluated as if ctrl-break had been pressed!
The nice thing is that only the target process is affected, and any process (even a windowed process) can be targeted. One downside is that my little app can't be used in a batch file, since it will kill it when it sends the ctrl-break event in order to discover the address of kernel32!CtrlRoutine.

(Precede it with start if running it in a batch file.)

A: Yes. The https://github.com/ElyDotDev/windows-kill project does exactly what you want:
windows-kill -SIGINT 1234

A: I guess I'm a bit late on this question but I'll write something anyway for anyone having the same problem.
This is the same answer as I gave to this question.
My problem was that I'd like my application to be a GUI application but the processes executed should be run in the background without any interactive console window attached. I think this solution should also work when the parent process is a console process. You may have to remove the "CREATE_NO_WINDOW" flag though.
I managed to solve this using GenerateConsoleCtrlEvent() with a wrapper app. The tricky part is just that the documentation is not really clear on exactly how it can be used and the pitfalls with it.
My solution is based on what is described here. But that didn't really explain all the details either and with an error, so here is the details on how to get it working.
Create a new helper application "Helper.exe". This application will sit between your application (parent) and the child process you want to be able to close. It will also create the actual child process. You must have this "middle man" process or GenerateConsoleCtrlEvent() will fail.
Use some kind of IPC mechanism to communicate from the parent to the helper process that the helper should close the child process. When the helper get this event it calls "GenerateConsoleCtrlEvent(CTRL_BREAK, 0)" which closes down itself and the child process. I used an event object for this myself which the parent completes when it wants to cancel the child process.
To create your Helper.exe create it with CREATE_NO_WINDOW and CREATE_NEW_PROCESS_GROUP. And when creating the child process create it with no flags (0) meaning it will derive the console from its parent. Failing to do this will cause it to ignore the event.
It is very important that each step is done like this. I've been trying all different kinds of combinations but this combination is the only one that works. You can't send a CTRL_C event. It will return success but will be ignored by the process. CTRL_BREAK is the only one that works. Doesn't really matter since they will both call ExitProcess() in the end.
You also can't call GenerateConsoleCtrlEvent() with a process groupd id of the child process id directly allowing the helper process to continue living. This will fail as well.
I spent a whole day trying to get this working. This solution works for me but if anyone has anything else to add please do. I went all over the net finding lots of people with similar problems but no definite solution to the problem. How GenerateConsoleCtrlEvent() works is also a bit weird so if anyone knows more details on it please share.

A: It should be made crystal clear because at the moment it isn't.
There is a modified and compiled version of SendSignal to send Ctrl-C (by default it only sends Ctrl+Break). Here are some binaries:

(2014-3-7) : I built both 32-bit and 64-bit version with Ctrl-C, it's called SendSignalCtrlC.exe and you can download it at: https://dl.dropboxusercontent.com/u/49065779/sendsignalctrlc/x86/SendSignalCtrlC.exe https://dl.dropboxusercontent.com/u/49065779/sendsignalctrlc/x86_64/SendSignalCtrlC.exe -- Juraj Michalak

I have also mirrored those files just in case:
32-bit version: https://www.dropbox.com/s/r96jxglhkm4sjz2/SendSignalCtrlC.exe?dl=0
64-bit version: https://www.dropbox.com/s/hhe0io7mcgcle1c/SendSignalCtrlC64.exe?dl=0
Disclaimer: I didn't build those files. No modification was made to the compiled
original files. The only platform tested is the 64-bit Windows 7. It is recommended to adapt the source available at http://www.latenighthacking.com/projects/2003/sendSignal/ and compile it yourself.

A: In Java, using JNA with the Kernel32.dll library, similar to a C++ solution. Runs the CtrlCSender main method as a Process which just gets the console of the process to send the Ctrl+C event to and generates the event. As it runs separately without a console the Ctrl+C event does not need to be disabled and enabled again.
CtrlCSender.java - Based on Nemo1024's  and KindDragon's  answers.
Given a known process ID, this consoless application will attach the console of targeted process and generate a CTRL+C Event on it.
import com.sun.jna.platform.win32.Kernel32;

public class CtrlCSender {

    public static void main(String args[]) {
        int processId = Integer.parseInt(args[0]);
        Kernel32.INSTANCE.AttachConsole(processId);
        Kernel32.INSTANCE.GenerateConsoleCtrlEvent(Kernel32.CTRL_C_EVENT, 0);
    }
}

Main Application - Runs CtrlCSender as a separate consoless process
ProcessBuilder pb = new ProcessBuilder();
pb.command("javaw", "-cp", System.getProperty("java.class.path", "."), CtrlCSender.class.getName(), processId);
pb.redirectErrorStream();
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
Process ctrlCProcess = pb.start();
ctrlCProcess.waitFor();

A: I found all this too complicated and used SendKeys to send a CTRL-C keystroke to the command line window (i.e. cmd.exe window) as a workaround.

A: A friend of mine suggested a complete different way of solving the problem and it worked for me. Use a vbscript like below. It starts and application, let it run for 7 seconds and close it using ctrl+c.
'VBScript Example
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "notepad.exe"

WshShell.AppActivate "notepad"

WScript.Sleep 7000

WshShell.SendKeys "^C"

A: // Send [CTRL-C] to interrupt a batch file running in a Command Prompt window, even if the Command Prompt window is not visible,
// without bringing the Command Prompt window into focus.
// [CTRL-C] will have an effect on the batch file, but not on the Command Prompt  window itself -- in other words,
// [CTRL-C] will not have the same visible effect on a Command Prompt window that isn't running a batch file at the moment
// as bringing a Command Prompt window that isn't running a batch file into focus and pressing [CTRL-C] on the keyboard.
ulong ulProcessId = 0UL;
// hwC = Find Command Prompt window HWND
GetWindowThreadProcessId (hwC, (LPDWORD) &ulProcessId);
AttachConsole ((DWORD) ulProcessId);
SetConsoleCtrlHandler (NULL, TRUE);
GenerateConsoleCtrlEvent (CTRL_C_EVENT, 0UL);
SetConsoleCtrlHandler (NULL, FALSE);
FreeConsole ();

A: SIGINT can be send to program using windows-kill, by syntax windows-kill -SIGINT PID, where PID can be obtained by Microsoft's pslist.
Regarding catching SIGINTs, if your program is in Python then you can implement SIGINT processing/catching like in this solution.

A: Based on process id, we can send the signal to process to terminate forcefully or gracefully or any other signal.
List all process :
C:\>tasklist

To kill the process:
C:\>Taskkill /IM firefox.exe /F
or
C:\>Taskkill /PID 26356 /F

Details:
http://tweaks.com/windows/39559/kill-processes-from-command-prompt/


text:
Q: In Terraform can you read then write a json file So I have a Terraform script that creates a Centos VM under Azure then grabs a tar file untars it and runs an installation script at the end of this script it creates a json manifest file, what I want to do is read that json script get a value then create another json file that the next installation script will use, is this possible?

A: Terraform is not the right tool for the job specified.
There is no way to do that from the terraform.
You need to use some other provisioning tool. And even then I would suggest creating your instances one by one so you have time to populate your new json file and share it to other instances


text:
Q: How to get Url Parameter in websphere commerce bean? I am trying to get URL, tried following two methods but got 'null' commandContext. Tried some other also but got null every time.
  Object req = commandContext.getRequest();
 com.ibm.commerce.webcontroller.HttpControllerRequestObject req1 = (com.ibm.commerce.webcontroller.HttpControllerRequestObject) req;
javax.servlet.http.HttpServletRequest httpReq = req1.getHttpRequest();
ses = httpReq.getSession();

 HttpServletRequest request =
 ((com.ibm.commerce.webcontroller.HttpControllerRequestObject) this
 .getCommandContext()
 .getRequest())
 .getHttpRequest();

Don't quite get what I am doing wrong, would please anyone help?
I want to catch parameters present in url that user hit in specific scenario.
For instance,
https://webAddress/MyForm?item=someitem&qty=1

I need to get 'item' and 'qty'.

A: It been a little late, but I think it will be helpful to others.
To get the query parameters in the controller command from the url, You can follow the either of the approach mentioned in this tutorial
or you can try like following , Get the request properties and fetched the value by using query parameter name
TypedProperty requestProp = getRequestProperties();
String item = requestProp.getString("item");
int itemQty = Integer.parseInt(requestProp.getString("qty"));

followed by your businees logic.
Hope this helps.

A: You don't mention the context in which you need the parameter values, so I'll assume you're writing the business logic for a Controller Command.
When a controller command is instantiated by the runtime framework, it will invoke the setRequestProperties() method, passing in a TypedProperties instance, which contains the request parameters (whether passed as GET or POST parameters, mapped from an XML message, or through the REST layer).
The default implementation of this (in com.ibm.commerce.commands.ControllerCommandImpl) will simply store this in the requestProperties attribute from which you can then access it in, say, performExecute().
I usually recommend people to override setRequestProperties() to pick out the values they want there and store them in instance variables, though.
Don't forget to validate the parameters in validateParameters().
Refer to the Creating business logic tutorial in the Knowledge Center for a more thorough walk-through.


text:
Q: How do you disable "stealth mode" on Windows Server 2008? After reading this article and this one I've decided to change all our firewalls to reject instead of block packets in most cases. My experience corroborates the arguments these articles make.
Unfortunately, Windows 2008 R2 uses the so-called "stealth mode" by default and I've found no obvious way to disable it correctly.
In comments below the Technet article, there is a link to the following msdn article that shows a key or struct of some sort that might disable it. But I was unable to find any key with "stealth" in the registry. Anyway, a second comment indicates this might not work anyway:

"Certain elements of the filtering platform are always active, even when the firewall is
  disabled, including Stealth Mode. There is no supported way to disable stealth mode."

So does "Stealth Mode" do anything other than reject packets? Does anyone know how to disable stealth mode?

A: In Windows 2008R2 or later, locate each of the following keys in the registry:
HKLM\Software\Policies\Microsoft\WindowsFirewall\DomainProfile
HKLM\Software\Policies\Microsoft\WindowsFirewall\PrivateProfile
HKLM\Software\Policies\Microsoft\WindowsFirewall\PublicProfile
HKLM\Software\Policies\Microsoft\WindowsFirewall\StandardProfile

Add or edit the following value: DisableStealthMode (type REG_DWORD), and set it to 1.
References:

*

*https://support.microsoft.com/en-us/help/2586744/disable-stealth-mode

*https://msdn.microsoft.com/en-us/library/ff720058.aspx


text:
Q: Proof of uniform continuity of the convolution. Assume throughtout that $1 \leq p < \infty$ and $1< q \leq \infty$ and $\frac{1}{p} + \frac{1}{q} = 1$ and $m$ is the lebesge measure. I have to prove the following theorem:

Theorem 2: If $f \in L^p(\mathbb{R}^n)$ and $g \in L^q(\mathbb{R}^n)$, then $f \star g$ is uniformly continuous.

We saw the following theorem in the lecture with proof:

Theorem 1: If $1 \leq p < \infty$ and $1< q \leq \infty$ and $f: \mathbb{R}^n \rightarrow \mathbb{R}$ is locally $p$-integrable, then $$\lim_{\rho \rightarrow 0} \int_K |f(x+\rho) -f(x)|^pdm = 0$$
  for any Lebesgue measurable subset $K \in \mathbb{R}^n$.

My attempt to prove uniform continuity is the following:
Let $\epsilon > 0$. Since I can use Theorem 1, there exists a $\delta > 0$ such that for all $|\rho| < \delta$ we have $$\int_{\mathbb{R}^n}|f(y+\rho)-f(y)|^pdm < (\frac{\epsilon}{||g||_{L^q}+1})^p$$
Now let $x,\rho \in \mathbb{R}^n$ with $|\rho|<\delta$. The convolution $(f \star g)(x)$ is defined as an integral $\int f(x-y)g(y)dm(y)$ outside of a set $A$, and as $0$ inside $A$, where A is the set where $f(x-y)g(y)$ is not Lebesgue integrable with respect to $y$. If $x+\rho$ and $x$ are in $A^c$, then I can estimate
\begin{align*}
|(f \star g)(x + \rho)-(f \star g)(x)| &= |\int_{\mathbb{R}^n}(f(x + \rho -y)-f(x-y))g(y)|dm(y) \\
&\leq ||f(x+\rho - \cdot)-f(x- \cdot)||_{L^p}||g||_{L^q} \\
&=(\int_{\mathbb{R}^n}|f(y+\rho)-f(y)|^pdm(y))^{1/p}||g||_{L^q} \\
&< \frac{\epsilon}{||g||_{L^q}+1}||g||_{L^q} \\
&<\epsilon.
\end{align*} .
This estimate works now fine if I assume that $x+\rho$ and $x$ are in $A^c$ where I can write the convolution as an Integral. And if $x+\rho$ and $x$ are in $A$, then the convolution is equal to $0$ and thus $$|(f \star g)(x + \rho)-(f \star g)(x)|=0 < \epsilon$$.
But if I have the cases

*

*$x+\rho \in A$ and $x \in A^c$

*$x+\rho \in A^c$ and $x \in A$

then I can no longer write the convolution $f \star g$ as an integral. How do I save the proof? Or do I have to use a completely different argument to include those cases?

A: The proof is actually correct.
Holder inequality gives that: $\ \ \forall x\in R^n,\ \ \int_{R^n}{\left|f(x-y)g(y)\right|\le\left(\int_{R^n}\left|f\right|^p\right)^\frac{1}{p}}\left(\int_{R^n}\left|g\right|^q\right)^\frac{1}{q}<+\infty$
This shows that A is empty, and your proof is correct.


text:
Q: Ler Json no PHP? Tenho o seguinte código no meu PHP:
<?php

  $url = "https://api.cartolafc.globo.com/mercado/destaques";

  $response =  file_get_contents($url);
  $jogadores = json_decode($response,true);

Ele deveria retorna o arquivo json, onde pego as informações e monto em outra página e isso funcionava até um tempo atras, mas parou. e absolutamente nada foi mudado.
Como posso resolver esse problema?

Quando uso:
var_dump(json_decode($response, true));

Ele só retorna NULL

A: Configure o USERAGENT com o paramentro Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0), tanto com file_get_contents ou curl:
Com file_get_contents:
<?php

    $url = "https://api.cartolafc.globo.com/mercado/destaques";

    $options = array(
        'http' =>
          array(
            'method' => 'GET',
            'user_agent' => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
            'timeout' => 1
            )
    );

    $context = stream_context_create($options);
    $file = file_get_contents($url, false, $context);
    $sol = json_decode($file, true);
    var_dump($sol);

Com curl:
<?php

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_URL => 'https://api.cartolafc.globo.com/mercado/destaques',
        CURLOPT_SSL_VERIFYPEER => FALSE,
        CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
    ));

    $result = curl_exec($curl);
    $sol = json_decode($result, true);
    var_dump($sol);

Referencias:

*

*file_get_contents

*curl

*User agent


text:
Q: Uncaught TypeError: Cannot read property 'replace' of undefined Вылезает ошибка. Пожалуйста, подскажите, как исправить?

Uncaught TypeError: Cannot read property 'replace' of undefined

Код строки:
var i = strpos(s.replace(',','.'),'.');

function check_digit(name,frac) {
    if (isNaN(frac)) frac = 0;
    if (frac <= 0) frac = -1;
    var s = $(name).val();
    var i = strpos(s.replace(',','.'),'.');
    if (i !== false && i >= 0 && i < s.length-frac-1) {
        $(name).val(s.substring(0,i+frac+1));
    }
}

Вот функция и в ней вылетает на реплейсе
Обновление
Так с этим вроде б разобрался, но теперь смотрите другая ошибка:

Uncaught ReferenceError: pay_type is not defined

Код строки:
 get("req.php", {
            plugin:pay_type.value,
            type:'verify',
            account:account.value,
            language:language.value,
            jek:jek.value,
            period:period.value
        }, parse_answer);
        return true;
    }

plugin:pay_type.value ---- здесь ошибку выдает


text:
Q: An adjective for the time that is excited by Christmas? The time leading to Christmas festival is kind of exciting, cheerful, active, etc.
Is "Christmas-excited time" a correct phrase when we mean to say the above point?
Example:

During this Christmas-excited time, I like to be alone.

Or other suggestion?

A: Judging by the Ngram the 'festive season' is apparently as common a way to describe Christmas as is 'Christmas' itself.
BrE uses it more often than 'Christmas', AmE less so.

People sometimes refer to the Christmas period as the festive season.
"For many of us, the festive season can be one of the most stressful times of the year."

Collins

A: Per Oxford:

holiday season
NOUN
(in the US) the period of time from Thanksgiving until New Year, including such festivals as Christmas, Hanukkah, and Kwanzaa.

Or, also per Oxford:

Advent
NOUN

*The first season of the Church year, leading up to Christmas and including the four preceding Sundays.

Or, per American Heritage:

Yule
n.
Christmas or the Christmas season, especially as traditionally celebrated in Northern Europe and North America with customs stemming in part from pagan celebrations of the winter solstice.

And, further from American Heritage:

Yuletide
n.
The season of Yule.


text:
Q: label appears from the GoPro SDK dependency I have a string resource for an application label:
 <string name="app_name">My application</string>

My AndroidManifest.xml is classical:
<manifest.. >
 <application
        android:name="my.package"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon">
        <activity ...

I have GoPro SDK as a dependency. And on some devices (HTC U Play) my application is signed not as "My application", but as "GoPro SDK".
I have figured out that GoPro SDK valuses are realy containing resource:
<string name="app_name">GoPro SDK</string>

GoPro SDK is an .arr archive.
How to fix it without renaming of the variable app_name?

A: Try to add to application tag the following attribute:
<application
    tools:replace="label, icon"/>

also I found that some of activities may contain label without tools:replace="label"
<activity android:label="@string/app_name" />

Just remove label from activities or add tools:replace="label" attribute


text:
Q: How to add selection box dynamically in rails 3.1.0? Here is a partial form _standards.html.erb we want to add to the view dynamically:

<%= f.association :standards, :collection => Standard.active_std.all(:order => 'name'), :label_method => :name, :value_method => :id :include_blank => true %>

Here is the view form itself _form_new.html.erb which calls _standards.html.erb:
<%= simple_form_for @rfq do |f| %>

  <%= render :partial => 'standards/standards', :collection => @rfq.standards, :locals => { :f => f } %>

  <%= link_to_function("Add std", nil) do |page| %>
    page.insert_html :bottom, 'std', :partial => 'standards/standards', :object => @rfq.standards.build
  <% end %>

  <%= f.button :submit, 'Save' %>
<% end %>

This solution did not work as link_to_function was not reacting to click by loading the _standards.html.erb. This solution seems out of date and does not work in rails 3.1.0. I am wondering if there is other solution to add dynamic content to the view page in rails 3.1.0. If you do, please don't hesitate to post. Thanks.

A: I know this answer is coming months after you need it but hopefully this helps someone else who stumbles across this question.  Here is how you can dynamically add a selection box unobtrusively for your example.
_form_new.html.erb
<%= simple_form_for @rfq do |f| %>

  Add Selection Box

<% end %>

Here is how you can do it using link_to_function
_form_new.html.erb
<%= simple_form_for @rfq do |f| %>
  <%= add_selection_box "Add Selection Box", @rfq.standards, f %>

<% end %>

helpers/my_form_helper.rb
module MyFormHelper
  def add_selection_box(name, collection, form)
    page = %{
      partial = "#{escape_javascript(render(:partial => "standards/standards", :collection => collection, :locals => { :f => form }))}";

      $("#std").append(partial);
    }

    link_to_function name, page
  end
end


text:
Q: Json script is not responding without search I am trying to return data from my database to a <table>. The statement I am using to select the data is: SELECT id, name, k_id FROM table. In mysql this statement is returning 100 rows.
When I run the json script I can see that the script dont fills my <table>. It shows only data when I search for data in the table: if( !empty($params['search']['value']) ) {.
With the search the SQL statement becomes like:
SELECT id, name, k_id FROM table WHERE ( k_id LIKE '100' OR name LIKE '100')

The SQL statement with search is showing me data.
Does someone know why my table is empty when I try to run the statement SELECT id, name, k_id FROM table without the search option?
Here is my full script:
<?php
    include_once("connection.php");
    $params = $columns = $totalRecords = $data = array();

    $params = $_REQUEST;

    //define index of column
    $columns = array(
        0 => 'id',
        1 => 'k_id',
        2 => 'name'
    );

    $where = $sqlTot = $sqlRec = "";

    // check search value exist
    if( !empty($params['search']['value']) ) {
        $where .=" WHERE ";
        $where .=" ( k_id LIKE '".$params['search']['value']."%' ";
        $where .=" OR name LIKE '".$params['search']['value']."%')";
    }

    if (!empty($where) ) {

   $where .= " ";
    } else {
     $where .= " ";
    }

    // getting total number records without any search
    $sql = "SELECT id, name, k_id FROM table ";
    $sqlTot .= $sql;
    $sqlRec .= $sql;
    //concatenate search sql if value exist
    if(isset($where) && $where != '') {

        $sqlTot .= $where;
        $sqlRec .= $where;
    }

    $sqlRec .=  " ORDER BY ". $columns[$params['order'][0]['column']]."   ".$params['order'][0]['dir']."  LIMIT ".$params['start']." ,".$params['length']." ";

    $queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));

    $totalRecords = mysqli_num_rows($queryTot);

    $queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");

    //iterate on results row and create new index array of data
    while( $row = mysqli_fetch_row($queryRecords) ) {
        $data[] = $row;
    }

    $json_data = array(
            "draw"            => intval( $params['draw'] ),
            "recordsTotal"    => intval( $totalRecords ),
            "recordsFiltered" => intval($totalRecords),
            "data"            => $data
            );

    echo json_encode($json_data);  // send data as json format
?>


text:
Q: How to update auto-receptionist greeting prompt using Zoom rest api I'm trying to modify the greeting prompt for a Zoom auto-receptionist using the zoom rest api.
The greeting prompt is normally "test1.mp3".  I want to use the rest api to change it to "test2.mp3".
PATCH: https://api.zoom.us/v2/phone/extension/{extensionId}/call_handling/settings/business_hours
{"sub_setting_type":"call_handling","settings":{"greeting_prompt_id":"{audioId}"}}
extensionId is the extension_id for the auto-receptionist;  audioId is the audio_id of "test2.mp3".
Making this call does not give an error.  However, the greeting prompt for the auto-receptionist changes to Default.
What am I missing?


text:
Q: Irrational number in python How to represent irrational numbers in Python?
e.g. I need sqrt(2) * sqrt(2) to be 2 (or 2.0)
But:
>>> sqrt(2) * sqrt(2)
2.0000000000000004

Same with floating point:
>>> sqrt(2.0) * sqrt(2.0)
2.0000000000000004

Decimal too:
>>> Decimal(2).sqrt() * Decimal(2).sqrt()
Decimal('1.999999999999999999999999999')


text:
Q: Layout a knob and button view I want to have this complex control ported into my Android XML Layout:
I need the buttons (heart, cloud,...) and the central knob as ImageButtons, so they should be separate objects and positioned in exact positions.
The problem is how to layout such complex button and backgrounds so it displays correctly on multiple devices having different resolutions.

A: In case you are allowed to implement it dynamically here are some hints:

*

*Create separate images(backgrounds)

*

*1 image for the knob

*1 image for each small button

*1 image for the background

*Radius

*

*measure the distance from the center of the background to the point where a small button should be placed (the radius of the background pattern) in pixels.

*you might need different sizes for different screens (different resolutions)

*Place the buttons:

*

*place the background image and the knob ImageButton so that the center of the knob matches the center of the background - both images should be rectangular, so the central point should be at the crossing point of the diagonals

*use spherical coordinates to retrieve the cartesian (x,y) coordinates of the small buttons - their centers should lie on those points

*Hit test

*

*all your images should have transparent background

*you can implement the hit test to be successful only when the event is in the non-transparent part of the ImageButton background

*Rotation

*

*To rotate the knob you can look for more info about rotating an ImageButton's background. I haven't tried something like this...

A: You may have to intercept onTouchEvent() and process the raw events. This way you would know where on your picture the user's finger is.
A simpler solution would be to use a RelativeLayout, if you can tolerate square buttons beneath the round icons. (3 states, normal-selected-pressed.) In fact, you don't need buttons, you may just make your views clickable.
I'm not sure what you want the user to do with the central knob: press it, turn with two or three fingers, etc. In principle, you may have a square view whose corners are covered by non-clickable transparent square views (or should they be clickable instead? the idea is that the clicks in that area should not be received by the knob).
One more possible approach is not to implement separate buttons, but to have one square image for each state of the whole combination of controls.
You will definitely have to know the actual size of your image -- see ViewTreeObserver.OnGlobalLayoutListener and getMeasuredWidth()/getMeasuredHeight() (when a click happens, the latter two already may be used, although before the layout happens they return zero).

A: You can start with ArcMenu or CircleLayout and customize it to support a widget positioned in the centre. Or you can create your own layout from scratch. Good article how to do so is available here.