text:
Q: Does Enumerable.Where in LINQ-to-objects preserve order? var source = new List<string> { "A1", "A2", "B1", "B2" };
var filtered = source.Where(s => s.StartsWith("A"));

foreach (var s in filtered)
    Console.WriteLine(s);    // outputs first A1 and then A2

It seems like Enumerable.Where keeps the original order of elements when used on an ordered IEnumerable (such as a List<T> or T[]). Is this always the case? If yes, where is this documented?

A: Microsoft does actually document that LINQ to Objects preserves ordering. The document
http://msdn.microsoft.com/en-us/library/dd460677%28v=vs.110%29.aspx says

In PLINQ, the goal is to maximize performance while maintaining
  correctness. A query should run as fast as possible but still produce
  the correct results. In some cases, correctness requires the order of
  the source sequence to be preserved; however, ordering can be
  computationally expensive. Therefore, by default, PLINQ does not
  preserve the order of the source sequence. In this regard, PLINQ
  resembles LINQ to SQL, but is unlike LINQ to Objects, which does
  preserve ordering.

As mentioned in this stackoverflow article microsoft documents for some LINQ methods that they do not preserve order. For example the documentation of distinct mentions that this method returns an unordered sequence.

A: The order is preserved using the Enumerable.Where method.
There was a similar question asked on SO, and the first answer breaks down which methods preserve the order:
Preserving order with LINQ

A: It's not documented. Documentation of the LINQ operators is seriously lacking in many aspects, including when and when isn't order kept, when and when isn't the operation buffered, or what are the complexity guarantees.
In this case, I don't mind depending on the implementation keeping the order, because that's what all practical implementations will do.
I recommend reading the Edulinq series by Jon Skeet where, before implementing the functionality, he explain what you should and what you should not expected of an operator.

A: Enumerable.Where will preserve the order of an IEnumerable<T>.  This is not documented, so not a guarantee, however, the implementation just iterates through the IEnumerable<T> sequentially - in effect, preserving order - though that order is reliant on the underlying IEnumerable<T>'s order.  (For example, Where on a HashSet<T> is not ordered, but it's because the HashSet<T>'s enumerable is unordered.)
It does, however, include special implementations to handle certain types (such as arrays and List<T>), so it's not impossible that a specific collection type, at some point in the future, might return results in a different order if this would be deemed a valuable improvement in terms of speed/perf./etc.  The documentation never specifically gives an ordering guarantee.

A: The Where implementation is essentially as follows with some additional variable checking added in:
public static IEnumerable<T> Where(this IEnumerable<T> source, Funct<T, bool> predicate)
{
   foreach (T item in source)
       if (predicate(item))
           yield return item;
}

As a result, assuming yield is not being done asynchronously or in parallel, it will retain the order. If your source is .AsParallel, all bets are off in terms of the order.

A: The decompilation of the LINQ where is:
private static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
{
    int num = -1;
    IEnumerator<TSource> getenumerator = source.GetEnumerator();
    while (getenumerator.MoveNext())
    {
        TSource current = getenumerator.Current;
        num++;
        if (predicate(current, num))
        {
            yield return current;
        }
    }
}

The decompilation of the System.Collections.Generic.List.MoveNext() has the code:
if (this.version == ts._version && this.index < ts._size)
{
    this.current = ts._items[this.index];
    this.index = this.index + 1;
    return true;
}

Using these two together you can see that the the order will be preserved.  Of course Microsoft could change it in the future, but based on .NET 4.0, List.Where will be ordered.

A: It seems that it must preserve order, because it is able to function on infinite IEnumerables.
void Main() {
    foreach (var element in Count().Where (i => i%2 == 1)) {
        // do something with all odd numbers
    }
}

IEnumerable<int> Count() {
    int i = 0;
    while (true) yield return ++i;
}

I can't find this documented anywhere though.

A: Yes, it's going to be ordered according to the iterator. Since this isnt PLINQ, the enumerable is iterated over in order of element position of the enumerable - so if you implemented some kind of custom IEnumerator for your class, it would return in that ordering.

A: Enumerable.Where follows the ordering of elements returned by the enumerator generated by calling  GetEnumerator on the underlying collection - looking at MSDN the enumerator on List<T> is documented to follow the indexing behaviour.

A: Without providing explicit OrderBy, the Where method cannot guarantee the order - otherwise, it would have been documented as doing such.


text: Q: Extensions not working at startup I am using Ubuntu Groovy Gorilla. I installed this extension called floating dock https://extensions.gnome.org/extension/3730/floating-dock/ from gnome extensions. I turned it on and it worked fine and suddenly made my desktop look way better. But when I restarted Ubuntu, the extension doesnt work and I just see the standard ubuntu dock. When I looked at 'extensions', floating dock was turned on. The extension started working again when I turned off and then turned on floating dock. I noticed the same happens when I restart the gnome shell (alt+f2 r). Can someone explain what is happening? Is this the extensions problem or Ubuntu's?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to print only the matching line in file? import re
shakes = open("output.txt", "r")
for line in shakes:
    if re.match(r'.*(\w*Daemon\w*).*', line):
        print(line)
        break
    else:
        print("none")

output:
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
none
local1.crit: Aug 23 09:08:42 abvlab_ confd[860]: - Daemon n_7 died

A: You can do for example:
matching_shakes = list(filter(lambda line: re.match(regex, line), shakes))


text:
Q: Save image downloaded from Parse.com In my application i have got a lot of images, 5 of them can change. I use Parse.com to upload my new image.
This code works great, but i cant save NEW image to my application. How i can do this easily?
            public class PrasePhotoProba extends Activity {
static final String TAG = "myLogs";
Button button;
private ProgressDialog progressDialog;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from main.xml
    setContentView(R.layout.photo);
    // Show progress dialog

    // Locate the button in main.xml
    button = (Button) findViewById(R.id.button);

    // Capture button clicks
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            progressDialog = ProgressDialog.show(PrasePhotoProba.this, "",
                    "Downloading Image...", true);

            // Locate the class table named "ImageUpload" in Parse.com
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                    "newImage");

            // Locate the objectId from the class
            query.getInBackground("1",
                    new GetCallback<ParseObject>() {

                        public void done(ParseObject object,
                                         ParseException e) {

                            ParseFile fileObject = (ParseFile) object
                                    .get("image");
                            fileObject
                                    .getDataInBackground(new GetDataCallback() {

                                        public void done(byte[] data,
                                                         ParseException e) {
                                            if (e == null) {
                                                Log.d("test",
                                                        "We've got data in data.");
                                                // Decode the Byte[] into
                                                // Bitmap
                                                Bitmap bmp = BitmapFactory
                                                        .decodeByteArray(
                                                                data, 0,
                                                                data.length);

                                                // Get the ImageView from
                                                // main.xml
                                                ImageView image = (ImageView) findViewById(R.id.image);

                                                // Set the Bitmap into the
                                                // ImageView
                                                image.setImageBitmap(bmp);

                                                // Close progress dialog
                                                progressDialog.dismiss();

                                            } else {
                                                Log.d("test",
                                                        "There was a problem downloading the data.");
                                            }

                                        }

                                    });
                        }
                    });

        }

    });

}

A: Save Bitmap using this code:
File file = new File(Environment.getExternalStorageDirectory() + filepath, GiveAnyimageName + ".png");
    FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();


text:
Q: Is a number with two consecutive sets of differing infinite digits a real number? Suppose I construct a number starting 0. (followed by an infinite number of digits that are 3) (followed by an infinite number of digits that are 1), like $0.\bar{3}\bar{1}$.
Is this a real number?
Can I do calculations with it?
Is it real if I simply follow it by a single digit as in $0.\bar{3}1$
What are the limitations here in combining sets of overbar statements to create numbers?

A: There is no object matching your description. In fact, the notation "$0.\bar{3}\bar{1}$" is not defined. More specifically, the phrasing "(followed by an infinite number of digits that are 3)(followed by an infinite number of digits that are 1)" does not make sense in any formalism I've heard of. Similarly, $0.\bar{3}1$ is undefined (and again, there is not really any sensible definition for it).
For reference, we define: $$0.a_{1}a_{2}\ldots a_{n}\bar{b} = 0.a_{1}a_{2}\ldots a_{n}+\sum_{k=n}^{\infty}\frac{b}{10^{k+1}},$$ and we may give a similar definition for when $b$ is replaced by a string of digits $b_{1},b_{2},\ldots, b_{m}$: $$0.a_{1}a_{2}\ldots a_{n}\overline{b_{1}b_{2}\ldots b_{m}} = 0.a_{1}a_{2}\ldots a_{n}+\sum_{k=n}^{\infty}\frac{\sum_{i=1}^{m}10^{m-i}b_{i}}{10^{k+m}}.$$ We simply neglect to define $0.\bar{3}1$ because the concept itself makes no sense.

A: If your number existed,
it could be defined as
$\begin{array}\\
\lim_{n \to \infty}
\left(
\sum_{k=0}^n 3\cdot 10^{-k}
+
\sum_{k=0}^n 10^{-k-n-1}
\right)
&=\lim_{n \to \infty}
\left(
3\sum_{k=0}^n \cdot 10^{-k}
+
10^{-n-1}\sum_{k=0}^n 10^{-k}
\right)\\
&=\lim_{n \to \infty}
(3+10^{-n-1})\sum_{k=0}^n \cdot 10^{-k}\\
&=\lim_{n \to \infty}
(3+10^{-n-1})\frac{1-10^{-n-1}}{9}\\
&=\lim_{n \to \infty}
(\frac13 -\frac29 10^{-n-1}+\frac19 10^{-2n-2})\\
&= \frac13\
\end{array}
$
which is the same as
$\lim_{n \to \infty}
\sum_{k=0}^n 3\cdot 10^{-k}
= \frac13
$.


text:
Q: How to set Gmail as default email client in Windows 8? How can I use Gmail (in Chrome) as the default email handler in Windows 8?
I used to use GmailNotifier in Windows 7, but that doesn't seem to work anymore. Clicking on a mailto: link simply opens Chrome with a blank page.
I am not interested in using the Mail app built into Windows 8.

A: Open Gmail in Chrome. Then see this. Click on the eye in the address bar.

A: Follow the steps after installation of Gmail Client

Change your Default Client to Gmail..
Hope this Helps...

A: *

*Close Chrome

*Open C:\Users\<your username>\AppData\Local\Google\Chrome\User Data\Local State with Notepad (or, any other text editor).

*Locate "javascript": true, in protocol_handler section of the file, replace true with false and save the file.

*Launch Chrome, visit Gmail and Sign in.

*In address bar of same tab, type/paste this & hit enter: javascript:navigator.registerProtocolHandler("mailto", "https://mail.google.com/mail/?extsrc=mailto&url=%s", "Gmail");

*[Optional] Close Chrome & revert back your changes in Local State file.

*Open Default Programs.

*Click Associate a file type or protocol with a program.

*Select MAILTO and then click Change program... button.

*Choose Google Chrome from the list.

Done!

A: See the below link. It expands upon Sant14's answer by first having you create the necessary entry that would then show up in your 'Default Programs' > 'Programs' list.
http://www.groovypost.com/howto/change-windows-8-default-email-client/

A: I found an easier solution.  The link below installs an applet which gives you the option as a check box, and you don't have to use Chrome.  I'm using Firefox because I have some sort of virus on Chrome that hijacks clicks and sends me to advertisements.
http://toolbar.google.com/gmail-helper/notifier_windows.html


text:
Q: Displaying multiple substring indices within a string by using recursion def subStringMatchExact(target, key):

    if (target.find(key) == -1):
        return []
    else:
        foundStringAt = [target.find(key)]
        target = target[foundStringAt[0] + len(key):]
        return foundStringAt + subStringMatchExact(target, key)

string = subStringMatchExact("your code works with wrongly correlated coefficients which incorporates more costs", "co")

print(string)

Current incorrect output:
[5, 22, 9, 19, 14]

I am having trouble summing the length of the substring on the previous recursion step. Like the second element of the list should be 29 instead of 22 as in len(previousSubstring) + len(key) - 1 + len(currentSubstring).
Any ideas to improve my code and/or fix my error too?

A: The fast way
You don't have to implement your own solution, its already done! Use the finditer function from the re module:
>>> import re
>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
>>> matches = re.finditer('co', s)
>>> positions = [ match.start() for match in matches ]
>>> positions
[5, 29, 40, 61, 77]

Your own way
If you want to make your own implementation (using recursion) you could take advantage of the extra arguments of the str.find function. Lets see what help(str.find) says about it:
S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

There is an extra argument called start that tells str.find where to start searching the substring. That's just what we need!
So, modifying your implementation, we can get a simple, fast and beautiful solution:
def substring_match_exact(pattern, string, where_should_I_start=0):
    # Save the result in a variable to avoid doing the same thing twice
    pos = string.find(pattern, where_should_I_start)
    if pos == -1:
        # Not found!
        return []
    # No need for an else statement
    return [pos] + substring_match_exact(pattern, string, pos + len(key))

What is the recursion doing here?

*

*You're first searching the substring in the string starting at position 0.

*If the substring wasn't found, an empty list is returned [].

*If the substring was found, it will be returned [pos] plus all the positions where the substring will appear in the string starting at position pos + len(key).

Using our brand new function
>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'
>>> substring_match_exact('co', s)
[5, 29, 40, 61, 77]

A: Currently, your code is attempting to find the index of co in the shortened string, rather than the original string. Therefore, while [5, 22, 9, 19, 14] may seem incorrect, the script is doing exactly what you told it to do. By including an offset, like the script below, this code could work.
def subStringMatchExact(target, key, offset=0): # note the addition of offset

    if (target.find(key) == -1):
        return []
    else:
        foundStringAt = target.find(key)
        target = target[foundStringAt + len(key):]
        foundStringAt += offset # added
        return [foundStringAt] + subStringMatchExact(target, key, foundStringAt + len(key))
        # added foundStringAt + len(key) part

string = subStringMatchExact("your code works with wrongly correlated coefficients which incorporates more costs", "co")
# no need to call w/ 0 since offset defaults to 0 if no offset is given

print(string)

I should add that making foundStringAt a list from the beginning isn't great practice when dealing with only one value, as you add some overhead with every [0] index lookup. Instead, since you want a list return type, you should just enclose it in [] in the return statement (as shown in my code).

A: You are always adding the position in the respective substring. In
return foundStringAt + subStringMatchExact(target, key)

, the result of the function call is related to the "new" string target which is different from the "Old" one, as it was redefined with target = target[foundStringAt[0] + len(key):].
So you should add exactly this value to the function call results:
    foundStringAt = target.find(key)
    offset = foundStringAt + len(key)
    target = target[offset:]
    return [foundStringAt] + [i + offset for i in subStringMatchExact(target, key)]

should do the trick (untested).

A: I wouldn't bother using recursion for this, except as an exercise.
To fix the problem:

I am having trouble summing the length of the substring on the previous recursion step.

What you really want to "sum" is the amount of the string that has already been searched. Pass this to the function as a parameter (use 0 for the first call), adding the amount of string removed (foundStringAt[0] + len(key):, currently) to the input value for the recursive call.
As a matter of formatting (and to make things correspond better to their names), you'll probably find it neater to let foundStringAt store the result directly (instead of that 1-element list), and do the list wrapping as part of the expression with the recursive call.


text:
Q: How to pass a screen as a parameter to another screen in flutter? this is my first time making a full flutter app and i am stuck. I have currently passed a screen as a widget to another class as i have a dashboard screen where multiples buttons within it go to the same screen (course_screen.dart) and then from their move away to different screens depending on what option they had chosen in the dashboard screen. however in the course_screen.dart file depending on the course chosen the number and all available quizzes of that course will be shown on the UI. How do i achieve this flutter?
course_screen.dart
   import 'package:lms_app/Screens/student_homescreen.dart';
   import 'package:lms_app/providers/courses_provider.dart';
   import 'package:provider/provider.dart';

   class CoursesScreen extends StatelessWidget {
      Widget nextScreen;
      CoursesScreen({required this.nextScreen, super.key});

      @override
      Widget build(BuildContext context) {
        final course_listner = Provider.of<CoursesProvider>(context).subjects;
        return Scaffold(
          body: Stack(
            children: [
              Container(
                color: Colors.grey[200],
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    width: double.infinity,
                    height: 700,
                    // color: Colors.red,
                    child: ListView.builder(
                        itemCount: course_listner.length,
                        itemBuilder: (context, index) =>
                            Container(
                                padding: EdgeInsets.symmetric(horizontal: 12),
                                width: 300,
                                height: 100,
                                margin: EdgeInsets.all(5),
                                child: GestureDetector(
                                  onTap: () => Navigator.of(context).push(
                                      MaterialPageRoute(
                                          builder: (context) => nextScreen, )),
                                  child: Card(
                                    color: Colors.deepPurple[400],
                                    elevation: 5,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    child: Padding(
                                     padding: const EdgeInsets.symmetric(horizontal: 15),
                                      child: ListTile(
                                        title: Padding(
                                          padding: EdgeInsets.symmetric(vertical: 10),
                                          child: Text(
                                            course_listner[index].subjectName,
                                            style: TextStyle(
                                                fontWeight: FontWeight.bold,
                                                fontSize: 25,
                                                color: Colors.white),
                                         ),
                                        ),
                                        subtitle: Text(
                                          course_listner[index].teacherName,
                                          style: TextStyle(color: Colors.white),
                                        ),
                                      ),
                                    ),
                                   ),
                                ),
                              ),
                            ),
                  ),
                ),
              ),
              Container(
                height: 120,
                width: double.infinity,
                // color: Colors.red,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(25),
                        bottomRight: Radius.circular(25)),
                    image: DecorationImage(
                       image: AssetImage('assets/background_img.png'),
                       fit: BoxFit.cover)),
                 child: Column(children: [
                  SizedBox(
                    height: 15,
                  ),
                 Padding(
                    padding: const EdgeInsets.symmetric(vertical: 15),
                    child: Row(
                     children: [
                        IconButton(
                            onPressed: () {
                              Navigator.of(context).push(MaterialPageRoute(
                                  builder: (context) => StudentHomeScreen()));
                            },
                            icon: Icon(
                              Icons.arrow_back_ios_new,
                              color: Colors.white,
                            )),
                        SizedBox(
                          width: 90,
                        ),
                        Text(
                          'Courses',
                           style: TextStyle(color: Colors.white, fontSize: 30),
                         )
                      ],
                    ),
                  ),
                ]),
              )
            ],
          ),
        );
      }
    }```

student_quiz_screen.dart

 ```import 'package:flutter/material.dart';
    import 'package:lms_app/models/courses_model.dart';
    import 'package:provider/provider.dart';

    class StudentQuizPage extends StatelessWidget {
      const StudentQuizPage({super.key});

      @override
       Widget build(BuildContext context) {
        return Scaffold(
          body: Stack(
            children: [
              Container(
               color: Colors.grey[200],
               // child: Center(child: Text(listener.subjectName)),
             ),
              Container(
                width: double.infinity,
                height: 200,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(25),
                        bottomRight: Radius.circular(25)),
                    image: DecorationImage(
                        image: AssetImage('assets/background_img.png'),
                        fit: BoxFit.cover)),
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 20),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          IconButton(
                            onPressed: (() {}),
                            icon: Icon(Icons.arrow_back_ios_new),
                            color: Colors.white,
                          )
                        ],
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        );
     }
   }```

[enter image description here][1]

[enter image description here][2]

[enter image description here][3]

  [1]: https://i.stack.imgur.com/JVRxF.jpg
  [2]: https://i.stack.imgur.com/wu7DA.jpg
  [3]: https://i.stack.imgur.com/jGMtC.jpg

A: Here are a few options.

*

*Use state management packages (ex. bloc, provider, riverpod, getx, ...etc)

*Passing additional parameters to the constructor
class StudentQuizPage extends StatelessWidget {
      const StudentQuizPage({super.key, int somedata, String somedata2});

A:  *onPressed: () { nextScreenArgs args =
                                nextScreenArgs(
                                    dashboardCubit
                                        .selectedcoursevalue!
                                        .toString(),
                                    name: dashboardCubit.name);
                                dashboardCubit.nextscreen();
                              }),*

-------------------------------------------------------------
 *int? dashboard;
String? name;

dashboardCubit(this.authenticationCubit, nextScreenArgs args)
      : super(dashboardScreenInitialState()) {
    dashboard= args.value as int;
    name= args.name;
}*
----------------------------------------------------------------
 *static Widget builddashboard(RouteSettings settings) {
    final NextscreenArgs args = settings.arguments! as NextscreenArgs ;
    return CProvider(
        create: (context) {
          final AuthenticationCubit authenticationCubit =
              BlocProvider.of<AuthenticationCubit>(context);
          return dashboardCubit(authenticationCubit, args)..init();
        },
        builder: (context) => DashboardScreen());
  }*

*class nextScreenArgs {
 int? selectedcoursevalue;
  final String? routeName;

  nextScreenArgs (this.selectedcoursevalue, {this.routeName});
}*


text:
Q: Where block inside guards (Parse Error) - Haskell For uni I'm programming a game in haskell, I'm stuck as i have ran into an error I dont know how to fix, the code is :
shoot :: Player -> Player
shoot player = player { playerbullets = newbullets}
              where newbullets | CONDITION = VALUE
                                            where thing1 = ...
                                                  thing2 = ...
                               | otherwise = OTHER VALUE
                                            where thing3 = ...

I get the following error:
src\Model.hs:61:32: error: parse error on input `|'
   |
61 |                                | otherwise = OTHER VALUE
   |                                ^

How do I fix this? any help at all is appreciated!!


text:
Q: What does rank_test_score stand for from the model.cv_results_? After I have built a model with GridSearchCV, I get the cross validation results with model.cv_results_. But among the results one parameter is confusing to me. What does rank_test_score stand for in this?
mean_fit_time                                        0.00265972
std_fit_time                                        0.000466648
mean_score_time                                      0.00133236
std_score_time                                      0.000470977
param_n_neighbors                                             1
param_weights                                          distance
params                {'n_neighbors': 1, 'weights': 'distance'}
split0_test_score                                       0.70405
split1_test_score                                       0.73125
split2_test_score                                       0.69906
mean_test_score                                        0.711458
std_test_score                                        0.0141423
rank_test_score                                               1
split0_train_score                                            1
split1_train_score                                            1
split2_train_score                                            1
mean_train_score                                              1
std_train_score                                               0
Name: 1, dtype: object

A: rank_test_score indicates the rank of a grid search parameter combination based on the mean_test_score.
If you try N parameter combinations in your grid search, rank_test_score reaches from 1 to N.
The parameter combination that results in the lowest mean_test_score will have a rank_test_score of N and the parameter combination with the highest mean_test_score will have a rank_test_score of 1.
If you use multiple metrics for evaluation (say, 'neg_mean_squared_error' and 'neg_mean_absolute_error') you will have more columns (here rank_test_neg_mean_squared_error and rank_test_neg_mean_absolute_error), each indicating the rank of the estimator based on the respective metric.


text:
Q: Change background color in a specific field with mat-form-field So, I have an existing mat-form-field and I want to change the background color of specific field.
I have tried this code in the css but it changed the background color of all the fields in my form:
::ng-deep .mat-form-field-appearance-outline .mat-form-field-outline {
    background-color: lightgray !important;
    border-radius: 5px;
}

Here is the code for my mat-form-field:
<mat-label>Filing Time</mat-label>

              <mat-form-field appearance="outline" class="width-1">
                <input
                  matInput
                  readonly
                  formControlName="filingTime"
                  [ngModel]="filingDate | date: 'HH:mm'"
                />
              </mat-form-field>

A: UPDATED with Working Example
You can change apply any CSS to a specific element by giving an id or class.
Here is the code to do it using Class
::ng-deep .mat-form-field-appearance-outline.specific-border .mat-form-field-outline  {
    background-color: lightgray !important;
    border-radius: 5px;
}

<mat-label>Filing Time</mat-label>

              <mat-form-field appearance="outline" class="width-1 specific-border">
                <input
                  matInput
                  readonly
                  formControlName="filingTime"
                  [ngModel]="filingDate | date: 'HH:mm'"
                />
              </mat-form-field>

Here is the code to do it using Id
::ng-deep .mat-form-field-appearance-outline#specific-border .mat-form-field-outline  {
    background-color: lightgray !important;
    border-radius: 5px;
}

<mat-label>Filing Time</mat-label>

              <mat-form-field appearance="outline" id="specific-border" class="width-1">
                <input
                  matInput
                  readonly
                  formControlName="filingTime"
                  [ngModel]="filingDate | date: 'HH:mm'"
                />
              </mat-form-field>

Demo Stackbiltz


text:
Q: SonarQube Eclipse Plugin: Incremental scan scans all files, not just those modified locally I am using version 3.4 of the SonarQube Eclipse Plugin and when I analyze a project, the scan is successful, but it scans all files. I know that the default scan mode is 'incremental' for this plugin, so I do not know why the analysis is scanning all of my files and not just those that I have modified locally. I have SonarQube running successfully on a server and I can view all of the current issues in my project using a web browser.
Also, when I view the sonar-report.json file that is generated on my computer as a result of the scan, all of the issues have the 'isNew' tag set to true and the update date equals the creation date which equals the time of the scan. I know this is incorrect because some of the issues are pre-existing and should have a creation date of a month ago because this is what I see when looking at the issue on my server through my web browser.
To me it seems as if Eclipse is not synchronizing the existing issues properly with the server because it seems to not recognize any of them. Please let me know what may be wrong. Thank you.


text:
Q: Why is Font Awesome not working with Bootstrap in JSFiddle? I created a JSFiddle trying to show a problem I'm having with FontAwesome and it seems Font Awesome is not working at all in JSFiddle when I add Bootstrap. Here's the example:
https://jsfiddle.net/pupeno/jjjesyvt/
The code is very simple:

        Bootstrap 3

Left

A: Font Awesome appears to be working fine - it's your markup that's problematic.

*

*When you have a fixed top navbar, you need to push the contents down by at least 50 pixels, not by 10 - so the .fa-camera-retro is being hidden by the navbar
Use this:
body { margin-top: 60px; }

Instead of this:
body { margin: 10px; }

*If you replace the FA icon in the navbar-right, with just plain text, you'll notice that doesn't show up either - for bootstrap styles to take affect in the navbar, they need to be in an a tag.
Use this:

Instead of this:

Working Demo in Fiddle


text:
Q: Periodic input to Windows gitbash terminal My bash terminal is receiving a space (chr 32) immediately followed by a backspace (chr 8) every 5 seconds (almost exactly). The effects aren't noticeable when typing, as the added space is deleted within a few milliseconds, however it does have other more obvious and annoying side effects. For example, when paging through a file via less, the space makes it automatically page through once every 5 seconds. This among other things is making it difficult to work, and I cant figure out why it's happening.
I'm on Windows 7, using git via the gitbash terminal that comes as part of the packaged download from git-scm.com.
I get the same behavior when just running the mintty.exe program that gets placed in C:\Program Files\Git\usr\bin. I've made sure to empty my .bashrc.
I've also tried restarting, as well as uninstalling and re-installing.
Also worth noting, the behavior continues even if the terminal is not the active focused window.
The issue has only started recently, but I can't think of any change made to my system that would cause this. Does anyone know what might cause this 5-second repeated ghost-input I'm seeing. Alternatively, how might I be able to track down where the input is coming from?

A: Most probably, this is some conflict resulting from your PATH. E.g. here, I'm getting an error at startup because /etc/bash.bashrc is looking for getent which is absent from Git's MSYS but is present in Cygwin which I have further in PATH.
.bashrc is not the only automatically parsed file. There's also /etc/profile, /etc/profile.d/*, /etc/bash.* and ~/.bash*.
To localize the problem,

*

*rename c:\Program Files\Git\etc to exclude startup files and any other behaviour-altering files like /etc/inputrc. If the problem persists, look for the reason in loaded modules' list (can be viewed with procexp).

*run bash -i --noprofile --norc to disable just the startup files.

*rename individual startup files/folders (half the amount at a time to pinpoint the culprit with logarithmic number of steps).


text:
Q: Accessing Google Adwords API from C#.NET windows service I am creating a C#.NET windows service to create adwords. I understand that I need to use OAuth2 authentication. Do I have to use the services account set up for achieving this?

A: No. Just install the client library from Nuget.
You can then add your credentials to the app.config file (installing via NuGet creates a template for these credentials in your app.config for you)


text:
Q: Issue with Date.parse in Chrome The implementation of Date.parse in Chrome has very unexpected behavior.
For example, Date.parse('foo 2014') should ideally return NaN as it is not a proper date format. But in Chrome this returns the value 1388514600000, which is equivalent to the date "Wed Jan 01 2014 00:00:00 GMT+0530 (India Standard Time)".
As long as the string ends with some sort of year, a proper date value is returned. This will not let us to properly validate dates.
According to ECMAScript this behavior is implementation dependent and chrome does a very loose validation and some how converts to a date.
Is there anyway in chrome to properly validate date without using any library or using heavy logic and matching patterns?

A: You can test date string with regular expression before parse.


text:
Q: Comparing rows of a multidimesional array in python I have two numpy array
a= np.array([[2,2],[3,2],[4,2],[3,3],[5,3]])
b= np.array([[1,1],[1,3],[5,3]])

I want to compare a with b and return a-b such that :
a-b = array([[2,2],
             [3,2],
             [4,2],
             [3,3]])

I have tried doing :
[x for x in a if x not in b]

and it resulted in
[array([2, 2]), array([3, 2]), array([4, 2])] # where clearly [3,3] is missing

I even tried comparing each row of both a and b within loop where it gave me an error
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Can anyone please help me to solve this problem ???

A: Broadcasting based vectorized approach -
a[~((b[:,None,:] == a).all(2)).any(0)]

Using cdist from scipy.spatial.distance -
from scipy.spatial.distance import cdist

a[~(cdist(a,b)==0).any(1)]

Sample run -
In [89]: a
Out[89]:
array([[2, 2],
       [3, 2],
       [4, 2],
       [3, 3],
       [5, 3]])

In [90]: b
Out[90]:
array([[1, 1],
       [1, 3],
       [5, 3]])

In [91]: a[~((b[:,None,:] == a).all(2)).any(0)]
Out[91]:
array([[2, 2],
       [3, 2],
       [4, 2],
       [3, 3]])

In [92]: a[~(cdist(a,b)==0).any(1)]
Out[92]:
array([[2, 2],
       [3, 2],
       [4, 2],
       [3, 3]])

A: One way to do this would be to convert the numpy arrays into list of tuples and b to set of tuples then do the same list comprehension you used on them. Example -
In [1]: import numpy as np

In [2]: a= np.array([[2,2],[3,2],[4,2],[3,3],[5,3]])

In [3]: b= np.array([[1,1],[1,3],[5,3]])

In [18]: alist = list(map(tuple, a))

In [19]: bset = set(map(tuple, b))

In [20]: np.array([x for x in alist if x not in bset])
Out[20]:
array([[2, 2],
       [3, 2],
       [4, 2],
       [3, 3]])


text:
Q: Mysql : how to add a where clause superior on text I want to add a superior on where clause but my row is a text not an int.
For instance :
SELECT * FROM table WHERE row>'20'
I've got results including 10 / 15 / 200.
Do you have any solution because i can't change row's type.
Thanks

A: Try it after removing quotes '.


text:
Q: Customize Chrome settings page This is normal Chrome settings page:

I customized this page using simple edit in Chrome developer tools like this:

I want my chrome settings page in this way. So I'm trying to keep this setting page permanent. How can I do that?
Edit: Got the idea based on adding the following code on the file %userprofile%\AppData\Local\Google\Chrome\User Data\Default\User StyleSheets\Custom.css gives me ability to see always the advanced settings in chrome without clicking.
body.uber-frame #advanced-settings {
display: block !important;
height: auto !important;
}

Edit2: The article is here: http://www.quora.com/Google-Chrome/How-do-I-show-Google-Chrome-advanced-settings-by-default
Thus still I'm looking for similar tweak for me.


text:
Q: How to add a SaveandContinueEdit Button to my form? I am working on a new Magento extension, in my Adminhtml form I want to add the button "saveAndContinueEdit"
I've added this code to my Edit.php file.
      $this->_addButton('saveandcontinue', array(
    'label'     => Mage::helper('adminhtml')->__('Save And Continue Edit'),
    'onclick'   => 'saveAndContinueEdit()',
    'class'     => 'save',
), -100);

But whene I click on it, I have this JavaScript error :

Erreur : ReferenceError: saveAndContinueEdit is not defined Fichier
  Source :
  http://X.X.X.X/magento/index.php/slider/adminhtml_config/new/key

Can you help me ?
Thanks

A: in your admin Block Constructor Put these lines.
$this->_formScripts[] = " function saveAndContinueEdit(){
            editForm.submit($('edit_form').action+'back/edit/');
        }
    ";

Please remember you have to write functionality for it in PHP also.
Now in you action just have a final check that if you are getting back as param .. redirect it to referer page.


text:
Q: Mounting Ubuntu ISO on USB failed and now USB doesn't work I'm using a laptop with Windows 10 and my plan was mounting Ubuntu's ISO on a USB, booting from that USB and installing Ubuntu on an external HDD so I can use it without having it inside my laptop.
So, I downloaded the ISO 16.04.1 desktop, downloaded Rufus and proceeded with the official guide, step by step.
Result: Mounting the ISO failed, I got an "Error while partitioning drive" and this showed up:

Now, my USB doesn't even work. When I plug it, Windows prompts me to format it. Formatting fails, Windows disconnects the USB.
Is there any way to solve this so I can try again mounting the ISO to discover Ubuntu or is my USB totally unrecoverable?

A: Cooler heads should prevail... reboot your computer, and the USB port will probably be fine. Prove it by plugging in a DIFFERENT USB device.
My experience is that building a USB flash drive is very unreliable, no matter how it's done. Burn your .ISO to a DVD, and then boot the DVD to install Ubuntu. It'll work fine.
While you're in Ubuntu, trying formatting the suspect USB flash drive, and it too, will probably work fine.

A: Retry making a bootable USB with pendrive. http://www.pendrivelinux.com/
I had issues with RUFUS as well. I found I never had issues with pendrive.


text:
Q: How do I make the picture tile in Share Point Picture Libraries transparent? Greetings Stack Overflow,
I humbly request assistance with a Sharepoint 2013 issue. I have a picture library in SP and it defaults to having a colored tile box over the image that expands when I hover over it. This is obscuring the finer details of some images. As such, my goal is to remove this box or make it transparent. Using related SO questions and fiddling around with inspect source, I have been trying to insert code into the Thumbnail.aspx in Sharepoint designer and have been wholly unsuccessful. An example of one such attempt is:
< style>
.ms-tileview-tile-detailsBox
{color:#fff;background-color: rgb(4 55 66 / 0%);position:absolute;top:130px;}
< /style>

Here is a before and after example of what I am hoping to achieve. I would greatly appreciate any help with this issue, or even any pointers towards an authoritative source on the subject.
Regards,
S

A: You could also use opacity: value to set element transparency.But when the transparency is to zero,the picture name will not be seen.
https://www.w3schools.com/cssref/css3_pr_opacity.asp
Test result:

The picture on the left shows the style has been modified

A: To make the color of the box transparent, you can apply.
background-color: rgb(0,0,0,0);

where the 4th value indicates transparency. Takes value between 1 and 0.


text:
Q: Django SMTPServerDisconnected error on password reset (but works elsewhere) I'm trying to set up self-serve password resets on a django setup. I have configured it to use the in-built password reset system, and have tested everything on my dev machine, and works fine. However, in production (i.e. actually sending emails), when I try to get a password reset email, it throws an SMTPServerDisconnected error:
[22/Sep/2017 15:04:59] ERROR [django.request:256] Internal Server Error: /password_reset/
Traceback (most recent call last):
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
    return func(*args, **kwargs)
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/views.py", line 182, in password_reset
    form.save(**opts)
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 256, in save
    html_email_template_name=html_email_template_name)
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 213, in send_mail
    email_message.send()
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 107, in send_messages
    sent = self._send(message)
  File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 123, in _send
    self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
  File "/usr/lib/python2.7/smtplib.py", line 735, in sendmail
    self.rset()
  File "/usr/lib/python2.7/smtplib.py", line 469, in rset
    return self.docmd("rset")
  File "/usr/lib/python2.7/smtplib.py", line 394, in docmd
    return self.getreply()
  File "/usr/lib/python2.7/smtplib.py", line 368, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed

I'm using G-Suite (Google) as the SMTP relay; the settings I'm using are:
EMAIL_HOST = 'smtp-relay.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

The weird thing is I can send emails fine in other places within the system, using django's django.core.mail.send_mail() function.

A: The problem turned out to be that I hadn't set DEFAULT_FROM_EMAIL, thus django was attempting to send from a localhost email address, which Google's SMTP servers silently rejected. In other uses for send_mail() I had specified the from address, so this didn't appear as an issue there.


text:
Q: JPA: N+1 query even after FetchType.LAZY I've read a few articles that shows how to solve n+1 query problem in JPA, but none of it worked for me.
When I try to fetch the data, JPA makes n+1 queries.
select owner0_.id as id1_1_, owner0_.created_at as created_2_1_, owner0_.updated_at as updated_3_1_, owner0_.name as name4_1_, owner0_.version as version5_1_ from owner owner0_

select cars0_.owner_id as owner_id6_0_0_, cars0_.id as id1_0_0_, cars0_.id as id1_0_1_, cars0_.created_at as created_2_0_1_, cars0_.updated_at as updated_3_0_1_, cars0_.license_no as license_4_0_1_, cars0_.owner_id as owner_id6_0_1_, cars0_.version as version5_0_1_ from car cars0_ where cars0_.owner_id=? [1]

select cars0_.owner_id as owner_id6_0_0_, cars0_.id as id1_0_0_, cars0_.id as id1_0_1_, cars0_.created_at as created_2_0_1_, cars0_.updated_at as updated_3_0_1_, cars0_.license_no as license_4_0_1_, cars0_.owner_id as owner_id6_0_1_, cars0_.version as version5_0_1_ from car cars0_ where cars0_.owner_id=? [2]

Below is the code snippet :
@Entity
public class Owner extends BaseEntity implements EntityTransformer<OwnerDto> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @Version
    private Long version;

    @OneToMany(mappedBy = "owner", fetch = FetchType.LAZY)
    private Set<Car> cars;

    @Override
    public OwnerDto convertToDto() {
        OwnerDto ownerDto = new OwnerDto();
        ownerDto.setId(this.getId());
        ownerDto.setName(this.getName());
        ownerDto.setVersion(this.getVersion());
        if (this.getCars() != null) ownerDto.setCars(this.getCars().stream().map(Car::convertToDto).collect(Collectors.toSet()));
        return ownerDto;
    }
}

and my Car class is as follow :
@Entity
public class Car {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String licenseNo;

    @Version
    private Integer version;

    @JoinColumn( name = "owner_id" )
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Owner owner;
    @Override
    public CarDto convertToDto() {
        CarDto carDto = new CarDto();
        carDto.setId(this.getId());
        carDto.setLicenseNo(this.getLicenseNo());
        carDto.setVersion(this.getVersion());
        return carDto;
    }
}

OwnerService :
@Service
public class OwnerServiceImpl implements OwnerService {

    @Autowired
    OwnerRepository ownerRepository;

    @Override
    public List<Owner> findAll() {
        return ownerRepository.findAll();
    }
}

OwnerController :
@RestController
public class OwnerController {
    @Autowired
    private OwnerService ownerService;

    @GetMapping(value = "/owners", produces = "application/vnd.demo.api.v1+json")
    public ResponseEntity<List<OwnerDto>> findAll() {
        return ResponseEntity.ok(ownerService.findAll().stream().map(Owner::convertToDto).collect(Collectors.toList()));
    }
}

cURL :
curl -X POST \
  http://localhost:8080/owner \
  -H 'Accept: application/vnd.demo.api.v1+json' \
  -H 'Content-Type: application/json' \
  -H 'Host: localhost:8080' \
  -d '{
    "name": "pranay5"
}'

curl -X POST \
  http://localhost:8080/owner/5/car \
  -H 'Accept: application/vnd.demo.api.v1+json' \
  -H 'Content-Type: application/json' \
  -H 'Host: localhost:8080' \
  -d '{
    "licenseNo": "MSH-5555"
}'

Is there something wrong with the code?
On a side note: @BatchSize(size = 5) JPA makes only two queries
When I set @BatchSize(size = 5) without making any other changes, it makes only two queries to the database.
select o_.id , o_.created_at, o_.updated_at, o_.name from owner o_

select c_.owner_id, c_.id, c_.created_at, c_.updated_at, c_.license_no, c_.owner_id, from car c_ where c_.owner_id in (?, ?, ?, ?, ?) [1,2,3,4,5]

But my doubt is why FetchType.LAZY making N+1 queries?
Code: https://github.com/pranayhere/exception-demo-mvn

A: Actually the problem is that you use the default findAll of the OwnerRepository and you put FetchType.LAZY.
Because you get the cars in the Owner::convertToDto, Hibernate has to fetch the cars it did not fetched because of the lazy fetching.
To avoid the additional queries, create a new JPA method in the OwnerRepository getAllBy with an EntityGraph to eagerly fetch the cars in the query:
public class OwnerRepository extend JpaRepository<Owner, Long> {

    @EntityGraph(attributePaths = {
            "cars",
    })
    List<Owners> getAllBy();

}

Then use it in your service instead of the findAll.

A: I just checked your code and I think the problem is in OwnerController:
@GetMapping(value = "/owners", produces = "application/vnd.demo.api.v1+json")
public ResponseEntity<List<OwnerDto>> findAll() {
    return ResponseEntity.ok(ownerService.findAll().stream().map(Owner::convertToDto).collect(Collectors.toList()));
}

The Owner.convertToDto() method iterates over Owner.cars field.


text:
Q: background image or color for a static box in vc++ anyone knows how we can set an image or color for the background in a static box in vc++

A: Derive your own class from CStatic, and override OnCtlColour
Here you got the docs + a sample.
http://msdn.microsoft.com/de-de/library/0wwk06hc.aspx
I am not sure if this works for images also, but you know where to look.


text:
Q: Re-resolve remote AD's ip address when using OpenLDAP as proxy to AD It is working when setting up OpenLDAP as proxy to AD. However after certain time, the OpenLdap proxy is unable to reach AD unless OpenLdap proxy is restarted.
I suspect that OpenLdap proxy caches remote LDAP IP address, and could not reach AD once IP is changed or AD is under round robin schedule.
Is there a way to force Open Ldap proxy to re-resolve remote AD naming?


text:
Q: How to work with ArrayList of ArrayLists of Integers? I'm trying to use an ArrayList of ArrayLists of Integers in Java, code:
Attributes and Constructor
int V;
    ArrayList<ArrayList<Integer>>  gpond;
    ArrayList<Integer> vpond;

    GrPond(int v){ //Number of total nodes (arraylists in the main arraylist)
        V=v;
        gpond = new ArrayList<>();
        for(int i=0;i<V;i++){
            gpond.add(new ArrayList<Integer>(V));
        }
    }

Im using this method to add the ArrayLists of Integers to the main ArrayList (gpond)
 void VPond(int v, int w,int val){ // v=origin, w=destination, val=value.
        ArrayList<Integer> temp = new ArrayList<Integer>(V);
        for(int i=0;i<V;i++){
            temp.add(null);
        }
        temp.set(w, val); //I want to set in the given index a certain value
        gpond.add(v, temp); //Then, add that ArrayList with the value (val)
                            //at the given index (w), to the main ArrayList.
    }

And trying to print it using:
void printGraph(){
        for(int i=0;i<V;i++){
            System.out.println("node "+i);
            if(gpond.get(i)!=null){  //Just want to print those who are occupied
                for(int j=0;j<V;j++){ //j<V, because each ArrayList<Integer> has maximum V values
                    if(gpond.get(i).get(j)!=null) //Just print the indexes with a given value
                        System.out.println("["+i+"]-> ["+j+"] | val: "+gpond.get(i).get(j));
                }
            }
        }

        for(ArrayList<Integer> e: gpond){ //Just want to test each ArrayList of the main ArrayList
            System.out.println("e: "+ e);
        }
    }

What I expect it to do if the input is, lets say:
v,w,val:
0 1 2
0 2 1
1 0 1

e: [null, 2, null], [null, null, 1] //or something like this. e=origin, [index->value]
e: [1, null, null]

is to print
node 0
[0]->[1] | val: 2
[0]->[2] | val: 1
[1]->[0] | val: 1

Instead its printing:
node 0
[0]->[2] | val: 1
node 1
[1]->[0] | val: 1
node 2
[2]->[1] | val: 2

e: [null, null, 1]
e: [1, null, null]
e: [null, 2, null]

I've tried changing set for add in temp and/or gpond in VPond
I think it's a pretty little mistake but I just can't figure it out

A: Your problem is that you always create a complete new List in your method VPond. So you loose your old values. You should create the new List in the constructor of GrPond and just set the new value in VPond.
GrPond(int v){ //Number of total nodes (arraylists in the main arraylist)
    V = v;
    gpond = new ArrayList<>();
    for(int i=0;i<V;i++){
        ArrayList<Integer> temp = new ArrayList<Integer>(V);
        for(int j=0;j<V;j++){
            temp.add(null);
        }
        gpond.add(temp);
    }
}

void VPond(int v, int w,int val){ // v=origin, w=destination, val=value.
    List<Integer> temp=gpond.get(v);
    temp.set(w, val); //I want to set in the given index a certain value
}

And please, think about the names of your variables. You use v, w, val, V, VPond, GrPond, i and j. If you touch this code a week after you wrote it you will be completely confused (just as I was). You even write comments to translate your variable names, why don't you use these meanings directly?
int sizeOfLists;
List<List<Integer>> gpond;
List<Integer> vpond;

GrPond(int listSize) {
    sizeOfLists = listSize;
    gpond = new ArrayList<>();
    for (int listIndex = 0; listIndex < sizeOfLists; listIndex++) {
        List<Integer> temp = new ArrayList<>(sizeOfLists);
        for (int indexInList = 0; indexInList < sizeOfLists; indexInList++) {
            temp.add(null);
        }
        gpond.add(temp);
    }
}

void VPond(int listIndex, int indexInList, int value) { listIndex=listIndex, indexInList=indexInList
    List<Integer> list = gpond.get(listIndex);
    list.set(indexInList, value);
}


text:
Q: Saving log files to pc in Android Studio Is it possible to write log files to my pc?
I'm creating a log file inside my android app which i need to analyze on my pc, is it possible to save this file directly to my pc? The app runs on my tablet which is connected via USB.

A: //to read the logcat programmatically
try {
 Process process = Runtime.getRuntime().exec("logcat -d");
 BufferedReader bufferedReader = new BufferedReader(
 new InputStreamReader(process.getInputStream()));

        StringBuilder log=new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null)
       {
         log.append(line);
       }
}
catch (IOException e) {
}

//to create a Text file name "logcat.txt" in SDCard
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
dir.mkdirs();
File file = new File(dir, "logcat.txt");


text:
Q: Main effect vs simple effect In the following linear model:
$y = \beta_0 +\beta_1 x_1 +\beta_2 x_2 + \beta_3x_1x_2 + \epsilon$
what are called $x_i$? The term $x_1x_2$ is the interaction. In ANOVA, $x_i$ are named "main effects", but in regression I saw a paper mentioning that it is wrong in the context of regression (even though I see it all the times in papers and on CV) and they should be called "simple effects" or "simple main effects". Is it really wrong? Would it be really better to call them "conditional relationship" or something similar?

A: I try to avoid the term "main effect" when there's an interaction, or at least wrap it in quotes if I feel forced to use it. The reason is perhaps mostly psychological, but avoiding the term can help avoid a lot of confusion.
The problem is that, with an interaction term involving a predictor, changing the reference value of its interacting predictor can change its own apparent "main effect"! See this page for a worked-through example. In your equation, if $\beta_3$ is non-zero, the value of $\beta_1$ will change if you change the centering of $x_2$ (continuous case) or change the $x_2$ reference level (categorical case).
I have frequently answered questions on this site about mysterious unexpected "lack of significance" of "main effects" known to be "important" when they are involved in interactions. The confusion always results from an attempt to interpret the "significance" of a "main effect" coefficient as representing the "importance" of a predictor that is involved in an interaction. If there's an interaction, evaluating the "importance" of the predictor must take into account its interaction coefficients too.
Why should something that sounds so definitive as a "main effect" of one predictor depend on how you have handled another predictor? The term "simple effect" sounds appropriately less definitive.


text:
Q: Columns index has to be unique for fixed format error in pandas time series I got ValueError: Columns index has to be unique for fixed format when I tried to save a dataframe which I formed by combining multiple time series dataframe. This is the sample of what I have done
df1=pd.concat([d1,d2,d3,d4],axis=1]
df2=pd.DataFrame(d5)
df3=pd.concat([d6,d7,d8],axis=1]

main_df=pd.concat([df1,df2,df3],axis=1)
main_df=main_df.dropna()
main_df.head()

till here it works fine but when I tried to save those data into a HDF5 file its giving me this error Columns index has to be unique for fixed format
fi=pd.read_hdf("data.h5")
fi['df']=main_df #this line cause the error

A: You can use cumcount for count duplicates, replace 0 if necessary and add it to original columns names:
df = pd.DataFrame([[1,2,3,4]], columns = list('abbc'))
print (df)
   a  b  b  c
0  1  2  3  4

s = df.columns.to_series()
df.columns = s + s.groupby(s).cumcount().astype(str).replace({'0':''})
print (df)
   a  b  b1  c
0  1  2   3  4


text:
Q: unrecognized selector sent to instance to a newly added method; messages to previously defined methods work fine '-[MTviewFilesVC launchVF]: unrecognized selector sent to instance 0x1e59fcd0'
I added a method to a class but calling it creates 'unrecognized selector' run time error
The calling code is:
self.viewFilesVCPtr = [[MTviewFilesVC alloc] init];
[self.viewFilesVCPtr launchVF];

This works if, for example, I substitute viewDidLoad which exists already hence I
think the calling code is OK.Is there something else I need to add to the declaration of lanuchVF
to make it visible?
The method declaration, etc is:
.h:
#import "DirectoryWatcher.h"

@interface MTviewFilesVC : UITableViewController   <QLPreviewControllerDataSource,
                                                    QLPreviewControllerDelegate,
                                                    DirectoryWatcherDelegate,
                                                    UIDocumentInteractionControllerDelegate>
-(IBAction)saveViewFiles;
- (void)launchVF;

@end

.m:
@interface MTviewFilesVC ()

@property (nonatomic, strong) DirectoryWatcher *docWatcher;
@property (nonatomic, strong) NSMutableArray *documentURLs;
@property (nonatomic, strong) UIDocumentInteractionController *viewFileController;
-(void) launchVF;
@end

...

- (void)lanuchVF
{
    UIStoryboard *settingsStoryBoard = [UIStoryboard storyboardWithName:
                                        @"viewFiles" bundle:nil];
    UIViewController *initialViewFilesVC = [settingsStoryBoard instantiateInitialViewController];
    initialViewFilesVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:initialViewFilesVC animated:YES];

}

A: Your method name in the .m has a typo, lanuchVF instead of launchVF :-)


text:
Q: How to remove null data from JavaPairRDD I am getting the Hbase data and trying to do a spark job on it. My table has around 70k rows and each row has a column 'type', which can have the values:post,comment or reply. Based on the type, I want to take out different Pair RDDs like shown below(for post).
JavaPairRDD<ImmutableBytesWritable, FlumePost> postPairRDD = hBaseRDD.mapToPair(
            new PairFunction<Tuple2<ImmutableBytesWritable, Result>, ImmutableBytesWritable, FlumePost>() {
                private static final long serialVersionUID = 1L;

                public Tuple2<ImmutableBytesWritable, FlumePost> call(Tuple2<ImmutableBytesWritable, Result> arg0)
                        throws Exception {
                    FlumePost flumePost = new FlumePost();
                    ImmutableBytesWritable key = arg0._1;
                    Result result = arg0._2;
                    String type = Bytes.toString(result.getValue(Bytes.toBytes("cf"), Bytes.toBytes("t")));
                    if (type.equals("post")) {
                        return new Tuple2<ImmutableBytesWritable, FlumePost>(key, flumePost);
                    } else {
                        return null;
                    }

                }

            }).distinct();

Problem here is, For all the rows with type other than post I have to send null value which is undesirable. And iteration goes on for 70k times for all the three types, wasting the cycles. So my first question is:
1) What is the efficient way to do this?
So now after getting 70k results I put the distinct() method to remove the duplication of null values. So I end up having one null value object in it. I expect 20327 results but I get 20328.
2) Is there a way to remove this null entry from the pair RDD?

A: You can use the filter operation on the RDD.
Simply call:
.filter(new Function<Tuple2<ImmutableBytesWritable, FlumePost>, Boolean>() {
   @Override
   public Boolean call(Tuple2<ImmutableBytesWritable, FlumePost> v1) throws Exception {
       return v1 != null;
   }
})

before calling distinct() to filter out the nulls.


text:
Q: What is special in /Applications/ folder? What happens when an .app bundle going copy to the /Applications/ folder? Are there any processes starting, any preferences copied to /Library/ ? Is a copy to /Applications/ folder a special trigger/event for the OS X?
I found that if I just copy Xcode then com.apple.dt.Xcode.plist appears in user's Preferences folder.

A: With the exception of installing app with package manager, there is no special events if you only copy application to any folders. The preferences stored in Library or Application Support are created when you run the application for the first time.


text:
Q: Impedir entrada duplicada em uma lista usando AngularJS HTML:

Lista de compras

                          Comprado?
                          Produto
                          Quantidade

                          <input type="checkbox" ng-model="item.comprado">
                          {{ item.produto }}
                          {{ item.quantidade }}

                <form class="form-inline" name="formItem">
                  <input type="text" ng-model="item.produto" placeholder="Produto">
                  <input type="number" ng-model="item.quantidade" placeholder="Quantidade" class="input-small">
                  <button class="btn btn-primary" ng-click="adicionaItem()">adicionar ítem</button>
                </form>

Controller:
function ListaComprasController($scope) {
    $scope.itens = [
        {produto: 'Leite', quantidade: 2, comprado: false},
        {produto: 'Cerveja', quantidade: 12, comprado: false}
    ];

    $scope.adicionaItem = function () {
        $scope.itens.push({produto: $scope.item.produto,
                           quantidade: $scope.item.quantidade,
                           comprado: false});
        $scope.item.produto = $scope.item.quantidade = '';

    };
}

Gostaria de evitar entrada de itens duplicados na lista.
Tentei utilizar indexoff e foreach sem sucesso.

A: Olá, segue seu código adaptado!
veja o método
$scope.verificaProdutoExistente = function(value) {
    for(var i = 0; i < $scope.itens.length; i++) {
        if($scope.itens[i].hasOwnProperty("produto") && $scope.itens[i]["produto"] === value) {
            return i;
        }
    }
    return -1;
}

e a sua utilização logo abaixo, OBS no StackOverflow o alert não irá funcionar.

angular.module('app',[]).controller('ListaComprasController', function($scope) {

    $scope.itens = [
         {produto: 'Leite', quantidade: 2, comprado: false},
         {produto: 'Cerveja', quantidade: 12, comprado: false}
        ];

    $scope.adicionaItem = function () {
        //Verifica se o produto ja existe
        if ( $scope.verificaProdutoExistente($scope.item.produto) === -1 ){

            $scope.itens.push({produto: $scope.item.produto,
                            quantidade: $scope.item.quantidade,
                            comprado: false});
            $scope.item.produto = $scope.item.quantidade = '';

        } else {
            //Logica caso o produdo ja exista na lista
            alert("Produto ja existe.")
        }
    };

    $scope.verificaProdutoExistente = function(value) {
        for(var i = 0; i < $scope.itens.length; i++) {
            if($scope.itens[i].hasOwnProperty("produto") && $scope.itens[i]["produto"] === value) {
                return i;
            }
        }
        return -1;
    }

});

Lista de compras

                  Comprado?
                  Produto
                  Quantidade

                  <input type="checkbox" ng-model="item.comprado">
                  {{ item.produto }}
                  {{ item.quantidade }}

        <form class="form-inline" name="formItem">
          <input type="text" ng-model="item.produto" placeholder="Produto">
          <input type="number" ng-model="item.quantidade" placeholder="Quantidade" class="input-small">
          <button class="btn btn-primary" ng-click="adicionaItem()">adicionar ítem</button>
        </form>


text:
Q: Postgresql migration without dump Greetings,
  after a hdd failure, I have a PostgreSQL DB restored, but OS is not working. I try to copy it to another server with a newer version of PostgreSQL but all I managed to get is:
An old version of the database format was found.
You need to upgrade the data format before using PostgreSQL.
See /usr/share/doc/postgresql-8.1.22/README.rpm-dist for more information.
I don't know the old version number.
Please, advice me something.

A: If you were able to get all of the files in the data directory, then there should be a PG_VERSION file.  Using this, you can build a database with that version.  From my analysis, I haven't been able to find a way to restore the database data without a database with the correct version.
Here are some steps for recovery if you know the version:
http://archives.postgresql.org/pgsql-general/2009-09/msg01152.php
If you know that your last version is 8.3 or greater, this should work:
http://www.postgresql.org/docs/9.0/static/pgupgrade.html
Not a pleasant answer.

A: The advise on looking for the pg_version file is good, and also you should probably be able to run pg_controldata against the $PGDATA and get some information out. In the worst case, just keep installing major versions (7.4.x, 8.0.x, 8.1.x, etc...) until you find a compatible match.
One you have a running database, you can worry about upgrading if needed. pg_dump / restore is one option. pg_upgrade will work on 8.3+. You also have the option of using a replication system like slony to do cross version replication (how well it will work depends on what version you end up on).
For all of these methods though (including pg_upgrade) you'll need a running copy of your system, so start with trying to find the matching/compatible version to start with.


text:
Q: What do the methods do in this Java program? I'm confused as to what methods do exactly, so I was hoping for someone to explain the concept to me with this example program:
import java.io.*;
import java.util.*;

public class programB {

   public static void main(String[] args) throws IOException {

      String filename;
      String total="";
      String c = "";
      String size = "";
      int num1=0, num2=0;
      char ch;

      Scanner keyboard = new Scanner(System.in);

      System.out.println("Enter the name of the file you want to read data from:");
      filename=keyboard.next();

      Scanner fromFile = new Scanner(new FileReader(filename));

      while (fromFile.hasNext()) {
         String type = fromFile.next();

         ch = fromFile.next().charAt(0);
         num1 = fromFile.nextInt();
         if (type.equals("rectangle")) {
            num2 = fromFile.nextInt();
         }
         System.out.print(type + " ");
         System.out.print(ch + " ");
         System.out.print(num1 + " ");
         if (type.equals("rectangle")) {
            System.out.print(num2);
        }
         System.out.println();
         if (type.equals("rectangle")){
            rectangle(ch,num1,num2);

         }
         if (type.equals("triangle")){
            triangle(ch, num1);
         }

      }

   }
   /** Draw a rectangle of the specified width and height
    @param c the character that creates the drawing
    @param height the height of the rectangle
    @param width the width of the rectangle
*/
   public static void rectangle(char c, int height, int width){

      for (int i=1; i<=height; i++) {
         System.out.println();
         for (int a=1; a<= width; a++) {
            System.out.print(c);
     }

  }
  System.out.println();

   // put statements here to display a rectangle on the screen using
   // character c and the width and height parameters
   }

/** Draw a right triangle.
@param c the character that creates the drawing
@param size the height and width of the triangle
*/

   public static void triangle(char c, int size){
      for (int i=1; i<=size;i++) {
         for (int j=1; j<=i; j++) {
            System.out.print(c);
         }
         System.out.println();

      // put statements here to display a triangle on the screen using
      // character c and the size parameter
      }
   }
 }

What are the methods for and what do they do? I've tried researching it online and I've been studying my textbook but I'm still really confused by the concept.

A: The documentation that accompanies the methods does a decent job of explaining what they do, I think. The rectangle() method, when called with parameters '-', 3, and 4, will "draw" a rectangle 3 dashes high and 4 wide in the console where the program is run:
----
----
----

The triangle() method is similar; when called with '-' and 3, you'll get a shape like this:
-
--
---

A: Methods, at a basic level, are ways of writing code that you can use multiple times. Methods in Java allow you to define certain actions within your code.
Think of it this way: you know how to draw a triangle, right? So if I told you, "go draw a triangle," you'd know exactly what to do. I wouldn't have to say, "put your pencil on a piece of paper and draw a short line, then without picking your pencil up, draw another line, then draw a final line connecting where your pencil is now to the point where you started." That's a whole lot of instructions, so let's just say, whenever I want you to draw a triangle, I'll just say, triangle(). Similarly, let's do the same for rectangle().
But what if this got a little more complicated? Instead of just telling you, "draw a triangle," I said, "draw a triangle using ASCII characters with a certain height and a certain width," how much harder could that be? It's actually very simple - you need to know three different things: the character, the height, and the width. Once you have those, you know exactly what to do.
And that's exactly what your code is doing when you call triangle() and rectangle() - you are passing in three parameters into each of them and your code draws a triangle and a rectangle. And you can do this as many times as you want.


text:
Q: Table of probability A six-sided, fair die is rolled twice. Let $X$ be the sum of both throws, $Y_1$ be the result of the first throw and $Y_2$ be the result of the second. How to create the table of probability?

A: There's a lot of possible "tables of probability", I'm unsure what you want to find. But these should be the probabilities you're insterested in. Have in mind that $P(X) = \sum_YP(X,Y)$
Here's $P(Y1,Y2)$
\begin{array}{c|c|c|c|c|c|c}
&1& 2 & 3 & 4&5&6 \\ \hline
1 &\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
2 &\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
3 &\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
4&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
5&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
6&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
\end{array}
Here's $P(X,Y1)$ (or $P(X,Y2)$)
\begin{array}{c|c|c|c|c|c|c|c|c|c|c|c}
& 2 & 3 & 4&5&6&7&8&9&10&11&12 \\ \hline
1 &\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&0&0&0&0&0\\ \hline
2 &0&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&0&0&0&0\\ \hline
3 &0&0&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&0&0&0\\ \hline
4&0&0&0&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&0&0\\ \hline
5&0&0&0&0&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&0\\ \hline
6&0&0&0&0&0&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}&\frac{1}{36}\\ \hline
\end{array}
P(X)
\begin{array}{c|c|c|c|c|c|c|c|c|c|c|c}
& 2 & 3 & 4&5&6&7&8&9&10&11&12 \\ \hline
1 &\frac{1}{36}&\frac{2}{36}&\frac{3}{36}&\frac{4}{36}&\frac{5}{36}&\frac{6}{36}&\frac{5}{36}&\frac{4}{36}&\frac{3}{36}&\frac{2}{36}&\frac{1}{36}\\ \hline
\end{array}


text:
Q: Encrypting the password value used to send an email via a bat file? I want to send a file to my Gmail account via a bat file and encrypt my email info in that bat file so that if someone opens the bat file they cannot get the email information from it.
My Script
I'm using this dynamic script Batch Script per help I received from the "Send a file to an email address using a bat file without exposing the email info?" post. At the moment this script works fine however I have to hard code sensivite values into it which is what I do not avoid if possible.
@ECHO OFF

SET GmailAccount=<GmailAccountName>
SET GmailPassword=<GmailPassword>
SET Attachment=<FullAttachmentPath>

CALL :PowerShell
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%' '%GmailAccount%' '%GmailPassword%' '%Attachment%'"
IF EXIST "%~FN0" DEL /Q /F "%~FN0"
EXIT

:PowerShell
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
SET PSScript=%temp%\~tmpSendeMail.ps1
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"

ECHO $Username      = $args[0]>> "%PSScript%"
ECHO $EmailPassword = $args[1]>> "%PSScript%"
ECHO $Attachment    = $args[2]>> "%PSScript%"
ECHO                          >> "%PSScript%"
ECHO $Username    = $Username                 >> "%PSScript%"
ECHO $EmailTo     = "EmailAddress@domain.com" >> "%PSScript%"
ECHO $EmailFrom   = "noreply@Whatever.notify" >> "%PSScript%"
ECHO $Subject     = "Email Subject"           >> "%PSScript%"
ECHO $Body        = "Email Body"              >> "%PSScript%"
ECHO $SMTPServer  = "smtp.gmail.com"          >> "%PSScript%"
ECHO $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body) >> "%PSScript%"
ECHO $Attachment  = New-Object System.Net.Mail.Attachment($Attachment)                            >> "%PSScript%"
ECHO $SMTPMessage.Attachments.Add($Attachment)                                                    >> "%PSScript%"
ECHO $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)                               >> "%PSScript%"
ECHO $SMTPClient.EnableSsl = $true                                                                >> "%PSScript%"
ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword) >> "%PSScript%"
ECHO $SMTPClient.Send($SMTPMessage)                                                               >> "%PSScript%"
GOTO :EOF

I'd like to be able to use encrypted values rather than the actual values for certain variables and such so when this script is run if someone sees it, they cannot easily see those sensitive values.

A: Obfuscate Sensitive Strings with PowerShell to Send an Email via a Batch Script
You can use a strategic variation of the PowerShell code mentioned in the "Simple Obfuscation with PowerShell using Base64 Encoding" post to...

*

*Encode the sensitive string(s) you wish to obfuscate to make those not so easily decipherable to anyone without a lot of technical know-how which could potentially see or copy the script logic at runtime

*Setup the process to cleanup and remove the batch script, and the dynamically generated PowerShell script, after both are executed and run the necessary logic
Get Encoded String Values
Whatever value you want to obfuscate, you will put that value enclosed within double quotes in the $SensitiveString per the below logic and then execute $OString to get the encoded value.
These will be the values you hard code into the below Batch Script rather than using the sensitive values themselves in a plain text format.
$SensitiveString = "ARealDumbPassword" ## -- Put sensitive string value to encode here
$OString         = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($SensitiveString))
$ConvertedString = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($OString))
$OString ## -- Get encoded string value

You can use the existing batch script with a few adjustments so the encoded values can be passed in or set in the batch script logic and have the other logic within the PowerShell script to decode those values for use. Once done, the PowerShell script and the batch script will be deleted.
Batch Script
@ECHO OFF

:: -- Set senvitive values and file attachment path
SET "GmailAccount=RwBtAGEAaQBsAEEAYwBjAG8AdQBuAHQAVQBzAGUAcgBuAGEAbQBlAF8AXwBCAGkAdABjAGgA"
SET "GmailPassword=QQBSAGUAYQBsAEQAdQBtAGIAQQBzAHMAUABhAHMAcwB3AG8AcgBkAA=="
SET "Attachment=<FullAttachmentPath>"

:: -- Set other email values
SET "EmailTo=Bob@BobMail.com"
SET "EmailSubject=This is the subject of the email"
SET "EmailBody=This is the body of the email"

CALL :PowerShell
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%' '%GmailAccount%' '%GmailPassword%' '%Attachment%'"
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
IF EXIST "%~FN0" DEL /Q /F "%~FN0"
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
EXIT

:PowerShell
SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
SET PSScript=%temp%\~tmpSendeMail.ps1
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"

ECHO $Username      = $args[0]                                                                                >> "%PSScript%"
ECHO $Username      = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Username))     >> "%PSScript%"
ECHO $EmailPassword = $args[1]                                                                                >> "%PSScript%"
ECHO $EmailPassword = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($EmailPassword))>> "%PSScript%"
ECHO $Attachment    = $args[2]                                                                                >> "%PSScript%"
ECHO $Attachment    = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Attachment))   >> "%PSScript%"
ECHO                                          >> "%PSScript%"
ECHO $Username    = $Username                 >> "%PSScript%"
ECHO $EmailTo     = "%EmailTo%"               >> "%PSScript%"
ECHO $EmailFrom   = "noreply@Whatever.notify" >> "%PSScript%"
ECHO $Subject     = "%EmailSubject%"          >> "%PSScript%"
ECHO $Body        = "%EmailBody%"             >> "%PSScript%"
ECHO $SMTPServer  = "smtp.gmail.com"          >> "%PSScript%"
ECHO $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body) >> "%PSScript%"
ECHO $Attachment  = New-Object System.Net.Mail.Attachment($Attachment)                            >> "%PSScript%"
ECHO $SMTPMessage.Attachments.Add($Attachment)                                                    >> "%PSScript%"
ECHO $SMTPClient  = New-Object Net.Mail.SmtpClient($SmtpServer, 587)                              >> "%PSScript%"
ECHO $SMTPClient.EnableSsl = $true                                                                >> "%PSScript%"
ECHO $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword) >> "%PSScript%"
ECHO $SMTPClient.Send($SMTPMessage)                                                               >> "%PSScript%"
GOTO :EOF

Supporting Resources

*

*Simple Obfuscation with PowerShell using Base64 Encoding

*Convert.ToBase64String Method

*Encoding Class

*UnicodeEncoding.GetString(Byte[], Int32, Int32) Method

*System.Convert Methods

*Convert.FromBase64String(String) Method


text:
Q: How do I know when Data finished downloading I would like to know when the function below has finished downloading the data.
I know I can use a completion handler, but this is in an NSObject and I'd like to know when to return the completion handler for this function, making sure the video is downloaded completely and ready to go, before the function returns the completion handler, and my View Controller resumes it's logic.
Thanks :)
func downloadVideo(identity:JSON_Video){
    // use guard to make sure you have a valid url
    let videoId = identity.video_id!
    let videoString:String = "\(Constants.endPoint_video)\(videoId).mp4"

    guard let videoURL = URL(string: videoString) else { return }
    let library_url = self.findVideo(video: identity)

    if self.findVideo(video: identity) != nil{
        print("Video exists. No need to download")
        print("Existing video \(library_url!)")
    }else{
        print("Video not found. Downloading now")

        // Variables to input on request
        let loginString = Constants.loginString
        let loginData = loginString.data(using: String.Encoding.utf8)!
        let base64LoginString = loginData.base64EncodedString()

        // URL request
        var urlRequest = URLRequest(url: videoURL)
        urlRequest.httpMethod = "GET"
        urlRequest.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in

            // do stuff with response, data & error here
            if let error = error{
                print("Data Session Error: \(error.localizedDescription)")
                print(response ?? "No response")
                return
            }
            if let data = data {
                print("Incoming video....")
                print("Data: \(data.description)")

                if let finalDatabaseURL = self.videosBaseUrl()?.appendingPathComponent("\(identity.video_id!).mp4"){
                    print("Copying from: \(videoURL)")
                    print("Copying to: \(finalDatabaseURL)")

                    do {
                        try
                        data.write(to: finalDatabaseURL)
                        print("Writing data to file")
                        // *****
                        // How do I know when data finished writing?
                        // Completion handler goes here ?
                        // *****
                    }catch{
                        print("Error writing data to file")
                        print(error.localizedDescription)
                    }
                }
            }

           }
        })
        task.resume()
    }
}


text:
Q: Laravel eloquent, how do i group by for 2 columns in relation I have a messages table that looks like this:

*

*id

*user_id

*target_user_id

*message
What i would like to do is group up these by conversation.
So some typical records can look like this:
#1
user_id = 5
target_user_id = 10
message = hello
#2
user_id = 10
target_user_id = 5
message = hello
#3
user_id = 15
target_user_id = 20
message = hello
#2
user_id = 15
target_user_id = 20
message = hello

What i would like to achieve is how i can group all my records together so that all messages between user 5 and 10 for example is in a group and  15 and 20 is in a group and sorted by latest.
This is my current attempt:
$msgs = Message::with('user')
     ->where(function($q) {
     $q->where('user_id', Auth::user()->id)
        ->orWhere('target_user_id', Auth::user()->id);
     })
     ->groupBy('user_id', 'target_user_id')
            ->get();

This is not a duplicate since the problem and question is very different and the solution suggested there is what i have already tried above if you can see that.

A: I guess that you can group them like this:
$msgs = Message::with('user')
             ->where(function($q) {
             $q->where('user_id', Auth::user()->id)
                ->orWhere('target_user_id', Auth::user()->id);
             })
    ->get();

$groupedMessages = $msgs->groupBy(function ($message) {
    return min($message->user_id, $message->target_user_id) .'-'. max($message->user_id, $message->target_user_id);
});


text:
Q: Retornar imagem por Web Service REST Server Tenho um Web Service REST rodando, esse web service faz a consulta no ERP quando o cliente solicita a requisição de um determinado dado, precisava retornar a imagem que o cliente fez a requisição e mostrar no browser.
fiz o seguinte código que retorna um stream, mas mesmo assim não tive sucesso.

Result := TFileStream.Create(sDirImagem,fmOpenRead or fmShareCompat);

A: Para visualizar a imagem direito no navegador, consegui resolver do seguinte modo, usei a função GetInvocationMetaData, tenho que especificar para o navegador qual o retorno. Vou colocar um exemplo de como eu fiz:
declarar no usues Data.DBXPlatform
function CarregarImagem(const sCaminho: String): AnsiString;
var
  oFileStream : TFileStream;
begin
  oFileStream:= TFileStream.Create(sCaminho, fmOpenRead or fmShareDenyWrite);
try
 if oFileStream.Size > 0 then
 begin
   SetLength(Result, oFileStream.Size);
   oFileStream.Read(Pointer(Result)^, oFileStream.Size);
 end;
finally
  FreeAndNil(oFileStream);
end;

end;
sImagem := CarregarImagem(sDirImagem);
if (bExtPNG) then
  GetInvocationMetadata().ResponseContentType := 'image/png'
else
begin
  GetInvocationMetadata().ResponseContentType := 'image/jpeg';
  GetInvocationMetadata().ResponseCode := 200;
  GetInvocationMetadata().ResponseContent := sImagem;
  GetInvocationMetadata().CloseSession    := True;
end;


text:
Q: The "award bounty" button is indistinguishable from the "bounty awarded" indicator in the mobile site This post has examples from blender.SE but I think all sites use the same theme on mobile (through the browser, not the SE app).
I've recently offered a bounty on a question. Then I visited the page on mobile and I thought I had mistakenly awarded it! There was a blue +150 under an answer!
I then realized that on mobile there is no distinction between the "award bounty" button and the "bounty awarded" indicator:
  ←  mobile
On desktop, at least in Blender.SE, the difference is highlighted by the color of the box:
  ←  desktop
and the mouse-over tooltip also helps removing any ambiguity.
Should this difference be highlighted on mobile as well?


text:
Q: How to delete dynamically created Content Projection Transclusion element in angular2? I have created two widget components, for example, Data and Chart widget which are transclusion by another component named Card component. In Card component, I have used a common close button so that I can use the close button in every widget by default. The Data and Chart widget created dynamically and save in an array and finally the components are rendered on html template. Now, I would like to delete the components from the array by clicking the close button on each widgets. I tried in the following way,
CardComponent.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import {WidgetComponent} from './widget.component';

@Component({
    selector: 'card',
    templateUrl: 'card.component.html',
})
export class CardComponent {

    @Input()
    public header: string = 'this is header';

    @Input()
    public footer: string = 'this is footer';

    @Output() closeWidget = new EventEmitter();

    close(){
      console.log('Card close');
      this.closeWidget.emit();
    }
}

CardComponent.html

    {{ header }}
  Close

  <ng-content></ng-content>

    {{ footer }}

chart-widget.component.ts
@Component({
selector: 'chart-widget',
templateUrl: './app/chart-widget.component.html',
providers: [{provide: WidgetComponent, useExisting: forwardRef(() => ChartWidget) }]
})

export class ChartWidget extends WidgetComponent implements OnInit {

}

chart-widget.component.html
<card header="Chart Panel" footer="Footer here" class="ui-toolbar-group-
right">

Chart Card

Chart showing here

</card>

AppComponent.ts
@Component({
  selector: 'app-root',
  templateUrl: './app/app.component.html',
  styleUrls: ['./app/app.component.css'],
  entryComponents: [ChartWidget,  DataWidget],
})

export class AppComponent {
   private elements: Array<{ view: ViewRef, component: WidgetComponent}>=[];
   private WidgetClasses = {
      'ChartWidget': ChartWidget,
      'DataWidget': DataWidget
  }
  @ViewChild(DynamicComponent) dynamicComponent:DynamicComponent;

  addComponent(widget: string ): void{
    let component = this.dynamicComponent.addComponent(this.WidgetClasses[widget]);
    let view: ViewRef = this.dynamicComponent.container.detach(0);
    this.elements.push({view,component});

    this.dynamicComponent.resetContainer();
  }

  onWidgetDelete(element: any){
        console.log('Call Delete called');
        var index = this.elements.findIndex((elt) => (elt===element));
        if (index !== -1) {
            this.elements.splice(index, 1);
        }

    }
}

app.component.html
<button (click)="addComponent('ChartWidget')">Add ChartWidget</button>
<button (click)="addComponent('DataWidget')">Add DataWidget</button>

<dynamic-component [hidden]="true" ></dynamic-component>

Dynamic Components

<widget *ngFor="let item of elements" (closeWidget)="onWidgetDelete(item)">
  <ng-container *view="item.view" ></ng-container>
</widget>

I am getting the click event message on console but the EventEmitter does not work. How do I delete the components by clicking the close button?
Here is my Plunker https://plnkr.co/edit/tFmcpre6FHysJ1uUFPp5?p=preview


text:
Q: Having a variable in the middle of an alias? I currently have a commonly used grep command:
    grep -r -w <SEARCH> --include \*.c --include \*.cpp --include \*.h

Want to have this as an alias (say, grepc) but be able to change the SEARCH in the middle. Is it possible to have this as a variable, and if so how would I do this / call it?

A: No need to pass argument for this use case
alias xyz="grep -r --include='*.'{c,h,cpp} -w"
xyz 'whatever'

When arguments are needed to be passed, use functions instead. See this Q&A on unix stackexchange for discussion between alias and functions