text:
Q: How to change the background color of android status bar I want to change the background color of the status bar by writing an application. My android device has black color, I want to change it to some other color. I saw some posts related to it here,  but they are telling about notification background.
If any body knows about this please help me.
The default status bar

After using a drawable as background to status bar

A: styles.xml was recently changed to themes.xml so most of the answers here are outdated. You can now just simply add this line of code to the themes.xml file to change the status bar color to green:
<item name="android:statusBarColor">@color/black</item>

A: Sorry, unless you are making a custom ROM this isn't possible, unless you only want the status bar changed for your app.
This would require a heck of a lot of work.
First you will need to add Theme.NoTitleBar.Fullscreen to your manifest
<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        >

Then once you have done that you need to create a standard layout which represents the status bar, this would mean that you have to add the time, and also receive all the notifications from other apps, I do not personally know how to do that but I'm sure there is a way.
If you really want to do this goodluck, you have a hard time ahead of you.

Sorry, unless you have the knowledge how to build custom ROMS I do not think this is possible

A: In styles.xml do this:
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_secondary</item>
        <item name="colorAccent">@color/color_accent</item>
         <!---Below is the code for status bar color------>
        <item name="android:statusBarColor">@color/color_primary</item>
    </style>
</resources>

Place this is in your values-v21/styles.xml, to enable this on Lollipop and later.
In order to do it programmatically you can do this:
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(activity.getResources().getColor(R.color.example_color));

A: This is possible on Kitkat and after.
If you want to use it in an application (like you asked), you could use this library https://github.com/jgilfelt/SystemBarTint
You only need to write:
// set a custom tint color for all system bars
tintManager.setTintColor(Color.parseColor("#99000FF"));
// set a custom navigation bar resource
tintManager.setNavigationBarTintResource(R.drawable.my_tint);
// set a custom status bar drawable
tintManager.setStatusBarTintDrawable(MyDrawable);

A: IF you want to update the status bar color on Lollipop without upgrading your ADT and SDK and all that related stuff, you can use reflections to reach the methods of API 21 (Lollipop) and higher
in your activity :
    if (Build.VERSION.SDK_INT >= 21) {
        Window window = getWindow();

        // original code, works on Lollipop SDKs
        // window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        // window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // window.setStatusBarColor(getResources().getColor(YOUR_COLOR));

        try {
            // to work on old SDKs
            int FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS = 0x80000000;
            window.addFlags(FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            Class<?> cls = window.getClass();
            Method method = cls.getDeclaredMethod("setStatusBarColor",
                    new Class<?>[] { Integer.TYPE });

            method.invoke(window, Res.color(theme.statusColor));

        } catch (Exception e) {
            // upgrade your SDK and ADT :D
        }

    }

my current minimum API is 15, if you cannot find
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS

in your SDK, you can get it's value from documentation as what i did with
WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS

hope this helped


text:
Q: How can I filter or subset multiple columns based on a greate than or less than criteria at the same time? I have a dataframe like this:
> head(ratio_da)
               Compound       PA1       PA2         PA3 PA1 : PA2 PA1 : PA3 PA2 : PA3
1 7.92_540.535223166667   3720068  42061995  22440957.7 0.0884425 0.1657714 1.8743405
2 7.64_538.520408833333 150348486 247654259 299620639.3 0.6070902 0.5017962 0.8265594
3 6.73_552.499681833333   2687581   5690404    869171.9 0.4723006 3.0921170 6.5469255
4      6.12_536.5044875  16289397  21130472  21314675.4 0.7708961 0.7642339 0.9913579
5 8.22_566.551271833333  24241911  49978630  48028396.5 0.4850455 0.5047412 1.0406059
6 8.64_594.582882166667   8772965  16609306  16694017.1 0.5281958 0.5255155 0.9949257

As you can see, the last three columns are the ratios of column PA1, PA2, and PA3. I would like to filter all ratio columns by this criteria: >= 1.2 | <= 0.83. I usually use this code:
test <- filter(ratio_da, ratio_da$`PA1 : PA2` >= 1.2, ratio_da$`PA1 : PA2` >= 0.83 | ratio_da$`PA1 : PA3` >= 1.2, ratio_da$`PA1 : PA3` >= 0.83 |ratio_da$`PA2 : PA3` >= 1.2, ratio_da$`PA2 : PA3` >= 0.83 )

Since I have tons of dataframes like this, I am trying to find a quicker way which can suit every input dataframe. So I tried apply():
t <- tt[apply(tt[5:7],1,function(x) any(x >=1.2 | x <= 0.83)),]

...but this did not filter all raios at the same time. Any codes can fixs this problem?
Thank you very much!

A: Thoughts:
base R
rowSums(ratio_da[,5:7] >= 1.2 | ratio_da[,5:7] <= 0.83) > 0
# [1] TRUE TRUE TRUE TRUE TRUE TRUE

or less-efficient:
Reduce(`|`, lapply(ratio_da[,5:7], function(z) z >= 1.2 | z <= 0.83))

dplyr
rowSums(!between(ratio_da[,5:7], 0.83, 1.2)) > 0

(not much savings here)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installing a Network Manager that works in the terminal on Debian9 Trying to find any Network Manager on the "apt" databases that works in the terminal. I usually use "NetworkManager-tui" but I can not find it.
Do anyone have a suggestion on good alternatives for WiFi management on Debian 9?

A: NetworkManager-tui presents in network-manager package as nmtui utility. You can use nmcli utility which is a part of the network-manager package too and provides CLI interface instead of ncurses. But ncurses interface is more friendly for beginers.
Ensure that NetworkManager service is started before using NetworkManager utilities:
systemctl status NetworkManager

If it will be stopped try it to start:
systemctl start NetworkManager

A: The network-manager package provide :
nmtui

nmtui - Text User Interface for controlling NetworkManager

nmcli

nmcli - command-line tool for controlling NetworkManager

alternatives
wpa_cli

wpa_cli - WPA command line client

Arch-linux wiki: connecting with wpa_cli
wpa_supplicant


text:
Q: height makes div go out of the parent This is the issue
https://i.imgur.com/WRfKm7w.jpg
The red line is the border of the div that is going out.
So, I have this on body and html:
html {
  height: 100%;
}
::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* make scrollbar transparent */
}

body {
  height: 100%;

  background:url('http://sf.co.ua/13/03/wallpaper-2682923.jpg') no-repeat center center fixed;

    -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

}

And this is the HTML

                    HOME

                    STAFF LIST

                Previous

                Next

                            test

The red line should stop where the white div ends,

But for some reason it goes all the way down and I don't understand why.
Also, I also don't understand why the white div doesn't go all the way down, as it has height 100% too:
.bodyc {
    position: relative;
    background-color: white;
    width: 90%;
    border-radius: 15px;
    height: 100% !important;
}

I am using bootstrap
JSFIDDLE
https://jsfiddle.net/8eddeuu1/2/

A: To fix the red border line, I came up with a quick hack, add:
overflow: hidden;

to .bodyc class.
The white div doesn't go all the way down because "height: 100%" doesn't do what you think it means. Percentages in CSS are relative to the containing element. If I have:

The inner div will not be any taller than the outer one. It will be just as tall.


text:
Q: Mocha/Chai: Test for exact throw error result There is a simple method, which throws an error:
methods.js
insertItem = new ValidatedMethod({
    name    : 'article.insert.item',
    validate: new SimpleSchema({
        parent: { type: SimpleSchema.RegEx.Id }
        value : { type: String }
    }).validator(),

    run({ parent, value}) {
        var isDisabled = true
        if (isDisabled)
            throw new Meteor.Error('example-error', 'There is no reason for this error :-)')
    }
})

Now I want to do a mocha test for this error. So I came up with this, which is working:
server.test.js
it('should not add item, if element is disabled', (done) => {
    const value = 'just a string'

    function expectedError() {
        insertItem.call(
            {
                parent: '12345',
                value
            }
        )
    }

    expect(expectedError).to.throw
    done()
})

Until this point everything is working.
The problem
But I would like to test for the exact error message.
I already tried
expect(expectedError).to.throw(new Meteor.Error('example-error', 'There is no reason for this error :-)'))

But it gives me a failing test:
Error: expected [Function: expectedError] to throw 'Error: There is no reason for this error :-) [example-error]'

A: I think the docs are a bit misleading/confusing on this - just remove the new operator from your expect and it'll match the error thrown:
expect(expectedError).to.throw(Meteor.Error('example-error', 'There is no reason for this error :-)'))

A: I found from this post that I needed to write it like this:
expect(expectedError).to.throw(Meteor.Error(), 'example-error', 'This is an error');

Note that the error messages are after the Error(),


text:
Q: Why does simplex noise seem to have *more* artifacts than classic Perlin noise? I read Stefan Gustavson's excellent paper on simplex noise, in which I was promised that:

Simplex noise has no noticeable directional artifacts

in contrast with "classic" Perlin noise. I excitedly implemented it to find out that the opposite appeared to be true. I do see artifacts in classic noise, but I see at least as many artifacts in simplex noise, aligned at 45 degrees to the main axes. They're especially noticeable when you map the noise to a step function.
To ensure it wasn't a problem with my implementation, I used someone else's JavaScript implementation. Compare some images:

*

*Classic noise vs simplex noise

*Classic noise step vs simplex noise step
And here's a gallery with all of them. In that last image, look for borders that are aligned at 45 degrees from horizontal/vertical. They're all over the place. I can highlight some of them if need be, but they seem really obvious to me. (And again, I see them in the classic noise image as well.)
EDIT: To be more quantitative, I sampled 1 million random points, and for each point I numerically computed the gradient of both classic and simplex noise, and took a histogram of the direction of the gradient projected onto the x-y plane. If there were no directional artifacts, the graph would be flat. But you can see that both classic and simplex noise spike every 45 degrees.
Is this a problem with the simplex noise algorithm? Is it something that can be fixed? Or am I the only one who sees this as a problem?

A: Value noise version of perlin noise produces straight lines also, and gradient noise version of perlin produces slightly rounder stuff, so maybe you have a value noise implementation of simplex there rather than a gradient version.
Otherwise the interpolation gradient in your code is wrong, because it is producing angle transitions in between quadrants. it seems online to say that simplex noise is not only faster but that the gradients are more rounded.
I interpret that to mean that the angles of the interpolation curves are rounder. Perhaps someone has mis stated Ken Perlins statement, he just said that the gradient contained less jitter(sorry for use of the wrong description), because the code doesn't actually produce a perfect mathematical curve like a sinus, if you multiply many Perlin together I found jitter/curve irregularities strong enough to measure, which is not the case with sine waves and maths functions. so you could research online other people's comments of simplex noise gradient.
I think there is a gradient look up table, which in your case it seems to be going up to 45' rather often, otherwise the grading curve that you are using in between 2 points is too far from the idealised sinusoidal curve that would produce round shapes and no straight lines at all, but that's computation less easy, especially on CPU. On GPU I think it stands to reason that sinus gradient with the faster than the polynomial gradient curve used.
did you also check what the turbulent and multi-fractal etc versions of your simplex make? In either case they are each about 5 lines expressing how the noise functions run and returning very different results every time.
improved Perlin noise for GPU from scrawkblog

A: I just read the paper, and I think I have an idea what might be causing the artifacts. The gradients for each vertex of the grid are pseudorandomly chosen from a rather small lookup table. As Gustavson states on page 3:
"A good choice for 2D and higher is to pick gradients of unit length but different directions. For 2D, 8 or 16 gradients distributed around the unit circle is a good choice."
This was the method used in classical Perlin noise, which is not what Perlin proposed for Simplex noise in his 2001 paper, page 14:
"Rather than using a table lookup scheme to compute the index of a pseudo-random gradient at each surrounding vertex, the new method uses a bit-manipulation scheme that uses only a very small number of hardware gates."
However, Gustavson states on page 7:
"I will use a hybrid approach for clarity, using the gradient hash method from classic noise but the simplex grid and straight summation of noise contributions of simplex noise. That is actually a faster method in software."
His 2D implementation actually uses the 12 gradients from the 3D gradient table, discarding the z coordinate. In that scheme, the edge coordinates are used twice each, but the corners are used only once, which would seem to introduce a bias at 90-degree intervals. But that's not relevant in your case, because the implementation you're using only has 8 gradients, quite suggestive of a bias at 45-degree intervals. The likelihood of visible patterns emerging from such minimal variance seems pretty high. But it should be easy to adapt that algorithm for 16 gradients, using a mod 16 permutation table, which should help reduce the directional artifacts significantly.
Ultimately, though, I think there will always be some visible patterns in a single octave of any gradient noise function, simply because they're band-limited by design, as the narrow range of frequencies will tend to align perturbations to the grid. Being a triangular grid, Simplex noise will probably exhibit some bias at 60-degree intervals even if the gradients were truly random. Well, that's just conjecture, but the point is that these noise functions are really designed to be combined in different frequencies, which tends to break up any patterns you might see in a single octave.
EDIT:
Another point I just realized, the corner gradients such as (1,1) are not of unit length, they are sqrt(2). The first quote makes it clear that the gradients should lie on the unit circle. This may be another source of bias. Interestingly, Gustavson uses these non-unit gradients too.


text:
Q: EnumDisplayDevices giving two Displays even though I have one I was making an application for Night Light using Python. I'm using windows API for use of Gamma Ramp to accomplish my task.
I used EnumDisplayDevicesW from user32.dll to get the information and number of displays connected to my PC.
I have only one monitor connected to my desktop, but the output is giving information of two monitors.
Here's my code. I'm using Python and accessing WinAPI through ctypes module.
import ctypes
from ctypes import wintypes

class DISPLAY_DEVICEW(ctypes.Structure):
    _fields_ = [
        ('cb', wintypes.DWORD),
        ('DeviceName', wintypes.WCHAR * 32),
        ('DeviceString', wintypes.WCHAR * 128),
        ('StateFlags', wintypes.DWORD),
        ('DeviceID', wintypes.WCHAR * 128),
        ('DeviceKey', wintypes.WCHAR * 128)
    ]

if __name__ == '__main__':
    EnumDisplayDevices = ctypes.windll.user32.EnumDisplayDevicesW       # get the function address
    EnumDisplayDevices.restype = ctypes.c_bool                          # set return type to BOOL

    displays = []           # to store display information
    i = 0                   # iteration variable for 'iDevNum'

    while True:
        INFO = DISPLAY_DEVICEW()            # struct object
        INFO.cb = ctypes.sizeof(INFO)       # setting 'cnSize' prior to calling 'EnumDisplayDevicesW'

        if not EnumDisplayDevices(None, i, ctypes.byref(INFO), 0):
            break       # break as soon as False is returned by 'EnumDisplayDevices'

        displays.append(INFO)       # append information to the list
        i += 1

    # display information in a sequential form
    for x in displays:
        print('DeviceName:\t\t', x.DeviceName)
        print("DeviceString:\t", x.DeviceString)
        print("StateFlags:\t\t", x.StateFlags)
        print("DeviceID:\t\t", x.DeviceID)
        print("DeviceKey:\t\t", x.DeviceKey)
        print(), print()

And the output returned by the code is as follows:-
DeviceName:      \\.\DISPLAY1
DeviceString:    Intel(R) HD Graphics 510
StateFlags:      5
DeviceID:        PCI\VEN_8086&DEV_1902&SUBSYS_D0001458&REV_06
DeviceKey:       \Registry\Machine\System\CurrentControlSet\Control\Video\{C31A4E45-2A30-11EB-953B-92862920CE33}\0000

DeviceName:      \\.\DISPLAY2
DeviceString:    Intel(R) HD Graphics 510
StateFlags:      0
DeviceID:        PCI\VEN_8086&DEV_1902&SUBSYS_D0001458&REV_06
DeviceKey:       \Registry\Machine\System\CurrentControlSet\Control\Video\{C31A4E45-2A30-11EB-953B-92862920CE33}\0001

As far as I know, the first one, i.e, \\.\DISPLAY1 is mine one, but why there's a need for a second one??
I own a Desktop PC with standard Samsung monitor.
Any help will be very helpful. Thanks in advance!

A:
I have only one monitor connected to my desktop, but the output is giving information of two monitors.

Running this code does not tell you that you have two "monitors", but two "adapters".
According to EnumDisplayDevicesW:

To get information on the display adapter, call EnumDisplayDevices with lpDevice set to NULL. For example, DISPLAY_DEVICE.DeviceString contains the adapter name.
To obtain information on a display monitor, first call EnumDisplayDevices with lpDevice set to NULL. Then call EnumDisplayDevices with lpDevice set to DISPLAY_DEVICE.DeviceName from the first call to EnumDisplayDevices and with iDevNum set to zero. Then DISPLAY_DEVICE.DeviceString is the monitor name.

So if you need to get the monitor information, you need to call:
EnumDisplayDevices(INFO.DeviceName,j,ctypes.byref(Monitor_INFO),0):

Here is a sample:
import ctypes
from ctypes import wintypes

class DISPLAY_DEVICEW(ctypes.Structure):
    _fields_ = [
        ('cb', wintypes.DWORD),
        ('DeviceName', wintypes.WCHAR * 32),
        ('DeviceString', wintypes.WCHAR * 128),
        ('StateFlags', wintypes.DWORD),
        ('DeviceID', wintypes.WCHAR * 128),
        ('DeviceKey', wintypes.WCHAR * 128)
    ]

if __name__ == '__main__':
    EnumDisplayDevices = ctypes.windll.user32.EnumDisplayDevicesW       # get the function address
    EnumDisplayDevices.restype = ctypes.c_bool                          # set return type to BOOL

    displays = []           # to store display information
    i = 0                   # iteration variable for 'iDevNum'
    j = 0
    while True:
        INFO = DISPLAY_DEVICEW()            # struct object
        INFO.cb = ctypes.sizeof(INFO)       # setting 'cnSize' prior to calling 'EnumDisplayDevicesW'
        Monitor_INFO = DISPLAY_DEVICEW()
        Monitor_INFO.cb = ctypes.sizeof(Monitor_INFO)
        if not EnumDisplayDevices(None, i, ctypes.byref(INFO), 0):
            break       # break as soon as False is returned by 'EnumDisplayDevices'
        #j = 0
        while EnumDisplayDevices(INFO.DeviceName,j,ctypes.byref(Monitor_INFO),0):
            print("monitor name:\t\t",Monitor_INFO.DeviceName,'\n\n')
            j+=1

        displays.append(INFO)       # append information to the list
        i += 1

    # display information in a sequential form
    for x in displays:
        print('DeviceName:\t\t', x.DeviceName)
        print("DeviceString:\t", x.DeviceString)
        print("StateFlags:\t\t", x.StateFlags)
        print("DeviceID:\t\t", x.DeviceID)
        print("DeviceKey:\t\t", x.DeviceKey)
        print(), print()

A: So, after doing required changes, following is the final code to get all the display monitors connected to all the display adapters.
import ctypes
from ctypes import wintypes

class DISPLAY_DEVICEW(ctypes.Structure):
    _fields_ = [
        ('cb', wintypes.DWORD),
        ('DeviceName', wintypes.WCHAR * 32),
        ('DeviceString', wintypes.WCHAR * 128),
        ('StateFlags', wintypes.DWORD),
        ('DeviceID', wintypes.WCHAR * 128),
        ('DeviceKey', wintypes.WCHAR * 128)
    ]

if __name__ == '__main__':
    EnumDisplayDevices = ctypes.windll.user32.EnumDisplayDevicesW       # get the function address
    EnumDisplayDevices.restype = ctypes.c_bool                          # set return type to BOOL

    """
    the following list 'displays', stores display adapter info in the following Structure:

        'List containing Tuple of displayAdapterInfo and list of monitorInfo controlled by the adapter'
        [
            (dispAdapterInfo1, [Monitor1, Monitor2, . . . ]),
            (dispAdapterInfo2, [Monitor1, Monitor2, . . . ]),
            . . . .
        ]

        Number of dispAdapter depends on the graphics driver, and number of Monitors per adapter depends on
        number of monitors connected and controlled by adapter.
    """
    displays = []

    i = 0                   # iteration variable for 'iDevNum'
    while True:
        DISP_INFO = DISPLAY_DEVICEW()               # struct object for adapter info
        DISP_INFO.cb = ctypes.sizeof(DISP_INFO)     # setting 'cb' prior to calling 'EnumDisplayDevicesW'

        if not EnumDisplayDevices(None, i, ctypes.byref(DISP_INFO), 0):
            break       # break as soon as False is returned by 'EnumDisplayDevices'

        monitors = []       # stores list of monitors per adapter
        j = 0
        while True:
            MONITR_INFO = DISPLAY_DEVICEW()              # struct object for Monitor info
            MONITR_INFO.cb = ctypes.sizeof(MONITR_INFO)  # setting 'cb' prior to calling 'EnumDisplayDevicesW'

            if not EnumDisplayDevices(DISP_INFO.DeviceName, j, ctypes.byref(MONITR_INFO), 0):
                break  # break as soon as False is returned by 'EnumDisplayDevices'

            monitors.append(MONITR_INFO)
            j += 1

        displays.append((DISP_INFO, monitors))      # add the tuple (dispAdapterInfo, [MonitorsInfo])
        i += 1

    for display in displays:
        if display[1]:      # filter out the adapter with no monitor connected, i.e, empty list
            print("Adapter object:", display[0])
            print("List of Monitor objects :", display[1])
            print()

Now, display[0] is the adapter object, and can be used to get the information by referring the above DISPLAY_DEVICEW class, and display[1] is the list of monitors, which can be iterated over to get the objects of the monitor info, and get the information about it by referring DISPLAY_DEVICEW class.


text:
Q: Using @angular-builder/custom-webpack to change a webpack property for Angular 13 I am building an Angular 13 application inside a NX monorepo. This repo contains a react library that uses jsx files. When I run my app, the React library files don't resolve the jsx extension correctly (all of the import statements for jsx files need to end in '.jsx'). I think to solve this I need to add 'jsx' to the resolve.extensions array in webpack config. To do this I am using angular-builder's custom webpack package. First I installed the package:
npm install --save-dev @angular-builders/custom-webpack@13
Then I created a custom-webpack.config.js file in the application root with the following contents:
module.exports = {
    resolve: {
        extensions: ['', '.tsx', '.ts', '.js','min.js', 'jsx']
      }
  };

Next I replaced architect.build.builder in the angular json:
"builder": "@angular-devkit/build-angular:browser" changed to "builder": "@angular-builders/custom-webpack:browser" I added the following to architect.build.options:
"customWebpackConfig": {
  "path": "custom-webpack.config.js",
  "replaceDuplicatePlugins": true
},

I changed architect.serve.builder from "builder": "@angular-devkit/build-angular:dev-server" to "builder": "@angular-builders/custom-webpack:dev-server"
When I run the applicaiton, it builds and serves fine, but if I change the import statement to exclude '.jsx' it breaks
export * from './lib/my-component' breaks but export * from './lib/my-component.jsx' works.
Is my approach correct? Am I creating a custom webpack file and including it the right way?


text:
Q: How to Create radio button group to the form to allow the selection of the smoking/non-smoking section of the restaurant? I wish to emulate the behaviour of radio buttons withing a bootstrap form-group so a line in a form has several buttons ("btn btn-success" for example), with the buttons being able to be "selected", but only one of them can be selected at a given moment.
I want a Output like this:

But I am getting this:

Also I am not able to select the Smoking button
The Code for the Following is :

    Section

              <input type="radio" name="options" id="option1" autocomplete="off" checked>Non-
               Smoking

             <input type="radio" name="options" id="option2" autocomplete="off">Smoking

A: try this
input[type="radio"] {
    visibility:hidden;
}

A: https://jsfiddle.net/auo9Ly54/
remove autocomplete="off" checked in:
<input type="radio" name="options" id="option1" autocomplete="off" checked>

A: Adding btn-group-toggleto your btn-group div will solve the issue.

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

    Section

              <input type="radio" name="options" id="option1" autocomplete="off" checked>Non-
               Smoking

             <input type="radio" name="options" id="option2" autocomplete="off">Smoking


text:
Q: Cant logout from custom Admin Panel Laravel 5.7 I liked Matrix Admin panel, so i started implementing it. I didnt like the option of having admin in User model (boolean check isAdmin), so i created a separate model called Admin. I set up all the routes, and it worked in my test admin page with the following routes:
 web.php

Route::get('/admin/login', 'Auth\AdminLoginController@showLoginForm')-
 >name('admin.login');
Route::post('/admin/login', 'Auth\AdminLoginController@login')-
 >name('admin.login.submit');
Route::get('/admin', 'AdminController@index')->name('admin.admin');

This is my AdminLoginController:
 public function showLoginForm()
{
    return view('admin/admin-login');
}
protected function guard(){
    return Auth::guard('admin');
}

use AuthenticatesUsers;

protected $redirectTo = '/admin/login';

 public function __construct()
{
    $this->middleware('guest:admin')->except('logout');
}

And my AdminController:
public function __construct()
{
    $this->middleware('auth:admin');
}

public function index()
{
    return view('admin.admin');
}

I call routes in the view like this:
href="{{ route('admin.login') }}"

For some reason, it doesn't log me out and get me to the login page, instead it just refreshes the page, hence returns me to the /admin page with the admin logged in. What am i missing here? Thanks for all replies.

A: In the constructor for the AdminLoginController, you have set the middleware to be 'guest:admin'.
This uses the guest middleware that is defined in /app/Http/Middleware/RedirectIfAuthenticated.php by default, or configured in /app/Http/Kernel.php
The $guard string passed for it to use is 'admin'.
I'm guessing that you provide an implementation for this admin guard.
Supposing that you're logged in as an admin, navigating to route('admin.login')
will redirect your request to '/home' in the default implementation;
there are likely chances that there exists a custom redirection to /admin in your implementation.
If you like to logout of the session, you can register a route for the logout method provided in Illuminate\Foundation\Auth\AuthenticatesUsers trait.
Route::get('/admin/logout', 'AdminController@logout')->name('admin.logout');

Since the AuthenticatesUsers::logout redirects to / by default, I'm guessing you need to override this behavior.
You can do exactly that by providing a custom implementation for AuthenticatesUsers::loggedOut in your controller.
protected function loggedOut(Request $request)
{
    return redirect('/admin');
}

Finally, provide this route for the href in your link {{ route('admin.logout') }}

A: It's all about session,
  \Auth::logout();
    $request->session()->invalidate();


text:
Q: Click Button Pressing Spacebar in VB.Net I had 2 goals:

*

*Make pressing enter over a textbox start a search function

*Make pressing spacebar over a button perform a click(thought it was its behaviour, seems not)

I reached the first goal programmatically clicking the button of the seach, executing then the search function:
Private Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
    If e.KeyValue = Keys.Enter Then
        btnSearch.PerformClick()
    End If
End Sub

It worked, so I tried the same method with my second goal:
Private Sub btnCancel_KeyDown(sender As Object, e As KeyEventArgs) Handles btnCancel.KeyDown
    If e.KeyValue = Keys.Space Then
        btnCancel.PerformClick()
    End If
End Sub

And this actually does nothing, kinda select the button, but it doesn't process the button_click event.
Did I miss something?

A: Try this.
Dim btn As New MouseButtons   'create a new instance of mousebutton
Dim a As New MouseEventArgs(btn, 1, 1, 1, 1) 'simulate a click

If e.KeyValue = Keys.Space Then
  Button1_MouseClick(sender, a)
End If

A: You have to Call BtnCancel.Focus() Before Btncancel.Keydown() or  Btncancel.KeyPress() event


text:
Q: Add another holiday to the built-in holiday calendar Mathematica offers holiday calendars, which is GREAT! Especially because adding a days to a date with DatePlus[{2015,4,2},{1,"BusinessDay"}] can skip straight to the next business day. While 4/3/15 would have been a Friday, however, it was a Good Friday, and markets didn't trade on that day. I'd like to add that information without having to rebuild the whole holiday history for the last 100 years of market trading. The only example I found shows how to create a completely new custom holiday calendar:
DayRange[DateObject[{2000, 1, 6}, "Day", "Gregorian", -6.`],
  DateObject[{2018, 7, 6}, "Day", "Gregorian", -6.`], "Holiday",
  HolidayCalendar -> {"Gregorian" -> {{True &, # == 5 &, # == 9 &}}}]

If I could build upon an existing or combine new with existing, that'd be really useful and would save a bunch of time. Any ideas? Thank you in advance.

A: You may use CalendarData to identify which market calendar to use for a country.
From the documentation
CalendarData["UnitedStates"]

{"Default", "GovernmentBond", "NERC", "NYSE"}

Use the "NYSE" calendar holidays in DayRange.
DayRange[PreviousDate[Today, "Year"], NextDate[Today, "Year"], "Holiday",
 HolidayCalendar -> {"UnitedStates", "NYSE"}]

This year's Good Friday can be seen in the list as a holiday.  Compare the result to that of HolidayCalendar -> "UnitedStates".
Hope this helps.


text:
Q: Break down the logic for a C for-loop into something I can implement in MIPS? (count number occurrences in an array) Hi all i am converting my C code to MIPS but problem is here i couldn't make correct logic for this
for (int i=0;i<count;i++)
  {
        h[a[i]]++;
  }

as far i make my own logic that is wrong
Assume That
a[]=$t1
b[]=$t2
li $s1,0

for:
bgt $s1,[size of array],end

lw $t3,($t1)
la $t1,4($t3)
lw $t4,($t2)
la $t2,4($t2)
sw $t3,0($t4)

add $s1,$s1,1
j for

i know this is wrong .. but in MIPS it gives me bad address error and exception 7 and 4 error

Also, how to get the array length into a MIPS register, like how C can calculate the number of elements for you without having to hard-code it?
int arr[]={1,3,5,7,9};
int n=sizeof(arr)/sizeof(arr[0]);

A: You need to understand what is being incremented.  One approach to gaining this understanding is decomposition: expressions can be decomposed using an approach like Three-Address Code.
Suggest then, to decompose this:
    h[a[i]]++;

as follows:
    int av = a[i];
    h[av]++;

In this approach, we separate various operations & elements of the expression into their own lines of code, and reconnect them using an introduced variable, aka a temporary or short-lived variable.
and we can continue decomposition:
    int av = a[i];

    // decompose h[av]++;
    int *hp = h + av;
    *hp = *hp + 1;

and yet still:
    int av = a[i];

    int *hp = h + av;

    // decompose *hp = *hp + 1;
    int  hv = *hp;
    hv++;
    *hp = hv;

That's about as decomposed as can be.  Hopefully, you can (1) translate that into MIPS assembly and (2) learn of the technique of decomposition.

Note that in the C language, when an array, a has int elements, in an expression such as a + i and h + j there is a hidden multiplication of the index (i and j) by sizeof(int), i.e. 4, called scaling that occurs before the addition — this scaling, automatic in C, must be explicitly done in assembly.

Control structures, i.e. structured statements can also be decomposed:
for (i = 0; i < count; i++) {
    ???
}

first decomposition:
i = 0;
while (i < count) {
    ???
    i++;
}

and further into if-goto-label style:
    i = 0;
loop1:
    if (i >= count) goto endLoop1;
    ???
    i++;
    goto loop1;
endLoop1:

Notice how the loop exit condition is inverted (negated) — this because in if-goto-label, we are writing when to exit the loop rather than when to continue the loop as in C for/while, which represents the exact opposite.
(This is not always the case: a do-while condition says when to continue the loop as well, and in assembly, since that is the natural place to put the backward branch for the next iteration of the loop, the condition test for do-while and if-goto-label versions will have the same condition sense — they are not opposites — whereas a repeat-until in Pascal uses the opposite condition sense.)
Also NB: the inversion/negation/opposite of   <   is   >= .

Decomposition is simplification by transformations of logical equivalence.  As long as we maintain logical equivalence, the decomposition will run the same as the original.


text:
Q: image function in R I'm trying to do something a little bit complicated for a beginner in programming.
I have a matrix 16x16 and I want to plot the values as a heatmap using image() in R.
How can I plot the "0" (zeros) in blue when the sum (row index + column index) is <= 15? Is that possible?
example matrix:
x <-  c(3045, 893, 692, 830, 617, 155, 246, 657, 105, 60, 18, 7, 7, 4, 2, 11234,
2985, 2242, 2471, 1575, 366, 503, 1283, 170, 79, 32, 6, 4, 1, 3, 19475, 4756,
3233, 3251, 1810, 409, 575, 1210, 139, 41, 11, 4, 2, 0, 0, 20830, 4739, 2990,
2531, 1346, 298, 325, 612, 60, 17, 1, 0, 1, 0, 0, 15304, 3196, 1885, 1440, 610,
117, 115, 185, 14, 2, 0, 0, 0, 0, 0, 8026, 1535, 806, 539, 223, 33, 37, 39, 0,
0, 0, 0, 0, 0, 0, 3300, 562, 286, 141, 45, 14, 5, 12, 0, 0, 0, 0, 0, 0, 0, 1067,
160, 65, 40, 14, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 277, 47, 6, 2, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 72, 6, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 5, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

xmat <- matrix(x, ncol = 12)
xmat <- cbind(xmat, rep(0,16), rep(0,16), rep(0,16), rep(0,16))
xmat <- rbind(xmat, rep(0,16))
dimnames(xmat) = list(0:15, 0:15)
xmat

Thanks!
Vitor

A: Plot the cases meeting the criteria as blue.
xmat.new <- xmat
xmat.new[!((row(xmat) + col(xmat) <= 15) & xmat==0)] <- NA
image(xmat.new,col="blue")

Plot the cases not meeting the criteria as normal. Notice the add=TRUE
xmat.new <- xmat
xmat.new[((row(xmat) + col(xmat) <= 15) & xmat==0)] <- NA
image(xmat.new,add=TRUE)

Result:

Edited to include @Marek's suggestion to simplify the statements.


text:
Q: Beginner "Learn Python 3 the hard way" ex 5, and 6. Chromebook w/ Linux beta vs repl.it Here's the script I'm trying to run, based off of Zed Shaw's Learn Python3 the hard way book.
      name = 'Zed A.Shaw'
      age = 35 # not a lie
      height = 74 # inches
      weight = 180 # lbs
      eyes = 'Blue'
      teeth = 'White'
      hair = 'Brown'
      inches_to_centimeters = 2.54
      lbs_to_kg = 0.45
      centimeters = "centimeters"
      kilograms = "kilograms"
      height = round(height * inches_to_centimeters)
      weight = round(weight * lbs_to_kg)

      print(f"Let's talk about {name}.")
      print(f"He's {age} years old.")
      print(f"He's {height} {centimeters} tall.")
      print(f"He's {weight} {kilograms} heavy.")
      print(f"Actually, that's not too heavy.")
      print(f"He's got {eyes} eyes and {hair} hair.")
      print(f"His teeth are usually {teeth} depending on the coffee.")

      total = age + height + weight
      print(f"If I add {age}, {height}, and {weight} I get {total}.")

I've tried it in a million different ways, but I'm pretty sure this is without flaws. Anywho, I can't get the bugger to run.
I keep getting this:
       File "ex5.py", line 15
           print(f"Let's talk about {name}.")
                                          ^

SyntaxError: invalid syntax
I've tried removing the quotes, putting them elsewhere, single quotes, removing the format function altogether. Nothing. Same error.
Weird part is, I put this code into
https://repl.it/languages/python3
and it works. Just like it's supposed to.
I updated my VM right before posting this question and tried it out, to no avail.
Any thoughts?
I'm new to coding and computers in general. I'm running Linux Beta on chromebook, and I'm using Caret as my text editor
Thanks!

A: You are using formatted string literals (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) with python version < 3.6.
When running your code on https://repl.it/languages/python3, which runs on newest pyhton version, there is no error.
If you try running in older version of python, like https://repl.it/languages/python, same error occurs.
So you either need to update your python version to 3.6, or not use formatted string literals.

A: It looks like you are be running your code in Python version less than 3.6 which does not support f-strings, i.e. format strings with the f prefix.
For example in Python 2.7:
Python 2.7.16 (default, Jul 13 2019, 16:01:51)
[GCC 8.3.0] on linux2
>>> name = 'bobo'
>>> print(f"Let's talk about {name}.")
  File "<stdin>", line 1
    print(f"Let's talk about {name}.")
                                    ^

SyntaxError: invalid syntax


text:
Q: How to make data model of this api? I want to make a data model for my cartList api. if you hit following api in your browser 5 product will be added to your cart.
https://www.moharaj.com.bd/_public/addToCart?quantity=5&slug=cotton-fleece-hoodie-for-men-tekka-8486&variant_id=$variant_id=24469
you can check your cart list through this api:
https://www.moharaj.com.bd/_public/cartToContent
But my problem is when I try to make a model of this cartToContent that means cart list api there always generate a unique row Id or token which I can't store. can anyone has any idea how to make a data model of this api?? I have made a data model. I have given below:
// To parse this JSON data, do
//
//     final cartToContentModel = cartToContentModelFromJson(jsonString);

import 'package:meta/meta.dart';
import 'dart:convert';

CartToContentModel cartToContentModelFromJson(String str) => CartToContentModel.fromJson(json.decode(str));

String cartToContentModelToJson(CartToContentModel data) => json.encode(data.toJson());

class CartToContentModel {
    CartToContentModel({
        required this.cartTotal,
        required this.cartContent,
        required this.itemCount,
    });

    String cartTotal;
    CartContent cartContent;
    int itemCount;

    factory CartToContentModel.fromJson(Map<String, dynamic> json) => CartToContentModel(
        cartTotal: json["cart_total"],
        cartContent: CartContent.fromJson(json["cart_content"]),
        itemCount: json["item_count"],
    );

    Map<String, dynamic> toJson() => {
        "cart_total": cartTotal,
        "cart_content": cartContent.toJson(),
        "item_count": itemCount,
    };
}

class CartContent {
    CartContent({
        required this.c827Cdf7Ba8F3127F293690569Aff167,
    });

    C827Cdf7Ba8F3127F293690569Aff167 c827Cdf7Ba8F3127F293690569Aff167;

    factory CartContent.fromJson(Map<String, dynamic> json) => CartContent(
        c827Cdf7Ba8F3127F293690569Aff167: C827Cdf7Ba8F3127F293690569Aff167.fromJson(json["c827cdf7ba8f3127f293690569aff167"]),
    );

    Map<String, dynamic> toJson() => {
        "c827cdf7ba8f3127f293690569aff167": c827Cdf7Ba8F3127F293690569Aff167.toJson(),
    };
}

class C827Cdf7Ba8F3127F293690569Aff167 {
    C827Cdf7Ba8F3127F293690569Aff167({
        required this.rowId,
        required this.id,
        required this.name,
        required this.qty,
        required this.price,
        required this.weight,
        required this.options,
        required this.discount,
        required this.tax,
        required this.subtotal,
    });

    String rowId;
    int id;
    String name;
    String qty;
    int price;
    int weight;
    Options options;
    int discount;
    int tax;
    int subtotal;

    factory C827Cdf7Ba8F3127F293690569Aff167.fromJson(Map<String, dynamic> json) => C827Cdf7Ba8F3127F293690569Aff167(
        rowId: json["rowId"],
        id: json["id"],
        name: json["name"],
        qty: json["qty"],
        price: json["price"],
        weight: json["weight"],
        options: Options.fromJson(json["options"]),
        discount: json["discount"],
        tax: json["tax"],
        subtotal: json["subtotal"],
    );

    Map<String, dynamic> toJson() => {
        "rowId": rowId,
        "id": id,
        "name": name,
        "qty": qty,
        "price": price,
        "weight": weight,
        "options": options.toJson(),
        "discount": discount,
        "tax": tax,
        "subtotal": subtotal,
    };
}

class Options {
    Options({
        required this.attributeId,
        required this.variantId,
        required this.image,
    });

    dynamic attributeId;
    String variantId;
    List<Image> image;

    factory Options.fromJson(Map<String, dynamic> json) => Options(
        attributeId: json["attribute_id"],
        variantId: json["variant_id"],
        image: List<Image>.from(json["image"].map((x) => Image.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "attribute_id": attributeId,
        "variant_id": variantId,
        "image": List<dynamic>.from(image.map((x) => x.toJson())),
    };
}

class Image {
    Image({
        required this.id,
        required this.productId,
        required this.productImage,
        required this.createdAt,
        required this.prefixUrl,
        required this.updatedAt,
    });

    int id;
    int productId;
    String productImage;
    DateTime createdAt;
    String prefixUrl;
    DateTime updatedAt;

    factory Image.fromJson(Map<String, dynamic> json) => Image(
        id: json["id"],
        productId: json["product_id"],
        productImage: json["product_image"],
        createdAt: DateTime.parse(json["created_at"]),
        prefixUrl: json["prefix_url"],
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "product_id": productId,
        "product_image": productImage,
        "created_at": createdAt.toIso8601String(),
        "prefix_url": prefixUrl,
        "updated_at": updatedAt.toIso8601String(),
    };
}

A: You can make the map of cartitems values to list of cartitems.
Here's the updated model.
// To parse this JSON data, do
//
//     final cartToContentModel = cartToContentModelFromMap(jsonString);

import 'dart:convert';

class CartToContentModel {
    CartToContentModel({
        this.cartTotal,
        this.cartContent,
        this.itemCount,
    });

    final String cartTotal;
    final List<CartContent> cartContent;
    final int itemCount;

    factory CartToContentModel.fromJson(String str) => CartToContentModel.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory CartToContentModel.fromMap(Map<String, dynamic> json) => CartToContentModel(
        cartTotal: json["cart_total"],
        cartContent: List<CartContent>.from(json["cart_content"].values.map((item) => CartContent.fromMap(item))),
        itemCount: json["item_count"],
    );

    Map<String, dynamic> toMap() => {
        "cart_total": cartTotal,
        "cart_content": List<dynamic>.from(cartContent.map((x) => x.toMap())),
        "item_count": itemCount,
    };
}

class CartContent {
    CartContent({
        this.rowId,
        this.id,
        this.name,
        this.qty,
        this.price,
        this.weight,
        this.options,
        this.discount,
        this.tax,
        this.subtotal,
    });

    final String rowId;
    final int id;
    final String name;
    final String qty;
    final int price;
    final int weight;
    final Options options;
    final int discount;
    final int tax;
    final int subtotal;

    factory CartContent.fromJson(String str) => CartContent.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory CartContent.fromMap(Map<String, dynamic> json) => CartContent(
        rowId: json["rowId"],
        id: json["id"],
        name: json["name"],
        qty: json["qty"],
        price: json["price"],
        weight: json["weight"],
        options: Options.fromMap(json["options"]),
        discount: json["discount"],
        tax: json["tax"],
        subtotal: json["subtotal"],
    );

    Map<String, dynamic> toMap() => {
        "rowId": rowId,
        "id": id,
        "name": name,
        "qty": qty,
        "price": price,
        "weight": weight,
        "options": options.toMap(),
        "discount": discount,
        "tax": tax,
        "subtotal": subtotal,
    };
}

class Options {
    Options({
        this.attributeId,
        this.variantId,
        this.image,
    });

    final dynamic attributeId;
    final String variantId;
    final List<Image> image;

    factory Options.fromJson(String str) => Options.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Options.fromMap(Map<String, dynamic> json) => Options(
        attributeId: json["attribute_id"],
        variantId: json["variant_id"],
        image: List<Image>.from(json["image"].map((x) => Image.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "attribute_id": attributeId,
        "variant_id": variantId,
        "image": List<dynamic>.from(image.map((x) => x.toMap())),
    };
}

class Image {
    Image({
        this.id,
        this.productId,
        this.productImage,
        this.createdAt,
        this.prefixUrl,
        this.updatedAt,
    });

    final int id;
    final int productId;
    final String productImage;
    final DateTime createdAt;
    final String prefixUrl;
    final DateTime updatedAt;

    factory Image.fromJson(String str) => Image.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Image.fromMap(Map<String, dynamic> json) => Image(
        id: json["id"],
        productId: json["product_id"],
        productImage: json["product_image"],
        createdAt: DateTime.parse(json["created_at"]),
        prefixUrl: json["prefix_url"],
        updatedAt: DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toMap() => {
        "id": id,
        "product_id": productId,
        "product_image": productImage,
        "created_at": createdAt.toIso8601String(),
        "prefix_url": prefixUrl,
        "updated_at": updatedAt.toIso8601String(),
    };
}


text:
Q: Binary search root of function using recursion I am trying to write a binary search function to find the root of function fun in the interval [,]:
Here is what I have which is close but missing the mark:
def binarySearchIter(fun, start, end,  eps=1e-10):
    '''
    fun: funtion to fund the root
    start, end: the starting and ending of the interval
    eps: the machine-precision, should be a very small number like 1e-10

    return the root of fun between the interval [start, end]
    '''

    root = (start + end)/2
    print(root)

    answer=fun(root)

    if abs(answer) <= eps:
        print(root)
        return root
    elif answer - eps > 0:
        binarySearchIter(fun, start, root, eps=1e-10)
    else:
        binarySearchIter(fun, root, end,  eps=1e-10)

Here is the function I am using to test:
def f(x):
return x ** 2 - 2

When I run: binarySearchIter(f, -3, 0, eps = 1e-10) I expect an answer of: -1.4142135623842478, however, root converges to -3 until it times out.
when I run binarySearchIter(f, 0, 3, eps = 1e-10) I am getting the correct answer of 1.4142135623842478.
I am obviously missing something that is making the function break depending on whether it gets (-3, 0) or (3,0).
Thank you for your help.

A: What you are seeing is that your function works only on increasing functions, which is true for x**2 - 2 between 0 and 3, but but does not work on decreasing functions, which is true for your function between -3 and 0.
There are several ways to fix your function. One way is to swap the values of start and end if fun(start) > fun(end). In other words, change your line root = (start + end)/2 to the three lines
if fun(start) > fun(end):
    start, end = end, start
root = (start + end)/2

This does slow down your routine, so there are better ways to do your routine. In particular, use iteration rather than recursion. Python does recursion pretty slowly compared to iteration.
However, your function is not robust. You should first check that fun(start) and fun(end) have differing signs. Your routine then would continue to redefine start and end so that their images continue to have opposite signs. If the signs are the same, there may not be a root of your function in that interval, and your routine definitely has no good way to decide which half of the interval to continue searching. One way to do this is to add these two lines before the ones I have already inserted:
if fun(start) * fun(end) > 0:
    raise 'Endpoints in binarySearchIter should yield opposite signs.'


text:
Q: change shapre of img I need help with Transform moving square image to circle in html canvas
I have imported a image that is a square. I want that image be round and still move.
Goal:

*

*square image to circle image, and still able to move.

I have tried alot of tutorial on stackoverflow mainly with c. stroke and c.split but when I apply those the image doesnt move anymore.
Does someone have any suggestions?

var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function Circle() {
    //Give var for circle
    this.x = 10;
    this.y = 100;
    this.dx = 1;
    this.dy = 1;
    this.radius = 50;
    this.diameter = 2 * this.radius;

    //Get external square picture (Needs to be converted in circle)
    var image = new Image();
    image.src = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";

    //Draw circle on canvas
    this.draw = function () {
        //Circle
        c.beginPath();
        c.arc(this.x, this.y, (this.radius*1), 0, Math.PI * 2, false);
        c.closePath();

        //TODO: cut square to circle

        //Place square (image) on top of the circle
        c.drawImage(image, (this.x-this.diameter/2) , (this.y-this.diameter/2), this.diameter, this.diameter);
    };

    //Update position
    this.update = function () {
        this.x += this.dx;
        this.draw()
    }
}

//Animate canvas
function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, innerWidth, innerHeight);
    this.update();
}

//Start
Circle();
animate();
canvas {
    border: 1px solid black;
    background: black;

}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<canvas></canvas>

</body>
</html>

A: The answer is to use context.clip(); in your case c.clip(); this creates a clipping filter on the canvas that you can then draw in. Before you make a clip you must make a save and then restore after you draw with c.save(); and c.restore() respectively.

var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
var circles = [];

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function Circle() {
    //Give var for circle
    this.x = 100;
    this.y = 100;
    this.dx = 1;
    this.dy = 1;
    this.radius = 50;
    this.diameter = 2 * this.radius;
    this.size = null;
    this.c = null;

    //Get external square picture (Needs to be converted in circle)
    var image = new Image();
    image.src = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";

    //Draw circle on canvas
    this.draw = function () {
        //Circle
        this.c.beginPath();
        this.c.arc(this.x, this.y, (this.radius*1), 0, Math.PI * 2, false);
        this.c.closePath();
        this.c.save();
        this.c.clip();
        //TODO: cut square to circle

        //Place square (image) on top of the circle
        this.c.drawImage(image, (this.x-this.diameter/2) , (this.y-this.diameter/2), this.diameter, this.diameter);
        this.c.restore();
    };

    //Update position
    this.update = function () {
        if(this.x - this.radius <= 0 || this.x + this.radius >= this.size.x){this.dx = -this.dx}

        this.x += this.dx;
        this.draw()
    }

    this.init = function(options) {

       Object.keys(options).forEach((key)=>{
          this[key]=options[key];
       })
    }
}

//Animate canvas
function animate() {
    requestAnimationFrame(animate);
    c.clearRect(0, 0, innerWidth, innerHeight);
    for(let i = 0; i < circles.length; i++){ circles[i].update(); }
}

//Start
for(let i = 0; i < 100; i-=-1){
    let circle = new Circle();
    circle.init({
        x: Math.random() * window.innerWidth,
        y: Math.random() * window.innerHeight,
        size: {x: window.innerWidth,y: window.innerHeight},
        c
    })
    circles.push(circle)
}
animate();
canvas {
    border: 1px solid black;
    background: black;

}
body {
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<canvas></canvas>

</body>
</html>

A: Start by generating your composed image and then use it in your animation code.
To make such a compositing, you'd better use compositing than clipping, because clipping is an all or nothing operation, it won't deal well with the antialiasing required by a circle.
To store this composed image in a convenient way, you can either use a second canvas, or in newest browsers an ImageBitmap, both will then be drawable by drawImage.
Here is an ES5 implementation, using a second canvas and a callback:

// older browsers version
function makeCircleImage(radius, src, success, failure) {
  var canvas = document.createElement('canvas');
  canvas.width = canvas.height = radius * 2;
  var ctx = canvas.getContext("2d");
  var img = new Image();
  img.src = src;
  img.onload = function() {
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    // we use compositing, offers better antialiasing than clip()
    ctx.globalCompositeOperation = 'destination-in';
    ctx.arc(radius, radius, radius, 0, Math.PI*2);
    ctx.fill();
    success(canvas);
  };
  img.onerror = failure;
}
var url = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";
makeCircleImage( 50, url, function( canvas ) {
  document.body.appendChild(canvas);
}, console.error );
canvas {
  border: 1px solid black;
  background: black;
}

And here is one that you can use in newest browsers which will store an ImageBitmap (preferable when available for memory and theoretical speed of drawing).

// newest browsers version
function makeCircleImage( radius, src ) {
  return new Promise( (resolve, reject) => {
    // this canvas will get Garbage Collected
    const canvas = document.createElement( 'canvas' );
    canvas.width = canvas.height = radius * 2;
    const ctx = canvas.getContext( "2d" );
    const img = new Image();
    img.src = src;
    img.onload = function() {
      ctx.drawImage( img, 0, 0, canvas.width, canvas.height );
      // we use compositing, offers better antialiasing than clip()
      ctx.globalCompositeOperation = 'destination-in';
      ctx.arc( radius, radius, radius, 0, Math.PI*2 );
      ctx.fill();
      resolve( createImageBitmap( canvas ) );
    };
    img.onerror = reject;
  });
}

async function init() {
  const url = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";
  const img = await makeCircleImage(50, url);
  document.querySelector('canvas')
    .getContext('2d')
    .drawImage(img, 0,0);
};
init().catch( console.error );
canvas {
  border: 1px solid black;
  background: black;
}
<canvas></canvas>

Now that we have a clear source ready to use, all our we have to do in the animation code is to put these pixels, without any heavy computation:

// older browsers version
function makeCircleImage(radius, src, callback) {
  var canvas = document.createElement('canvas');
  canvas.width = canvas.height = radius * 2;
  var ctx = canvas.getContext("2d");
  var img = new Image();
  img.src = src;
  img.onload = function() {
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    // we use compositing, offers better antialiasing than clip()
    ctx.globalCompositeOperation = 'destination-in';
    ctx.arc(radius, radius, radius, 0, Math.PI*2);
    ctx.fill();
    callback(canvas);
  };
}

function Circle( x, y, radius ) {
  //Give var for circle
  this.x = x;
  this.y = y;
  this.dx = 1;
  this.dy = 1;
  this.radius = radius;
}
// use prototyping if you wish to make it a class
Circle.prototype = {
//Draw circle on canvas
  draw: function () {
    var
      x = (this.x - this.radius),
      y = (this.y - this.radius);
    // draw is a single call
    c.drawImage( this.image, x, y );
  },
  update: function () {
    var
      max_right = canvas.width + this.radius,
      max_left = this.radius * -1;
    this.x += this.dx;
    if( this.x > max_right ) {
      this.x += max_right - this.x;
      this.dx *= -1;
    }
    if( this.x < max_left ) {
      this.x += max_left - this.x;
      this.dx *= -1;
    }
  },
  init: function(callback) {
    var url = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";
    makeCircleImage( this.radius, url, function(img) {
      this.image = img;
      callback();
    }.bind(this));
  }
};

//Animate canvas
function animate() {
  c.clearRect(0, 0, window.innerWidth, window.innerHeight);
  circles.forEach(function( circle ) {
    circle.update();
  });
  circles.forEach(function( circle ) {
    circle.draw();
  });
  requestAnimationFrame(animate);
}

var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var circles = [
  new Circle(10, 100, 50),
  new Circle(10, 200, 30),
  new Circle(10, 300, 50)
];
var ready = 0;
circles.forEach(function(circle) {
  circle.init(oncircledone);
});
function oncircledone() {
  if(++ready === circles.length) {
    animate()
  }
}
canvas {
    border: 1px solid black;
    background: black;

}
<!DOCTYPE html>
<html>
<head>
</head>
<body>

<canvas></canvas>

</body>
</html>

And for newest browsers:

// newest browsers version
function makeCircleImage( radius, src ) {
  return new Promise( (resolve, reject) => {
    // this canvas will get Garbage Collected
    const canvas = document.createElement( 'canvas' );
    canvas.width = canvas.height = radius * 2;
    const ctx = canvas.getContext( "2d" );
    const img = new Image();
    img.src = src;
    img.onload = function() {
      ctx.drawImage( img, 0, 0, canvas.width, canvas.height );
      // we use compositing, offers better antialiasing than clip()
      ctx.globalCompositeOperation = 'destination-in';
      ctx.arc( radius, radius, radius, 0, Math.PI*2 );
      ctx.fill();
      resolve( createImageBitmap( canvas ) );
    };
    img.onerror = reject;
  });
}

class Circle {
  constructor( x, y, radius ) {
    this.x = x;
    this.y = y;
    this.dx = 1;
    this.dy = 1;
    this.radius = radius;
  }
  draw() {
    const x = (this.x - this.radius);
    const y = (this.y - this.radius);
    c.drawImage( this.image, x, y );
  }
  update() {
    const max_right = canvas.width + this.radius;
    const max_left = this.radius * -1;
    this.x += this.dx;
    if( this.x > max_right ) {
      this.x += max_right - this.x;
      this.dx *= -1;
    }
    if( this.x < max_left ) {
      this.x += max_left - this.x;
      this.dx *= -1;
    }
  }
  async init() {
    const url = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";
    this.image = await makeCircleImage( this.radius, url );
  }
}

//Animate canvas
function animate() {
  c.clearRect(0, 0, window.innerWidth, window.innerHeight);
  circles.forEach( (circle) => circle.update() );
  circles.forEach( (circle) => circle.draw() );

  requestAnimationFrame(animate);
}

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const circles = [
  new Circle(10, 50, 50),
  new Circle(10, 150, 30),
  new Circle(450, 250, 80)
];

Promise.all(circles.map( (circle) => circle.init() ))
  .then(animate)
  .catch(console.error);
canvas {
    border: 1px solid black;
    background: black;

}
<canvas></canvas>

But if you are going to have a lot of Circle instances and that they will only differ in their radius, but share the same original image's source, then you might prefer to store a single high quality version of the composed image and just rescale it in each instance's draw call.

// newest browsers version
function makeCircleImage( radius, src ) {
  return new Promise( (resolve, reject) => {
    // this canvas will get Garbage Collected
    const canvas = document.createElement( 'canvas' );
    canvas.width = canvas.height = radius * 2;
    const ctx = canvas.getContext( "2d" );
    const img = new Image();
    img.src = src;
    img.onload = function() {
      ctx.drawImage( img, 0, 0, canvas.width, canvas.height );
      // we use compositing, offers better antialiasing than clip()
      ctx.globalCompositeOperation = 'destination-in';
      ctx.arc( radius, radius, radius, 0, Math.PI*2 );
      ctx.fill();
      resolve( createImageBitmap( canvas ) );
    };
    img.onerror = reject;
  });
}

(async () => {
const url = "https://assets.coingecko.com/coins/images/2607/large/molecular_future.png?1547036754";
const image = await makeCircleImage(250, url); // original size of the png image
class Circle {
  constructor( x, y, radius ) {
    this.x = x;
    this.y = y;
    this.dx = 1;
    this.dy = 1;
    this.radius = radius;
  }
  draw() {
    const x = (this.x - this.radius);
    const y = (this.y - this.radius);
    // now they all use the same image
    // with a bit more computation though due to resizing
    c.drawImage( image, x, y , this.radius * 2, this.radius * 2);
  }
  update() {
    const max_right = canvas.width + this.radius;
    const max_left = this.radius * -1;
    this.x += this.dx;
    if( this.x > max_right ) {
      this.x += max_right - this.x;
      this.dx *= -1;
    }
    if( this.x < max_left ) {
      this.x += max_left - this.x;
      this.dx *= -1;
    }
  }
}

//Animate canvas
function animate() {
  c.clearRect(0, 0, window.innerWidth, window.innerHeight);
  circles.forEach( (circle) => circle.update() );
  circles.forEach( (circle) => circle.draw() );

  requestAnimationFrame(animate);
}

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const rand = (n) => Math.random() * n;
const circles = Array.from({ length: 50 })
  .map( () =>
    new Circle(
      rand(canvas.width),
      rand(canvas.height),
      rand(125)
    )
  );

animate();

})()
.catch(console.error);
canvas {
    border: 1px solid black;
    background: black;

}
<canvas></canvas>


text:
Q: I need Linux (eGPU, Cuda, Tensorflow) on my MacBook Pro Im at the end of my wits. Im having an MacBook Pro 2018 15" and all I want to do is just to install ubuntu and its a nightmare.
I want to use macOS when im on the go, at university etc and when im come I want to plug in my mouse, keyboard, eGPU and external SSD and boot onto ubuntu that is installed on the SSD and do my ML stuff.
I have to use Ubuntu since macOS doesn't have any Nvidia RTX drivers, and tensorflow for Mac does not support GPU for some strange reason.
Here is what I did:
I booted into recovery and turned off secure boot and also executed the csrutil disable command. After that I can boot from the USB and im trying to install it onto an external SSD via usb 3.0.
I tried that on my iMac and it wiped my boot partition and I had to reinstall everything.
When im installing it on my MacBook Pro im getting two error messages:
Executing 'grub-install/dev/sda' failed this is a fatal error
The 'grub-efi-amd64-signed' packaged failed to install into target /. Without the GRUB boot loader, the installed system will not boot
The weird thing is I was able to install PopOS but the wifi chip, keyboard and touchpad don't work and I didnt manage to install the Nvidia drivers either.
I really need some help im about to throw the towel down or my MacBook out of the window. PLEASE HELP ME im losing my mind.


text:
Q: javascript - creating URI string from objects I have the following variables in javascript
var domain= http://example.com/api/v1/purchases/get_purchases.json?
var header = 'df0a96ddbe1ada9fda4b1ed9b02cf67c'
var params = {
                   search:{
                         status_eq: 'frozen',
                         email_eq: 'a@a.com',
                         phone_number_eq: ''
                   }
                  }
var api_string = domain + header + params;

I need output of api_string to be:
http://example.com/api/v1/purchases/get_purchases.json?headers%5B_token%5D=df0a96ddbe1ada9fda4b1ed9b02cf67c&search%5Bemail_eq%5D=a@a.com&search%5Bphone_number_eq%5D=12345&search%5Bstatus_eq%5D=frozen

I tried JSON.stringify, encodeURI, encodeURIComponent but it doesnt work as expected.
I need to use this api_string in fetch function of react-native.

A: You could use a serializing function, like so:
serialize = function(obj, prefix) {
  var str = [], p;
  for(p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push((v !== null && typeof v === "object") ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}

console.log(serialize(params));

Gives:
search%5Bstatus_eq%5D=frozen&search%5Bemail_eq%5D=a%40a.com&search%5Bphone_number_eq%5D=`

A: Good news, string concatination can be done with just the + operator. So you can do something like this
let result = domain + "headers%5B_token%5D=" + header + "&search%5Bemail_eq%5D=" + params.search.eqmail_eq

(obviously extend this for the rest of the parameters, assuming you only have those three params ever)

A: Have you tried using the npm package url ?
This is an example of how it works:
    const url = require('url')

    let my_url = url.format({
          hostname: "mydomain.com",
          protocol: "http",
          query: {status_eq: 'frozen', email_eq: 'a@a.com',},
          pathname: '/my/path'
    })

here is the documentation if you need to know more about how it works.
WARNING
url.format takes in an object of the parameters you want to send to the server. Make sure that if one of the parameters you want to pass is an object you JSON.stringify it before adding it to the query. Here is a stackoverflow question that explains it.


text:
Q: Google stackdriver monitoring agent behind firewall I have a Google compute engine vm ubuntu host with stackdriver monitoring agent installed.
The vm host has a VPC firewall rule to deny all communication apart from a proxy server (to get system updates) and it has only an internal IP.
I have configured the stack driver agent according to doc's at https://cloud.google.com/monitoring/agent/install-agent.
The monitoring agent is unable to send monitor data to stackdriver unless i turn off the firewall rule.
What changes should i make to the VPC firewall rule in order for the agent to able to send data to stackdriver?

A: Stackdriver uses HTTPS to communicate with the Google API endpoints.
However, if your VM only has private IP addresses, you must also configure Private Google Access. I cover the requirements in this article:
https://www.jhanley.com/google-compute-stackdriver-logging-installation-setup-debugging/
These endpoints must be reachable for Stackdriver logging and monitoring to function:

*

*oauth2.googleapis.com

*monitoring.googleapis.com

*stackdriver.googleapis.com


text:
Q: Manage list of members acording to active/inactive I have a ruby program in which Member model posses
has_many :earnings
earning
belongs_to :member
members has two kind

    <%= f.label :kind %>

    <%= f.select :kind, ["active", "inactive"] %>

    <%= f.label :member %>

    <%= collection_select(:earning, :member_id, Member.all, :id, :bd, {}, {:multiple => false}) %>

//////////////////////
I have made this selection bar in earning/new.html.erb. But I actually want to list the active members only. not the inactive members. they should remain hidden. I am using rails 4.2.0 and ruby 2.0.0p598

A: You need define a scope in your Member model like this
class Member < ActiveRecord::Base
  scope :active_members, -> { where(kind: 'active') }
end

And use this in the collection_select like this

  <%= f.label :member %>

  <%= collection_select(:earning, :member_id, Member.active_members, :id, :bd, {}, {:multiple => false}) %>


text:
Q: Dynamic rendering of ui:include won't work when ui:repeat is used in included facelet Hello,
I'm putting ui:include inside h:panelGroup and rendering it dynamically when required.
The usual assumption and theory is, ManagedBean associated with the included page should not get initialized when ui:include is not rendered.
This is not happening when I use ui:repeat inside included page.
Here is a Example to repeat the Issue:
page.1.xhtml
<h:body>
    <h:form>

    </h:form>

    <h:panelGroup rendered="false" layout="block">
        <ui:include src="page2.xhtml"/>
    </h:panelGroup>
</h:body>

MBeanOne.java
@ManagedBean
@ViewScoped
public class MBeanOne implements Serializable{

    private String beanOnetxt;

    public MBeanOne() {
        System.out.println("MBeanOne - Constructor");
    }

    @PostConstruct
    public void init(){
        beanOnetxt = "This is Managed Bean 1";
        System.out.println("MBeanOne - Postconstruct");
    }
    //SETTERS and GETTERS
}

page2.xhtml
<h:body>
    <h:outputText value="#{mBeanTwo.beanTwotxt}"/>

    <ui:repeat var="var" value="#{mBeanTwo.versionList}">
        <h:outputText value="#{var}"/>

    </ui:repeat>
</h:body>

MBeanTwo.java
@ManagedBean
@ViewScoped
public class MBeanTwo implements Serializable{

    private String beanTwotxt;
    private List<String> versionList;

    public MBeanTwo() {
        System.out.println("MBeanTwo - Constructor");
    }

    @PostConstruct
    public void init(){
        beanTwotxt = "This is Managed Bean 2";

        versionList = new ArrayList<String>();
        versionList.add("Playground");
        versionList.add("Kestrel");
        versionList.add("Merlin");
        versionList.add("Tiger");

        System.out.println("MBeanTwo - Postconstruct");
    }
    //SETTER and GETTER
}

As you can see in page1.xhtml I have use rendered="false" for h:paneGroup which encapsulates ui:include, but still MBeanTwo is getting initialized when I load page1.xhtml.
If I remove ui:repeat from page2.xhtml then MBeanTwo is not getting initialized.
Is this a bug in JSF, if so any workaround available?
Versions used and tested:
Primefaces 3.5
JSF 2.1.13 and 2.2.0-m05

A: The <ui:include /> piece is not relevant in your question, it could be everything done in the same view with identical behaviour.
Anyway, it seems that <ui:repeat /> tag doesn't check its parents rendered attributes before doing bean initialization. However, the mBeanTwo#getVersionList method never gets evaluated, just the managed bean is created. That could bring you to a slowdown if you perform data access when you construct your bean, but never should break your view. I'm able to reproduce the problem in Mojarra 2.1.x versions, however they have fixed it for 2.2.x latest minors.
Seems a Mojarra implementation bug rather than an expected behaviour.
See also:

*

*JSF ui:repeat included by ui:include wrapped in h:panelGroup with conditional rendering... A mouthfull


text:
Q: Intellij IDEA don't offer 'new Class' for creating I have Maven project and when I want to create new class, it isn't in an offer. There is only new File. Also packages aren't available but instead of them, there are directories.
What I should turn on?
Edit:
I have IDEA 12, here is screenshots from different projects.
Project 1 - correct:

Project 2 - incorrect

A: New/Class and New/Package actions are only available within source roots. If you have a project folder selected, or some subfolder that is not within a src root, you won't be able to create classes there

A: Mark your directory as Source root and your problem is solved

A: Wrong.  IntelliJ 12 does allow you create new classes.  Under File->New you'll see Java Class, Package, all the usual suspects.
I don't see what Maven has to do with this at all.

A: If you set mark the folder as source root, the color is turned to be blue and now you can right click the folder to add your packages.
Click the link to see the snapshot.
http://i.stack.imgur.com/CTFS0.jpg


text:
Q: Kubernetes client-go creating services and enpdoints I am looking for pointers on how to create/update services and endpoints using the client-go API. Can't seem to find any examples or documentation on how to do it.
Thanks!
Satish

A:    clientset.CoreV1().Services("kube-system").Create(&corev1.Service{
            ObjectMeta: metav1.ObjectMeta{
                Name:                       controllerSVCName,
                Namespace:                  "kube-system",
                Labels: map[string]string{
                    "k8s-app": "kube-controller-manager",
                },
            },
            Spec: corev1.ServiceSpec{
                Ports:                    nil,
                Selector:                 nil,
                ClusterIP:                "",

            },
   })

A: Based on this.
For Services:
serviceClient := clientset.AppsV1().Services(apiv1.NamespaceDefault)

service := &corev1.Service{
        ObjectMeta: metav1.ObjectMeta{
            Name:                       "myservice",
            Namespace:                  "default",
            Labels: map[string]string{
                "app": "myapp",
            },
        },
        Spec: corev1.ServiceSpec{
            Ports:                    nil,
            Selector:                 nil,
            ClusterIP:                "",

        },
})

// Create Service
fmt.Println("Creating service...")
result, err := servicesClient.Create(service)
if err != nil {
    panic(err)
}

For deployments:
deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)

deployment := &appsv1.Deployment{
    ObjectMeta: metav1.ObjectMeta{
        Name: "demo-deployment",
    },
    Spec: appsv1.DeploymentSpec{
        Replicas: int32Ptr(2),
        Selector: &metav1.LabelSelector{
            MatchLabels: map[string]string{
                "app": "demo",
            },
        },
        Template: apiv1.PodTemplateSpec{
            ObjectMeta: metav1.ObjectMeta{
                Labels: map[string]string{
                    "app": "demo",
                },
            },
            Spec: apiv1.PodSpec{
                Containers: []apiv1.Container{
                    {
                        Name:  "web",
                        Image: "nginx:1.12",
                        Ports: []apiv1.ContainerPort{
                            {
                                Name:          "http",
                                Protocol:      apiv1.ProtocolTCP,
                                ContainerPort: 80,
                            },
                        },
                    },
                },
            },
        },
    },
}

// Create Deployment
fmt.Println("Creating deployment...")
result, err := deploymentsClient.Create(deployment)
if err != nil {
    panic(err)
}


text:
Q: Remote Push Notification badge count not increasing when app is in background I am working on remote push notification and getting badge count in payload. it's working fine when my app is active(foreground) but when app run in background and i got push then badge count not increases. Please help.
when app is active it calls didReceiveNotification method.
I am receiving this type of info in payload.
{aps = {alert = "Hi all.";badge = 6;sound = default;};}

I am not sure where is issue.

A: Try this
-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] cancelAllNotifications];
}


text:
Q: Есть ли разница в вызовах ивента без отписки и с отпиской? Разрабатываю оверлей для одной игры. Оверлей специфичный, не такие какие есть. Отображение урона нанесенного членами группы боссам, и еще немного полезной информации.
Возник такой вопрос, есть ли разница между вызовами событий у подписчиков событий в таком виде:
/// <summary>
///     Sends debug messages to the client.
/// </summary>
public event DebugMessage Message;

protected virtual void OnMessage(DebugMessageEventArgs eventArgs)
{
    Message?.Invoke(this, eventArgs);
}

И такого рода с удалением подписчика, если ссылка на него была удалена, но он остался подписан:
/// <summary>
///     Sends debug messages to the client.
/// </summary>
public event DebugMessage Message;

protected virtual void OnMessage(DebugMessageEventArgs eventArgs)
{
    if (Message == null)
    {
        return;
    }

    Delegate[] eventListeners = Message.GetInvocationList();
    DebugMessage subscriber = null;

    foreach (Delegate eventListener in eventListeners)
    {
        try
        {
            subscriber = (DebugMessage)eventListener;
            subscriber.Invoke(this, eventArgs);
        }
        catch
        {
            Message -= subscriber;
        }
    }
}

Есть ли разница между такими вызовами и нужно ли вообще так делать?


text:
Q: Passing Data from Slide menu to UITableViewController through UINavigationViewController How can I pass data from UINavigationController to The root UITableViewController?
I have implemented the ECSlidingViewController (https://github.com/edgecase/ECSlidingViewController). User selects one of the cells in the menu that correspond to different urls I want to display information from on my tableView that sitts on top of the UINavigationController. (u know the default combination that u get my dragging UINavigationController to ur storyboard). I am able to get the data from the sliding menu to my navigationController now I am trying to pass that same info on my tableview?
In my menu I have:
 UINavigationController *newTopViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"NavigationTop"];
    newTopViewController = [(NavigationTopViewController*)newTopViewController initWithCinema:self.myCinema];

In UINaviationController:
    - (id)initWithCinema:(Cinema *)cinema {
    self = [super init];
    if(self) {
        _myCinema = [[Cinema alloc] init];
        _myCinema = cinema;
    }
    return self;
}

- (void) viewDidLoad {
    [super viewDidLoad];

    // this log works I get the info to here.
    NSLog(@"url(navigation):%@", self.myCinema.cinemaURL);

    //MoviesTableViewController *moviesTableViewController = [[MoviesTableViewController alloc] initWithCinema:self.myCinema];

    //UITableViewController *newTopViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MoviesTable"];

    //NavigationTopViewController *newTopViewController = [[NavigationTopViewController alloc] initWithCinema:self.myCinema];
    //newTopViewController = [(MoviesTableViewController *)newTopViewController initWithCinema:self.myCinema];
    //[self performSegueWithIdentifier:nil sender:self.myCinema];
    [self prepareForSegue:nil sender:self.myCinema.cinemaURL];

}

In my UITableView:
  - (void)setCinema:(Cinema *)cinema {
    // works here too
    NSLog(@"Table(setCinema):%@", cinema.cinemaURL);
    self.myCinema = [[Cinema alloc] init];
    if(!cinema) {
        cinema.cityIndex = kAstanaIndex;
        cinema.name = kKeruen;
        cinema.nameForText = kKeruenText;
        cinema.cinemaURL = kKeruenURL;
        cinema.cinemaURLTomorrow = kKeruenURLtomorrow;
    }
    self.myCinema = cinema;
    // works here too!!!
    NSLog(@"Table(myCinema):%@", self.myCinema.cinemaURL);
}

However its gone in viewDidLoad:
- (void)viewDidLoad
{
    [super viewDidLoad];

    // set delegate to self
    self.tableView.delegate = self;

    // set loading theater's url

// does not work here: I GET NULL !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    NSLog(@"url(moviesTable):%@", self.myCinema.cinemaURL);
    _model = [[MovieModel alloc] initWithURL:self.myCinema.cinemaURL];
}

None of the methods I have tried (commented in Navigation worked...) at least for me. Please give me any suggestions. Thank you in advance.

A: UINavigationController does not hold any data, but rather a stack of view controllers. I'd recommend you check out frameworks such as the free Sensible TableView. The framework will automatically handle detail view generation and passing data between them. Saves me tons of development time in my projects.


text:
Q: keyboard vs menu conflict on Java 7, Mac OS How can I get a Java 7 application to have its menu bar at the top of the screen (on a Mac) and also have correctly working keyboard shortcuts?
I have a Java application with a Swing user interface. Many menus have keyboard equivalents, which are essential.
There is very little that is system-dependent, but on Mac OS X the menu bar should appear at the top of the screen instead of on each window, so I set apple.laf.useScreenMenuBar.
This works fine on Java 6, but on Java 7 (out last week!) compiling and running the same code causes the keyboard shortcuts to carry out their menu actions twice. For example, in the attached code, Command ⌘ + O opens two file dialogues instead of one. (The other keyboard shortcuts also act twice, but you sometimes have to move windows to see that they did.)
The keyboard problem goes away if I don't set apple.laf.useScreenMenuBar, and that's what I'll do if I have to, but my Mac users will be displeased. I'd really like to have the menu bar in the right place and the keyboard shortcuts working.

System: Mac OS 10.7.3 (Lion) on a late-2010 MacBook Pro
Java 7:
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b21)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)
Java 6:
java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04-415-11M3635)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode)

Where I've looked:
A discussion of why apple.laf.useScreenMenuBar should be gotten rid of
-- I'm all for it, but it doesn't seem to have happened.
A discussion about not using mrj.version to detect that you're on a Mac
-- not directly relevant, but sounded promising.
My apologies for the length of the attached code (148 lines), but my Swing coding is very old-fashioned. It should compile and run from the command line without any special flags or settings.
import javax.swing.*;
import java.awt.Toolkit;
import java.awt.*;
import java.awt.event.*;

/**
 * Shows that using the single screen-top menu bar on a Mac with Java 7
 * causes keyboard shortcuts to act twice.
 *
 * To see the problem(on a Mac -- running OS X 10.7.3 in my case):
 *   1) compile on either Java 6 or Java 7
 *   2) run on Java 7
 *   3) give the command-O shortcut
 * You will see two file dialogues.
 *
 *      -- J. Clarke, May 2012
 */

public class MenuBug {

    private static void go(String[] args) {

        // Comment out the following line to fix the problem;
        // leave it active to see the problem.
        // It doesn't help to ...
        // ... put the line into a static block.
        // ... put the line right after the setLookAndFeel call.
        // ... put the line before after the setLookAndFeel call.
        System.setProperty("apple.laf.useScreenMenuBar", "true");

        MainWindow mainWindow = new MainWindow();
    }

    public static void main(final String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    e + " while loading look and feel",
                    "MenuBug error", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                go(args);
            }
        });
    }
}

class MainWindow extends JFrame {

    MainWindow() {
        super ("Main Window");

        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener (new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    dispose();
                    System.exit(0);
                }
            });

        JMenuBar menuBar = createMenuBar();
        setJMenuBar(menuBar);

        pack();
        setSize(350,300);
        setVisible(true);
    }

    private JMenuBar createMenuBar() {
        JMenuBar mBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        String[] menuItemNames = new String[] {"New", "Open...", "Other"};
        for (int i = 0; i < menuItemNames.length; i++) {
            String miName = menuItemNames[i];
            JMenuItem mi = new JMenuItem(miName);
            mi.setActionCommand(miName);
            linkMenuItemToAction(mi);
            menu.add(mi);
        }
        mBar.add(menu);
        return mBar;
    }

    /**
     * Create an Action for menuItem, and make sure the action and the menu
     * item know about each other; where appropriate, add keyboard equivalents.
     * @param menuItem  The menu item to be linked to an action.
     */
    private void linkMenuItemToAction(JMenuItem menuItem) {
        final int META_MASK =
                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
        Action a = null;

        String miName = menuItem.getActionCommand();
        if (miName.equals ("New")) {
            a = new NewAction();
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
                    META_MASK));
        }
        else if (miName.equals ("Open...")) {
            a = new OpenAction();
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
                    META_MASK));
        }
        else if (miName.equals ("Other")) {
            a = new OtherAction();
            menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
                    META_MASK));
        }

        menuItem.setEnabled(a.isEnabled());
        menuItem.addActionListener(a);
    }

    private class NewAction extends AbstractAction {
        public void actionPerformed(ActionEvent e) {
            new MainWindow();
        }
    }

    private void makeDialog() {
        String dialogTitle = "Please choose a file to open";
        FileDialog fileDialog = new FileDialog(this, dialogTitle,
                FileDialog.LOAD);

        fileDialog.setVisible(true);
        String fileName = fileDialog.getFile();
    }

    private class OpenAction extends AbstractAction {
        public void actionPerformed(ActionEvent e) {
            makeDialog();
        }
    }

    private class OtherAction extends AbstractAction {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "an example message",
                    "not really an error", JOptionPane.ERROR_MESSAGE);
        }
    }
}

A: I'm answering my own question -- sort of. As noted in the comments to the original, the trouble goes away with Java 1.7u10.

A: It looks like that this problem still exist but now it can be reproduced with fn + backSpace (delete) on mac with 1.7_21.
I used the same example as above just added text field. Select part of text in textfield and press delete (fn+backspace)
Change KeyStroke to "DELETE" in linkMenuItemToAction method
else if (miName.equals ("Other"))
{
 a = new OtherAction();
 menuItem.setAccelerator(KeyStroke.getKeyStroke("DELETE"));
}

and add this:
JTextField textField = new JTextField(10);
textField.setText("Long long long long long long long text");
add(textField, BorderLayout.PAGE_START);

to MainWindow constructor.


text:
Q: Ljoop http get - callbacks not executed I want to use the ljoop library to make http requests. However, when I execute the get method or post, it just jumps over it, doesn't go into the callbacks.
The ip address delivers a json result in the browser successfully. So it could either use the 10.0.2.2 I am aware of that but it works fine with 192.... in the browswer as well.
I have added the internet permission but it just desn't seem to send the get request. The nodejs server with express does not receive anything only when using chrome on the emulator.
import android.app.Activity;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.conn.ConnectTimeoutException;
import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.message.BasicHeader;
import cz.msebera.android.httpclient.protocol.HTTP;
import schaschinger.eggermode.Restservice.Models.Item;
import schaschinger.eggermode.Restservice.Models.Stammkunde;

public class HttpRequestTask {

    public static final String URL_STAMMKUNDEN = "http://192.168.1.190:9999/stammkunden/stammkunden";
    public static final String URL_ITEMS = "http://192.168.1.190:9999/item/items";

    Activity activity;
    final AsyncHttpClient asyncHttpClient;
    HttpResponseHandler httpResponseHandler;

    public HttpRequestTask(Activity activity) {
        this.activity = activity;
        this.asyncHttpClient = new AsyncHttpClient();
        httpResponseHandler = new HttpResponseHandler();

        this.asyncHttpClient.allowRetryExceptionClass(IOException.class);
        this.asyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class);
        this.asyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class);
    }

    public boolean insertStammkunde(Stammkunde stammkunde) {

        String stammkundenJson = stammkunde.getJson();

        StringEntity stringEntity = null;
        try {
            stringEntity = new StringEntity(stammkundenJson);
        } catch (UnsupportedEncodingException e) {
            return false;
        }
        stringEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        RequestHandle requestHandle = asyncHttpClient.post(activity.getApplicationContext()
                , HttpRequestTask.URL_STAMMKUNDEN, stringEntity, "application/json", httpResponseHandler);

        return requestHandle.isFinished();
    }

    public List<Item> getItems(){

        asyncHttpClient.setConnectTimeout(1000);

        asyncHttpClient.get("https://www.google.com", new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                // called before request is started
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                // called when response HTTP status is "200 OK"
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
                // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            }

            @Override
            public void onRetry(int retryNo) {
                // called when request is retried
            }
        });

        return null;
    }

}

A: Your code isn't supposed to invoke the callback when control reaches the row with the asynchronous call. Instead, the callback is invoked later, when the server sends a response to your request. This is what "asynchronous" means.
You can return the items wrapped in a Future by, for instance, changing the return type of  getItems to CompletableFuture<List<Item>> and returning a CompletableFuture. Call that future's complete in the onSuccess callback and completeExceptionally in the onFailure callback.
Then, you have a choice of either calling the future's get to synchronously get the result (which will block until the request completes or times out), or assign callbacks with handle (or thenAccept and exceptionally) from CompletionStage, which CompletableFuture implements.