text:
Q: Adding fragments to display a full screen layout I want to use fragments to display the Now playing screen whenever a user clicks on a song.I am having a main_activity layout that displays the list of songs and a item click listener.Now i want to open another layout which completely occupies the screen showing the current song that is being played.I think i can achieve this using a fragment but can't find a way to implement it.
Here is my main_activity xml file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"/>``
</RelativeLayout>

Now i want to replace this entire layout with now playing layout
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/AppTheme.NoActionBar">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="320dp"
    android:fitsSystemWindows="true"
    android:id="@+id/image"/>

A: your main_activity.xml should be like this :
  <FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_frame"

android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
  >

<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:fitsSystemWindows="true"
 tools:context=".MainActivity"
 tools:showIn="@layout/activity_main">

<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>``
</RelativeLayout>

</FrameLayout>

on button click you have perform this code :
  Fragment fragment = new NowPlayingFragment();

 ((FragmentActivity) view.getContext()).getFragmentManager().beginTransaction()
                .replace(R.id.main_frame, fragment).addToBackStack(null).commit();

so this will replace a fragment on your current activity
EDIT:
Here is my fragment class
public class NowPlayingFragment extends android.support.v4.app.Fragment {

public NowPlayingFragment() {
}
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_playing, container, false);
}


text:
Q: Finding users with highest percentage of accepted or top voted answers? I am attempting to improve a data.SE query to find users with the highest percentage of accepted answers to include a percentage where the answer is not accepted, but highest voted.
This query works well for the first part - accepted answers - but does not address the situation where the answer is:

*

*not accepted

*highest scored

I was trying this as an additional case clause... but it seems more complicated than I can figure out.
 --this really doesn't work.. at all
  sum(case
    when
        q.AcceptedAnswerId <> a.Id
        and a.Score = select MAX(Score) from Posts ps where ps.ID=q.ID
    then
        1
    else
        0
    end) AS NumHighestNotAccept,

Any help would be greatly appreciated!

A: Having the query there doesn't really work. Instead I forked yours to this one and added an left outer join to get a set of the highest scoring answers per question.
-- Users with highest accept rate of their answers
-- Does not count self-answers.
-- Shows users with at least @MinAnswers answers.

DECLARE @MinAnswers int = ##MinAnswers##

SELECT TOP 100
  u.Id AS [User Link],
  count(*) AS NumAnswers,
  sum(case
    when
        TopAnswer.id is not null
    then
        1
    else
        0
    end) AS NumHighestNotAccept,
  sum(case when q.AcceptedAnswerId = a.Id then 1 else 0 end) AS NumAccepted,
  (sum(case when q.AcceptedAnswerId = a.Id then 1 else 0 end)*100.0/count(*)) AS AcceptedPercent
FROM Posts a
INNER JOIN Users u ON u.Id = a.OwnerUserId
INNER JOIN Posts q ON a.ParentId = q.Id
left outer join (
 -- get the id's from the answers
 -- on a question ...
 select ps.id
 from Posts ps
 -- that have a score
 where score = (select max(score)  -- maxium of all answers
                from posts pas
                -- on this question
                where ps.parentid = pas.parentid)
) as TopAnswer
     -- for a specific answer
     on topanswer.id = a.id
WHERE
  (q.OwnerUserId <> u.Id OR q.OwnerUserId IS NULL)   --no self answers
GROUP BY u.Id
HAVING count(*) >= @MinAnswers
ORDER BY AcceptedPercent DESC
       , NumAnswers DESC

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using root to clear the status bar notifications I am currently working on an app using an accessibility service to handle notifications. What is particularly annoying is there is no way for third party apps to clear the status bar notifications, other than launching the intent linked to the notification (and launch the app).
I have searched for a long time for a way to use root to dismiss a notification or clear the complete list, but I have failed.
I think I remember an app I saw that cleared the status bar by quickly opening the status bar and clicking the clear button programmatically, but I can't find it anymore, and I think it was on Android 2.2.
I was wondering if there was a way to interact with the status bar notifications using some kind of database or with a simple SU call.

A: UPDATE - See working solution below
All this stuff gets handled by the NotificationManagerService (see here: https://github.com/android/platform_frameworks_base/blob/master/services/java/com/android/server/NotificationManagerService.java). I think in particular you'd be interested in the void cancelAll(int userId) method. When you press clear on the status screen that's the method that  actually gets invoked (with ActivityManager.getCurrentUser() as parameter).
You could try to obtain an instance of it by calling NotificationManager.getService via reflection (see hidden getService() method in NotificationManager http://androidxref.com/4.2.2_r1/xref/frameworks/base/core/java/android/app/NotificationManager.java) and then try to somehow invoke cancelAll on the returned service (e.g. via reflection again).
UPDATE
I found an easier way to clear notifications via the statusbar service. The following code should work:
IBinder b = (IBinder) Class.forName("android.os.ServiceManager").getMethod("getService", new Class[] {
    String.class
}).invoke(null, new Object[] {
    "statusbar"
});

Object iFace = Class.forName("com.android.internal.statusbar.IStatusBarService$Stub").getDeclaredMethod("asInterface", new Class[] {
    IBinder.class
}).invoke(null, new Object[] {
    b
});

iFace.getClass().getMethod("onClearAllNotifications", new Class[0]).invoke(iFace, (Object[]) null);

This will throw a SecurityException if you are not running as root but successfully clears notifications if you have root permissions

A: You can clear all the notifications by calling
service call notification 1

in the shell with root permission


text:
Q: How to get users from SharePoint via CSOM? How can I efficiently grab users (with their properties) from a SharePoint web using CSOM?
The code below results in multiple calls to the server (one for each user). It's ridiculously inefficient.
Also, is it possible to perform a Filter on the server?
    public static List<Contact> GetUsers(Uri requestUri, string Filter = "")
    {
        ClientContext context;
        var users = new List<Contact>();
        if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, null))
        {
            using (context)
            {
                var web = context.Web;
                var peopleManager = new PeopleManager(context);

                context.Load(web, w => w.Title, w => w.Description, w => w.SiteUsers);
                var siteUsers = web.SiteUsers;
                context.ExecuteQuery();

                foreach (var user in siteUsers)
                    if (user.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User)
                        if (user.Title.ToLower().Contains(Filter.ToLower()) && !users.Any(x => x.FullName == user.Title))
                        {
                            var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
                            context.Load(userProfile);
                            context.ExecuteQuery();

                            var contact = new Contact() { FullName = user.Title, EmailAddress = user.Email };
                            if (userProfile.IsPropertyAvailable("Title"))
                                contact.Position = userProfile.Title;
                            if (userProfile.IsPropertyAvailable("UserProfileProperties") && userProfile.UserProfileProperties.ContainsKey("WorkPhone"))
                                contact.PhoneNumber = userProfile.UserProfileProperties["WorkPhone"];
                            users.Add(contact);
                        }
            }
        }
        return users;
    }

A: When you are in a specific context of a website you can do followings:
using (var ctx = new ClientContext("http://theWebsite"))
{
    var list = ctx.Web.SiteUserInfoList;
    var users = list.GetItems(new CamlQuery());
    ctx.Load(users);
    ctx.ExecuteQuery();

    // do what you want with the users
}

A: Major improvements
Since SharePoint CSOM supports Request Batching all the user profiles could be retrieved using a single request, for example instead of:
foreach (var user in siteUsers)
{
   var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
   context.Load(userProfile);
   context.ExecuteQuery();
}

user profiles could be retrieved as:
var userProfilesResult = new List<PersonProperties>(); //for storing user profiles
foreach (var user in siteUsers)
{
   var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
   context.Load(userProfile);
   userProfilesResult.Add(userProfile);
}
context.ExecuteQuery();  //submit a single request

Minor improvements
1)Since SharePoint CSOM supports CAML queries, the filtering operation could be performed on the server side, for example:
var siteUsers = from user in web.SiteUsers
                    where user.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User
                    select user;
var usersResult = context.LoadQuery(siteUsers);
context.ExecuteQuery();

2)You could also use the following checking to determine whether user profile exist for a specified user:
var hasUserProfile = userProfile.ServerObjectIsNull != null && userProfile.ServerObjectIsNull.Value != true;

Modified example
public static List<Contact> GetUsers(Uri requestUri, ICredentials credentials, string filter = "")
{
        ClientContext context;
        var users = new List<Contact>();
        if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, credentials))
        {
            var userProfilesResult = new List<PersonProperties>();
            using (context)
            {
                var web = context.Web;
                var peopleManager = new PeopleManager(context);

                var siteUsers = from user in web.SiteUsers
                    where user.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User
                    select user;
                var usersResult = context.LoadQuery(siteUsers);
                context.ExecuteQuery();

                foreach (var user in usersResult)
                {
                    if (user.Title.ToLower().Contains(filter.ToLower()) && !users.Any(x => x.FullName == user.Title))
                    {
                        var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
                        context.Load(userProfile);
                        userProfilesResult.Add(userProfile);
                    }
                }
                context.ExecuteQuery();

                var result = from userProfile in userProfilesResult
                             where userProfile.ServerObjectIsNull != null && userProfile.ServerObjectIsNull.Value != true
                        select new Contact() {
                            FullName = userProfile.Title,
                            EmailAddress = userProfile.Email,
                            Position = userProfile.IsPropertyAvailable("Title") ? userProfile.Title : string.Empty,
                            PhoneNumber = userProfile.IsPropertyAvailable("UserProfileProperties") && userProfile.UserProfileProperties.ContainsKey("WorkPhone") ? userProfile.UserProfileProperties["WorkPhone"] : string.Empty
                        };
                users = result.ToList();
            }
        }
        return users;
 }


text:
Q: Dynamic Lambda condition on nested array I want to perform a Dynamic Lambda in a collection with an array of strings[] on it:
public class ClassStudentsViewModel
{
    public string[] Disciplines { get; set; }
    public TeacherName { get; set; }
}

This is what I'm trying:

The source is a collection of ClassStudentsViewModel and the values is an array of strings with one string. When executed, it throws me this exception:

No property or field 'y' exists in type 'String'

After some searching, I have found this question which is almost the same problem and the OP ended changing the source code of Dynamic.cs, that isn't a nice option for me. I wonder what I'm trying isn't supported or might be a bug. The problem is that the above mantioned question was asked almost 4 years ago.
The following snippet works nice:
classStudents.AsQueryable().Where(x => x.Disciplines.Any(y => y == "Turma 2")).ToList();

How can I get rid of that error?
UPDATE:
A little context of what I'm trying: My controller receives a viewModel with a collection of filters sent by the 3rd party grid, which contains basically a value and a operator, like eq, gt etc... A method loops all those filters and transforms on lambda operators, like eq to == or contains to .Contains(). In a simple string property like TeacherName(updated viewModel above), the dynamic filters works, e.g. if the predicate in the screenshot is: "TeacherName.Contains(@0)" it works well.
UPDATE 2:
This code generates the predicate:
public static string ToLambdaOperator(string field, string oper, int index, string sufix = null)
{
    var result = String.Empty;

    switch (oper)
    {
        case "eq":
        case "neq":
        case "gte":
        case "gt":
        case "lte":
        case "lt":
            result = string.Format(field + ToLinqOperator(oper) + "@" + index);
            break;

        case "startswith":
            result = field + ".StartsWith(" + "@" + index + ")";
            break;

        case "endswith":
            result = field + ".EndsWith(" + "@" + index + ")";
            break;

        case "contains":
            result = field + ".Contains(" + "@" + index + ")";
            break;

        case "doesnotcontain":
            result = "!" + field + ".Contains(" + "@" + index + ") || " + field + ".Equals(String.Empty)";
            break;
    }

    if (!String.IsNullOrEmpty(sufix))
    {
        result += sufix;
    }

    return result;
}

// Use example
var operator = "eq";
var paramCounter = -1;
var predicate = ToLambdaOperator("Disciplines.Any(y => y", operator, ++paramCounter, ")");

The predicate above will result: Disciplines.Any(y => y == @0). With the operator contains will result in this: Disciplines.Any(y => y.Contains(@0)).

A: I think what you are trying to do is to generate an expression tree based on the arguments provided. Here are some examples about how to do that.
https://gist.github.com/afreeland/6733381
How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic)


text:
Q: bash date invalid date (-d 'feb 29 -3years') I was working with the date command today and discovered some behaviour I cannot explain (I skimmed through: ~$ info '(coreutils) date invocation' but didn't find anything) and hope that someone here might help me to understand why this is happening.
~$ date -u +%F -d "feb 28 -3years"
>> 2012-02-28
~$ date -u +%F -d "feb 29 2012"
>> 2012-02-29
~$ date -u +%F -d "feb 29 -3years"
>> date: invalid date 'feb 29 -3years'
~$ date -u +%F -d 'feb 29 3 years ago'
>> date: invalid date 'feb 29 3 years ago'

This is happening on all leap years/leap days (...2008/2012/2016...) and I just can't figure out why.
I' am running above commands on my Ubuntu Gnome Edition (15.04) and on my Server which runs Debian/Jessie.

A: It's kinda hacky but a good way of getting the last day of the month is to go to the first day of the next month, then back by one day:
$ date -u +%F -d "mar 1 -3years -1day"
2012-02-29

I don't claim to know how the date command is implemented but it stands to reason that feb 29 is the first part of the string that is interpreted, before making the subtractions. So the safest thing to do is to use a date that is always valid, then make a series of subtractions.


text:
Q: Jackson deserialization for php-like array concatenated with another object Here is a bit weird json structure from external service:
{
   "entity_list_self_mapped_by_ids": {
     "0": { "ent_prop1": "ent0_prop_value1", "ent_prop2": "ent0_prop_value2" },
     "1": { "ent_prop1": "ent1_prop_value1", "ent_prop2": "ent1_prop_value2" },
     "2": { "ent_prop1": "ent2_prop_value1", "ent_prop2": "ent2_prop_value2" },
     "unexpected_other_property_here": {
       "foo": "bar"
     }
   },
   "one_more_not_so_important_property": { "something": "here" }
}

Anyway I wonder if there is any smart compact way to deserialize it to something like this
class ResponseContainer {
  @JsonDeserialize(converter=MapToListConverter.class)
  List<Entities> entities;
  OtherProperty unexpectedOtherProperty;
  OneMoreProperty oneMoreProperty;
}

MapToListConverter is quite obvious to me - just convert map values to list. Hovewer I am not sure if there is simple way to extract that 'unexpected_other_property' so it can go not to the map but to other dedicated property of ResponseContainer.


text:
Q: How to add more than one action to same controller in zend2 I need to add 'addAction' and 'deleteAction' for existing controller.here I used zendframework-ZendSkeletonApplication-zf-release-2.0.3, I add these 2 action in IndexController and also I created 2 pages for each action within the index folder. but how it add to the module.config.php this is the code my module.config.php file
<?php

return array(
    'router' => array(
        'routes' => array(
            'home' => array(
                'type' => 'Zend\Mvc\Router\Http\Literal',
                'options' => array(
                    'route'    => '/application',
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action'     => 'index',
                    ),
                ),
            ),
            'application' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/application',
                    'defaults' => array(
                        '__NAMESPACE__' => 'Application\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                    ),
                ),

                'may_terminate' => true,
                'child_routes' => array(
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
        ),
    ),
    'translator' => array(
        'locale' => 'en_US',
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
            ),
        ),
    ),
    'controllers' => array(
        'invokables' => array(
            'Application\Controller\Index' => 'Application\Controller\IndexController'
        ),
    ),
    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
);

please help me.

A: This is a sample Route configuration i use in my project, where everything is based off of the root path /
'router' => array(
    'routes' => array(
        'kz' => array(
            'type'    => 'literal',
            'options' => array(
                'route'    => '/',
                'defaults' => array(
                    'controller' => 'Kennzahlen\Controller\Index',
                    'action'     => 'index',
                ),
            ),
            'may_terminate' => true,
            'child_routes' => array(
                'add' => array(
                    'type' => 'literal',
                    'options' => array(
                        'route' => 'add',
                        'defaults' => array(
                            'action' => 'add'
                        )
                    )
                ),
                'edit' => array(
                    'type' => 'literal',
                    'options' => array(
                        'route' => 'edit',
                        'defaults' => array(
                            'action' => 'edit'
                        )
                    )
                )
            )
        ),
    ),
),

The first route named kz has the basePath /
After that you have two separate child-routes called add  and edit who append the base-path with either add or edit, so the full route for them become /add and /edit
Please consider checking the online Documentation for further clarification on your questions regarding routing, as that really is a great place to start.
Alternatively you may also want to check out DASPRiDs Router Presentation from ZendCon


text:
Q: How Do You Filter and Sort Data in a CollectionView I have a CollectionView on a page that is displaying data from a List<> of items.  I do sorting and filtering in a code behind on the page by changing the List with LINQ, and then setting the BindingContext of the view, like this:
MyView.BindingContext = FilteredData;

On IOS this works fine, every time, no problem.  On Android, I can change the data a few times (it varies - normally three to five) and then the page doesn't display any data.  In the debugger I can check and still see the ItemsSource has all of the items, but nothing is displayed.  I then "switch" to my other view on the page, which is done by hiding one DataGrid row and showing another, then "switching" back.  The data still isn't displayed, but after I do that I can run the code again that does the sorting and filtering and it starts working again - the data is displayed on the page.  Not only that, but after I do that, it works every time from that point forward on Android.
I've spent hours trying every thing I can think of to try and find an event or property or anything that would indicate when this problem occurs so I can try and find a work around for it.  I'm at a complete loss; wondering if there are suggestions for how to capture and/or fix this problem.

A: I did find a combination that worked to resolve this issue.  I changed the page so that the CollectionView at issue is in the Grid row that has a non-zero (i.e. visible) height when the ContentPage loads.  After doing that, the code works as expected.  Previously, it was in a Grid.Row whose height was set to an absolute 0 when the page loaded, and then the height was changed to a non-zero value when a button was clicked.
FWIW, this is similar to other issues I've seen with MAUI on Android, where the visibility of certain controls as well as the order in which you modify them can interfere with rendering data binding results.

A: I solved sorting using a SortedList and made the list items inherit from IComparable, but I don't love the solution because a SortedList is not an ObservableCollection, and because implementing IComparable can be tricky and leaky.


text:
Q: Best way to modify a list in a loop C# I am curious as to what is the best way to modify a list in c#. As far as I'm aware, the foreach loop is used to iterate over the list to get the desired information and if you need to modify the list then use a for loop. I have found 3 ways to modify a list but they all seem to pretty much remove the items as intended.
So my questions are:
1) What is the difference between these 3 ways shown below?
2) is there a specific time where one of them should be used over the other way?
3) Is there any other better ways to modify a list?
4) When removing you are meant to reverse the list, is this simply to not mess up the order and cause unpredictable side effects?
Reverse for loop:
List<int> integerListForReverse = new List<int>();
for(int i = 0; i <10; i ++)
{
    integerListForReverse.Add(i);
}

for (int i = integerListForReverse.Count - 1; i >= 0; i--)
{
    int ints = i;
    if(ints % 2 == 0)
    {
        integerListForReverse.Remove(ints);
        Console.WriteLine(ints + " reverse for loop");
    }
}

Create a copy of the list
List<int> integerListForeachCopy = new List<int>();
for (int i = 0; i < 10; i++)
{
    integerListForeachCopy.Add(i);
}

foreach (int ints in integerListForeachCopy.ToList())
{
    if (ints % 2 == 0)
    {
        integerListForeachCopy.Remove(ints);
        Console.WriteLine(ints + "copy of the list ");
    }
}

Reverse foreach loop
List<int> integerListReverseForeach = new List<int>();
for (int i = 0; i < 10; i++)
{
    integerListReverseForeach.Add(i);
}
foreach (int ints in integerListReverseForeach.Reverse<int>())
{
    if (ints % 2 == 0)
    {
        integerListReverseForeach.Remove(ints);
        Console.WriteLine(ints + "reverse foreach");
    }
}

Just a few things that were confusing me and would like cleared up.
Thank you in advance.

A: Removing the items one by one seems like the least efficient way ( closer to quadratic O(n²) complexity ), but making a new list is closer to linear O(n) complexity:
var L = Enumerable.Range(0, 10).ToList();

L = L.Where(i => (i & 1) > 0).ToList();
//L = Enumerable.Range(0, L.Count / 2).Select(i => L[(i << 1) + 1]).ToList();
//L = Enumerable.Range(0, L.Count).Where(i => (i & 1) > 0).Select(i => L[i]).ToList();
//L.RemoveAll(i => (i & 1) == 0); // { 1, 3, 5, 7, 9 } // O(n)

Removing all items at once with .RemoveAll and .RemoveRange is O(n)
The answer here seems like the most efficient as it just moves the items without removing them, and then removes the extra items at the end: Removing alternate elements in a List<T>

A: The best way for removing items from a List<T> based on condition is using the RemoveAll method which is internally optimized for such operation:
var list = new List<int>();
for(int i = 0; i <10; i ++)
    list.Add(i);

list.RemoveAll(value => (value % 2) == 0);

A: Do it with LINQ, which will just go once through the list being very efficient.
var result = list.Where(x => (x % 2) != 0);

if you need to operate further on the given list, do (even tho it creates a new List with references):
list = list.Where(x => (x % 2) != 0).ToList();

Greetings
Konstantin


text:
Q: How to show that bound? How to show that $\prod\limits_{i=1}^k \dfrac{k+i}{4i}$ is less than or equal to $1/2$ for all
$k \ge 1$ Integer.
I coulden't understand the answer in How to prove the bound on the probability?

A: Note $u_k=\prod\limits_{i=1}^k \dfrac{k+i}{4i}$. You have $\frac{u_{k+1}}{u_k}= \frac{2k+1}{2k+2}<1$. So $u_k$ is decreasing. The result then follows from $u_1=\frac{1}{2}$.

A: Use a simple mathematical induction.
${\displaystyle \prod_{i=1}^{k} \frac{k+i}{4i}}$  , $k\geq 1$
Basis: $k=1$
$${\displaystyle \prod_{i=1}^{1} \frac{1+i}{4i}}=\frac{2}{4} \leq \frac{1}{2}$$
Now show that if it holds for any fixed k it also holds for k+1.
Therefore assume $${\displaystyle \prod_{i=1}^{k} \frac{k+i}{4i}} \leq \frac{1}{2}$$
Inductive step: $k \rightarrow k+1$
$$
\begin{gather*}
{\displaystyle \prod_{i=1}^{k+1} \frac{k+1+i}{4i}} \\
= {\displaystyle \prod_{i=1}^{k} \frac{k+i}{4i}} \times \frac{k+1+k}{4k}
\leq \frac{1}{2} \times \frac{k+1+k}{4k} \\
= \frac{1}{2} \times \frac{2+1}{4} \\
= \frac{1}{2} \times \frac{3}{4} \leq \frac{1}{2}
\end{gather*}
$$
q.e.d.


text:
Q: error pagination in codeigniter 3 My pagination is work fine, but it's show error when wanting to raise data over existing data
For example, show/index/5 or show/index/10 works fine and the data is right. But if I go to show/index/120 it shows error
   Invalid argument supplied for foreach()

Here's my controller
   public function index(){
       $config['base_url']=base_url()."book/show/index";
       $config['total_rows']= $this->book_model->get_book();
       $config['per_page']=5;
       $config['num_links'] = 5;
       $config['uri_segment']=4;
       $config['full_tag_open'] = "
";
       $config['full_tag_close'] ="
";
       $config['num_tag_open'] = '
';
       $config['num_tag_close'] = '
';
       $config['cur_tag_open'] = "

";

       $config['first_link']='< Pertama ';
       $config['last_link']='Terakhir > ';
       $config['next_link']='> ';
       $config['prev_link']='< ';
       $this->pagination->initialize($config);

       $this->load->model('admin/book_model');
       $data['book']=$this->book_model->count_book($config);
       $this->load->view('admin/book', $data);
  }

A: In your view you have to apply a check in your code
if(!empty($result)&& isset($result)){
     foreach($results as $data){
                    ----your code--
                     }


text:
Q: Best Practice to report user location continuously I'm designing an application where application in server side need to be continuously aware of user location. I'm thinking to create an Android service that run in the background and continuously query user location and send the result to an application in the backend server. However, I wonder if this is the best approach in terms of battery saving.  For example, in iOS, there is something called "Significant-Change" to serve such purpose, does Android have similar thing.

A: I suggest to create a background Service which just uses the NETWORK_PROVIDER and the PASSIVE_PROVIDER. You can use the minTime and the minDistance parameter to avoid draining the battery. Documentation
And Reto wrote a great post about obtaining users location
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Regarding your comment you have to start your service sticky:
Documentation


text:
Q: My laptop display/screen doesn't work, is it the hardware? Problem: The screen of my laptop doesn't work, not even a "black" back-light. The laptop itself works, the HDD light goes on, it makes sounds etc. etc.
What I tried:
Plugged in an external Packard Bell screen via the VGA, before buying an entirely new screen. This doesn't work, while the external screen does work on a different laptop.
This makes me think it could be:

*

*the GPU

*some sort of cable issue

*another piece of video-card related hardware I'm unaware of

Laptop: HP Pavilion dv2 1160ed
As far as I could discern (but I am not even sure about that) the video chip or gpu used is ATI Mobility Radeon HD 3410, more info on where it is used here:   https://www.techpowerup.com/gpu-specs/mobility-radeon-hd-3410.c1216 .  I don't know if it is soldered to the motherboard, or if it's replaceable.
Question: How to fix this problem, as in get this screen working again? Is it the hardware? If not, what software problem could it be?
Follow up: ** The above chip is out of stock, what can I use as a replacement?**
Also: How can I test your solution?
Any solution will be hard to try, because I can't of course, SEE, anything.
P.S.

*

*If this question is asked in the wrong way, please tell me how.

*This is a REPAIR question, so I'd appreciate it if there's no "buy a new laptop!" remarks.


text:
Q: swGenericSaveError when using SolidWorks API to save assembly as part (C++) I am trying to use the C++ API implementation to save an assembly (.SLDASM) as a part document (.SLDPRT), but I keep getting swGenericSaveError.
Using the following code:
void guardarModelo()
{
  //Guardar como part
  wchar_t exportedfilename[MAX_PATH], assemblyname[MAX_PATH], *pext, *pname;
  long error = 0, warning = 0;
  VARIANT_BOOL result = 0;
  CComPtr<IModelDocExtension> swExtension; //Extension (formato de fichero)
  swUserPreferenceIntegerValue_e part = swSaveAssemblyAsPartOptions; //Opciones de part

  //Arreglamos la extension y la ubicacion del fichero
  wcscpy(exportedfilename, filename);
  pext = wcsrchr(exportedfilename, L'\\') + 1;
  wcscpy(pext, L"-modelo\\");
  CreateDirectory(exportedfilename, NULL);

  wcscpy(assemblyname, filename);
  pname = wcsrchr(assemblyname, L'\\') + 1;
  pext = wcsrchr(assemblyname, L'.');
  wcsncpy(pext, L".SLDPRT\0", 8);
  wcscat(exportedfilename, pname);

  CComBSTR sFileName(exportedfilename);

  swModel->get_Extension(&swExtension);

  //swApp->SetUserPreferenceIntegerValue(part, swSaveAsmAsPart_AllComponents, &result);
  swExtension->SetUserPreferenceInteger(swSaveAssemblyAsPartOptions, swDetailingNoOptionSpecified, swSaveAsmAsPart_AllComponents, &result);

  swExtension->SaveAs(sFileName, swSaveAsCurrentVersion, swSaveAsOptions_Silent, NULL, &error, &warning, &result);

  if (error == 0)
  wcout << "Modelo completo guardado como part." << endl;
  else
  wcout << "ERROR " << error << " guardando modelo completo como part." << endl;

}

The code works fine when exporting the asssembly to a Parasolid binary (.x_b):
void exportarModelo()
{
  //Exportar a parasolid
  wchar_t exportedfilename[MAX_PATH], assemblyname[MAX_PATH], *pext, *pname;
  long error = 0, warning = 0;
  VARIANT_BOOL result = 0;
  CComPtr<IModelDocExtension> swExtension; //Extension (formato de fichero)
  swUserPreferenceIntegerValue_e parasolid = swParasolidOutputVersion; //Opciones de Parasolid

  //Arreglamos la extension y la ubicacion del fichero
  wcscpy(exportedfilename, filename);
  pext = wcsrchr(exportedfilename, L'\\') + 1;
  wcscpy(pext, L"-modelo\\");
  CreateDirectory(exportedfilename, NULL);

  wcscpy(assemblyname, filename);
  pname = wcsrchr(assemblyname, L'\\') + 1;
  pext = wcsrchr(assemblyname, L'.');
  wcsncpy(pext, L".x_b\0", 5);
  wcscat(exportedfilename, pname);

  CComBSTR sFileName(exportedfilename);

  swModel->get_Extension(&swExtension);

  //Elegir version de Parasolid y guardar
  swApp->SetUserPreferenceIntegerValue(parasolid, swParasolidOutputVersion_150, &result);

  swExtension->SaveAs(sFileName, swSaveAsCurrentVersion, swSaveAsOptions_Silent, NULL, &error, &warning, &result);

  if (error == 0)
  wcout << "Modelo completo exportado a Parasolid." << endl;
  else
  wcout << "ERROR " << error << " exportando modelo completo a Parasolid." << endl;

}

Anyone has any idea why this isn't working? Is there an alternative way to save all components of an assembly in a single part document?

A: Found the solution. The key is to use the ActivateDoc3 method to activate the loaded assembly before saving the document. This takes care of the swGenericSaveError and works great.


text:
Q: TTS is not reading the text of proper fragment I guess I'll fail to explain the issue because it is WEIRD.
I need an app similar to online tutorials,the basic functionality is to switch among the pages(fragments in my case) and the content should read out.
So, I've followed Mr.Tamada " - The life saviour" tutorials The TTS and Fragments and I've merged them both.
Motto is to read the data in fragments.
Code:
public class TopRatedFragment extends Fragment implements TextToSpeech.OnInitListener
{
    private static TextToSpeech tts;
    TextView tv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
        tv = (TextView) rootView.findViewById(R.id.tv);
        tts = new TextToSpeech(getActivity(), TopRatedFragment.this);
        speakOut();
        return rootView;
    }

    @Override
    public void onInit(int status)
    {
        if (status == TextToSpeech.SUCCESS)
        {
            int result = tts.setLanguage(Locale.US);
            tts.setSpeechRate(0);
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "Language is not supported");
            } else {
                speakOut();
            }
        } else {
            Log.e("TTS", "Initilization Failed");
        }
    }

    @Override
    public void onDestroy()
    {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }

    private void speakOut()
    {
        tts.speak(tv.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
        Log.e("root ",  tv.getText().toString());
    }
}

The text in textview is reading out. But the text of 1st fragment is read in 2nd fragment that too only when I swipe backward.
fragment 3 --> fragment 2 (here fragment 1 text is read).
I really do not understand what is happening.
And when I open the app from recently opened apps list then it is reading its own text.
Kindly help if possible....Thank you..

A: Well the problem is that at start- Fragment1 is loaded along with Fragment2. So u can hear contents from Fragment1 and Fragment2 resp.
Now when u navigate to Fragment2 [already loaded so you cannot hear chapter2] then Fragment3 is loaded so you can hear Chapter3.
When you navigate to Fragment3, then Fragment1 is removed.
Now if you navigate from Fragment3 to Fragment2 then Fragment1 is loaded. Hence u can hear chapter1.
Solution:- Simply check if the Fragment is visible and then perform the rest of action. In your case TTS thing.

*

*Extend FragmentPagerAdapter.

*override setUserVisibleHint().
@Override
public void setUserVisibleHint(boolean isVisibleToUser)
{
    super.setUserVisibleHint(isVisibleToUser);
    Log.d(TAG, "setUserVisibleHint: " + isVisibleToUser);
}

Now u can perform ur action inside setUserVisibleHint() if(isVisibleToUser){} instead of onCreateView() okay.


text:
Q: VB.net - Target object using string (Object is under tab then panel then splitter) In php and javascript I can do something like this
If ($a == 1){
  $set_num = 1
} Else {
  $set_num = 2
}

textbox_ . $set_num = "Some text here"
checkbox_ . $set_num = "Some text here"
radio_ . $set_num = "Some text here"

How can I do this in vb.net?

In my design page I have many panel, splitter, textbox, checkbox and other things and please take note that this design is under the panel tab (index 2). What I want is to create a short code (Short as possible) so when the user types in a certain textbox I will know what schedule to activate so every time the user clicks the apply button the system will just send the set that has a last text_change.
This is my code in vb.net and I wanted to use me.controls to call an object in a string, but it's not working
     Dim lab As Label

     For i As Integer = 1 To 10
        lab = Me.Controls("tb_hour_" & i)
        lab.Text = "Test" & i
     Next

By the way, the name of my textbox, checkbox and radio button is something like this
tb_hour_1, tb_minute_1, cb_monday_1, etc. _1 stands for schedule 1 so for the schedule 2 it will be like this tb_hour_2, tb_minute_2, cb_monday_2, etc.
Actually my code is working, the problem comes in when I put the textboxes, checkboxes, etc inside the panel and splitter. The purpose of panel and splitter is just to have a design (my aim is the border).
Currently this is the code that I used to achieved my goal, but my code is so hard to maintain because I nested a condition. That's why I want to apply while loop and target all of the objects in a string
If Lbl_Temp_1.Text = "0" Then
        frmTerminal.Lbl_Settings_Cmd.Text = "CSR01^"
        frmTerminal.cmdSend_Click(sender, e)
    Else
        If Lbl_Temp_2.Text = "0" Then
            frmTerminal.Lbl_Settings_Cmd.Text = "CSR02^"
            frmTerminal.cmdSend_Click(sender, e)
        Else
            If Lbl_Temp_3.Text = "0" Then
                frmTerminal.Lbl_Settings_Cmd.Text = "CSR03^"
                frmTerminal.cmdSend_Click(sender, e)
            Else
                If Lbl_Temp_4.Text = "0" Then
                    frmTerminal.Lbl_Settings_Cmd.Text = "CSR04^"
                    frmTerminal.cmdSend_Click(sender, e)
                Else
                    If Lbl_Temp_5.Text = "0" Then
                        frmTerminal.Lbl_Settings_Cmd.Text = "CSR05^"
                        frmTerminal.cmdSend_Click(sender, e)
                    Else
                        If Lbl_Temp_6.Text = "0" Then
                            frmTerminal.Lbl_Settings_Cmd.Text = "CSR06^"
                            frmTerminal.cmdSend_Click(sender, e)
                        Else
                            If Lbl_Temp_7.Text = "0" Then
                                frmTerminal.Lbl_Settings_Cmd.Text = "CSR07^"
                                frmTerminal.cmdSend_Click(sender, e)
                            Else
                                If Lbl_Temp_8.Text = "0" Then
                                    frmTerminal.Lbl_Settings_Cmd.Text = "CSR08^"
                                    frmTerminal.cmdSend_Click(sender, e)
                                Else
                                    If Lbl_Temp_9.Text = "0" Then
                                        frmTerminal.Lbl_Settings_Cmd.Text = "CSR09^"
                                        frmTerminal.cmdSend_Click(sender, e)
                                    Else
                                        If Lbl_Temp_10.Text = "0" Then
                                            frmTerminal.Lbl_Settings_Cmd.Text = "CSR10^"
                                            frmTerminal.cmdSend_Click(sender, e)
                                        Else
                                            Tmr_Schedule_Get.Enabled = False
                                            frmTerminal.Tmr_Write_Check.Enabled = True
                                            Btn_Schedule.Enabled = False
                                            Me.Settings_Tab.TabPages(1).Enabled = True

                                            If Cb_Set_1.Checked = True Or Cb_Set_2.Checked = True Or Cb_Set_3.Checked = True Or Cb_Set_4.Checked = True Or Cb_Set_5.Checked = True Or Cb_Set_6.Checked = True Or Cb_Set_7.Checked = True Or Cb_Set_8.Checked = True Or Cb_Set_9.Checked = True Or Cb_Set_10.Checked = True Then
                                                Btn_Schedule.Enabled = True
                                            End If

                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
    End If

A: When you doubleclick on the checkboxes etc. the IDE automatically creates a handler for that where you can put the code you want to have. You need to have the different arguments in your handles-sub to make it work.
 Private Sub CB_reloadText_CheckedChanged(sender As Object, e As EventArgs) Handles CB_reloadText.CheckedChanged
    Dim enabled As Boolean

    If CB_reloadText.Enabled = True Then
        enabled = True
    Else
        enabled = False
    End If

End Sub

A: It seems that right now it isn't possible to target an object that is under the panel, and that panel is also under the panel.
I managed to fix this issue by re-creating my design layout, as much as possible I limit the use of panels to one object is under 1 panel only, by doing it like that I can easily target the object using this code.
For Each Ctrl_Panel_Set As Control In Schedule_Tab
        If TypeOf Ctrl_Panel_Set Is Panel And Ctrl_Panel_Set.Name.StartsWith("Panel_Set_") Then
            For Each Ctrl_Lbl_Temp In Ctrl_Panel_Set.Controls
                If TypeOf Ctrl_Lbl_Temp Is Label Then
                    If Ctrl_Lbl_Temp.Name.StartsWith("Lbl_Temp_") Then
                        If Ctrl_Lbl_Temp.Text = "0" Then
                            Panel_Set_Num = CType(Ctrl_Panel_Set, Panel).Name
                            Set_Num = "CSR" & Panel_Set_Num.Substring(Panel_Set_Num.Length - 2) & "^"
                            Return Set_Num
                        End If
                    End If
                End If
            Next
        End If
    Next Ctrl_Panel_Set


text:
Q: Is pointer holds a base address or it holds whole limits? We have
int i;

which have 4 bytes lets have address from 1000 to 1004.
if we declared a pointer
int* p;
p = &i;

now is the pointer holds only 1000 or from 1000 to 1004?
The pointer holds the addresses then why we need to declare a datatype to a variable?
when we declare a datatype to pointer, can a pointer can be typecasted?
why can't we use void* p which can hold any datatype?

A: The pointer holds only the memory address 1000. The fact that the memory of a (32-bit) int extends to 1003 is implied by the declaration of the pointer as being of int* type. You can use a void*, but then you lose information about the underlying type and its size. Sometimes recasting pointers or overlapping them, can be used to perform all sorts of efficient tricks, but those tricks are out of vogue nowadays


text:
Q: How to make dragged objects always appear in front of obstructed objects in Unity 3d I'm having hard time figuring out how to make a dragged object always appear in front of other objects. To goal is to be able to place the sphere (or any other object) on top of the other blocks.
I have the following script to illustrate my problem.
What obvious thing am I missing here ? Should I be continuously checking what's behind and move the object in front ? I think I'm lost here ... if anyone could point me on the right track.
using UnityEngine;

public class MouseDrag : MonoBehaviour
{
    private Vector3 mOffset;
    private float mZCoord;
    private Transform tr;
    private Camera mainCamera;
    [SerializeField] private Vector3 gridSize = new Vector3(4f, 3f, 4f);

    private void Awake()
    {
        if (mainCamera == null) mainCamera = Camera.main;
        tr = transform;
    }

    private void OnMouseDown()
    {
        var position = tr.position;
        mZCoord = mainCamera.WorldToScreenPoint(position).z;
        mOffset = position - GetMouseAsWorldPoint();
    }

    private Vector3 GetMouseAsWorldPoint()
    {
        var mousePoint = Input.mousePosition;
        mousePoint.z = mZCoord;
        return mainCamera.ScreenToWorldPoint(mousePoint);
    }

    private void OnMouseDrag()
    {
        transform.position = GetMouseAsWorldPoint() + mOffset;
    }

    private void OnMouseUp()
    {
        var pos = tr.position;
        transform.position = new Vector3(
            Mathf.RoundToInt(pos.x) / gridSize.x * gridSize.x,
            Mathf.RoundToInt(pos.y) / gridSize.y * gridSize.y,
            Mathf.RoundToInt(pos.z) / gridSize.z * gridSize.z);
    }
}


text:
Q: How to filter column and plot bunch of files I have 30 files that each of which has 6 columns. I want to plot 2 first columns as my X and Y but considering the points that have zero value(Almost zero because my value is 0.0003) in the 6th column. The columns are float and I need to have comparison on float numbers. The code is below :
filenames = [f for f in sorted(os.listdir('.')) if f.startswith('config')]
files = {}
for filename in filenames:
    with open(filename, "r") as file:
        if filename in files:
            continue
        #files[filename] = file.read()
        lines = file.readlines()
        near = [float(line.split()[5]) for line in lines]
        x = [float(line.split()[0]) for line in lines]
        y = [float(line.split()[1]) for line in lines]
plt.plot(x[near<=0.0], y[near<=0.0], lw=1.75)
plt.plot(x,y)
plt.axis('equal')
plt.show()

Also I have used a for loop and using numpy to read and plot files but the problem is still alive. the code which I mentioned(using numpy is below):
l = [f for f in sorted(os.listdir('.')) if f.startswith('config')]

maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in l])
l = ['configuration_%d.out' % i for i in range(maxnum)]
for i, d in enumerate(l[::100]):
    a = np.loadtxt(d).T
    num = os.path.splitext(d)[0]
    plt.plot(a[0], a[1], c=cmap.to_rgba(i+1),label=num[-3:], lw=0.75)
    idx = np.argwhere(a[0] == 0)
    #plt.colorbar(cmap, ticks = c)
    #print(idx)
#plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1))

plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title("Longterm simulation")
plt.plot(a[0],a[1],c='b')
plt.plot(a[0][a[5]<=0.000], a[1][a[5]<=0.000], c='r', lw=2)

A: You can ① get a Boolean array checking the values of a column and ② use that array to index the columns that you want to plot.
E.g.,
In [25]: import matplotlib.pyplot as plt
    ...: import numpy as np
    ...:
    ...: # prepare some data for the following example
    ...: N = 10000
    ...: a = np.zeros((N,3))
    ...: a[:,0] = np.linspace(0, 10, N)
    ...: a[:,1] = np.sin(a[:,0])
    ...: a[:,2] = np.random.random(N)
    ...:
    ...: # construct a boolean array by testing the values of the last column
    ...: indices = a[:,-1]<0.012
    ...: # plot (as points) the single values where a[n,3]<0.012
    ...: plt.plot(a[indices,0], a[indices,1], '.')
    ...: # and, as a visual reference, the complete first columns...
    ...: plt.plot(a[:,0], a[:,1], alpha=0.3)
    ...: plt.show()

A: Use pandas library for this:
df = pd.read_csv("file_name") # If Not CSV files, appropriate read fn
df_near = df[df[5]<=0.0]
plt.plot(df[0],df[1])

Hope this helps :)


text:
Q: SQL Server Backup Jobs Failing. The error seems to be related to MaximumErrorCount, but I am not sure how to fix value or if changing it will resolve? My backup jobs are failing with following error when check it's history. I have already checked this link regarding maximumerrorcount value: SQL Server 2008 - Change the MaximumErrorCount or fix the errors.
At this point I'm not sure what to do if maximumerrorcount is only masking the actual problem.
Log job history (DB_TaxExemption_BKP.Subplan_1):

Step ID 1 Server INHOUSE-DB Job Name DB_TaxExemption_BKP.Subplan_1
Step Name Subplan_1 Duration 00:00:00 Sql Severity 0 Sql Message ID 0
Operator Emailed Operator Net sent Operator Paged Retries Attempted 0
Message Executed as user: NT AUTHORITY\LOCAL SERVICE. Microsoft (R)
SQL Server Execute Package Utility Version 14.0.1000.169 for 64-bit
Copyright (C) 2017 Microsoft. All rights reserved. Started: 10:12:00
PM Error: 2022-03-30 22:12:00.47 Code: 0xC00291EC Source:
{4D6AAF94-D3FC-4873-9F66-E35E323A6BEE} Execute SQL Task Description:
Failed to acquire connection "Local server connection". Connection may
not be configured correctly or you may not have the right permissions
on this connection. End Error Warning: 2022-03-30 22:12:00.47 Code:
0x80019002 Source: OnPreExecute Description: SSIS Warning Code
DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but
the number of errors raised (1) reached the maximum allowed (1);
resulting in failure. This occurs when the number of errors reaches
the number specified in MaximumErrorCount. Change the
MaximumErrorCount or fix the errors. End Warning Error: 2022-03-30
22:12:00.48 Code: 0xC0024104 Source: Back Up Database (Full)
Description: The Execute method on the task returned error code
0x80131904 (Login failed for user 'backupuser'.). The Execute method
must succeed, and indicate the result using an "out" parameter. End
Error ## Heading ##Error: 2022-03-30 22:12:00.48 Code: 0xC0024104
Source: {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} Description: The
Execute method on the task returned error code 0x80131904 (Login
failed for user 'backupuser'.). The Execute method must succeed, and
indicate the result using an "out" parameter. End Error Warning:
2022-03-30 22:12:00.48 Code: 0x80019002 Source: OnPostExecute
Description: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The
Execution method succeeded, but the number of errors raised (2)
reached the maximum allowed (1); resulting in failure. This occurs
when the number of errors reaches the number specified in
MaximumErrorCount. Change the MaximumErrorCount or fix the errors. End
Warning DTExec: The package execution returned DTSER_FAILURE (1).
Started: 10:12:00 PM Finished: 10:12:00 PM Elapsed: 0.219 seconds. The
package execution failed. The step failed

I know for sure that the user for this backup job is sysadmin and it is not locked out all rights are grated. And this is production so I cannot take many risks. What am I missing ?

A: You are using a SSMS maintenance plan. Try to look up for errors in the maintenace plan not in the sql server agent job history.
You will find the true error.

(written as answer because i can't paste images on the comments)

A: Honestly to me this part screams your issue Login failed for user 'backupuser'.
So either the job is trying to login with that user and the user doesn't exist OR the user is not a backup operator potentially and can't initiate those tasks. I know it sounds silly but I've had sysadmins that couldn't run backup jobs without backup operator role.


text:
Q: Desplazarse por los Inputs con las flechas del teclado Quisiera saber cómo puedo cambiar el focus entre dos inputs que están en diferentes
 con las flechas derecha e izquierda usando javascript/jquery, aquí el código:

    No.
    <input type="text" class="input" size="10" maxlength="8" id="IpatCOp1-org" tabindex="10"/>

    NOMBRE
    <input type="text" id="nomorganismo" class="w-100 input" tabindex="-1"/>

Gracias.

A: Para moverte por los inputs a través de las teclas direccionales (right y left, también puede funcionar con up y down) puedes emplear jquery a través del evento keyup y una función que encuentre el siguiente o anterior elemento del input actual.
En este ejemplo en caso de llegar al limite se regresa al primero o al ultimo según el caso:

$(function()
{
  $('.input').keyup(function(e) {
    if(e.keyCode==37)//38 para arriba
      mover(e,-1);
    if(e.keyCode==39)//40 para abajo
      mover(e,1);
  });
});

function mover(event, to) {
   let list = $('input');
   let index = list.index($(event.target));
   index = (index + to) % list.length;
   list.eq(index).focus();
}

    No.
    <input type="text" class="input" size="10" maxlength="8" id="IpatCOp1-org" tabindex="10"/>

    NOMBRE
    <input type="text" id="nomorganismo" class="w-100 input" tabindex="-1"/>

    input3
    <input type="text" id="input3" class="input" tabindex="-1"/>

    input4
    <input type="text" id="input4" class="w-100 input" tabindex="-1"/>

En este ejemplo solo se puede navegar hasta los limites hacia arriba y abajo:

$(function()
{
  $('.input').keyup(function(e) {
    if(e.keyCode==37)//38 para arriba
      mover(e,-1);
    if(e.keyCode==39)//40 para abajo
      mover(e,1);
  });
});

function mover(event, to) {
   let list = $('input');
   let index = list.index($(event.target));
   index = Math.max(0,index + to);
   list.eq(index).focus();
}

    No.
    <input type="text" class="input" size="10" maxlength="8" id="IpatCOp1-org" tabindex="10"/>

    NOMBRE
    <input type="text" id="nomorganismo" class="w-100 input" tabindex="-1"/>

    input3
    <input type="text" id="input3" class="input" tabindex="-1"/>

    input4
    <input type="text" id="input4" class="w-100 input" tabindex="-1"/>

Construí la función mover() en base a este código, créditos a su autor.
Espero sea lo que estas buscando, saludos.

A: Estuve usando esta función:

 $(".table-section").keydown(function (e) {
  var items = $(this).find('.input'),
  activo = document.activeElement;

  if (e.which == 39) {
    //ciclo for que valida si NO es el último
    for (var i = 0; i < items.length - 1; i++) {
      if(activo === items[i]){
        items[i + 1].focus();
      }
    }
  }
  if (e.which == 37) {
    //ciclo for que valida si NO es el primero
    for (var i = 1; i < items.length; i++) {
      if (activo === items[i]) {
        items[i - 1].focus();
      }
    }
  }
});

    No.
    <input type="text" class="input" size="10" maxlength="8" tabindex="10"/>

    NOMBRE
    <input type="text" class="w-100 input" tabindex="-1"/>

    input3
    <input type="text" class="input" tabindex="-1"/>

    input4
    <input type="text" class="w-100 input" tabindex="-1"/>


text:
Q: php:count data from db then show at other page dear all..i have this data inside DB:
line     model        serial
fa01     kd-g335ud   105x0001
fa01     kd-g335ud   105x0002
fa01     kd-g335ud   105x0003 //up to 20pcs or regardless of the number of goods in the db
fa02     kd-r311ed   105x0001
fa02     kd-r311ed   105x0002 //up to 20pcs or regardless of the number of goods in the db

i want if every "model" have reached 20 pcs or regardless of the number of goods in the db, the data will appear at quantity page like:
line     model      qty
fa01    kd-g335ud    20
fa02    kd-r311ed    20

please help, thanks before :-)

A: SELECT line, model, count(serial) as qty FROM table_name GROUP BY line, model
Not 100% sure on my query, but that is along the lines of what you want. Hopefully that query is correct!

A: you are not explaining it well.
you said "i want if every "model" have reached 20 pcs or regardless of the number of goods..."
what about the line. regardless of the line or in regards :)?
 If you want every model regardless of the line and serial then:
SELECT model, count(model) AS QUANITY FROM [table name] GROUP BY model;


text:
Q: How do I install a GUI from the command line? I have a CENTOS 6.0 machine that I have installed from a x86_64 minimal ISO. It runs at init 3 at the moment, and I want to install a GUI on it. When I do an init 5 from the prompt, all I get is "Starting system logger:
Retrigger failed udev events [  OK  ]" and it does not boot a GUI.
What do I need to yum install to get a graphical user interface?

A: For this you need X Windows at a minimum, and a desktop environment like Gnome or KDE (I am guessing you want a DE).
Use
yum grouplist

to find out what groups are available.  If you wanted KDE for example, you would need to install the following groups:
yum groupinstall "X Window System" "KDE (K Desktop Environment)"


text:
Q: 1+2+3+4+… and −⅛ Is there some deeper meaning to the following derivation (or rather one-parameter family of derivations) associating the divergent series $1+2+3+4+…$ with the value $-\frac 1 8$ (as opposed to the value $-\frac 1 {12}$ obtained by zeta-function regularization)? Or is it just a curiosity?
Formally put $x=1+2+3+4+\dotsb$. Writing $$x-1=(2+3+4)+(5+6+7)+\dotsb=9+18+27+\dotsb=9x$$ we get $8x=-1$. Or, writing $$x-1-2=(3+4+5+6+7)+(8+9+10+11+12)+\dotsb=25+50+75+\dotsb=25x$$ we get $24x=-3$. Or, writing $$x-1-2-3=(4+\dotsb+10)+(11+\dotsb+17)+\dotsb=49+98+147+\dotsb=49x$$ we get $48x=-6$. Etc.
It is not surprising that values other than $-\frac 1 {12}$ can be obtained as "values" of this divergent series. What surprises me is that all of these methods of grouping terms give the same answer. It makes me wonder whether there is a larger story here.

A: Yes there is, in $p$-adics.
You are probably familiar with the relation
$$8T(n)+1=(2n+1)^2.$$
Now for any $p$ except $2$ (which has to be excluded because of the non-unit coefficients in the above relation) we can identify a subsequence of whole numbers $n$ such that the squared quantity on the right converges $p$-adically to zero. Then $T(n)$ follows suit, converging to $-1/8$.
For instance, we may put in $p=3$, in which case $-1/8$ is rendered as the $3$-adic integer $\overline{01}$. Then using base $3$ arithmetic we develop the sequence
\begin{align*}
\newcommand\pdots{{\ldots}}
& T(\pdots1)=\pdots01 \\
& T(\pdots11)=\pdots0101 \\
& T(\pdots111)=\pdots010101
\end{align*}
where the base on the left side is set up to converge to $-1/2$ (for which the corresponding square is zero) and the right side then converges quadratically to $-1/8$ in the subsequence. The quadratic convergence to $-1/8$ is unique to that target value bevause of the critical value of the corresponding square.
This quadratic convergence leads to ordinary integer triangular numbers being "attracted" to the $3$-adic representation $\overline{01}=-1/8$. Below is a table wherein the columns represent possible two-digit endings for any $81$ consecutive triangular numbers in base $3$; the rows represent possible values for the preceding two digits and the entries describe how many triangular numbers out of the block of $81$ will end with the resulting four-digit pattern. Combinations not shown correspond to no triangular numbers represented in base 3.

The table shows that there us an excess of triangular numbers ending with $...01$ in base $3$ ($27/81$ versus $18/81$ for the other possible two-digit endings) and among those triangular numbers ending with $...01$, the four-digit ending $...0101$ is further overrepresented. The overrepresentation of patterns matching $\overline{01}$ grows when we cobsider longer strings of terminal digits in base $3$. Similar attraction is seen to $\overline{03}$ in $5$-adics, $\overline{06}$ in $7$-adics, and so on.
Triangular numbers are not the only ones with this property. We can set up similar patterns with any polygonal number pattern, for instance octagonal numbers quadratically converging to $-1/3$ and favoring that fraction in $p$-adic subsequences where the prime $p\ne3$.

A: You are not using all partial sums, but only a restricted choice of them. So you are not really looking at the limit of all partial sums. An analogue would be deciding to compute $1 - 1 + 1 - 1 + 1 - 1 + \cdots$ by only focusing on the even-indexed partial sums (every other partial sum).
For your general calculation, assuming $x$ makes sense, pick $N \geq 1$ and subtract $\sum_{j=1}^N j$ from $x$ and then look only at the partial sums of what is left using multiples of $2N+1$: the $(2N+1)$-th partial sum, the $(2N+1)2$-th partial sum, and so on.  Collecting terms $2N+1$ at a time, centered at the multiples of $2N+1$ (with $N$ terms preceding and $N$ terms succeeding those multiples), we get
$$
x - \sum_{j=1}^N j = \sum_{k \geq 1} \left(\sum_{i=-N}^N ((2N+1)k + i)\right) = \sum_{k \geq 1} (2N+1)^2k  = (2N+1)^2x,
$$
so
$$
x = (2N+1)^2x + \frac{N(N+1)}{2} = (4N(N+1) + 1)x + \frac{N(N+1)}{2}.
$$
Subtract $x$ from both sides and solve for $x$:
$$
x = -\frac{N(N+1)/2}{4N(N+1)} = -\frac{1}{8}.
$$
The series $1 + 2 + 3 + \cdots$ is not convergent even in the $p$-adics: for no prime $p$ are the terms of the partial sums tending $p$-adically to $0$.


text:
Q: Javascript Functions (Multiple) I have 1 function inside of each of my 4 radio buttons with onclick attributes I've set inside my input tags.
My goal is to change the values of 2 variables depending on which radio button you click.
However, once the value of the variables change an extra function would be called outside/seperately showing me the new value of the 2 variables.
The problem is I can only keep my variable inside of the 4 functions and can't use them outside of them for the new function I'm using. What should I do? Could I have a basic example?
I'm kind of new here, not sure how to post code so I made a hastebin:
https://hasteb.in/hefehoqi.xml

A: I'm guessing the variables you wanna use are module and tmodule.
So like I said in the comment sections. Just define them outside of the functions.
let module = '';
let tmodule = 1;

function radio1(){
    let radio1 = true;
    module = 'module1';
    tmodule = 1;
    alert('radio1 function');
}

function radio2(){
    let radio1 = true;
    module = 'module2';
    tmodule = 2;
    alert('radio2 function');
}
function radio3(){
    let radio1 = true;
    module = 'module3';
    tmodule = 'tmodule3';
    alert('radio3 function');
}
function radio4(){
    let radio1 = true;
    module = 'module4';
    tmodule = 'tmodule4';
    alert('radio4 function');
}

function commencer(){
    console.log(module);
    console.log(tmodule);
    document.getElementById("module1").style.display = "block";
    document.getElementById("module2").style.display = "none";
    document.getElementById("module3").style.display = "none";
    document.getElementById("module4").style.display = "none";
    document.getElementById("module1").innerHTML = "";
}


text:
Q: How to give up power-up bought by unicoins? I bought some Stack Overflow power-ups. Now I change my mind and do not want some of them, how to give them up? With or without refund :-)

A: *

*Open the dialog box

*Select the powerup you wish to give up

*Click "Recycle Now," which costs 10 Unicoins.

Note: There is no refund, and you are charged 10 Unicoins to remove the powerup.

A: Go to the 'Buy Powers' tab, then click on the power-up you don't want anymore. You can recycle it for 10 Unicoins


text:
Q: Import psycopg2 to establish a connection to postgres server, and interact with it in python I  am on the Udacity Full Stack Nanodegree and the instructions are not very clear for installing psycopg2 on visual studio code for postgresql. I  am using postgresql15
PLEASE HELP, i've spent 4 days trouble shooting instead of attempting my 1st project
I have installed the psycopg2 using the following commands and its says it has been satisfied, however it's still not allowing me to use psycopg2:
brew install openssl
Downloading https://formulae.brew.sh/api/cask.json
100.0%
Warning: openssl@3 3.0.8 is already installed and up-to-date.
To reinstall 3.0.8, run:
brew reinstall openssl@3
ada@adas-mbp ~ % export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/
ada@adas-mbp ~ % pip3 install psycopg2
Requirement already satisfied: psycopg2 in ./.pyenv/versions/3.9.5/lib/python3.9/site-packages (2.9.5)

My visual studio code is not connecting to the database:
Exception has occurred: ImportError
dlopen(/Users/ada/.pyenv/versions/3.9.7/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Library not loaded: @rpath/libssl.1.1.dylib
Referenced from: /Users/ada/.pyenv/versions/3.9.7/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so
Reason: image not found
File "/Users/ada/class-demos/demo.py", line 1, in <module>
import psycopg2
ImportError: dlopen(/Users/ada/.pyenv/versions/3.9.7/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): Library not loaded: @rpath/libssl.1.1.dylib
Referenced from: /Users/ada/.pyenv/versions/3.9.7/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so
Reason: image not found


text:
Q: Secure web services using Symfony So I have Symfony project which is also in charge of database abstraction and the data layer. In short - all data requests should go through it.
Now I want to have external components that will want to query / update stuff in the database, using web service API that I expose.
Question: How do I make sure these web services are running inside a secure channel? I don't want unauthorized users to update my database, and I don't want eavesdroppers get hold of sensitive data. Is setting up client authentication using PKI a viable option? or is it overkill? What's the way this is tackled?
Thanks!
-DBG

A: First of all, you if you have a limited number of service users, and know their ips, you can restict access to ceirtain urls by ips.
Next, have a look at Practical symfony, where they embed an authentication token into the url.


text:
Q: CSS Sub Navigation Auto Width This has been bugging me quite a while. Please look at my fiddle here.
http://jsfiddle.net/y9uEf/
You can see that the Subnav can't seem to "grow" bigger if there's a very long text in it. I know that it's because its width will always be 100% of the parent (in this case the top menu Home, Who, Contact). I can add width in the subnav ul so that the subnav ul will be bigger, but that will work on all subnavs regardign the width of the subnav content.
Now what if I want it to be dynamic? For instance, if the subnav content only has "Short Text" (let's say it's about 50 pixels), then the subnav width will be 50 pixels. Then if the subnav content has a list with "A Very Very Very Long Text" (let's say it's about 200 pixels) then the subnav width will automatically be 200px.
Thanks

A: You can try to add a white-space: nowrap to your li.


text:
Q: MVC MapRoute gets 404 error I have created the following MapRoute function. And it's being called right from Application_Start() in Global.asax.
public static class RouteConfig
{
    public static void RegisterRoutes( RouteCollection routes )
    {
        routes.MapRoute(
                name: "TestMe",
                url: "TestMe.axd",
                defaults: new { controller = "Access", action = "SignOn" }
            );
    }
}

While I can access the specific controller if I use
http://localhost/TestSite/Access/SignOn,

I can't access it with this URL.
http://localhost/TestSite/TestMe.axd.

Can someone please point out what I am missing here?
Many thanks!!

A: Found some information from this link
I added
<modules runAllManagedModulesForAllRequests="true" />

into my Web.config and it's working now.


text:
Q: Kubernetes memory and persistenvolumeclaims In kubernetes, for a Pod we specify memory limit and request. There is a PVC which is requested out from PV and created. How do PVC and memory limits corelate during memory allocation and usage, and what if there are conflicts between the two?
I am little confused that any one could have served the purpose.

A: There is no corelation between PVC and memory limits and requests. PVC provides storage space and memory limit and requests provides RAM.

A:
How do PVC and memory limits corelate during memory allocation and usage, and what if there are conflicts between the two?

There is no direct correlation between Resource Limits and PVC.
It's common to get a little confuse with the word memory as it's a generic term.
Kubernetes uses the word memory as commonly we call RAM Memory which has it's Default Value, and it's Minimum and Maximum Values set into the cluster configuration.

If so then can a PVC be shared by multiple pods ?

Yes, you can share a Persistent Volume with diferent pods in the same namespace.
There are many types of Storage Volumes, which servers different purposes.
A PersistentVolumeClaim (PVC) is used to mount a PersistentVolume into a Pod.


text:
Q: I am using javaFx and i am trying to determine if a point is inside a bounding box This is the class that i am using
public class Spot {

private static final int IMAGE_HEIGHT = 500;
private static final int IMAGE_WIDTH = 500;

private static final int DOT_HEIGHT = 20;
private static final int DOT_WIDTH = 20;

private static final Color DOT_COLOR = Color.RED;
private Random ran = new Random();

private int x = this.ran.nextInt(IMAGE_WIDTH);
private int y = this.ran.nextInt(IMAGE_HEIGHT);
/**
 * Draws spot onto given playfield object
 *
 * @param playfield
 */
public void drawSpot(Playfield playfield) {
    playfield.getGraphicsContext2D().setFill(DOT_COLOR);
    playfield.getGraphicsContext2D().fillOval(x, y, DOT_WIDTH, DOT_HEIGHT);
    this.drawSpot(playfield);

}

I am trying to figure out a way to write a method that would determine if the given x and y coordinate is inside the bounding box.
public boolean isINSpot(int x, int y){
        if (x > this.x && x < this.x + DOT_WIDTH && y > this.y && y < this.y + DOT_HEIGHT) {
        return false;
    } else {
        return true;
    }
    }
}

}

A: This may help:
return x > boxX && x < boxX + boxWidth && y > boxY && y < boxY + boxHeight;

If not, I messed up.


text:
Q: sql with rounding issue I have a problem with sql(maths).
I have a total payable given to vendor which is 33.333, and I need to divide the amount with two users. So I have select
select (16.666 * 2) from dual which gives me 33.332 that is .1 less than the total amount I have to give.
If I have this sql
select (16.667 * 2) from dual, then it gives me 33.334 which  .1 greater than 33.333.
How can I divide the total amount which I could equally distribute?
Thanks

A: Do it the other way around:
select 33.333/2

A: I'm not sure from where are you executing your query, but it works here (SQLDeveloper, 10g):
SELECT (33.333 / 2) FROM dual;
16,6665

SELECT (16.6665 * 2) FROM dual;
33,333

A: You are most likely working with the wrong column type. You should be using DECIMAL instead of e.g. FLOAT.
Here is a good summary: http://lists.mysql.com/mysql/189592
Depending on the SQL standard you are using the type can be MONEY, DECIMAL or NUMBER.


text:
Q: Monotouch: TableView parent data class, sections, and items setup i'm a newbie to both C# and Monotouch/iOS programming.
I am creating a table view's data source and was setting up the object data for it. Here is what i need to implement:
Restaurant Menu --> Menu Sections --> Section Items. One additional requirement that the restaurant has multiple menus. I designed the classes as follows:
public class Menu
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<MenuSection> Sections { get; set; }
    public List<SectionItem> Items { get; set; }
}

public class MenuSection
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class SectionItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

Do i declare the Items (SectionItems) in Menu class or in MenuSection class? What is the correct implementation of such a hierarchy in C# ? Thanks!
UPDATE
@Jason, With the solution you proposed i am running into an implementation issue. How do i relate Items to a Menu? I have to go through the hierarchy Item->Section->Menu. Would i be able to add Items to a specific menu given your proposed structure?
Ex:
List<Menu> menuList = new List<Menu> ();
Menu menu;

menu = new Menu (){ Id = 1, Name = "Lunch Menu" };
menu.Sections.Add(new MenuSection(){ Id = 1, Name = "Specials"});
menuList.Add(menu);

menu = new Menu (){ Id = 2, Name = "Dinner Menu" };
menu.Sections.Add(new MenuSection(){ Id = 1, Name = "Salads"});
menuList.Add(menu);

How do i add items without knowing which menu and which sections i am adding it to? Can you please provide an example of adding an item to one of the menus above? One solution that comes to mind is to denormalize Menu and Section by adding Menu.Id and Menu.Name to Section then i only have to deal with a single hierarchy; but, that would be avoiding the issue. There must be a better way. Thanks for helping.

A: Item should be a child of Section.
public class Menu
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<MenuSection> Sections { get; set; }

}

public class Section
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SectionItem> Items { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
}

UPDATE
To access/add items to a Menu (there are multiple ways)
// adding by index
menuList[0].Sections[0].Items.Add(new Item() { .. init .. });

// keep a reference to a section
Section dinner = new Section() { .. init .. };
dinner.Items.Add(new Item() { .. init ..});
dinner.Items.Add(new Item() { .. init ..});
menu.Sections.Add(dinner);


text:
Q: Host 'X' is blocked because of many connection errors mysql gets stuck with that message

Mysql2::Error: Host 'X' is blocked
  because of many connection errors; unblock with 'mysqladmin
  flush-hosts'

in the meantime, I receive loads of timeouts from Rails

ActiveRecord::ConnectionTimeoutError: could not obtain a database
  connection within 5 seconds (waited 5.00223 seconds). The max pool
  size is currently 5; consider increasing it.

Is mysql getting hit by ActiveRecord each time? Could the Rails timeouts be causing the mysql lock?
Or are those 2 errors due to too many attemps/not enough resources problem?

A: Increase the connection pool size, first.
Connection Pool size

Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
MinimumPoolSize=10;maximumpoolsize=50;

Here's some other connection string/ mysql setting you can try. http://www.connectionstrings.com/mysql


text:
Q: What caused Realm notification Can anybody explain how can I know what operation caused my realm notification trigger?
I have Objects, and I create notifications on Object's changes. These objects can be updated from many places and I'd like to know exact place where it happened

A: I'm pretty sure there is no way to tell from within the Realm APIs which object change caused the notification.
One option you have, however, is to create an ignored property on your object and set a value on the object to know who wrote to it. Here's an example:
//Class definition
class Stuff: Object{
  @objc dynamic var whatever = ""

  //In memory only
  @objc dynamic var blame = ""
  override static func ignoredProperties() -> [String] {
    return ["blame"]
  }
}

Then elsewhere in your code:
//Place #1 where object is changed
let myObject = Stuff()
myObject.blame = "place1"

//Place #2 where object is changed
let myObject = Stuff()
myObject.blame = "place2"

Then in your Realm listener, you can access the blame property on the object to find out where it was changed:
token = myObject.observe { change in
  switch change {
  case .change(let properties):
    for property in properties {
      print(property.blame) //<-- This tells you where it changed
    }
  case .error(let error):
    print("An error occurred: \(error)")
  case .deleted:
    print("The object was deleted.")
  }
}

Hopefully this helps. Good luck!


text:
Q: Excel data validation with fixed letters and numerals I need to set data validation on an excel cell to be a specific format. I haven't been able to figure it out myself so far.
The requirements are:
8 characters in length
first character is the letter B
characters 2&3 are numeric
character 4 is a dash -
character 5 is a numeral
character 6 is the letter V
characters 7&8 are numerals
Can anyone help me with this? Thank you!

A: Go to data > data validation and then choose custom and add this formula:
=AND(LEN(A1)=8, LEFT(A1,1) = "B", ISNUMBER(NUMBERVALUE(MID(A1,2,2))), MID(A1,4,1) = "-", ISNUMBER(NUMBERVALUE(MID(A1,5,1))), MID(A1,6,1) = "V", ISNUMBER(NUMBERVALUE(MID(A1,7,2))))

Formula breakdown:
=AND(
 LEN(A1)=8, 8 characters in length
 LEFT(A1,1) = "B", first character is the letter B
 ISNUMBER(NUMBERVALUE(MID(A1,2,2))), characters 2&3 are numeric
 MID(A1,4,1) = "-", character 4 is a dash -
 ISNUMBER(NUMBERVALUE(MID(A1,5,1))), character 5 is a numeral
 MID(A1,6,1) = "V", character 6 is the letter V
 ISNUMBER(NUMBERVALUE(MID(A1,7,2))) characters 7&8 are numerals
)

A: You could use:
=AND(ISNUMBER(SEARCH("B??-?V??",A1)),SUMPRODUCT(--ISNUMBER(--MID(A1,{2,3,5,7,8},1)))=5,LEN(A1)=8)


text:
Q: Magento 2: Creating product with custom Options I have tried several different ways that to add custom options programmatically to a new product in Magento 2. I am doing this from a CLI command and everything is working well except for the custom options which give me an error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (magento_ee.catalog_product_option, CONSTRAINT CATALOG_PRODUCT_OPTION_PRODUCT_ID_CATALOG_PRODUCT_ENTITY_ROW_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (row_id) ON), query was: INSERT INTO catalog_product_option (type, is_require, sort_order) VALUES (?, ?, ?)

Here is the stripped down code:
function __construct(
    \Magento\Catalog\Model\Product $product,
    \Magento\Catalog\Model\Product\Option $option,
    \Magento\User\Model\UserFactory $userFactory,
    \Magento\Framework\App\State $state
)
{
    $this->product = $product;
    $this->option = $option;
    parent::__construct();

    /**
     *
     * Bug fix for known Magento issue where product status cannot be changed in custom CLI command without an admin session
     * https://github.com/magento/magento2/issues/5664
     *
     */
    $model = $userFactory->create()->loadByUsername('admin_username_here');

    $state->emulateAreaCode('adminhtml', function ($model) {
        $session = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Backend\Model\Auth\Session');
        $session->start();
        $session->setUser($model);
        $session->processLogin();
    }, array($model));

}

// Process some stuff here and call setOptions when necessary

// code goes here

private function setOptions(array $dealArray, $lang) {
    if(count((array) $dealArray['offerItems']) > 1) {
        $this->output->writeln('Multiple Options found, processing...');

        $values = [];
        $i = 1;
        foreach($dealArray['offerItems'] as $item) {
            $this->output->writeln('Setting option: '.$item->$lang->offerItemSKU);

            $values[] = array(
                'title'             => $item->$lang->offerItemValue,
                'price'             => $this->product->getPrice(),
                'price_type'        => "fixed",
                'sku'               => $item->$lang->offerItemSKU,
                'sort_order'        => $i
            );

            $i++;
        }

        $optionArray = array(
                "sort_order"    => 1,
                "title"         => "Options",
                "type"          => "drop_down",
                "is_require"    => 1,
                "values"        => $values
            );

        $this->output->writeln('Setting options for SKU: '.$this->product->getSku().PHP_EOL.print_r($optionArray, true));
        $this->option->addData($optionArray);
        $this->option->save();

        $this->product->setOptions([$this->option]);
        $this->option->clearInstance();

    } else {
        $this->output->writeln('No Options found.');
    }
}

A: I found the solution:
Instead of calling setProductId like this:
$this->option->setProductId($this->product->getId());

I had to call it like this:
$this->option->setProductId($this->product->getData('row_id'));

It seems to want the row_id instead of the entity_id, which is inconsistent with the rest of Magento2 implementations.
Final code looks like this:
private function setOptions(array $dealArray, $lang) {
    if(count((array) $dealArray['offerItems']) > 1) {
        $this->product->setHasOptions(1);
        $this->product->setCanSaveCustomOptions(true);
        $this->output->writeln('Multiple Options found, processing...');

        $values = [];
        $i = 1;
        foreach($dealArray['offerItems'] as $item) {

            $values[] = array(
                'title'             => $item->$lang->offerItemValue,
                'price'             => $this->product->getPrice(),
                'price_type'        => "fixed",
                'sku'               => $item->$lang->offerItemSKU,
                'sort_order'        => $i
            );

            $i++;
        }

        $this->option->setTitle('Options');
        $this->option->setType('drop_down');
        $this->option->setSku($this->product->getId().'_option');
        $this->option->setProductId($this->product->getData('row_id'));
        $this->option->setProductSku($this->product->getSku());
        $this->option->setIsRequire(true);
        $this->option->setSortOrder(1);
        $this->option->setValues($values);
        $this->option->save();

        $this->product->setOptions([$this->option]);

    } else {
        $this->output->writeln('No Options found.');
    }
}


text:
Q: SSJS Codes behind the button runs after page is refreshed I have SSJS code behind a button. When i click the button that code creates a document in another database.
When i click the button It Works fine but I look at the Domino Admin COnsole I realize that The code behind to button Works twice.. I think When the page is refreshed It Works again? How can i prevent it?
What is it thet I miss?
<xp:button value="Label" id="button1">

    <xp:eventHandler event="onclick" submit="true"
        refreshMode="complete">
        <xp:this.action><![CDATA[#{javascript:print("Before createNewDoc()");
createNewDoc();
print("After createNewDoc()");
}]]></xp:this.action>
    </xp:eventHandler></xp:button>

A: Add print statements to the beforePageLoad, afterPageLoad etc events to confirm where it is running. Also, it's worth using XPages OpenLog Logger or some other logging framework that can output a full stack trace. That might identify whether the code is running twice in the refresh, and where from.
There is no reason the code should be running twice from the button. I'm assuming this is an SSJS function in a Script Library, maybe something else is triggering that.


text:
Q: javascript how to fix pitfalls counter I'm trying to run a for loop and print the current index without use let
here my code:
function init() {
  for (var index = 0; index < 5; ++index) {
    setTimeout(() => {
      console.log(index);
    }, index);
  }
}

I expected to: 0 1 2 3 4
but i get 5 5 5 5 5
Once the Var  replace in Let the problem will be solved
I want to stay with Var
How can the problem be solved?
Thanks

A: function init() {
  for (var index = 0; index < 5; ++index) {
   const i = index;
   setTimeout(() => {
    console.log(i);
   }, i);
  }
 }

This should work.


text:
Q: Macro constants concatenation using ## I'm writing some libraries for a microcontroller, and for that purpose, I use macro-like functions. For example, a macro-like function to enable an I2C module is defined as:
#define I2C_MODULE_ENABLE(_x) \
    I2C##_x##CONLbits.I2CEN = 1

where _x is the module number (e.g.,1 or 2 in my case).
If a user calls this macro-like function as I2C_MODULE_ENABLE(1), it would be expanded by a preprocessor as I2C1CONLbits. I2CEN = 1.
However, if a user calls this macro-like function as I2C_MODULE_ENABLE(MY_I2C), where MY_I2C is a macro constant defined in a user-defined config.h file that is included by my i2c.h library (e.g., the macro constant is defined as #define MY_I2C 1), the macro-like function would be expanded as I2CMY_I2CCONLbits. I2CEN = 1.
I know that I need to somehow evaluate the MY_I2C macro constant before concatenation, and I can do that by adding another macro level:
#define __I2CxCONLbits(_x) I2C##_x##CONLbits
#define I2C_MODULE_ENABLE(_x) \
    __I2CxCONLbits.I2CEN = 1

My question is: is there a more elegant solution to this problem since I have multiple registers like the CONLbits register. Using this approach I would need to define a special __I2CxREGISTER(_x) macro for every register.
I tried to do something like this:
#define __I2Cx(_x) I2C##_x
#define I2C_MODULE_ENABLE(_x) \
    __I2Cx(_x)##CONLbits.I2CEN = 1

but that produces an output like this: I2C1 CONLbits .I2CEN = 1, and my compiler is complaining about the whitespace between I2C1 and CONLbits tokens.

A: You aren't adding the macro level properly, as I see it. The usual idiom is to define a wrapper that does nothing but forward the argument. That way, if the argument is itself a macro, it will be expanded before being passed to the macro that is wrapped:
#define I2C_MODULE_ENABLE__(x_) \
    I2C##x_##CONLbits.I2CEN = 1

#define I2C_MODULE_ENABLE(x_) \
    I2C_MODULE_ENABLE__(x_)

I took the liberty of renaming your macro parameter, since identifiers with leading underscores are defined as reserved for the implementation, I think it's better to be safe than sorry.

To solve your problem of the space I'd go with the proverbial level of indirection, and use a function like macro to generate the correct prefix token, and pass it along two levels to make sure it's expanded correctly:
#define I2Cx__(x_) I2C##x_
#define I2C_MODULE_ENABLE__(IC_) \
    IC_##CONLbits.I2CEN = 1
#define I2C_MODULE_ENABLE_(IC_) \
    I2C_MODULE_ENABLE__(IC_)
#define I2C_MODULE_ENABLE(x_) \
    I2C_MODULE_ENABLE_(I2Cx__(x_))

See it live here
The whole shtick is to make sure the preprocessor sees and produces valid tokens at each step. Which can be a bit tiresome.


text:
Q: How do you get ApplicationContext to recognize CouchBaseRepositoyr beans from src/test/java? I'm writing some unit tests for a reactive web application that uses couchbase repositories, however the ApplicationContext fails to load due to a NoSuchBeanDefinitionException being thrown when trying to @Autowire a ReactiveCouchbaseRepository.
From src/main/java, the application runs just fine, and I can send requests from PostMan and get valid responses. No configuration class is necessary. My application.properties is set up like this:
spring.couchbase.bootstrap-hosts=subdomain.domain.com
spring.couchbase.bucket.name=some_bucket_name
spring.couchbase.bucket.password=a_password
spring.couchbase.env.timeouts.connect=10000

I created a src/test/resources folder, marked it as the testing resources folder (in IntelliJ), and copied over the application.properties, but still the same exception is thrown. I also created a couchbase config class in the test folder that looks like this:
@Configuration
@EnableCouchbaseRepositories
public class CouchbaseConfiguration extends AbstractCouchbaseConfiguration {

    @Value("${spring.couchbase.bootstrap-hosts}")
    private String hosts;

    @Value("${spring.couchbase.bucket.name}")
    private String bucketName;

    @Value("${spring.couchbase.bucket.password}")
    private String password;

    @Override
    protected List<String> getBootstrapHosts() {
        return Collections.singletonList(hosts);
    }

    @Override
    protected String getBucketName() {
        return bucketName;
    }

    @Override
    protected String getBucketPassword() {
        return password;
    }

}

My test class looks like this:
@RunWith(SpringRunner.class)
@WebFluxTest
public class ReactiveSpringApplicationTests {

    @Autowired
    WebTestClient webTestClient;

    @Test
    public void create_Test_Post_Event() throws Exception {

        EventData eventData = new EventData();
        eventData.setIdentifier("1111");

        webTestClient.post().uri("/ad/acc")
                .contentType(MediaType.APPLICATION_JSON_UTF8) // Set the media type of the body, as specified by the Content-Type header.
                .accept(MediaType.APPLICATION_JSON_UTF8) // Set the list of acceptable media types, as specified by the Accept header.
                .header("Corr", "0000")
                .body(Mono.just(eventData), EventData.class) // Set the body of the request to the given asynchronous Publisher.
                .exchange() // Perform the exchange without a request body.
                .expectStatus().isCreated()
                .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
                .expectBody(EventData.class);

    }
}

The following exceptions are thrown (full exception stack omitted for brevity, only the first and last exception shown):
java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.amex.gar.accounts.repository.CouchBaseDocRepository<?, ?>' available: expected at least 1 bean which qualifies as autowire candidate.

(CouchBaseDocRepository extends ReactiveCouchBaseRepository)
How do I get the ApplicationContext to properly recognize the couchbase repositories from the test directory?


text:
Q: Using co-ordinating conjunctions My question is about the following sentence. Punctuation omitted.

If the man comes back and I am home I will arrest him

In the sentence there is one dependent subordinate  clause and two independant clauses.
I have two questions.

*

*How would this sentence be punctuated, and coördinating conjunctions are said to separate like things. Subjects, verbs, and independent clauses as examples.

*Why does it sound perfectly normal that in the example a subordinate clause is being separated by an independent clause using a coördinating conjunction?

A: First, I cannot agree that there are two independent clauses here.  There is one simple independent clause:  "I will arrest him".  There is a compound subordinate clause: "the man comes back and I am home".  The coordinating conjunction "and" combines two complete clauses.  The subordinating conjunction "if" relates the entire compound to the independent clause.
When a coordinating conjunction connects two independent clauses, a comma makes sense.  In this case, the clauses are not independent.
When a sentence begins with a long introductory structure, a comma at the end of that structure makes sense.  In this case, the compound subordinate clause is a long introductory structure.
Given these guidelines, it is appropriate to punctuate the sentence as follows:

If the man comes back and I am home, I will arrest him.

The reason that the "and" sounds natural is that it does connect two like things.  Each of those things is a complete subordinate clause.  The sentence also sounds natural if each of the subordinate clauses has its own subordinating conjunction:

If the man comes back and if I am at home, I will arrest him.

If the middle clause were independent, the meaning of the sentence would be completely different:

If the man comes back, I am at home, and I will arrest him.


text:
Q: How do you render @ContentChildren bodies in Angular6 I'm making a pretty simple tab view (want something custom as I will be modifying this heavily later), but stuck with one basic step of getting the child tab to render.
My template for the tab-view (container for the tabs) is:

{{ title }}

          {{tab.label | translate}}

          tab content goes here.. {{tab}}

the tab temlate is simply:

    <ng-content></ng-content>

how im using the tabs is:
<app-tab-view title="My Tabs">
    <app-tab label="General">this is the content for the general tab </app-tab>
    <app-tab label="Other">this is the content for the other tab </app-tab>
</app-tab-view>

clearly {{tab}} isnt the correct way to render the child tab, but how do i render these ?  I wish to wrap each child tab hence me not just using "" in the tab-view template,


text:
Q: ruby on rails - No route matches [POST] "/login/index" i am pretty new to rails, and i recently have a problem..
I made a login page which looks like that:
<!DOCTYPE html>

    <form action="#" method="POST" id="login-form">
        <fieldset>

                username
                <input type="text" id="login-username" class="round full-width-input" autofocus />

                password
                <input type="password" id="login-password" class="round full-width-input" />

            <%= submit_tag "Login" %>
        </fieldset>
    </form>

And this view in under app/views/login/index.html.erb
the matching controller is under app/controllers/login_controller.erb, and looks like that:
class LoginController < ApplicationController
  def index
  end

  def login
  end

end

and my routing looks like that:
BonhamNew::Application.routes.draw do

  get "login/index"
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'login#index'
end

when i click on the sumbit, i get:
No route matches [POST] "/login/index"
I know its pretty basic, but maybe some1 can give me a hand here ?
Thanks!

A: You should create an additional route post "login/index"

A: You should add the route to your routes.rb file as post 'login/index' in addition to the get route. This will make sure the form doesn't cause an error, but keeps the behaviour as is, with the form sending the request to login#index not login#login.
Also, instead of explicitly using HTML form tags, use the form_tag helper. It is better practise in rails, and allows you to use HTTP methods that your browser might not support, like PUT and DELETE. It also adds fields that Rails needs to make sure your form is not being sent via a cross site request. (The authenticity token)
Also note the text_field_tag, label_tag and password_field_tag helpers on the same page as the form_tag above. You should get into the habit of using these in preference to raw HTML.

A: Read up on resourceful routing in Rails. The examples there only use ActiveRecord models for resources, but you could also make one without an ActiveRecord model.
Login could be considered as a resource, where creating a login would not create a database record, but instead log the user into the application.
In your routes.rb define a resource as follows:
BonhamNew::Application.routes.draw do
  resource :login, only: [:show, :create]
end

This would make your controller as follows:
class LoginsController
  def show
    # Renders a page with the login form
  end

  def create
    # Logs the user in, your old login action
  end
end

Notice how the name of the controller by default is the plural form, LoginsController. If you want the singular name, just specify the controller to use for your resource as follows:
resource :login, controller: 'login', only: [:show, :create]

Then your controller looks like this:
class LoginController
  # actions
end