text:
Q: Responsive issue in constraint layout My layout has a constraint layout as a root element. There is the issue of responsiveness in the forgot password section as a view.Following is the code snippet that has an error in responsive.Please Suggest me.

This chunk of code is for password edit text view and forgot password view
//TextInputLayout for password visibility
  <com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="@dimen/_20sdp"
    android:layout_marginTop="@dimen/_40sdp"
    android:layout_marginEnd="@dimen/_80sdp"
    android:background="@drawable/shapelogin"
    app:hintEnabled="false"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/backgroundImage"
    app:layout_constraintVertical_bias="0.573"
    app:passwordToggleEnabled="true"
    tools:ignore="MissingConstraints">

 //edit textfield
            <EditText
                android:id="@+id/epassword"
                style="@style/activity_font_edit_field_password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/shapelogin"
                android:drawableStart="@drawable/ic_icon_password"
                android:drawablePadding="@dimen/_20sdp"
                android:hint="@string/prompt_password"
                android:inputType="textPassword"
                android:paddingLeft="@dimen/activity_start_padding"
                android:singleLine="true"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/backgroundImage"
                app:layout_constraintVertical_bias="0.573" />

         </com.google.android.material.textfield.TextInputLayout>

//forgot password imageview
       <ImageView
            android:id="@+id/imageView7"
            android:layout_width="@dimen/_68sdp"
            android:layout_height="@dimen/_40sdp"
            android:background="@drawable/shapelogin"
            app:layout_constraintBottom_toBottomOf="@+id/textInput"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.91"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/textInput"
            app:layout_constraintVertical_bias="0.573" />

 //forgot text inside button
       <TextView
        android:id="@+id/textViewForget"
        style="@style/activity_font_forgot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/password_forgot"
        android:background="@drawable/shapelogin"
        android:textColor="@color/linkColor"
        app:layout_constraintBottom_toBottomOf="@+id/textInput"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.891"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/textInput"
        app:layout_constraintVertical_bias="0.516" />

A: You need to change the layout height for your view textViewForget.
Instead of wrap_content make it 0dp which will be treated as MATCH_CONSTRAINT that indicates the view should fill up all available space specified wrt top and bottom constraints (in this case your edit text view)
Also in your layout there seems to be arbitrary horizontal/vertical bias set, you might want to check for correctness in the layout preview with different screen sizes.
Please refer to the documentation for more info - https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout#DimensionConstraints


text:
Q: Google Scripts -- Domain Not Found When Adding User I created a script for my Google Form that will add a user to Google Admin. It was running fine yesterday, but today when I run it, it gives met the following error:
GoogleJsonResponseException: API call to directory.users.insert failed with error: Domain not found.

Any idea what may have caused this? Here is the relevant snippet of my code:
    AdminDirectory.Users.insert(user); //adds user to google admin
    Logger.log('User %s created with PW %s.', user.primaryEmail, user.password);

I have also included the following services:

**EDIT: Also, I have Apps Access Control set to unrestricted for Apps Script Runtime, Apps Script API, and Google Drive.

A: Domain not found error will occur if you input an incorrect domain name in your primary email when adding a user.
Sample Code (Issue will be seen):
var user = {
    primaryEmail: 'user1@invaliddomain.com',
    name: {
      givenName: 'Test',
      familyName: 'Test'
    },
    // Generate a random password string.
    password: 123456789
  };

  var user = AdminDirectory.Users.insert(user);
  Logger.log(user);

redpajama_set_name: RedPajamaStackExchange


text:
Q: crossplatform solution for symlink handling with VCS The thing I'm trying to do is to implement version control for huge amount of XSLT files in our system. The problem is, that the way I'm trying to manage XSLT files isn't supported by Windows (that is used by most part of developers as a desktop OS):
Each XSLT is used to transform appropriate customers data and it's location in filesystem is a directory named as customers identifier (like 1234567890123). It makes this structure very human-unreadable.
 Thats why I made symlinks to each directory with name like "Company Name" and init mercurial repository.
 So, cloning this repository is working alright in Linux, but in Windows i received text files instead of symlinks.
Any usefull advice, how to solve my problem, is welcome. Hope for You, people!

A: In case of Mercurial your choice must be Subrepository (read also Subrepositories from "Mercurial Kick Start Exercises" of Aragost) (or GuestRepo as better iteration of idea)
Why
Directory of subrepo inside super-repo may have different name, than real basename of subrepo. This way you may have 1234567890123 as directory of subrepo, but .hgsub will show direct relation of 1234567890123 with `Acme Co.
How
Define non-trivial path for subrepo in .hgsub, like
1234567890123 = /PATH/TO/ACME


text:
Q: How to infer correct type when returning `payload is T` in typescript? I have a type guard check function that does tells JavaScript that a value is a promise or not, and at the same time it tells TypeScript that the variable is a promise:
function getType (payload: any): string {
  return Object.prototype.toString.call(payload).slice(8, -1)
}

function isPromise (payload: any): payload is Promise<any> {
  return getType(payload) === 'Promise'
}

It works really well, however, I realised I need to not hard code the promise resolve to any but infer that type instead.
This one example why I saw that any doesn't work properly:
export type PlainObject = { [key: string]: any }
let a: PlainObject | PlainObject[] | Promise<PlainObject | PlainObject[]>
let b = isPromise(a) ? await a : a

In this example, b is inferred as PlainObject while it SHOULD be PlainObject | PlainObject[]....
Question 1: Why is this happening?
My attempted solution at a better isPromise function:
type Unpacked<T> =
    T extends (infer U)[] ? U :
    T extends (...args: any[]) => infer U ? U :
    T extends Promise<infer U> ? U :
    T;

function isPromise2 <T extends any>(payload: T): payload is Promise<Unpacked<T>> {
  return getType(payload) === 'Promise'
}

In theory I don't see why this wouldn't work. But I get this error:

A type predicate's type must be assignable to its parameter's type.
    Type 'Promise>' is not assignable to type 'T'.
      'Promise>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'any'

Question 2: Why doesn't payload is Promise<Unpacked<T>> work and
how could I infer this otherwise?
Here is everything above in the TypeScript PlayGround:
https://www.typescriptlang.org/v2/en/play?#code/KYDwDg9gTgLgBDAnmYcAKAbAhgSwHYDyARgFbADG8AvHAN5wDaA1sIgFxwDOMU+A5gF0OWPIjgBfAFCSAZgFc8lHBDxw+wGABVkqABRgsiDBCwATYaICUHbrzx86kuHCga5UVcTKUAdGCgQMIE6PkEAyjz8PuRYGBj6hsZmlj6cGDjkwLoAHAA0cAC0AIyWkuLOztLyijDKqjicaAEAtg16BkYm5nAiiNZwHUmmcA3oLW0APL0AfI7OrjDuqupaOgmdyXBU23AA5E0QrZzAu2XSGBo9HJi4hKQU8AA+6Nj4Xg8MAnDPB0fAEzc3vdKN8Xrd3pRPtNJBd4EQtiNGuNjrosJY4AB+HoAd1w8CwcGE0gA9MS4NiABZYeAASRcwFiGDEuLw8CCcFMEERbEkSBQcAAqngDOQWKYJppZlQnBVNHBQDBgHhTJw4Lp8DJgFBBZZPpjBYSZc45QqlSq1T5LVgoHxOBZEJ90VRZhqtQasQLDRU4CaQIrlarfpNXdqBbMPV7ZQBuKoKJQqRFB44AJjgEvlfrNqpm6yGHE0-UGXURY0OkyFIrFEums1oMoWSzUGm0KFzXSdO32yJOZyAA

A:
1: Why is this happening?

PlainObject[] is a subtype of PlainObject. In set theory, when you have  a union Subtype | Supertype, then the resulting type will be Supertype - it absorbs Subtype. So b gets type PlainObject  here.
Why is PlainObject[] a subtype? It gets clearer, when we look at  Array and PlainObject types:
interface Array<T> { [n: number]: T} // T is PlainObject for PlainObject[]
type PlainObject = { [key: string]: any }

In JS, number property key will become string. And no matter what T is, it  is assignable to any.
type PlainObjArr_extends_PlainObj  = PlainObject[] extends PlainObject ? true : false // true

2: Why doesn't payload is Promise> work and how could I infer this otherwise?

For custom type guards, the type predicate (is xxx) must be a subtype of the checked argument. TS cannot verify here, that Promise<Unpacked<T>> is a subtype of T. Neglecting that fact, isPromise does its job filtering out all incompatible values of a:
let b = isPromise(a) ? await a /*Promise<PObj | PObj[]>*/ : a /*PObj | PObj[]*/

any - as often - is the evil one :o). A solution is to make PlainObject[] incompatible to PlainObject:
export type PlainObject = { [key: string]: unknown } // e.g. replace `any` by `unknown`
let b = isPromise(a) ? await a : a  // b: PlainObject | PlainObject[]


text:
Q: Corrupted image in tkinter asksaveasfile I tried to make a pop-up save qr code image window using asksaveasfile, but it gives me a corrupted image file.
This is what happens if you open it
My code:
root = Tk()

root.geometry("400x350")

root.title("QR Code Generator")

label = Label(text="QR Code Generator", fg="black", font="NexaHeavy")

label.pack(pady=20)

link_entry = Entry()
link_entry.insert(0, 'Link')
link_entry.pack(pady=50)

name_entry = Entry()
name_entry.insert(0, 'QR Code name')
name_entry.pack(pady=50)

def savefile():
    asksaveasfile(defaultextension='*.jpg', filetypes=[
        ("All types", '.*'),
        ("JPG File", ".jpg")
    ])

# Generate QR Code
def make():
    qr_code = qrcode.make(link_entry.get())
    qr_codename = (f"{name_entry.get()}.png")
    qr_code.save(qr_codename, savefile())

make_button = Button(text="Make QR Code", command=make)
make_button.pack(pady=1)

root.mainloop()

A: If you want to use asksaveasfile() to select the output filename, you should not construct the filename using qr_codename = (f"{name_entry.get()}.png"):
def savefile():
    # return the selected file object
    return asksaveasfile(defaultextension='*.jpg', filetypes=[
        ("All types", '.*'),
        ("JPG File", ".jpg")
    ], mode="wb")  # must use binary mode for image data

# Generate QR Code
def make():
    qr_codename = savefile()
    if qr_codename:
        qr_code = qrcode.make(link_entry.get())
        qr_code.save(qr_codename)


text:
Q: Does ServiceStack.OrmLite Support Optimistic Concurrency I was surprised to find no documentation on the subject, does anyone know if OrmLite supports Optimistic Concurrency? Any documentation or example references would be most welcome.

A: That's not really up to OrmLite. It depends on the isolation level and your database setup.
Example:
using (var trans = Db.BeginTransaction(IsolationLevel.ReadCommitted) as SqlTransaction)
            {
                try
                {
                    //do something
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
            }
}

From MS SQL Sever Docs

READ COMMITTED
  Specifies that statements cannot read data that has
  been modified but not committed by other transactions. This prevents
  dirty reads. Data can be changed by other transactions between
  individual statements within the current transaction, resulting in
  nonrepeatable reads or phantom data. This option is the SQL Server
  default. The behavior of READ COMMITTED depends on the setting of the
  READ_COMMITTED_SNAPSHOT database option:
If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row
  versioning to present each statement with a transactionally consistent
  snapshot of the data as it existed at the start of the statement.
  Locks are not used to protect the data from updates by other
  transactions.

Alternatively, you can use BeginTransaction(IsolationLevel.Snapshot) and have optimistic concurrency in that you avoid locks, but SQL Server uses rowversion before committing to avoid modifying data that was modified outside the current transaction.
From other MS SQL Server docs:

Transactions running under snapshot isolation take an optimistic
  approach to data modification by acquiring locks on data before
  performing the modification only to enforce constraints. Otherwise,
  locks are not acquired on data until the data is to be modified. When
  a data row meets the update criteria, the snapshot transaction
  verifies that the data row has not been modified by a concurrent
  transaction that committed after the snapshot transaction began. If
  the data row has been modified outside of the snapshot transaction, an
  update conflict occurs and the snapshot transaction is terminated. The
  update conflict is handled by the Database Engine and there is no way
  to disable the update conflict detection.


text:
Q: Bootstrap template is not aligned to the middle I have got a little problem. I'm building a template with twitter-bootstrap and I got into these two problems. Here you can see my site:
http://jsfiddle.net/e9SGL/embedded/result/ - fullscreen
http://jsfiddle.net/e9SGL/ - small one with code
As you can see the site is not aligned to the center. It is aligned to the right by 5px from the center. I know that it's moved by padding: 5px; but I want to keep that padding because it looks weird without it.
The second problem is that text Mira's Koding. It is on top of #logo div. I want to make it on the bottom of the #logo div. Here is my code:
CSS to bootstrap and my CSS.
<link rel="stylesheet" href="css/wise.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap-responsive.css" type="display">

HTML

Mira's Koding

Home

My Work

Example 1

No need of long text here.

                Read more ››

Example 1

Lorem ipsum...

Author

 my@mail.com

wise.css
::selection {
    color:#1f7bac;
}
::-moz-selection {
    color:#1f7bac;
}
html, body {
    background-color: #ebeaea;
    overflow: auto;
}
#back {
    background-color: #ebeaea;
}
#logo {
    background-color: #1f7bac;
    border-left: 1px solid #1f7bac;
    border-right: 1px solid #1f7bac;
    height: 50px;
    font-size: 28px;
    padding: 5px;
    color: white;
}
#menu {
    background-color: #fff;
    border-left: 1px solid #1f7bac;
    border-right: 1px solid #1f7bac;
    border-bottom: 1px solid #1f7bac;
    padding: 5px;
    height: 20px;
    margin-bottom: 20px;
}
#content {
    background-color: white;
    border: 1px solid #1f7bac;
    padding: 5px;
}
.footer {
    height: 100px;
    background-color: #1f7bac;
    position:fixed;
    bottom:0;
    width: 100%;
}

bootstrap.css and bootstrap-responsive.css are not edited. It's default bootstrap CSS.
Thank you very much.

A: There are probably a number of ways to fix problem #1, but this one does the trick:
.row-fluid {
    width: auto;
}

As far as problem #2, I don't see a div with ID 'header', but it looks to me like you simply need to move #logo below #menu.
Edit: I see a div#head. Maybe that's what you meant. However, in Firefox #logo is below #head. Please clarify.
Edit again: You could do this:
#logo {position: relative;}
#logo > div {position: absolute; bottom: 0;}

Again, you have plenty of options.

A: Remove all confusion and unnecessary codes, just place
.container, .container-fluid {margin: 0 auto;}
This code will align your page to center.
Your second problem is very easy, just dive into css.
Hope it helps.


text:
Q: WireCloud redirect url with proxy Where can I manually set the redirect_uri that is part of the url parameters when clicking on sign in in the default WireCloud setup?
We want to show our platform to the internet and need to address our WireCloud server via our proxy. The problem now is, that not the proxy url gets used as redirect url but the internal server url. This leads to the error {"state": "eCUfYmpXnDV34IVR1P8Vtt2Ke8Xhoxtm", "error": "mismatching_redirect_uri"} (HTTP 400).

A: Add the following lines into the settings.py file:
USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

this will configure WireCloud to trust the following headers: X-Forwarded-Host, X-Forwarded-Port and X-Forwarded-Proto. These headers are usually provided by the proxy servers when calling the backend service.
If you prefer to no rely on these headers, you can set the specific values in the settings.py file using the following settings instead:
FORCE_PROTO = 'https'
FORCE_DOMAIN = 'my.domain.com'
FORCE_PORT = 8000


text:
Q: ios: Communicating between host and USB-Connected device Android provides "adb" as a mechanism for communicating between host and apps on a USB-connected device. This is useful for automation (e.g. execute some code on the device and collect the results). We need this capability for iOS. Does a similar mechanism exist for iOS?

A: Yes, there is a similar mechanism. The underlying technology/service is called usbmuxd. It is basically a multiplexing service that allows you to connect to your iOS device via USB using the TCP protocol. Apple uses this service for any communication between your iOS device and iTunes or Xcode, e.g., to install apps via iTunes.
If you want to leverage this mechanism, there is a library that provides a high level API for iOS. They have reverse engineered the whole protocol including things like remote debugging via lldb and app installation.
http://www.libimobiledevice.org
If you just want to sideload compiled binary bundles into your own app you might get away with using my library. It allows you transmit arbitrary data via USB to your app and supports both iOS and tvOS.
http://www.github.com/jensmeder/DarkLightning


text:
Q: Jquery Onclick functionality not working for div, as specific loaded after sometime For
Test
. Jquery click functionality is added in document.ready function . But editdiv loading in page dynamically with delay.
So when I click on the div. Function is not calling. By using timeout function is working fine.
I need a different approach to solve this functionality.

A: It is really difficult to understand whats going wrong from your question. What I guess is you are loading a specific div using Ajax or similar technologies - meaning the div is not available initially.
The way jQuery works is that, it only binds the event to the elements only available at the time the part is executed.
If a

 is not present when $('#myDiv').click(function(){}) is called, it won't work.
One workaround is to do it like this:
$('body').on('click','#myDiv',function(){});

This registers the click on body and then checks if the clicked element is having a id 'myDiv' or not. We can expect the  to be present always. So the problem we had with previous code won't happen here.

A: If your .editdiv is loaded dynamically after your js loading so your click event can't detect it and it will not work, instead you should use event delegation on() to deal with fresh DOM :
$('body').on('click', '.editdiv', function(){
    //Your click event code
})

If you want to avoid setTimeout you could use delay with queue callback method :
$('div.scroll-area-blue')
    .delay(5000)
    .queue(function() {
        $(this).enscroll({
             showOnHover: false,
             verticalScrolling: true,
             verticalTrackClass: 'vertical-track-blue',
             verticalHandleClass: 'vertical-handle-blue'
        });
    });

If you will use setTimeout better to use it like :
setTimeout( enscrollDiv, 5000);

function enscrollDiv(){
    $('div.scroll-area-blue').enscroll({
         showOnHover: false,
         verticalScrolling: true,
         verticalTrackClass: 'vertical-track-blue',
         verticalHandleClass: 'vertical-handle-blue'
    });
}

Hope this helps.

A: maybe you're loading the javascript codes before the html elements(tags) are loaded.
try adding the script which includes "document.ready()" before the end tag of the body when all html tags have already finished loading.
I'm hitting targets in the dark. Hope it works for you. It's difficult to generate any solution without analyzing the problematic code......


text:
Q: Why is my array not being populated? Ok, I'm a bit out of my league but here goes... I'm working on making some updates to an iPhone app for a client (it hasn't been updated since 2013...just to put into context how old the programming is). While making simple updates to the app, I noticed the twitter feed section kept crashing. I checked the debug and came up with this error.
[_NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array

I know the array is empty... I'm just not sure why. Here's the code where I think it is filling the array
- (void)loadData {
NSURL *tutorialsUrl = [NSURL URLWithString:@"https://twitter.com/EdwinOrange/lists/kentucky-general-assembly"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];

TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:tutorialsHtmlData];

NSString *tutorialsXpathQueryString = @"//p[@class='TweetTextSize js-tweet-text tweet-text']";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];

NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in tutorialsNodes) {

    NSString *strResponse = @"";

    for (int l=0; l<[[element children] count]; l++)
    {

            strResponse =[strResponse stringByAppendingString:[[[element children] objectAtIndex:l]  content]];

        NSArray *_children = [[[element children] objectAtIndex:l]  children];

        NSLog(@"count = %d",[_children count]);

        for (int k=0; k<[_children count]; k++)
        {
            NSLog(@"%@",[[_children objectAtIndex:k] children]);
            NSArray *_internalChildren = [[_children objectAtIndex:k] children];

            for (int j=0; j<[_internalChildren count]; j++)
            {
                NSLog(@"%@",[[_internalChildren objectAtIndex:j] content]);
                strResponse = [strResponse stringByAppendingFormat:@"%@",[[_internalChildren objectAtIndex:j] content]];
            }

        }

    }

    Tutorial *tutorial = [[Tutorial alloc] init];
    [newTutorials addObject:tutorial];

    tutorial.title = strResponse;

   NSLog(@"strResponse = %@",strResponse);

    NSLog(@"Data---%@",tutorial.title);

}
_data = newTutorials;

delegateObj.arrDetailContent = [_data mutableCopy];

}

It might also we worth it to note the Log does not return any information for the above code. I added an exception breakpoint which breaks at this line (because the _data array is empty)
 Tutorial *data = [_data objectAtIndex:indexPath.row];

This may also help to track down the problem (this is at the top of the TwitterController.m)
#pragma mark - Calling Twitter feeds

-(void)getAndParseTwitterFeeds
{
[self loadAtData];
[self loadNames];
[self loadData];

[self loadImages];
[self loadHours];

[self loadLink];
[self loadImages];
[self loadHours];
}

-(void)getFeeds
{
 [self getAndParseTwitterFeeds];
}

-(void)getFeedsLocally
{
_link = delegateObj.arrTwitterLink;
_objects = delegateObj.arrObjects;
_members = delegateObj.arrMemberName;
_data = delegateObj.arrDetailContent;
arrProfileImages = delegateObj.arrImages;
_hours = delegateObj.arrHour;

[self updateTableViewWithTheData];
}

Hope that is enough explanation... I'm really hoping someone can help me figure out why the array is not being filled. Thanks!!!!
EDIT: I'm starting to wonder now if the HTML parser is having trouble with images in tweets. This code is from around 2013 which pre-dates twitter's inline images. Could this be causing the array to return empty?
Also of note the arrays _link, _members, _hours, etc. are all being populated correctly and have identical coding up until the "NSString *strResponse" section for loadData.


text:
Q: SwipeRefreshLayout animation frozen I am trying to use swipe refresh layout to update some data.
All works fine but a small bug that I can't seem to solve
When I pull to refresh, the animation gets frozen.
I have implemented it this way:
myRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        // Do some stuff
        // Sleep as a demonstrator of the issue
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myRefreshLayout.setRefreshing(false);
    }
});

and also tried this:
myRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        myRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                // Do some stuff
                // Sleep as a demonstrator of the issue
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }
});

but the animation remains frozen until the everything is done, and then it just vanishes (because it hits the setRefreshing(false))
After searching a little, I thought it could be the UI that is waiting for the stuff to finish, so I tried to implement it this way:
myRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // Do some stuff
                    // Sleep as a demonstrator of the issue
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myRefreshLayout.setRefreshing(false);
                        }
                    });
                }
            });
        }
    });
}

What happens in this case is that the refresh indicator never vanishes, so I guess it is not calling the runOnUiThread
I tried the same thing with the main looper (handler) instead of the runOnUiThread with the same effect.
Is there any neat way of implementing this?
Am I missing some detail?
I tried the steps described above and I also looked on Stack Overflow for similar issues to no avail.
Thanks!

A: It's right to do refreshing on background thread,and setRefreshing(false) on main thread. The problem is you forgot to call start() after new thread.
myRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // Do some stuff
                    // Sleep as a demonstrator of the issue
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myRefreshLayout.setRefreshing(false);
                        }
                    });
                }
            }).start();// start the thread here
        }
    });
}


text:
Q: How do I prevent iPhone from alerting twice when a text message arrives? How do I prevent the iPhone 5 from beeping twice when a text message arrives?
It beeps twice when there is a new message. I only want one notification. How do I have only one notification instead of two? It plays the notification sound, waits about 2 minutes, then plays it again if the phone is not touched. How do I turn double notification sounds off?

A: Settings App -> Notifications -> Messages -> Repeat Alerts
change that to "never."  :-)
Let me know if that helped...


text:
Q: How to parse data stored in child node of Zookeeper /hbase/region-in-transition? I'm trying to find out if any region is going through split by looking at
data in zookeeper.
I triggered a region split manually and captured the data from child Zookeeper
node /hbase/region-in-transition which corresponded to the region.
The data looks something like below
"ÿ^@^@^@^Tmaster:60000^R!¯^R<83><9d>^OJPBUF^H3^R4bar,,1526471941526.ac8b42de46021dcbf3d597326eb60de1.^X«<8f>Óƶ,"^V
        localhost^PôÔ^C^X÷<84>ÊŶ,*^@"

But whenever I tried to parse the above data using protobuf class ClusterStatusProtos.RegionInTransition , the parsing is failing.
Is there a way to parse this data somehow and determine if this corresponds
to a region in SPLIT or SPLITTING state?
Environment

*

*Hbase Version - 1.2.0

*Zookeeper - 3.4.8

A: This has been answered in hbase email thread

Hi,
Using the above clue I researched further to found out that I need to
  first use
  org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.removeMetaData(byte[]
  data) to remove the metadata and then org.apache.hadoop.hbase.
  RegionTransition.parseFrom(byte[] data)
Regards, Nand
On Fri, May 18, 2018 at 2:34 PM, Balazs Meszaros <
  balazs.meszaros@cloudera.com> wrote:

Hi,
HBase parses the binary data in region-in-transition ZooKeeper node with
    org.apache.hadoop.hbase.RegionTransition.parseFrom(byte[] data). It is in
    the hbase-client jar. These APIs are private, so use them carefully.
Best regards,
    Balazs
On Fri, May 18, 2018 at 5:49 AM Debraj Manna
    wrote:

Hi
We posted the same in stacker flow.
How to parse data stored in child node of Zookeeper /hbase/region-in-transition?
We didn't get any reply there also. Anyone any thoughts?
On Wed 16 May, 2018, 6:54 PM Nand kishor Bansal,
      wrote:

Hi Users,
I'm trying to find out if any region is going through split by looking
        at
        data in zookeeper.
I triggered a region split manually and captured the data from child ZK
        node /hbase/region-in-transition which corresponded to the region.
"ÿ^@^@^@^Tmaster:60000^R!¯^R<83><9d>^OJPBUF^H3^R4bar,,1526471941526.
        ac8b42de46021dcbf3d597326eb60de1.^X«<8f>Óƶ,"^V
                localhost^PôÔ^C^X÷<84>ÊŶ,*^@"
But when I tried to parse the above data using protobuf class
ClusterStatusProtos.RegionInTransition, it failed to parse.
Is there a way to parse this data somehow and determine it correspond
        to a region in SPLIT or SPLITTING state.
I am using HBase 1.2.0 and Zookeeper 3.4.8
Thanks,
Nand


text:
Q: editText icons won't color when that field is pressed I am trying to create a login activity with two fields - email and password. This is my activity XML where I implemented the 2 edit text labels. I want, when pressed, the icon from the edit text to change its color, but it seems that what I did doesn't work properly.
<EditText
        android:id="@+id/etLoginEmail"
        android:layout_width="375dp"
        android:layout_height="60dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="70dp"
        android:drawableStart="@drawable/custom_email_icon"
        android:drawablePadding="10dp"
        android:background="@drawable/custom_input"
        android:paddingStart="12dp"
        android:paddingEnd="12dp"
        android:hint="Email"
        android:inputType="text"
        android:textSize="24sp"
        android:fontFamily="@font/fredokamedium"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo" />

<EditText
        android:id="@+id/etLoginPass"
        android:layout_width="375dp"
        android:layout_height="60dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="40dp"
        android:drawableStart="@drawable/custom_lock_icon"
        android:drawablePadding="10dp"
        android:background="@drawable/custom_input"
        android:paddingStart="12dp"
        android:paddingEnd="12dp"
        android:hint="Password"
        android:inputType="textPassword"
        android:textSize="24sp"
        android:fontFamily="@font/fredokamedium"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etLoginEmail" />

This is what i did for the custom icon xml files
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"
        android:drawable="@drawable/ic_lock_focused"/>

    <item android:state_focused="false"
        android:drawable="@drawable/ic_lock"/>
</selector>

Does anyone know what the issue may be?
EditText-selected - shows border, but icon doesnt change color


text:
Q: Why do I need to update uvs? I'm working with the three.js editor where I parse an object from JSON format. As usual it first parses the materials and geometries, then I create meshes from it. While parsing materials I also load textures. The issue now is that I have to call...
object.geometry.uvsNeedUpdate = true;
object.geometry.buffersNeedUpdate = true;
... after the image for the texture completely loaded - but why?! The geometry never changed before, neither did its uvs or anything like it. It's still the plain old geometry, yet I always get a GL ERROR :GL_INVALID_OPERATION : glDrawElements: attempt to access out of range vertices in attribute 2 when trying to render. It only works with this "hack" although the geometry is always the same.
In my opinion it should also work perfectly when I update the uvs after object creation (or not at all). I didn't find anything in the three.js editor code that would update the geometry or its faceVertexUvs.
I know it's a bit of an abstract problem, I'm mainly looking for some hints or insights why this hack might be necessary.
Thanks!

A: Three.js "guesses" whether uvs are needed according to your used textures in bufferGuessUVType. If you want to preallocate uv buffers you can either init a map attribute with an empty THREE.Texture, update the geometry after the map was assigned, etc.


text:
Q: Can we observe an event that occurs more than 13.7 billion light years away? In Kurzgesagt's latest video about the largest black holes, the narrator says that two black holes have been observed orbiting each other at a distance of 17 billion light years from Earth. So light must take at least take 17 billion years to reach Earth.
But the universe is only about 13.7(or maybe 14) billion years old.
So, how is it possible that the black holes are 17 billion light years from Earth?
Video Link with time tag: 3:32

A: The easiest way to think about this (and without going into cosmology concepts such as the Hubble horizon) is that when the light was emitted, the black hole was not 17 billion light years away from Earth. They were closer. They are 17 billion light years away now because the universe has expanded while the light was travelling towards us.
You can calculate how much closer the black hole was when it emitted the light if you also know the relevant cosmological parameters such as the Hubble parameter. This will depend on the exact cosmological model you're using, such as how much matter/radiation/dark energy is in the universe - see the Hubble horizon article linked above.


text:
Q: Calculating the angle of a ring segment So, say I have a sector of a ring. I know the thickness of the ring (in the diagram lines BC, DF, and GE are all this thickness). I also know the width of the sector which is set by the length of the chord which defines the outer arc (DE). And I also know the height between the base of the sector (the chord of the inner arc) and the peak of the ring (the line BH). From this, is it possible to calculate either the radii of the inner and outer arcs, and/or the angle the sector encompasses (the angle DAE)?

Diagram of what I'm trying to explain and the points I refer to.
I hope that makes some sense as a question? Any help would be great, I've tried working it through with what little I know about the geometry of a circular segment, but it's been a while since I dusted off my algebra and unless I'm missing something obvious, I don't know if I'm even looking for the right stuff...
Thanks for any help :)

A: Yes, it is possible. Here is how.
Let us give the names $a,b,c$ to the measurements:
$$\begin{cases}a&:=&DE=CB=GE\\ b&:=&HB \\ c&:=&FG& \text{assumed measurable}\end{cases}\tag{1}$$
(I have prefered to take $FG$ instead of $DE$ because the explanations are simpler like this).
Let us denote by $R,r$ the outer and inner radii resp., and $\theta = \angle BAD \ \iff \ 2 \theta = \angle EAD$.
(1) yields:
$$\begin{cases}a&=&R-r\\ b&=&HB=HC+CB=AC-AH+CB=r-r \cos \theta +a \\ c&=&FH+HG=2 r \sin \theta\end{cases}$$
These 3 equations with three unknowns $R,r,\theta$ can be written in the following way :
$$\begin{cases}R-r&=&a&(i)\\ r(1-\cos \theta)&=&b-a&(ii) \\ 2 r \sin \theta&=&c&(iii)\end{cases}$$
In order to be able to extract in particular $\theta$, let us use classical trigonometry formulas on equations (ii) and (iii):
$$\begin{cases}2 r(\sin \tfrac{\theta}{2})^2&=&b-a \\ 4r \sin \tfrac{\theta}{2}\cos \tfrac{\theta}{2}&=&c\end{cases}$$
Taking their ratio, one gets:
$$\tfrac{1}{2}\tan \tfrac{\theta}{2}=\tfrac{(b-a)}{c} \ \iff \ \theta=2 \tan^{-1}\tfrac{2(b-a)}{c}$$
which is perfectly defined quantity.
Having $\theta$, one can compute the value of $r$, using equation (ii) above, and finally the value of $R$ using equation (i).
Remark: having preferred $DE$ to $FG$, it is important to recall that the connection between these two lengths is very simple:
$$\frac{DE}{FG}=\frac{R}{r}$$


text:
Q: Error while using svn2git for SVN to GIT migration I am getting below error when I tried to use svn2git command to import svn files
Running command: git svn init --prefix=svn/ --no-metadata --trunk=trunk --tags=tags --branches=branches https://svnserver.com/abc/svn/projectname
Running command: git svn fetch
Invalid filesystem revision number: svn: E160006: Invalid revision number '-1' a
t /mingw64/share/perl5/site_perl/Git/SVN.pm line 150.
command failed:
git svn fetch
I got the same error when I tried to check out using tortoise SVN client. Then I installed the client same as the SVN server version and the issue got resolved.
But when using svn2git, same error occurs? Is there any version compatibility issue? I am using SVN 1.7.9 and svn2git 2.3.2.

A: You are using an svn2git tool that uses git-svn under the hood.
For a one-time migration git-svn is not the right tool for conversions of repositories or parts of repositories. It is a great tool if you want to use Git as frontend for an existing SVN server, but for one-time conversions you should not use git-svn, but svn2git which is much more suited for this use-case.
There are plenty tools called svn2git, the probably best one is the KDE one from https://github.com/svn-all-fast-export/svn2git. I strongly recommend using that svn2git tool. It is the best I know available out there and it is very flexible in what you can do with its rules files.
You will be easily able to configure svn2gits rule file to produce the result you want from your current SVN layout, including any complex histories that might exist and including producing several Git repos out of one SVN repo or combining different SVN repos into one Git repo cleanly.
If you are not 100% about the history of your repository, svneverever from http://blog.hartwork.org/?p=763 is a great tool to investigate the history of an SVN repository when migrating it to Git.

Even though git-svn (or the svn2git you used) is easier to start with, here are some further reasons why using the KDE svn2git instead of git-svn is superior, besides its flexibility:

*

*the history is rebuilt much better and cleaner by svn2git (if the correct one is used), this is especially the case for more complex histories with branches and merges and so on

*the tags are real tags and not branches in Git

*with git-svn the tags contain an extra empty commit which also makes them not part of the branches, so a normal fetch will not get them until you give --tags to the command as by default only tags pointing to fetched branches are fetched also. With the proper svn2git tags are where they belong

*if you changed layout in SVN you can easily configure this with svn2git, with git-svn you will loose history eventually

*with svn2git you can also split one SVN repository into multiple Git repositories easily

*or combine multiple SVN repositories in the same SVN root into one Git repository easily

*the conversion is a gazillion times faster with the correct svn2git than with git-svn
You see, there are many reasons why git-svn is worse and the KDE svn2git is superior. :-)


text:
Q: vscode vim extension doesn't work with other languages (e.g. Spanish) So I have installed vim extension for VSCode and I really like it, but when I switch my language from English to any other language extension stops working. When I switch back to English it works again. I use ubuntu btw

A: That's just the way the Vim extension is built - it can't support any other languages (perhaps for technical reasons).
You can, however, make a suggestion or a GitHub Issue for a feature request.


text:
Q: Get Popular words in PHP+MySQL How do I go about getting the most popular words from multiple content tables in PHP/MySQL.
For example, I have a table forum_post with forum post; this contains a subject and content.
Besides these I have multiple other tables with different fields which could also contain content to be analysed.
I would probably myself go fetch all the content, strip (possible) html explode the string on spaces. remove quotes and comma's etc. and just count the words which are not common by saving an array whilst running through all the words.
My main question is if someone knows of a method which might be easier or faster.
I couldn't seem to find any helpful answers about this it might be the wrong search patterns.

A: Somebody's already done it.
The magic you're looking for is a php function called str_word_count().
In my example code below, if you get a lot of extraneous words from this you'll need to write custom stripping to remove them. Additionally you'll want to strip all of the html tags from the words and other characters as well.
I use something similar to this for keyword generation (obviously that code is proprietary). In short we're taking provided text, we're checking the word frequency and if the words come up in order we're sorting them in an array based on priority. So the most frequent words will be first in the output. We're not counting words that only occur once.
<?php
$text = "your text.";

//Setup the array for storing word counts
$freqData = array();
foreach( str_word_count( $text, 1 ) as $words ){
// For each word found in the frequency table, increment its value by one
array_key_exists( $words, $freqData ) ? $freqData[ $words ]++ : $freqData[ $words ] = 1;
}

$list = '';
arsort($freqData);
foreach ($freqData as $word=>$count){
    if ($count > 2){
        $list .= "$word ";
    }
}
if (empty($list)){
    $list = "Not enough duplicate words for popularity contest.";
}
echo $list;
?>

A: I see you've accepted an answer, but I want to give you an alternative that might be more flexible in a sense: (Decide for yourself :-)) I've not tested the code, but I think you get the picture. $dbh is a PDO connection object. It's then  up to you what you want to do with the resulting $words array.
<?php
$words = array();

$tableName = 'party'; //The name of the table
countWordsFromTable($words, $tableName)

$tableName = 'party2'; //The name of the table
countWordsFromTable($words, $tableName)

//Example output array:
/*
$words['word'][0] = 'happy'; //Happy from table party
$words['wordcount'][0] = 5;
$words['word'][1] = 'bulldog'; //Bulldog from table party2
$words['wordcount'][1] = 15;
$words['word'][2] = 'pokerface'; //Pokerface from table party2
$words['wordcount'][2] = 2;
*/

$maxValues = array_keys($words, max($words)); //Get all keys with indexes of max values     of $words-array
$popularIndex = $maxValues[0]; //Get only one value...
$mostPopularWord = $words[$popularIndex];

function countWordsFromTable(&$words, $tableName) {

    //Get all fields from specific table
    $q = $dbh->prepare("DESCRIBE :tableName");
    $q->execute(array(':tableName' = > $tableName));
    $tableFields = $q->fetchAll(PDO::FETCH_COLUMN);

    //Go through all fields and store count of words and their content in array $words
    foreach($tableFields as $dbCol) {

        $wordCountQuery = "SELECT :dbCol as word, LENGTH(:dbCol) - LENGTH(REPLACE(:dbCol, ' ', ''))+1 AS wordcount FROM :tableName"; //Get count and the content of words from every column in db
        $q = $dbh->prepare($wordCountQuery);
        $q->execute(array(':dbCol' = > $dbCol));
        $wrds = $q->fetchAll(PDO::FETCH_ASSOC);

        //Add result to array $words
        foreach($wrds as $w) {
            $words['word'][] = $w['word'];
            $words['wordcount'][] = $w['wordcount'];
        }

    }
}
?>


text:
Q: Bundle install killed message? I run bundle install on server machine - digital ocean and it is always gets killed like this:
RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too,
you can ignore these warnings with 'rvm rvmrc warning ignore /home/rails/car_main/Gemfile'.
To ignore the warning for all files run 'rvm rvmrc warning ignore allGemfiles'.

Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle as
root will break this application for all non-root users on this machine.
Fetching gem metadata from https://rubygems.org/.........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies...
Using rake 10.5.0
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.8.4
Using thread_safe 0.3.5
Using tzinfo 1.2.2
Using activesupport 4.2.0
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile2 2.0.0
Killed

What do I do?

A: I had a similar issue while using DigitalOcean and was resolved by increasing the RAM to 1GB from 512MB.
Alternatively you could create a swap file too, but I chose to increase the RAM.

A: In my case it was caused by RAM shortage.
to make sure this is the problem:
open htop while bundle is running to see if memory usage goes to 100%
to fix this do one of the following:
A. get more RAM or swap as +haris suggested
B. see what eats your machine RAM and close some services (in my case I was trying to update a service while it was running, and the 2GB machine had not enough RAM to run those two at the same time)


text:
Q: Game class diagram I have a problem with taking a class diagram for a game.
The world in which the game takes place, can be represented by fields. Each
field is identified by the coordinates x and y. The field may be convenient to
establish a settlement or not. If there is a settlement on the field, the only
one. Each field is linked to a landscape as a bitmap. In some fields, there
may be resources (eg coal, ore), or other artifacts which are not proprietary.
Each player is the ruler of a principality. May belong to the Duchy of many
settlements. The Principality of nationality and citizenship designates
settlements truck. The settlers are citizens of the duchy through belonging
to one of the settlements of the principality. The settlement may, however,
live in different nations, whose nationality does not coincide with
citizenship. Individual nations living in village characterized by loyalty to
the principality, which owns the village. For the settlers imposed a head tax,
which every week has to be diverted to the principality. Taxes feed the
treasury of the duchy. Too high taxes lowers the morale of the settlers.
Collected funds for in importance to the maintenance of buildings and
armies.
In the villages you can put different types of buildings. Some of them can be
built only a single copy of each settlement (eg, ditch), others in larger
quantities (eg, plant furrier). To the sediment was in the building, part of
the settlers must work as a builder of a specified number of hours and must be
available appropriate products and raw materials for their construction. ¬
precipitate diameter of each day may work in other occupations (such as
armorer, scouts). To the settlers could carry out their jobs, usually the
appropriate buildings are required (such as a forge, sawmill). Most workers
provide artifacts - manufactures products (eg, a blacksmith, a farmer) or
producing natural resources (eg, a miner, a lumberjack). Manufacture of the
product may be needed for some artifacts. Then, post workers, who by the
requisite number of hours will work in production. The artifact,
which was created as a result of the settlers, is a product. For the most
backwards area of the product to be Armor (eg, sword, chain mail) and food
(eg bread, meat). The most important type of artifact that is not a product is
a natural resource. To the pellet could be stored in the artifact more,
you must build a warehouse.
I'm not even asking about all the task - i know it is large and time spending.
I just would like to hear some suggestions, what to put as abstract class, what to put as interface here. What class should have operations to build a building?
Thanks in advance for any your idea, event single sentence!

A: You actually have a pretty good start at an analysis model. An analysis model should represent the domain, which in this case is the world of your game. If you convert the nouns into classes and the verbs you already have into association-end properties, a first version of your analysis model will fall out. (But, make sure the classes are singular, not plural.) One way to do this conversion is to make a bullet list of natural-language sentences, in both directions, such as:

*

*Game represented by [one or more] Fields

*Field represents [one] Game

*Field identified by [one] Coordinate

*Coordinate identifies [one] Field

*Settlement contained in [zero or one] Field

*Field contains [zero or one] Settlement

*. . .

(I think it may be premature for you to take on superclasses, abstract classes, and interfaces since you're asking about the basics here. Please ask another more specific question after you have more experience under your belt.)
You can then convert the association-end-property names into participial phrases to look more normal in your target OO language, while still retaining semantics. These participial phrases tell the reader of your code the purpose of the association, as well as disambiguate multiple associations between two classes for different purposes.  Here are some examples of what I mean by participial phrases (i.e., verb phrases used as adjectives), used as role names:

*

*|Game| -representedGame-----representingField- |Field|

*|Field| -identifiedField-----identifyingCoordinate- |Coordinate|

*|Settlement| -containedSettlement----containingField- |Field|

*. . .

At this point, make a list of verbs, representing the things you want your classes to accomplish. These are your operations. Sometimes it is obvious which class should be responsible for an operation; other times you have to anthropomorphize.
Now, code methods for those operations using graphical and I/O libraries, and you have yourself a game!
For more information, I highly recommend you read Leon Starr's How to Build Articulate UML Models article or H. S. Lahman's book, Model-Based Development: Applications.


text:
Q: $stateChangeStart - State-change not prevented If a user without authorization tries to access a restricted state, the restricted state loades before he is sent back by $state.go(fromState.name). It seems like the event.preventDefault(); doesn't fire?
$rootScope.$on('$stateChangeStart',
               function (event, toState, toParams, fromState, fromParams) {

    if (toState.name == 'app.admin' || toState.name == 'app.bonus') {
        AuthService.isAuthenticated().then(function (response) {
            if (!response) {
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
            } else {
                event.preventDefault();
                if ('data' in toState && 'authorizedRoles' in toState.data) {
                    var authorizedRoles = toState.data.authorizedRoles;
                    if (!AuthService.isAuthorized(authorizedRoles)) {
                        $state.go(fromState.name, {}, {
                            reload: true
                        });
                        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
                    }
                }
            }
        }, function () {
            event.preventDefault();
            $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
        });
    }
});

A: You're calling event.preventDefault() from an asynchronous callback. So, at the time it's called, the event listener function has already returned, and since the event hasn't been prevented, the router has navigated to the next state.
It would work if you did
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if ((toState.name == 'app.admin' || toState.name == 'app.bonus')
        && !AuthService.isAuthenticated()) {
        event.preventDefault();
    }
}

But of course, that means your service needs to return a boolean synchronously, rather than a promise.


text:
Q: SQL Server : exclude table from transaction Is it possible to exclude a complete table from a transaction?
The background is that we have a table which is used as a Next-ID table, so for every other table in the database there is a record in the table which has got the information which ID to use for the next record.
If we start a transaction and this one blocks on record another user can´t use the Next-ID table as it is still blocked.
So it would be nice if the table Next-ID is not blocked during a transaction. If the NextID is 1509 or 1510 or 1984 does not matter at all.
Kind regards
Markus


text:
Q: Bash compare an input array and a text file and update the file I have read in a string, split it based on delimiter and store it into an array. I want to iterate through a text file and delete the lines that do not contain the strings I stored in the array. Say my resulting array is  ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
and my text file is:

foo
grault
bar
xyzzy
baz
quz
quux

I want to delete the line grault, xyzzy (because they are not in the array) and add corge at the end so my resulting file would be:

foo
bar
baz
quz
quux
corge

I am planning to use a for loop to iterate through my array and use grep to add the lines that are missing from the file, but how should I delete the lines that do not exist in the array but exist in the file?

A: Let's define the list of approved words:
$ words='foo bar baz qux quux corge'

Now, let's remove from file any word that is not in words:
$ awk -v s="$words" 'BEGIN{split(s,a,/ /); for (i in a) b[a[i]]} ($0 in b){b[$0]++;print}' file
foo
bar
baz
quux

If we want to remove any word not in words and also add the end any word in words that was not in file, then:
$ awk -v s="$words" 'BEGIN{split(s,a,/ /); for (i in a) b[a[i]]} ($0 in b){b[$0]++;print} END{for (w in b) if (b[w]==0) print w}' file
foo
bar
baz
quux
corge
qux

How it works

*

*-v s="$words"
This defines an awk variable s which has the contents of the shell variable words.

*BEGIN{split(s,a,/ /); for (i in a) b[a[i]]}
Before we read file, this splits up the words in s into an array a whose values are those words.  Then, we create an associative array b with one key for each of the words.

*($0 in b){b[$0]++;print}
As we read through file, if the line matches a word in b, then increment the count of the number of times that that word has appeared and also print the word.

*END{for (w in b) if (b[w]==0) print w}
After we have finished reading the file, if any word in array b was not printed, that is its count b[w] is still zero, then print it.

A: If your original stuff is in a nice file like the second one you can just do
(grep -f <good list> <bad list>; echo 'corge')

to get the right list otherwise you could try
(grep -f <(printf '%s\n' "${array[@]}") <bad file>; echo 'corge')

which will use process substitution to make your array be like a file that grep could use to search the file for you
This will give you only the lines that are in your word list from the original file, plus corge that you had identified.  If you just want the other file to match the word list though you could probably skip all the line matching and just write your array to the file.


text:
Q: Como cargar una Imagen en delphi salvada desde c# tengo una aplicacion en .net mvc y estoy tratando de guardar una imagen en un campo de la Base de datos, esto lo hace bien, el problema es que esta imagen posteriormente sera leida desde una aplicacion hecha en delphi, aqui en delphi usan blobfield, cuando la guardo en delphi sale la imagen negra completa, sin embargo si se crea de delphi y la leo desde la aplicacion .net mvc lo lee perfectamente:
Desde javascript creo el base64 de la imagen de esta forma:
var dataURL = canvas.toDataURL("image/png");
val = dataURL.replace(/^data:image\/(png|jpg);base64,/,"");

en c# obtengo el base64 y obtengo el array bytes para insertarlo en la BD
byte[] imageBytes = Convert.FromBase64String(base64);

como pudiera ayudarme con esto si alguien le ha pasado alguna vez.


text:
Q: Using ng-if on a parent element depending on src of img I am showing and image within a  as follows:

I want to remove the  if my image is using the fallback-src. My fallback-src directive is:
 angular.module('myApp').directive('fallbackSrc', function () {
   var fallbackSrc = {
     link: function postLink(scope, iElement, iAttrs) {
       iElement.bind('error', function () {
         angular.element(this).attr("src", iAttrs.fallbackSrc);
       });
     }
   }
   return fallbackSrc;
 });

{{logo_src}} returns a string of the image URL from an API so it's up to the browser to find the image or throw a 404, so that's why I have a fallbackSRC directive. The issue now is that I want to remove the parent
 (which I need when there is an image) when we are using the fallback-src.
What ng-if expression do I need to detect if the img src is using the fallback-src?

A: Assuming your directive uses fallback source when the logo_src variable is not available, use

This code means that when logo_src is available, the div is rendered.
I think you will need to change your directive to hide the image if src is equal to the value of fallbackSrc. I can't think of a way for the ngIf to figure out both the src and the fallbackSrc to do a comparison. The ngIf above hides the logo-wrap only if there is no value on the logo-src variable.
If you want to hide the directive if there is a 404 error, your html code will need to change a bit like so...

and your directive...
angular.module('myApp').directive('fallbackSrc', function () {
  var fallbackSrc = {
    link: function postLink(scope, iElement, iAttrs) {
      // Remember to remove the class hidden if the image src changes.
      iElement.bind('error', function () {
        angular.element(this).attr("src", iAttrs.fallbackSrc).parent().toggleClass("hidden", true);
      });
    }
  }
   return fallbackSrc;
});

css for hidden class...
.hidden {
    display: none;
}

I'll admit, this solution doesn't solve the problem in the way you want, i.e. doesn't remove the div but I believe it achieves the same result.


text:
Q: How do I craft Crossbow Bolts? I joined the dawn-guard and then I became a vampire. I love to use my crossbow but I don't have any more bolts. I tried to craft them but I couldn't so I upgraded my smithing.  However, they still don't show up in the smithing menu.
How can I make bolts?

A: To be able to smith crossbow bolts, you must first finish the Ancient Technology quest. To start this quest, A New Order must be completed, and you must talk to Sorine Jurard.

A: Step 1
Complete the quest A New Order.
Step 2
Make sure you have the Steel Smithing perk & talk to Sorine Jurard.  She should train you in constructing a basic crossbow & steel bolts.
Step 3
Locate Gunmar's Forge, you'll need it to craft most crossbow & bolt recipes in much the same way as the Skyforge is required for Nord Hero gear.
You can now start making bolts
Step 4 (Optional)
Complete an Ancient Technology quest for Sorine.  Your reward will be plans for either an improved crossbow or exploding bolts.  When you start getting plans for dwarven gear, get the Dwarven Smithing perk if you don't already and you plan on using them.
Repeat Step 4 until you have common & enhanced crossbow recipes and common & 3 elemental bolt recipes, all in both steel & dwarven varieties.

A: You can not craft crossbows or bolts if you have gone the vampire route in the dawngaurd dlc. The quests everyone is mentioning and sorrine are only if you go dawngaurd and refuse Harkins gift of becoming a vampire lord.


text:
Q: $ (1*...*1)(n) =\# \{(m_1,...,m_k)\in (\mathbb{N}\setminus \{0\})^k : m_1...m_k = n\} $ We call an arithmetic function any element of $\mathcal{F} (\mathbb{N}\setminus \{0\} , \mathbb{C})$. We endow $\mathcal{F} (\mathbb{N} \setminus \{0\}, \mathbb{C})$ binary operation convolution and defined by $(f*g) (n): = \sum_{d|n}{f (d) g (n/d)}$ that is commutative and associative.
We consider the function $\tau_k \in \mathcal{F} (\mathbb{N}\setminus \{0\} , \mathbb{C})$ defined by $$\tau_k = \underbrace{1*...*1}_{k \text{ times}}$$ where $1\in  \mathcal{F} (\mathbb{N}\setminus \{0\}, \mathbb{C})$ denotes the constant function being equal to $1$. When $n \in \mathbb{N}\setminus \{0\} $,
I see if $k=1$ (resp, $2$) then $\tau_1(n)=1$ (resp, $\tau_2(n)= \# \{\text{ divisor of n}\}$)
My problem why, for $k\geq 2$:
$$
\tau_k(n) =\# \{(m_1,...,m_k)\in (\mathbb{N}\setminus \{0\})^k : m_1...m_k = n\}
$$

A: Assume $\tau_k(n) = \# \{(m_1 , \dots , m_k) \in \mathbb{Z}_+^k | m_1 \dots m_k = n \} $
Then
\begin{align*}
 (\tau_k \ast 1 )(n) & = \sum_{d |n} \# \{(m_1 , \dots , m_{k}) \in \mathbb{Z}_+^{k} | m_1 \dots m_{k} = \frac{n}{d} \} \\
& = \sum_{d |n} \# \{(m_1 , \dots , m_{k}) \in \mathbb{Z}_+^{k} | m_1 \dots m_{k}d = n \} \\
& =  \# \{(m_1 , \dots , m_{k},d) \in \mathbb{Z}_+^{k+1} | m_1 \dots m_{k}d = n \} \\ & = \tau_{k+1}(n)
\end{align*}


text:
Q: A quick question on graphing Heaviside functions I'm trying to graph the function $f(t) = \sin(2(t-\pi))\mathcal{U}(t-\pi)$, where $\mathcal{U}$ is the Heaviside function defined by:
$\mathcal{U}(t-a) = \begin{cases} 0 &\mbox{} t \lt a \\
1 & \mbox{} t \geq a \end{cases}$
I know that $\sin(2(t-\pi))=\sin(2t)$, so I figured $f$ is just a piecewise function that looks like
$f(t) = \begin{cases} 0 &\mbox{} t \lt \pi \\
\sin(2t)& \mbox{} t \geq \pi \end{cases}$
So then $f(t) = \sin(2(t-\pi))\mathcal{U}(t-\pi)$ would simply be the graph of $\sin(2t)$ after $t=\pi$ and $0$ everywhere else? I feel as though I am simplifying this too much.


text:
Q: Navigate between html files I have two html file index.html  and test.html and I want to navigate from index to test when pressing a button.
I tried this but it is not working well .
function change_page(){
   console.log("change_page");
   $('body').load( "test.html");
}

<input type="button" value="create page" onclick="change_page();"/>

If you know some better way, please tell me.

A: function change_page(){
  window.location.href = "test.html";
}

<input type="button" value="create page" onclick="change_page()"/>

A: Solutions:
1: Use an anchor tag to switch between the pages
2. If you really want to use Javascript you can do this
function change_page(){
   // similar behavior as an HTTP redirect
   window.location.replace("test.html");
   //or
   // similar behavior as clicking on a link
   window.location.href = "test.html";
};

A: You can use anchor tag href attribute to navigate another page like
 Test Page

OR
You can try this
 <input type="button" value="create page" onclick="location.href='test.html'"/>


text:
Q: Erro :non-static method set(int,int) na MainActivity Estava copilando os códigos quando cheguei no final e deparei com erros na  MainActivity, estou usando API 16,alguém me ajuda ?

**código **
 import android.app.AlarmManager;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.TaskStackBuilder;
 import android.content.Context;
 import android.content.Intent;
 import android.icu.util.Calendar;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.support.v7.app.NotificationCompat;
 import android.view.View;

 public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){
        @Override
        public void  onClick(View view){

            Calendar calendar = Calendar.getInstance();

            Calendar.set(Calendar.HOUR_OF_DAY,18);
            Calendar.set(Calendar.MINUTE,45);
            Calendar.set(Calendar.SECOND,00);

            Intent intent = new Intent(getApplicationContext(),Notification_reciever.class);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
        }
    });
   }
 }

A: O problema começa no import que não está correto. No topo o Calendar está a ser importado com :
import android.icu.util.Calendar;

Quando o código que está a ser utilizado do Calendar refere-re a biblioteca standard do java em java.util. Logo o import citado acima devia ser trocado por:
import java.util.Calendar;

Para além disso a inicialização/utilização do Calendar:
Calendar calendar = Calendar.getInstance();

Calendar.set(Calendar.HOUR_OF_DAY,18);
Calendar.set(Calendar.MINUTE,45);
Calendar.set(Calendar.SECOND,00);

Não está correta também. Repare que o Calendar.set está a ser feito com inicial maiúscula, logo refere a classe Calendar e não o objeto calendar criado acima que era o que se pretendia.
Troque este bloco de código por:
Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY,18);
calendar.set(Calendar.MINUTE,45);
calendar.set(Calendar.SECOND,00);


text:
Q: How can I slow down the time between animations? I'm trying to slow down the time between animations in my cycle.
I've tried increasing the animation time for my keyframes, but that didn't work.
    span {
     animation: rotateWordsFirst 15s linear infinite 0s;

      &:nth-child(2) {
        animation-delay: 5s;
        }

        &:nth-child(3) {
        animation-delay: 10s;
             }

        &:nth-child(4) {
        animation-delay: 15s;
        }
    }

@keyframes rotateWordsFirst {
     0% { opacity: 0; }
    2% { opacity: 0; -webkit-transform: translateY(-30px); }
    5% { opacity: 1; -webkit-transform: translateY(0px);}
    17% { opacity: 1; -webkit-transform: translateY(0px); }
    20% { opacity: 0; -webkit-transform: translateY(30px); }
    80% { opacity: 0; }
    100% { opacity: 0; }
}

I was hoping to keep the text visible for a longer period of time between animations, but everything I've tried seems to throw off my animation cycle.
I've been using this tutorial:
http://www.css3transition.com/rotating-words-css-animations/

A: I stumbled upon a similar problem when making a semi complex city animation with cars, planes and trains moving all at the same time.
I then came across this article from Chris Coyier:
https://css-tricks.com/css-keyframe-animation-delay-iterations/

here is an animation-delay property, but that won't help us here. That delays the start of the animation, but after it's started it runs continuously.

So, what he suggests, similar to what ChrisW was trying to explain, is to include the delays into your keyframe logic:
EXAMPLE
My original animation lasts 4 seconds, I want it to run infinitely but with a delay of 1s at end. This means I have to add the delay to the total animation time, in this case, 4s + 1s = 5s. Apply the following changes:
.your-element {
  animation: name-of-your-animation 5s infinite;
}

Now, for the keyframes, let us assume we had something like this:
@keyframes name-of-your-animation {
  0% {
    //do something
  }
  25% {
    // do something
  }
  50% {
    //do something
  }
  75% {
    //do something
  }
  100% {
   // do something
  }
}

We need to factor in the 1s delay at the end, so our animation must take place in 4s out of 5s, in other words, 4/5th's of the animation or 80% of the 100%:
@keyframes name-of-your-animation {
  0% {
    //do something
  }
  50% {
    // do something
    opacity:0.5;
  }
  /* Finish changes by here, as an example, let's think of moving opacity from 0 to 1, gradually or not */
  79% {
    opacity:1;
  }
  /* Between 80% and 100%, nothing changes, so the 'end state' is repeated */
  80%, 100% {
   // do something
   opacity:1;
  }
}

Give it a try and let us know if you need additional help.
Cheers
G


text:
Q: How to implement the on change value on switch component in react native using native base & navigation 5 I have problem on changing the value of switch the default state is boolen: false, so when I toggle the switch to true, the state immediately will turn to false. I don't know where is the problem.
I read some documents we both same properties via using onValueChange setting the value using the state.
I am confuse what the documentation tells

*

*It mentions that setstate can't call

When we define our button this way, the this variable in options is not the HomeScreen instance, so you can't call setState or any instance methods on it. This is pretty important because it's extremely common to want the buttons in your header to interact with the screen that the header belongs to. So, we will look how to do this next.

Any recommendation to fix this switches on the headerRight?
Goal: is when I toggle the switch button must change the value itself
State:
switchDriverOnlineValue: false,

Navigation Header:
      DriverHeader() {
    this.props.navigation.setOptions({
      headerLeft: () => <View style={{ flexDirection: "row", justifyContent: "flex-end", paddingLeft: 20 }}>
        <TouchableOpacity
          onPress={() => this.props.navigation.openDrawer()}
        >
          <Icon type="font-awesome" name="user-circle-o" size={30} color="white" />
        </TouchableOpacity>
      </View>,

      headerRight: () => <View style={{ flexDirection: "row", justifyContent: "flex-end" }}>
        <Text adjustsFontSizeToFit numberOfLines={2} style={{ color: '#FFFF', fontSize: 18, fontWeight: 'bold' }}>Online</Text>
        <Switch style={{ marginTop: 0 }} value={this.state.switchDriverOnlineValue} onValueChange={(value) => this.setState({ switchDriverOnlineValue: value })} />
      </View>,
    });
  }

Current Output:

Logs:

A: Here you have to toggle the previous value of the switchDriverOnlineValue state every time the value of the switch is changed so adding a ! to previous value will make it work.
<Switch style={{ marginTop: 0 }} value={this.state.switchDriverOnlineValue} onValueChange={(value) => this.setState({ switchDriverOnlineValue: !value })} />


text:
Q: How to make JPA EntityListeners validate the existence of an interface I am working in J2EE 5 using JPA, I have a working solution but I'm looking to clean up the structure.
I am using EntityListeners on some of the JPA objects I am persisting, the listeners are fairly generic but depend on the beans implementing an interface, this works great if you remember to add the interface.
I have not been able to determine a way to tie the EntityListener and the Interface together so that I would get an exception that lead in the right direction, or even better a compile time error.
@Entity
@EntityListener({CreateByListener.class})
public class Note implements CreatorInterface{
    private String message;....
    private String creator;
    ....
}

public interface CreatorInterface{
    public void setCreator(String creator);
}

public class CreateByListener {
    @PrePersist
    public void dataPersist(CreatorInterface data){
        SUser user = LoginModule.getUser();
        data.setCreator(user.getName());
    }
}

This functions exactly the way I want it to, except when a new class is created and it uses the CreateByListener but does not implement the CreatorInterface.
When this happens a class cast exception is thrown somewhere deep from within the JPA engine and only if I happen to remember this symptom can I figure out what went wrong.
I have not been able to figure a way to require the interface or test for the presence of the interface before the listener would be fired.
Any ideas would be appreciated.

A: @PrePersist
public void dataPersist(Object data){
    if (!(data instanceof CreatorInterface)) {
        throw new IllegalArgumentException("The class "
                                           + data.getClass()
                                           + " should implement CreatorInterface");
    }
    CreatorInterface creatorInterface = (CreatorInterface) data;
    SUser user = LoginModule.getUser();
    creatorInterface.setCreator(user.getName());
}

This does basically the same thing as what you're doing, but at least you'll have a more readable error message indicating what's wrong, instead of the ClassCastException.


text:
Q: CakePHP "Cannot modify header information" problem is NOT whitespace Here's the error:
Warning (2): Cannot modify header information - headers already sent by (output started at /usr/share/php/cake/basics.php:111) [CORE/cake/libs/controller/controller.php, line 640]

$status =   "Location: http://mydomain.com/blog/index"

header - [internal], line ??
Controller::header() - CORE/cake/libs/controller/controller.php, line 640
Controller::redirect() - CORE/cake/libs/controller/controller.php, line 621
PostsController::add() - APP/controllers/posts_controller.php, line 25
Object::dispatchMethod() - CORE/cake/libs/object.php, line 115
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 227
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 194
[main] - APP/webroot/index.php, line 88

Here's the code for posts_controller.php:
function add() {
    if (!empty($this->data)) {
        $this->Post->create();
        if ($this->Post->save($this->data)) {
            $this->Session->setFlash(__('Post saved!!', true));
            $this->redirect(array('action'=>'index')); // line 25
        } else {
        }
    }
    $tags = $this->Post->Tag->find('list');
    $statuses = $this->Post->Status->find('list');
    $this->set(compact('tags', 'statuses'));
}

Here's line 111:
echo "\n
\n";
Output of debug_print_backtrace() in basics.php core cake file:
http://pastebin.com/fBFrkYsP
I've got through all the files I have edited (as opposed to ones I just baked) and I there isn't any whitespace outside of the php brackets (). I used this script: Find all files with Blank or WS at BOF or EOF.
My text editor is set to UTF-8. Basically the problem goes away when I comment out line 25 (marked above with comment). But I should be able to use a redirect...can anyone point me in the right direction?
EDIT:
added line at 111 above; EDIT 2: added output of debug_print_backtrace()

A: 640 is the start of a foreach loop in stripslashes_deep()
111 is debug()
Appears to me you're calling the debug() function somewhere in your code?
Aslo in your code is it:
    header -
and not =

A:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

In your case, you are using echo on line 111, which is the "or from PHP" part above.
Since this line appears to be from the core package, I guess you are calling a function that somehow causes this output. You can use debug_print_backtrace() near line 111 to see the chain of function calls leading to the echo call.

A: Not only whitespace but any output, e.g. the echo you do, is creating output that will prevent using header() later on.
You can work around this be enabling output buffering by default:
; output_buffering
;   Default Value: Off
;   Development Value: 4096
;   Production Value: 4096

output_buffering = 4096

But only if the (accidental) output is less than the buffer size.
Another workaround is to check if headers have been send prior sending headers. The function to check is called headers_sent(). So for a workaround at the place of doing the redirect (no idea if that's applicable for the cakes in the bakery):
$url = 'http://absolut.http/uri';
if (!headers_sent()) {
   header('Location: '.$url, 301);
} else {
   printf('<meta http-equiv="Location" content="%s>"', $url);
}
printf('
Moved.
', $url);
exit;


text:
Q: R predict - How to format output I use the predict function to predict the results based on a model.
What I get is a vector of the predicted classes. I want to retrieve the same results but instead of the form
1 class_1
2 class_1
3 class_4
4 class_2

I want to have the results in the form
    class_1 class_2 class_3 class_4
1         1       0       0       0
2         1       0       0       0
3         0       0       0       1
4         0       1       0       0

I have tried passing type=class and type=response but the results are the same.
I am completely new to R and I am still trying to find my way around R's documentation but I think that this is something trivial that I should be able to figure out, though I am pretty stuck.

A: After viewing the docs on predict.randomForest at
https://cran.r-project.org/web/packages/randomForest/randomForest.pdf
It appears the valid choices for type are response, prob. or votes.
Using the code below, I was able to reproduce your format, but using probabilities.
> predict(model, x, type='prob')
      0     1
1 1.000 0.000
2 0.180 0.820
3 0.138 0.862
attr(,"class")

To obtain booleans, another option is you could do one hot encoding on the response results
result_classes = list()
for (level in levels(y)){
    result_classes[[level]] <- predict(model, x, type='response') == level
}

data.frame(result_classes )

Result:
     X0    X1
1  TRUE FALSE
2 FALSE  TRUE
3 FALSE  TRUE


text:
Q: Datatables: keep zebra stripes after hiding / showing table rows I am hiding rows dynamically in a table ('myTable') based based on manually added classes ('myClass').
The table uses the Datables plugin with the standard zebra-striped background colors.
Is there a way to keep these zebra stripes after manually hiding rows in that table ?
This works fine when sorting and filtering the table by using the standard Datatables functions so I assume there is a setting that allows this.
I am using a simple Show / Hide function based on a class that I add manually:
$('.myClass').hide(); / $('.myClass').show();

Can someone here help me with this ?
Many thanks in advance, Tim.

A: I use datatables as well. Love it but dont use the added classes for 'zebra stripes' lol.
If your users are past IE8 you could just let CSS do it like so:
tr:nth-child(even) {
    background-color: #000000;
}

EDIT: Based on comment. If you will be hiding rows rather than removing them jQuery is the best answer. Note the ":visible" in the selector.  Using addClass would be a better call hence we could removeClass from the tr selector before we stripe the table.
Or use jQuery:
$(document).ready(function()
{
    $("tr:visible:even").css("background-color", "#000000");
});

A: The selected solution will get graphically glitchy. If you set the base style with css and then overwrite them with the given jquery, you will need to reset both the "odd" and "even", with inline styling every time you filter. This is definitely an option, but I just wanted to give you another one which I implemented just today (because this one is quite on top of google):
First, build an extra table like this:
<table id="filteredOutTable" style="display:none;">
  <tbody>
  </tbody>
</table>

Then use jquery to move around the data, like this:
if(<move out of table>){
  $('#dataTableID tbody .rowClass').detach().appendTo('filteredOutTable tbody');
}
if(<move to table>){
  $('#filteredOutTable tbody .rowClass').detach().appendTo('#dataTableID tbody');
}

This is a tad heavier than simple inline styling depending on the amount of rows you have, but it's guaranteed to save you from zebra-related graphical issues. CSS will work with this without problems.


text:
Q: Javascript : get mid point (centroid) between Lat Long in Google Maps I have a google maps based program that can calculate the area based on user input. Here the  Demo JSFiddle
The HTML should be like this

Length (red line):
    0 mt - Area (grey area): 0 mt2

And the Javascript
    var map;

// Create a meausure object to store our markers, MVCArrays, lines and polygons
var measure = {
    mvcLine: new google.maps.MVCArray(),
    mvcPolygon: new google.maps.MVCArray(),
    mvcMarkers: new google.maps.MVCArray(),
    line: null,
    polygon: null
};

// When the document is ready, create the map and handle clicks on it
jQuery(document).ready(function() {

    map = new google.maps.Map(document.getElementById("map"), {
        zoom: 15,
        center: new google.maps.LatLng(39.57592, -105.01476),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        draggableCursor: "crosshair" // Make the map cursor a crosshair so the user thinks they should click something
    });

    google.maps.event.addListener(map, "click", function(evt) {
        // When the map is clicked, pass the LatLng obect to the measureAdd function
        measureAdd(evt.latLng);
    });

});

function measureAdd(latLng) {

    // Add a draggable marker to the map where the user clicked
    var marker = new google.maps.Marker({
        map: map,
        position: latLng,
        draggable: true,
        raiseOnDrag: false,
        title: "Drag me to change shape",
        icon: new google.maps.MarkerImage("/images/demos/markers/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))
    });

    // Add this LatLng to our line and polygon MVCArrays
    // Objects added to these MVCArrays automatically update the line and polygon shapes on the map
    measure.mvcLine.push(latLng);
    measure.mvcPolygon.push(latLng);

    // Push this marker to an MVCArray
    // This way later we can loop through the array and remove them when measuring is done
    measure.mvcMarkers.push(marker);

    // Get the index position of the LatLng we just pushed into the MVCArray
    // We'll need this later to update the MVCArray if the user moves the measure vertexes
    var latLngIndex = measure.mvcLine.getLength() - 1;

    // When the user mouses over the measure vertex markers, change shape and color to make it obvious they can be moved
    google.maps.event.addListener(marker, "mouseover", function() {
        marker.setIcon(new google.maps.MarkerImage("/images/demos/markers/measure-vertex-hover.png", new google.maps.Size(15, 15), new google.maps.Point(0, 0), new google.maps.Point(8, 8)));
    });

    // Change back to the default marker when the user mouses out
    google.maps.event.addListener(marker, "mouseout", function() {
        marker.setIcon(new google.maps.MarkerImage("/images/demos/markers/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5)));
    });

    // When the measure vertex markers are dragged, update the geometry of the line and polygon by resetting the
    //     LatLng at this position
    google.maps.event.addListener(marker, "drag", function(evt) {
        measure.mvcLine.setAt(latLngIndex, evt.latLng);
        measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
    });

    // When dragging has ended and there is more than one vertex, measure length, area.
    google.maps.event.addListener(marker, "dragend", function() {
        if (measure.mvcLine.getLength() > 1) {
            measureCalc();
        }
    });

    // If there is more than one vertex on the line
    if (measure.mvcLine.getLength() > 1) {

        // If the line hasn't been created yet
        if (!measure.line) {

            // Create the line (google.maps.Polyline)
            measure.line = new google.maps.Polyline({
                map: map,
                clickable: false,
                strokeColor: "#FF0000",
                strokeOpacity: 1,
                strokeWeight: 3,
                path:measure. mvcLine
            });

        }

        // If there is more than two vertexes for a polygon
        if (measure.mvcPolygon.getLength() > 2) {

            // If the polygon hasn't been created yet
            if (!measure.polygon) {

                // Create the polygon (google.maps.Polygon)
                measure.polygon = new google.maps.Polygon({
                    clickable: false,
                    map: map,
                    fillOpacity: 0.25,
                    strokeOpacity: 0,
                    paths: measure.mvcPolygon
                });

            }

        }

    }

    // If there's more than one vertex, measure length, area.
    if (measure.mvcLine.getLength() > 1) {
        measureCalc();
    }

}

function measureCalc() {

    // Use the Google Maps geometry library to measure the length of the line
    var length = google.maps.geometry.spherical.computeLength(measure.line.getPath());
    jQuery("#span-length").text(length.toFixed(1))

    // If we have a polygon (>2 vertexes inthe mvcPolygon MVCArray)
    if (measure.mvcPolygon.getLength() > 2) {
        // Use the Google Maps geometry library tomeasure the area of the polygon
        var area = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
        jQuery("#span-area").text(area.toFixed(1));
    }

}

function measureReset() {

    // If we have a polygon or a line, remove them from the map and set null
    if (measure.polygon) {
        measure.polygon.setMap(null);
        measure.polygon = null;
    }
    if (measure.line) {
        measure.line.setMap(null);
        measure.line = null
    }

    // Empty the mvcLine and mvcPolygon MVCArrays
    measure.mvcLine.clear();
    measure.mvcPolygon.clear();

    // Loop through the markers MVCArray and remove each from the map, then empty it
    measure.mvcMarkers.forEach(function(elem, index) {
        elem.setMap(null);
    });
    measure.mvcMarkers.clear();

    jQuery("#span-length,#span-area").text(0);

}

I'm trying get the mid point (centroid) and return the Long Lat value. It's kinda like this JSFiddle. The problem is I'm trying to get the mid point (centroid) but alywas getting an error. It's return like this :
I am appreciate if anyone can help :D
Thanks

A: You can declare LatLngBounds() object first, then extend your bound objects for each marker:
    var bounds = new google.maps.LatLngBounds();
    var loc = measure.polygon.getPath().b;
    for (i = 0; i < loc.length; i++) {
        bounds.extend(new google.maps.LatLng(loc[i].lat(), loc[i].lng()));
    }

    var marker = new google.maps.Marker({
        position: bounds.getCenter(),
        map: map
    });

https://jsfiddle.net/xvbLr993/13/


text:
Q: Pairwise non-isomorphic interval-isomorphic lattices Let us call a lattice $(L,\leq)$ interval-isomorphic if for all $a<b \in L$ we have $L \cong [a,b]$, where $[a,b]=\{x\in L:a\leq x\leq b\}$.
Are there $2^{\aleph_0}$ pairwise non-isomorphic interval-isomorphic lattices on the ground set $\omega$?

A: This is not a solution, but a description of a potential solution.
I conjecture that ``Yes, there
are $2^{\aleph_0}$-many self-similar countable lattices.''
I am pretty sure that any irreducible continuous geometry
has the property that any two proper nontrivial intervals are
isomorphic to each other. I am less confident that the whole
lattice is isomorphic to any of its intervals, but it seems plausible.
But continuous geometries are uncountable, so they do not
answer the question. Nevertheless,
they have countable dense sublattices. One way to construct
such a countable dense sublattice was described by von Neumann:
Let $\mathbb D$ be a countable division ring and let
$PG(\mathbb D, 2^n-1)$ be $(2^n-1)$-dimensional
projective space over $\mathbb D$ equipped with a
dimension function normalized so that the dimension of
the whole space is $1$. There are dimension-preserving
embeddings
$PG(\mathbb D, 1)\leq PG(\mathbb D, 3)\leq PG(\mathbb D, 7)\leq \cdots .$
Let $PG(\mathbb D, \omega)$ be the direct limit of these embeddings.
This is a countable, complemented, modular lattice with normalized dimension
function taking values in the dyadic rationals. It is also a
metric space with metric given by
$d(a,b) = \dim(a\vee b)-\dim(a\wedge b)$.
The continuous geometry over
$\mathbb D$, $CG(\mathbb D)$,  is the (uncountable) metric completion of
$PG(\mathbb D, \omega)$. But let's hold off and not complete
this lattice. Instead, let's stay with the countable and very homogeneous
modular lattice $PG(\mathbb D, \omega)$. I think it is a good
candidate for a countable lattice isomorphic to each of its
proper intervals.
$PG(\mathbb D, \omega)$ encodes information about $\mathbb D$.
I do not know the circumstances when
$PG(\mathbb D, \omega)\cong PG(\mathbb D', \omega)$
implies $\mathbb D\cong \mathbb D'$, but in Birkhoff's paper
Von Neumann and Lattice Theory the author write
``Curiously, the real and quaternion continuous geometries are isomorphic.''
This indicates that the related implication
$CG(\mathbb D)\cong CG(\mathbb D')$ implies $\mathbb D\cong \mathbb D'$
can fail, but that Birkhoff found it curious when it happened,
even for closely related division algebras.
I'm not sure what this says about the implication for
$PG(\mathbb D, \omega)$ in place of $CG(\mathbb D)$.
But let's suppose that it is often the case that
$\mathbb D\not\cong \mathbb D'$ implies
$PG(\mathbb D, \omega)\not\cong PG(\mathbb D', \omega)$
There surely ARE $2^{\aleph_0}$-many
choices for $\mathbb D$.
For example,
$\mathbb D = \mathbb Q[\sqrt{p_1}, \sqrt{p_2},\ldots]$,
where we adjoin some set of square roots of primes to $\mathbb Q$,
is a countable field, and fields constructed this way are not
isomorphic if they are contructed from different sets of primes.
Thus, I propose the lattices $PG(\mathbb D, \omega)$ for countable fields
$\mathbb D$ as likely candidates to solve this problem.
[In the comments to the question
it is noted that the countable atomless
Boolean algebra is an example of a countable self-similar
lattice. This example may be thought of as arising from
the above construction starting with $\mathbb D$
equal to the ``field of one element''. By this I mean
replace $PG(\mathbb D, 2^n-1)$ in von Neumann's
construction with the power set lattice with $2^n$ atoms.]


text:
Q: How to save Reactive Form data on refresh / changing page? Which would be the best solution to save the data insert by user in a Reactive Form?
In my Angular app i have a stepper, each step is a Reactive Form, when the form is valid the user can go ahead to the next step or get back to previous and change form values.
The issue comes when like the user want change items inside the cart or refresh the page, as there are lot of informations that he is filling out in the forms it would be nice that after refesh or changing the page the data inserted inside the reactive form will be keept in it.
So which would be the best approach to do it? should i go for localstorage, cookies or something else?

A: Using LocalStorage in this case can be a good solution to persist data. in the component ngOnInit() check the LocalStorage and if there is the related data fill the forms.
You can have a setLocalStorage() function which will be invoked on the form change event if keeping every single data persistent is very important to you like this:
app.component.ts
ngOnInit() {
  this.myForm.valueChanges.subscribe( val => {
     this.setLocalStorage(val);
  });
}

setLocalStorage( newValue: any ): void {
  // Set Localstorage code here
}

Otherwise you can call setLocalStorage() on the stepper next button or form submit event or any required event.


text:
Q: Expectancy and variation of coin toss set What is expectancy in the sense of sample mean and variance of this coin toss set
$$S=[1,1,0,1,0]$$
probability of $P(x=1)$ is $p$
Variance is $$var(S) = E(S^2) - E(S)^2$$
but I don't know how to calculate $E(S^2)$ given there are many 1's

A: If you can calculate E(S), the it happens $E(S^2)=E(S)$, since 0 and 1 are equal to their squares.


text:
Q: Is my partial derivation of MSE loss function correct w.r.t to w1? $ mse = \dfrac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y_i})^2 $
where
$ \hat{y_i} = w_1 * x_{i1} + w_2 * x_{i2} + b $ where $ x_{i1} $ and $ x_{i2} $ and $ b $ are scalars
$ \dfrac{\partial}{\partial w_1} mse =  \dfrac{1}{n} \sum_{i=1}^{n} \dfrac{\partial}{\partial w_1}(y_i - \hat{y_i})^2 $
$ \dfrac{\partial}{\partial w_1} mse =  \dfrac{-2}{n} \sum_{i=1}^{n} (y_i - \hat{y_i}) \dfrac{\partial}{\partial w_1} \hat{y_i} $
$ \dfrac{\partial}{\partial w_1} mse =  \dfrac{-2}{n} \sum_{i=1}^{n} (y_i - \hat{y_i}) x_{i1} $
$ \dfrac{\partial}{\partial w_1} mse =  \dfrac{-2}{n} \sum_{i=1}^{n} (y_i - \hat{y_i}) x_{i1} $
Edit:
Corrected  derivation with guidance from Paul. I tested out the formula with pytorch package below. Pls ignore the below code, this was just my way of validating
import torch
from torch.nn import Linear, functional
import numpy as np

red = lambda x:print(f'\x1b[31m{x}\x1b[0m')
X = torch.tensor([[0.1019, 0.0604],
        [1.0000, 0.7681]], dtype=torch.float32)
y = torch.tensor([[1.],
        [0.]], dtype=torch.float32)

xi1 = X.numpy()[:,0].reshape(2,1)
red('xi1')
print(xi1)
red('y')
print(y)
n = len(X)
torch.manual_seed(44)
model = Linear(2,1)
w1, w2 = model.weight[0]
red('Initial weights')
print(f'w1={w1}, w2={w2}')

ycap = model(X)
red('ycap')
print(f'{ycap.detach().numpy()}' )
loss = functional.mse_loss(ycap, y)
loss.backward()
d1, d2 = model.weight.grad[0]
red('partial diff of w1 of mse_loss fn')
print(f'd1={d1}, d2={d2}')

d_x_i1 = - 2/n * np.sum( (y.numpy() - ycap.detach().numpy()) * xi )
red('manual diff of w1 using formula')
print(d_x_i1)

assert d1 == d_x_i1