Sunday 31 March 2019

Django unable to delete/clear data on form

i have a edit_profile view at my django application that also checks if the pgp key the users saves to his profile is in RSA format, Anyways if i add a profile avatar for the very first time it works like a charm, if i want to clear or delete it, im always jumping onto the execpt block and the user avatar remains unchanged. Well i dont see a clear reason why at the point can maybe smb give me a hint here:

validators.py

def default_image_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.jpg', '.jpeg', '.png']
    if not ext.lower() in valid_extensions:
        raise ValidationError(u'Unsupported file extension. Allowed types are: .jpg, .jpeg, .png')

def default_image_size(value):
    limit = 2 * 1024 * 1024
    if value.size > limit:
        raise ValidationError('File too large. Size should not exceed 2 MiB/MB.')

models.py

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('media', filename)


def get_file_path_user_avatar(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return os.path.join('user_avatar', filename)

...


    class User(AbstractBaseUser):
    user = models.CharField(verbose_name='Username', max_length=20, unique=True)
    bio = models.TextField(verbose_name='Bio', blank=True, null=True, max_length=2500)
    pubpgp = models.TextField(verbose_name='Public RSA PGP Key - (ASCII-Armored)', blank=True, null=True, max_length=3000)
    avatar = fields.ImageField(
                              null=True,
                              blank=True,
                              upload_to=get_file_path_user_avatar,
                              validators=[default_image_size, default_image_file_extension],
                              dependencies=[FileDependency(processor=ImageProcessor(
                                  format='PNG', quality=99, scale={'max_width': 700, 'max_height': 700}))])

views.py

def edit_profile(request):
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES, instance=request.user)
        try:
            pubpgp = request.POST.get('pubpgp')
            if not pubpgp or PGPKey.from_blob(pubpgp.rstrip("\r\n"))[0].key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign:
                if form.is_valid():
                   form.save()
                   messages.success(request, "Profile has been updated successfully.")
                   return redirect(reverse('home'))
                else:
                  print(form.errors)
                  return render(request, 'app_Accounts/edit_profile.html', {'form': form})
            else:
                messages.error(request, "Uuups, something went wrong, please try again.")
                return render(request, 'app_Accounts/edit_profile.html', {'form': form})
        except Exception as e:
            print(e.args)
            messages.error(request, "PGP-Key is wrong formated.")
            return render(request, 'app_Accounts/edit_profile.html', {'form': form})
    else:
        form = UserForm(instance=request.user)
        args = {'form': form}
        return render(request, 'app_Accounts/edit_profile.html', args)

forms.py

class UserForm(forms.ModelForm):

    class Meta:
        model = User
        fields = (
            'avatar',
            'bio',
            'pubpgp'
        )
    captcha = CaptchaField()

    field_order = ['avatar', 'bio', 'pubpgp']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['avatar'].label = mark_safe('Avatar:')
        self.fields['avatar'].help_text = mark_safe("<h4 class='help_text'>→ Choose a Avatar for your Profile (max. 2 MB)</h4>")
        self.fields['bio'].widget.attrs.update({'class': 'class-two-input-fields'})
        self.fields['bio'].help_text = mark_safe("<h4 class='help_text'>→ Something about you</h4>")
        self.fields['pubpgp'].widget.attrs.update({'class': 'class-two-input-fields'})
        self.fields['pubpgp'].label = 'Public PGP-key (Optional)'



from Django unable to delete/clear data on form

Xamarin Forms - CustomRenderer Not Working After Navigating Away

I have a custom renderer in my iOS Native code for my main page. It works perfectly fine when the app start up, and renders Navbar items using the iOS System icons which is what I want. However, if I navigate away from the main page, when I navigate back the RightBarButtonItems array only contains two uninstantiated objects, I put in a check (RightNavItems.Title == null) to continue when this was the case to see what would happen, and indeed the items are not rendered, if I navigate away and back again the app crashes since the RightBarButtonItems array is now empty.

Why is it that the toolbar items are uninitialised when navigating back to the main page? What is the proper way to deal with navigation in a custom renderer like this?

Here is the code for the custom renderer:

public class ItemsPageRenderer : PageRenderer
{
    public new ItemsPage Element
    {
        get { return (ItemsPage)base.Element; }
    }

public override void ViewWillAppear(bool animated)
{
    base.ViewWillAppear(animated);

    var rightNavList = new List<UIBarButtonItem>();

    var navigationItem = this.NavigationController.TopViewController.NavigationItem;

    for (var i = 0; i < Element.ToolbarItems.Count; i++)
    {
        var reorder = (Element.ToolbarItems.Count - 1);
        var ItemPriority = Element.ToolbarItems[reorder - i].Priority;

        UIBarButtonItem RightNavItems = navigationItem.RightBarButtonItems[i];
        if (RightNavItems.Title == null)
            continue;

        if (RightNavItems.Title.ToLower() == "add")
        {
            rightNavList.Add(new UIBarButtonItem(UIBarButtonSystemItem.Add)
            {
                Action = RightNavItems.Action,
                Target = RightNavItems.Target
            });
        }
        else if (RightNavItems.Title.ToLower() == "edit")
        {
            rightNavList.Add(new UIBarButtonItem(UIBarButtonSystemItem.Edit)
            {
                Action = RightNavItems.Action,
                Target = RightNavItems.Target
            });
        }
        else
        {
            rightNavList.Add(RightNavItems);
        }
    }

    navigationItem.SetRightBarButtonItems(rightNavList.ToArray(), false);
}
}



from Xamarin Forms - CustomRenderer Not Working After Navigating Away

How do you get a string to a character array in JavaScript?

How do you get a string to a character array in JavaScript?

I'm thinking getting a string like "Hello world!" to the array ['H','e','l','l','o',' ','w','o','r','l','d','!']



from How do you get a string to a character array in JavaScript?

How to make screenshots from TS video stream?

I would like to make screenshots each 1 minutes from the video stream. The video stream is provided as m3u8 file:

#EXTM3U
#EXT-X-TARGETDURATION:6
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:112076
#EXT-X-PROGRAM-DATE-TIME:2019-03-19T16:16:53Z
#EXTINF:6.000, 2019/03/19/16/16/53-06000.ts
#EXTINF:6.000, 2019/03/19/16/16/59-06000.ts
#EXTINF:6.000, 2019/03/19/16/17/05-06000.ts
#EXTINF:6.000, 2019/03/19/16/17/11-06000.ts

I found a library to parse it - https://github.com/globocom/m3u8. But I don't understand how I can convert this TS video stream to single jpeg file. Am I supposed to

  1. download TS file
  2. find needed frame
  3. extract it
  4. delete ts file?

Should I use OpenCV or is there any easier solution?

use OpenV



from How to make screenshots from TS video stream?

Jest - Simple tests are slow

I am using Jest to test an angular app and it is taking a really long time for simple tests to run and I can not seem to figure out why.

My Jest setup in package.json:

"jest": {
  "modulePaths": [
    "<rootDir>/src",
    "<rootDir>/node_modules"
  ],
  "testPathIgnorePatterns": [
    ".git/.*",
    "node_modules/.*"
  ],
  "transformIgnorePatterns": [
    "node_modules/.*",
    ".*\\.js"
  ],
  "setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.js",
  "preset": "jest-preset-angular",
  "testEnvironment": "jsdom",
  "testRegex": "src/app/.*\\.spec\\.ts$",
  "moduleFileExtensions": [
    "ts",
    "js",
    "json"
  ],
  "verbose": true,
  "cacheDirectory": ".jest-cache",
  "coveragePathIgnorePatterns": [
    ".*\\.(shim\\.ngstyle|ngfactory)\\.ts"
  ],
  "globals": {
    "ts-jest": {
      "tsConfigFile": "./tsconfig.json"
    },
    "__TRANSFORM_HTML__": true
  }
}

My Jest setup file:

'use strict';
require('core-js/es6/reflect');
require('core-js/es7/reflect');
require('zone.js');
require('zone.js/dist/proxy.js');
require('zone.js/dist/sync-test');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('jest-zone-patch');

const getTestBed = require('@angular/core/testing').getTestBed;
const BrowserDynamicTestingModule = require('@angular/platform-browser-dynamic/testing').BrowserDynamicTestingModule;
const platformBrowserDynamicTesting = require('@angular/platform-browser-dynamic/testing')  .platformBrowserDynamicTesting;

getTestBed().initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
);

Here is my simple test:

fdescribe('RichTextEditorComponent', () => {
  it('should be fast', () => {
    expect(true).toBeTruthy();
  });
});

Does anyone have any idea as to why this is taking 9+ seconds? enter image description here



from Jest - Simple tests are slow

StartLockTask fails with Hardware Buttons

I have gone through the provisioning and ownership requirements to use SetLockTaskPackages() and StartLockTask(). In the emulators the StartLockTask() works as expected. The on-screen buttons are removed and message "Unpinning isn't allowed by your organization." is displayed on the screen.

This method seems to work good on supported devices for locking the user into a kiosk like environment. Although some devices, such as the Samsung Galaxy TabA 7, have hardware buttons. Even though the user is told "Unpinning isn't allowed by your organization." they can still use the hardware button combination to exit the application.

My solution for this was to detect the OnLockTaskModeExiting then notify my MainActivity to re-apply my policies and StartLockTask()

So I made EventPasser class. It's job is to raise an event from DeviceAdminReceiver to my MainActivity.

    public class EventPasser
    {
        public static event EventHandler ScreenUnlocked;

        public static void RaiseUnlockEvent()
        {
            EventHandler handler = ScreenUnlocked;
            if (null != handler) handler(null, EventArgs.Empty);
        }
    }

In my DeviceAdminReceiver I listen for OnLockTaskModeExiting and raise an event that is attached in my MainActivity.

    public class DeviceAdmin : DeviceAdminReceiver
    {
        public override void OnLockTaskModeExiting(Context context, Intent intent)
        {

            base.OnLockTaskModeExiting(context, intent);

            // Raise our Unlock Event
            EventPasser.RaiseUnlockEvent();

        }
     }

In my MainActivity on the OnCreate I hook up to the static event.

    EventPasser.ScreenUnlocked += EventPasser_ScreenUnlocked;

The event just re-applies my locking policies and StartLockTask().

    private void EventPasser_ScreenUnlocked(object sender, EventArgs e)
    {
        RegisterAndLock();
    }

This works very well asides from the small annoyance that you see the message "Application locked on screen".

I am a c# programmer, not quite yet an Android developer. I am very new to Android and I have solved this the way that I know how. I feel like I should be able to avoid this event passing solution I just don't know how.

Is there a more direct way to re-apply my StartLockTask() packages on OnLockTaskModeExiting? Or even better; is there a way to enforce the StartLockTask() to respect hardware buttons?



from StartLockTask fails with Hardware Buttons

Problem in building pgs4a project (project.properties file error)

I am creating a game for Android using pygame and pgs4a. When I run android.py build mygame release it throws this error :

Updating build files.  

Updated project.properties
Updated local.properties
Added file F:\pgs4a-master\build.xml
Updated file F:\pgs4a-master\proguard-project.txt

Creating assets directory.


Packaging internal data.

Listing private ...
Listing private\include ...
Listing private\include\python2.7 ...
Listing private\lib ...
Listing private\lib\PIL ...
Listing private\lib\android ...
Compiling private\lib\android\__init__.py ...
Compiling private\lib\android\apk.py ...
Compiling private\lib\android\mixer.py ...
Listing private\lib\encodings ...
Listing private\lib\json ...
Listing private\lib\pygame ...
Listing private\lib\pygame\threads ...
Listing private\lib\python2.7 ...
Listing private\lib\python2.7\bsddb ...
Listing private\lib\python2.7\compiler ...
Listing private\lib\python2.7\config ...
Listing private\lib\python2.7\distutils ...
Listing private\lib\python2.7\distutils\command ...
Listing private\lib\python2.7\email ...
Listing private\lib\python2.7\email\mime ...
Listing private\lib\python2.7\encodings ...
Listing private\lib\python2.7\hotshot ...
Listing private\lib\python2.7\importlib ...
Listing private\lib\python2.7\json ...
Listing private\lib\python2.7\lib-dynload ...
Listing private\lib\python2.7\logging ...
Listing private\lib\python2.7\multiprocessing ...
Listing private\lib\python2.7\multiprocessing\dummy ...
Listing private\lib\python2.7\plat-linux3 ...
Listing private\lib\python2.7\pydoc_data ...
Listing private\lib\python2.7\site-packages ...
Listing private\lib\python2.7\site-packages\android ...
Listing private\lib\python2.7\site-packages\jnius ...
Listing private\lib\python2.7\site-packages\pygame ...
Listing private\lib\python2.7\site-packages\pygame\threads ...
Listing private\lib\python2.7\sqlite3 ...
Listing private\lib\python2.7\sqlite3\test ...
Listing private\lib\python2.7\unittest ...
Listing private\lib\python2.7\wsgiref ...
Listing private\lib\python2.7\xml ...
Listing private\lib\python2.7\xml\dom ...
Listing private\lib\python2.7\xml\etree ...
Listing private\lib\python2.7\xml\parsers ...
Listing private\lib\python2.7\xml\sax ...
Listing private\lib\sqlite3 ...
Listing mygame ...
Compiling mygame\rotating_cube.py ...

I'm using Ant to build the package.

Buildfile: F:\pgs4a-master\build.xml

-check-env:
 [checkenv] Android SDK Tools Revision 24.0.2
 [checkenv] Installed at F:\pgs4a-master\android-sdk

-setup:
     [echo] Project Name: MYCUbe-1.0
  [gettype] Project Type: Application

-pre-clean:

clean:

BUILD FAILED
F:\pgs4a-master\android-sdk\tools\ant\build.xml:459: ../../google-play-services_lib resolve to a path with no project.properties file for project F:\pgs4a-master

Total time: 3 seconds

I have absolutely no idea how to proceed further. I know that it has something to do with path of project.properties file. Even searching on internet for similar problem didn't help me.Can anyone tell me how to edit the project.properties file. Many thanks in advance!

A request:

If somebody has already completed a project using pgs4a it can really help me if you could provide the example of the code directory location, the contents of the project.properties file and other relevant details about the project. I will edit my files and locations accordingly!. I would be very grateful.

Note: F:\pgs4a-master\mygame is folder containing python script `rotating_cube.py'



from Problem in building pgs4a project (project.properties file error)

didDropSampleBuffer is called very often in iOS

I capture the video and do some analyses on it in captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer delegate. but after a short time this method is not called. then captureOutput:(AVCaptureOutput *)output didDropSampleBuffer delegate is called.

When I don't do anything in didOutputSampleBuffer, everything is okay.
I run a tensor flow model in this delegate. And this causes the problem.

Problem:
The problem is that when didDropSampleBuffer is called, didOutputSampleBuffer will not called again.

My solution:
My solution was stoping and starting avCaptureSession. but that caused extra memory usage! Which finally caused my app to crash.

 - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
    {
        // ******  do heavy work in this delegate *********
        graph = [TensorflowGraph new];
        predictions = [graph runModelOnPixelBuffer:pixelBuffer orientation: UIDeviceOrientationPortrait CardRect: _vwRect];
    }

    - (void)captureOutput:(AVCaptureOutput *)output didDropSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
    {
                CFTypeRef droppedFrameReason = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_DroppedFrameReason, NULL);
                NSLog(@"dropped frame, reason: %@", droppedFrameReason);
    }

----> dropped frame, reason: OutOfBuffers

According to [https://developer.apple.com/library/archive/technotes/tn2445/_index.html]:

This condition is typically caused by the client holding onto buffers for too long, and can be alleviated by returning buffers to the provider.

How can I return buffer to the provider?

1



from didDropSampleBuffer is called very often in iOS

domain = AVFoundationErrorDomain , code = -11828

I am using the streaming url from CloudFront.

Sample url: https://d14nt81hc5bide.cloudfront.net/qyYj1PcUkYg2ALDfzAdhZAmb

On android , it is working fine but in iOS it says: domain = AVFoundationErrorDomain , code = -11828

From apple doc the error code 11828 is AVErrorFileFormatNotRecognized. The media could not be opened because it is not in a recognized format.

Can someone suggest how to fix this error ?



from domain = AVFoundationErrorDomain , code = -11828

Subscriptions are not stable. Prisma terminates with a GqlConnectionTerminate error

I just implemented subscriptions in my API which use graphql-yoga. I have one prisma server which have the following config:

databases:
  default:
    connector: postgres
    host: 
    database: prisma
    port: 5432
    user: admin
    password: ${DB_PASSWORD}
    migrations: true
    rawAccess: true
    ssl: true
    connectionLimit: 5

Note that I have limited the number of connections because I'm connecting to a Google Cloud SQL instance which have limited number of allowed connections. Now I have 4 yoga apps connecting to this one prisma server. The problem is, sometimes the subscriptions work and sometimes it throws the following error (In the playground):

{
  "error": "Could not connect to websocket endpoint wss://yourapi.com/subscriptions. Please check if the endpoint url is correct."
}

When I check the prisma container logs, I found this:

Deployment worker initialization complete.
Version is up to date.
[SubscriptionSessionActor] Received unknown message: com.prisma.subscriptions.protocol.SubscriptionProtocolV07$Requests$GqlConnectionTerminate$@494aa66a
Killed
Obtaining exclusive agent lock...
Initializing workers...
Obtaining exclusive agent lock... Successful.
Successfully started 1 workers.
Server running on :4466

My APIs are behind an Nginx proxy:

server {
  server_name example.com;
  listen 443 ssl http2;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_set_header X-Custom-Referrer "idToken";
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_max_temp_file_size 0;
    proxy_pass http://127.0.0.1:4050;
    proxy_redirect off;
    proxy_read_timeout 240s;
  }


    ssl_certificate ___ # managed by Certbot
    ssl_certificate_key ___ # managed by Certbot
}

I can't figure it out where is the issue. Any clue or guidance will be much appreciated. Thanks in advance.



from Subscriptions are not stable. Prisma terminates with a GqlConnectionTerminate error

Xcode Command /usr/bin/codesign failed with exit code 1 : errSecInternalComponent

I am trying to add new provisioning profile to my Xcode, to test an app on the device. Here are the steps I followed:

  1. Deleted all certificates and provisioning profiles

  2. Create/Add IOS Dev Certificate

  3. Add My IOS Device Online

  4. Create IOS Provisioning Profile

  5. Add IOS Provisioning Profile

  6. Clean App

  7. Build Then Run App

  8. Set Codesigning nd Provisioning Profile In Build Settings

  9. Lots of Googling > to no successes

Here is the error I get:

CSSM_SignData returned: 800108E6
/Users/alexpelletier/Library/Developer/Xcode/DerivedData/MyExpense-efnqzvoqwngzcmazaotyalepiice/Build/Products/Debug-iphoneos/MyExpense.app:     errSecInternalComponent
Command /usr/bin/codesign failed with exit code 1



from Xcode Command /usr/bin/codesign failed with exit code 1 : errSecInternalComponent

Removed Contents replaced back after hitting back button in jquery

enter image description here

enter image description here

i have a two columns where i will move selected field from one column to another column after clicking on next button and if i come back all moved fields will be present.

Image 1 shows how it is before clicking on next button.(working fine)

Image 2 shows after clicking on next button and coming back to first page

Column 1 HTMl

<div class="menu">
    <select multiple="multiple" id='lstBox1' >
</select>

Column 1 JS code

self.firmData.forEach(function (data) {             
 $("#lstBox1").append($('<option class="items">').text(data.DisplayName).attr('value', data.DisplayName));                        
  });

2nd column HTML

<div class="menu">
    <select multiple="multiple" id='lstBox2' >
</select>

2nd column JS code

self.data.forEach(function (data) { 
$("#lstBox2").append($('<option class="items">').text(data.columnsexpo).attr('value', data.columnsexpo));
 });

NOTE

self.data and self.firmData values are coming from api



from Removed Contents replaced back after hitting back button in jquery

3D scatterplot using custom image

I am trying to use ggplot and ggimage to create a 3D scatterplot with a custom image. It works fine in 2D:

library(ggplot2)
library(ggimage)
library(rsvg)

set.seed(2017-02-21)
d <- data.frame(x = rnorm(10), y = rnorm(10), z=1:10,
  image = 'https://image.flaticon.com/icons/svg/31/31082.svg'
)

ggplot(d, aes(x, y)) + 
  geom_image(aes(image=image, color=z)) +
  scale_color_gradient(low='burlywood1', high='burlywood4')

enter image description here

I've tried two ways to create a 3D chart:

  1. plotly - This currently does not work with geom_image, though it is queued as a future request.

  2. gg3D - This is an R package, but I cannot get it to play nice with custom images. Here is how combining those libraries ends up:

library(ggplot2)
library(ggimage)
library(gg3D)

ggplot(d, aes(x=x, y=y, z=z, color=z)) +
  axes_3D() +
  geom_image(aes(image=image, color=z)) +
  scale_color_gradient(low='burlywood1', high='burlywood4')

enter image description here

Any help would be appreciated. I'd be fine with a python library, javascript, etc. if the solution exists there.



from 3D scatterplot using custom image

How to remove the badge in app shortcut icon?

enter image description hereHow to remove the badge in app shortcut icon in android? When i create app pinned shortcut programmatically, along with the icon specified for shortcut, app icon comes at the bottom-right corner of the icon. I don't want that badge.



from How to remove the badge in app shortcut icon?

NodeVisitor class for PEG parser in Python

Imagine the following types of strings:

if ((a1 and b) or (a2 and c)) or (c and d) or (e and f)

Now, I'd like to get the expressions in parentheses, so I wrote a PEG parser with the following grammar:

from parsimonious.grammar import Grammar

grammar = Grammar(
    r"""
    program     = if expr+
    expr        = term (operator term)*
    term        = (factor operator factor) / factor
    factor      = (lpar word operator word rpar) / (lpar expr rpar)

    if          = "if" ws
    and         = "and"
    or          = "or"
    operator    = ws? (and / or) ws?

    word        = ~"\w+"
    lpar        = "("
    rpar        = ")"

    ws          = ~"\s*"
    """)

which parses just fine with

tree = grammar.parse(string)

Now the question arises: how to write a NodeVisitor class for this tree to get only the factors? My problem here is the second branch which can be deeply nested.


I tried with
def walk(node, level = 0):
    if node.expr.name == "factor":
        print(level * "-", node.text)

    for child in node.children:
        walk(child, level + 1)

walk(tree)

but to no avail, really (factors bubble up in duplicates).
Note: This question is based on another one on StackOverflow.



from NodeVisitor class for PEG parser in Python

Saturday 30 March 2019

Using python lime as a udf on spark

I'm looking to use lime's explainer within a udf on pyspark. I've previously trained the tabular explainer, and stored is as a dill model as suggested in link

loaded_explainer = dill.load(open('location_to_explainer','rb'))

def lime_explainer(*cols):
    selected_cols = np.array([value for value in cols])
    exp = loaded_explainer.explain_instance(selected_cols, loaded_model.predict_proba, num_features = 10)
    mapping = exp.as_map()[1]

    return str(mapping)

This however takes a lot of time, as it appears a lot of the computation happens on the driver. I've then been trying to use spark broadcast to broadcast the explainer to the executors.

broadcasted_explainer= sc.broadcast(loaded_explainer)

def lime_explainer(*col):
    selected_cols = np.array([value for value in cols])
    exp = broadcasted_explainer.value.explain_instance(selected_cols, loaded_model.predict_proba, num_features = 10)
    mapping = exp.as_map()[1]

    return str(mapping)        

However, I run into a pickling error, on broadcast.

PicklingError: Can't pickle at 0x7f69fd5680d0>: attribute lookup on lime.discretize failed

Can anybody help with this? Is there something like dill that we can use instead of the cloudpickler used in spark?



from Using python lime as a udf on spark

Cannot select where ip=inet_pton($ip)

I have a unique column in database which is named ip

IP addresses are stored in this column as BINARY(16) (with no collation) after converting them using the PHP function

$store_ip = inet_pton($ip);

When I try to insert the same IP twice it works fine and fails because it is unique,

But when I try to select the IP it doesn't work and always returns FALSE (not found)

<?php

try {
    $ip = inet_pton($_SERVER['REMOTE_ADDR']);
    $stmt = $db->prepare("SELECT * FROM `votes` WHERE ip=?");
    $stmt->execute([$ip]);
    $get = $stmt->fetch();

    if( ! $get){
        echo 'Not found';
    }else{
        echo 'Found';
    }

    // close connection
    $get = null;
    $stmt = null;

} catch (PDOException $e) {
    error_log($e->getMessage());
}

The part where I insert the IP:

<?php

if( ! filter_var($ip, FILTER_VALIDATE_IP)){
        return FALSE;
}

$ip = inet_pton($_SERVER['REMOTE_ADDR']);

try {
    $stmt = $db->prepare("INSERT INTO votes(ip, answer) VALUES(?,?)");
    $stmt->execute([$ip, $answer]);
    $stmt = null;
} catch (PDOException $e) {
    return FALSE;
}



from Cannot select where ip=inet_pton($ip)

Why isn't getElementById() available on Elements?

Most DOM query methods are available on both Documents and Elements. For example,

console.assert(
  document.getElementsByTagName   && document.body.getElementsByTagName &&
  document.getElementsByClassName && document.body.getElementsByClassName &&
  document.querySelector          && document.body.querySelector &&
  document.querySelectorAll       && document.body.querySelectorAll
);

However, getElementById is only available on Document:

console.assert(document.getElementById);
console.assert(document.body.getElementById == undefined);

Why is this so?


The WHATWG DOM Living Standard tells us that:

Web compatibility prevents the getElementById() method from being exposed on elements

The W3C DOM4 Recommendation is a bit more specific:

The getElementById() method is not on elements for compatibility with older versions of jQuery. If a time comes where that version of jQuery has disappeared, we might be able to support it.

However, I still have a hard time understanding what the issue could be. How could the presence of this methods adversely affect the behaviour of jQuery or other libraries?

I've tried looking through old versions of jQuery (such as 1.0.0 and 1.7.0) to see if any of their use of getElementById hints at why this may have been a problem. I see that getElementById used to be buggy in some older browsers, but they detect that and fall back to a reliable manual implementation instead. I don't see anywhere that it could be called on an element and cause a bug. Where does this compatibility concern come from?



from Why isn't getElementById() available on Elements?

What is the Angular/Mobile friendly way to use a variable found within the component class to modify the value of an attribute on a pseudo-element?

Is there a better way to modify a pseudo-elements attribute using a component variable than what I am currently doing? I am not doing it the Angular way, but that is my goal. My way will surely break down when porting to mobile. I would like to put a variable within the component style sheet:

component:

@Input() public variable = variable;

component-style-sheet:

input[type=range].MPslide.pvd-slider::-webkit-slider-runnable-track{
 background:linear-gradient(#568200, #568200) 0/variable 100% no-repeat #ccc
}

Unfortunately it doesn't exist in my template so I can not place an [ngClass] or [style.margin-left.px]="containerX-9" or anything on it. At the moment I am doing this by setting a global CSS variable onFormChanges().

component:

  onFormChanges(): void {
this.myForm.valueChanges.subscribe(() => {
            document.documentElement.style.setProperty('--variable', variable)
}
}

component-style-sheet:

background:linear-gradient(#568200, #568200) 0/var(--variable) 100% no-repeat #ccc

But this seems like a workaround and hard to track. What is the Angular way to do this? Does Angular not have a way to use a component variable value in a pseudo element? What am I missing? Is there a cleaner way to do this? Thanks for any insights or suggestions!



from What is the Angular/Mobile friendly way to use a variable found within the component class to modify the value of an attribute on a pseudo-element?

cdkVirtualFor not rendering new items

I'm building a vertically scrolling calendar. I'm getting the initial days to load, but when new days are added to the list, they aren't being rendered.

<cdk-virtual-scroll-viewport
  class="demo-viewport"
  [itemSize]="100"
  (onContentScrolled)="handleScrollChange($event)"
>
  <calendar-day
    *cdkVirtualFor="let day of days; trackBy: trackByFn"
    [day]="day"
  ></calendar-day>
</cdk-virtual-scroll-viewport>
<button (click)="goToToday()">go</button>

I have a service with a BehaviorSubject updating the days. I know the list of days is being updated, but the change doesn't seem to be detected.

  ngOnInit() {
    this._daysService.days$.subscribe(days => {
      this.days = days;
    })
    this.watchScroll();
    this.handleScrollingUp();
    this.handleScrollingDown();
  }

For more info, the StackBlitz repo is public https://stackblitz.com/edit/material-infinite-calendar



from cdkVirtualFor not rendering new items

How would I prevent redirecting of a href during touchmove and mousemove?

I've got an issue while I'm trying to combine touchstart and mousedown in 1 function. I've used an a tag as the target element of the function for going to the link directly when I touched or clicked the tag.

The issue is when I touch the middle of a tag, link doesn't respond. it only works when I click the element or touch the edge of the a tag, and the output fires mousedown.

enter image description here

In the mobile mode, try to click the edge of a tag as much as you would possible like a grey dot in the picture above. I've created an CodePen example for looking, testing and understanding better.

How would I fix this issue?

class Slider {
  constructor($el, paragraph) {
    this.$el = $el;
    this.paragraph = paragraph;
  }
  start(e) {
    e.preventDefault();
    var type = e.type;
    if (type === 'touchstart' || type === 'mousedown') this.paragraph.text(this.paragraph.text() + ' ' + type);
    return false;
  }
  apply() {
    this.$el.bind('touchstart mousedown', (e) => this.start(e));
  }
}
const setSlider = new Slider($('#anchor'), $('.textbox'), {passive: false});
setSlider.apply();
  a {
    display: block;
    width: 100px;
    height: 100px;
    background-color: orange;
  }
<a id="anchor" href="https://google.co.uk">Tap or Click Me</a>
<p class="textbox"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

========= Progress Update ==========

I've just added move & end function then I have to click twice for moving on to the linked website. It keeps getting worse and have no idea how to solve this issue.

class Slider {
  constructor($el, paragraph) {
    this.$el = $el;
    this.paragraph = paragraph;
  }
  start(e) {
    e.preventDefault();
    var type = e.type;
    if (type === 'touchstart' || type === 'mousedown') this.paragraph.text(this.paragraph.text() + ' ' + type);
    this.$el.bind('touchmove mousemove', (e) => this.move(e));
    this.$el.bind('touchend mouseup', (e) => this.end(e));
    return false;
  }
  move(e) {
    var type = e.type;
    if (type === 'touchstart' || type === 'mousedown') this.paragraph.text(this.paragraph.text() + ' ' + type);
    return false;
  }
  end(e) {
    console.log('test');
    this.$el.on('click');
    this.$el.off('touchstart touchend');
    return false;
  }
  apply() {
    this.$el.bind('touchstart || mousedown', (e) => this.start(e));

  }
}
const setSlider = new Slider($('#anchor'), $('.textbox'));
setSlider.apply(); 


======== Progress Updated After Bounty (Latest) ========

After dozens of tried, I've finally figured out and solve the previous problem but I've faced up a new issue that can't draggable and redirecting instantly.

When I use the preventDefault in the start function, all of the events work fine. The only issue of this case is dragging doesn't prevent redirecting link from the a tag. It always send me to the website no matter which ways to call the functions, clicked or dragged.

when I don't use the preventDefault, dragging doesn't work. it only works clicking the elements.

My final goal is to prevent redirecting link of the a tag from the both events, touchmove and mousemove. I've been searched about on google so many times but haven't got any of the clues.

I've written an example in Codepen and this is what I've done so far:

class Slider {
  constructor($el, paragraph) {
    this.$el = $el;
    this.paragraph = paragraph;
  }
  start(e) {
    var type = e.type;
    if (type === 'touchstart') {
      this.paragraph.text(this.paragraph.text() + ' ' + type);
    } else if (type === 'mousedown') {
      this.paragraph.text(this.paragraph.text() + ' ' + type);
    }
  }
  move(e) {
    var type = e.type;
  }
  end(e) {
    var type = e.type;
    if (type === 'touchend') {
      console.log('touchstart enabled');
    } else if (type === 'mouseup') {
      console.log('mousedown enabled');
    }
  }
  apply() {
    this.$el.bind({
      touchstart: (e) => this.start(e),
      touchmove: (e) => this.move(e),
      touchend: (e) => this.end(e),
      mousedown:(e) => this.start(e),
      onmousemove: (e) => this.move(e),
      mouseup:  (e) => this.end(e)
    });
  }
}
const setSlider = new Slider($('#anchor'), $('.textbox'));
setSlider.apply();
    a {
      display: block;
      width: 100px;
      height: 100px;
      background-color: orange; 
    }
    <a id="anchor" href="https://google.co.uk">Tap or Click Me</a>
    <p class="textbox"></p>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


from How would I prevent redirecting of a href during touchmove and mousemove?

which is good WebRtc or wifi P2P to share audio from one device to another device

I have music player and need to add sync play functionality with other mobile for example if 2 or more users are using my music player and want to play same song on all devices then they just connect through same network and can play music on all devices from one device with complete music player control of all devices on single device.

can anyone explain me which is best and how can i share audio from one android device to another device on Sync and what are the steps to do so

I don't know why i am getting down votes i need clarification and help so i am asking this. and this is the best site for asking this development question

Points i know about WiFi P2P-

  • create connection

  • create socket for sharing

  • share a complete file

Points i want to know:-

  • How can i share file without storing in another device storage.

  • How to play sound on both devices at same position (ON SYNC).

and after Wifi P2P i want to say that i don't know about WebRTC like:- * How it works?

  • How to setup connection for this ?

  • Is it always required internet connection ?

  • Is same application is required in both devices to create connection between devices?

please help to understand this.....

Thanks



from which is good WebRtc or wifi P2P to share audio from one device to another device

Specialized shouldComponentUpdate on PureComponent

I am trying to create a component that shouldn't when a certain property is true, but should perform a shallow compare (the default for PureComponent).

I've tried doing the following behavior:

export default class ContentsListView extends PureComponent<Props> {
  shouldComponentUpdate(props: Props) {
    if (props.selecting) {
      return false;
    }
    return super.shouldComponentUpdate(props);
  }

  render() {
  }
}

However, super.shouldComponentUpdate is not defined. Is there some way to "tap into" the shallow compare of PureComponent without writing my own?



from Specialized shouldComponentUpdate on PureComponent

How to align text left on a plotly bar chart (example image contained) [Plotly-Dash]

I need my y-axis to be on the inside like the image below (not interested in the dynamic update of graphs please ignore that). I want it positioned to the left and if the barchart is small it just goes over the bar:

enter image description here

I have tried text = 'y' and text-position = 'inside' but the text goes vertical or gets squashed for small bar charts so it can fit inside. For larger bar charts it's positioned on the right (i.e. at the end of the horizontal bar chart instead of the beginning). I just want it to write across as in the image above. Any ideas?



from How to align text left on a plotly bar chart (example image contained) [Plotly-Dash]

Window.Callback is overwritten by Toolbar

I found that in setActionBar method from Activity:

public void setActionBar(@Nullable Toolbar toolbar) {
    final ActionBar ab = getActionBar();
    if (ab instanceof WindowDecorActionBar) {
        throw new IllegalStateException("This Activity already has an action bar supplied " +
                "by the window decor. Do not request Window.FEATURE_ACTION_BAR and set " +
                "android:windowActionBar to false in your theme to use a Toolbar instead.");
    }

    // If we reach here then we're setting a new action bar
    // First clear out the MenuInflater to make sure that it is valid for the new Action Bar
    mMenuInflater = null;

    // If we have an action bar currently, destroy it
    if (ab != null) {
        ab.onDestroy();
    }

    if (toolbar != null) {
        final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
        mActionBar = tbab;
        mWindow.setCallback(tbab.getWrappedWindowCallback());
    } else {
        mActionBar = null;
        // Re-set the original window callback since we may have already set a Toolbar wrapper
        mWindow.setCallback(this);
    }

    invalidateOptionsMenu();
}

As you can see there mWindow.setCallback(tbab.getWrappedWindowCallback()) is called with wrapped callback. And if we check implementation of ToolbarAractionBar:

ToolbarActionBar(Toolbar toolbar, CharSequence title, Window.Callback windowCallback) {
    mDecorToolbar = new ToolbarWidgetWrapper(toolbar, false);
    mWindowCallback = new ToolbarCallbackWrapper(windowCallback);
    mDecorToolbar.setWindowCallback(mWindowCallback);
    toolbar.setOnMenuItemClickListener(mMenuClicker);
    mDecorToolbar.setWindowTitle(title);
}

public Window.Callback getWrappedWindowCallback() {
    return mWindowCallback;
}

It wraps last parameter of constructor, which was this (instance of Activity).

The problem appears if before calling setActionBar we set our own implementation of Window.Callback (that correctly wraps original one). In this case not our implementation is wrapped by ToolbarActionBar but original one.

It would not be a problem if getWindow().getCallback() used instead of this as ToolbarActionBar constructor parameter. So it looks like a bug in android sdk.

The question is: does anyone know how to deal with such situation or some workaround for that issue? (lets assume that we should set our callback before adding action bar)


btw. setSupportActionBar looks not the same but very similar and have the same issue.



from Window.Callback is overwritten by Toolbar

Training loss does not decrease

I am trying to implement autoencoders using CNN in tensorflow. Firstly, I trained my model on MNIST dataset and everything worked perfectly, I got the lower loss and when I ran the inference model worked perfectly (giving good output images). But then I decided to test my network on CelebA dataset, but my model fails and loss never decreases. The model processes fast and I tried decreasing the learning rate. Even though I decreased the learning rate, there is not much difference between the time it takes to train.

Here I will try to put all the code that I use

**Note I've set up GitHub repository as well, in case it's easier for you to read the code there

self.batch_size = 64
self.shape = shape

self.output_height = 64
self.output_width = 64
self.gf_dim = 64
self.c_dim = 3

self.strides_size = 2
self.kernel_size = 2
self.padding = 'SAME'
def encoder_conv_net(self, input_):

    self.conv1 = Model.batch_norm(self, Model.conv_2d(self, input_, [3,3,self.c_dim,32], name = 'conv1'))

    self.conv2 = Model.batch_norm(self, Model.conv_2d(self, self.conv1, [3,3,32,64], name = 'conv2'))

    self.conv3 = Model.batch_norm(self, Model.conv_2d(self, self.conv2, [3,3,64,128], name = 'conv3'))

    self.conv4 = Model.batch_norm(self, Model.conv_2d(self, self.conv3, [3,3,128,128], name = 'conv4'))

    fc = tf.reshape(self.conv4, [ -1, 512 ])

    dropout1 = tf.nn.dropout(fc, keep_prob=0.5)

    fc1 = Model.fully_connected(self, dropout1, 512)
    return tf.nn.tanh(fc1)

def decoder_conv_net(self, 
                     input_,
                     shape):

    g_width, g_height = shape[1], shape[0]
    g_width2, g_height2 = np.ceil(shape[1]/2), np.ceil(shape[0]/2)
    g_width4, g_height4 = np.ceil(shape[1]/4), np.ceil(shape[0]/4)
    g_width8, g_height8 = np.ceil(shape[1]/8), np.ceil(shape[0]/8)

    input_ = tf.reshape(input_, [-1, 4, 4, 128])

    print(input_.shape, g_width8, self.gf_dim)
    deconv1 = Model.deconv_2d(self, input_, [self.batch_size, g_width8, g_height8, self.gf_dim * 2],
                              [5,5],
                              name = 'deconv_1')

    deconv2 = Model.deconv_2d(self, deconv1, [self.batch_size, g_width4, g_height4, self.gf_dim * 2],
                              [5,5],
                              name = 'deconv_2')

    deconv3 = Model.deconv_2d(self, deconv2, [self.batch_size, g_width2, g_height2, self.gf_dim],
                              [5,5],
                              name = 'deconv_3')

    deconv4 = Model.deconv_2d(self, deconv3, [self.batch_size, g_width, g_height, self.c_dim],
                              [5,5],
                              name = 'deconv_4',
                              relu = False)

    return tf.nn.tanh(deconv4)

these are the functions for model encoder and decoder.

The main function looks like this

dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.shuffle(len(filenames))
dataset = dataset.map(parse_function, num_parallel_calls=4)
#dataset = dataset.map(train_preprocess, num_parallel_calls=4)
dataset = dataset.repeat().batch(batch_size)
#dataset = dataset.apply(tf.contrib.data.batch_and_drop_remainder(batch_size))
dataset = dataset.prefetch(1)

iterator = tf.data.Iterator.from_structure(dataset.output_types,
                                           dataset.output_shapes)

next_element = iterator.get_next()
init_op = iterator.make_initializer(dataset)

#print(next_element)
x = next_element
#plt.imshow(x)
#x = tf.reshape(x, [64, 64, 64, 3])

ENC = Encoder(shape)
DEC = Decoder(shape)

encoding = ENC.encoder_conv_net(x)

print("Encoding output shape " + str(encoding.shape))    

output = DEC.decoder_conv_net(encoding, [64,64])

print(output.shape)
loss = tf.reduce_mean(tf.squared_difference(x, output))

opt = tf.train.AdamOptimizer(learning_rate=0.1e-5)
train = opt.minimize(loss)
saver = tf.train.Saver()
init = tf.global_variables_initializer()

I call this train session in the normal way

with tf.Session(graph=graph) as sess:
  #saver.restore(sess, '')

  sess.run(init) 
  sess.run(init_op)

  a = sess.run(next_element)

  for ind in tqdm(range(nb_epoch)):    
      loss_acc, outputs, _ = sess.run([loss, output, train])
      print(loss_acc)

      if ind % 40 == 0:
          print(loss_acc)
          saver.save(sess, save_path = "./checkpoints/" \
                       "/model_face.ckpt", global_step = ind) 

After all of this training starts without an error, but my loss does not decrease.

Here are utility functions as well

def parse_function(filename):
  image_string = tf.read_file(filename)
  image = tf.image.decode_jpeg(image_string, channels=3)
  image = tf.image.convert_image_dtype(image, tf.float32)
  image = tf.image.resize_images(image, [64, 64])
  return image

def train_preprocess(image):
  image = tf.image.random_flip_left_right(image)
  image = tf.image.random_brightness(image, max_delta=32.0 / 255.0)
  image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
  image = tf.clip_by_value(image, 0.0, 1.0)
  return image



from Training loss does not decrease

Data not refreshing after login to homepage in reactjs

I'm saving userdata to localStorage in login component and then redirecting to the homepage. In homepage username is not updating on first visit. I have to reload the page. Then data binds to page after refresh. Please help how can I show data on first visit?

below is my homepage code

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

export default class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLogin: false,
      isLogout: false,
      user: ""
    };
  }

  componentDidMount() {
    const userData = localStorage.getItem("userData");
    const user = JSON.parse(userData);
    this.setState({ user: user });
    if (userData) {
      this.setState({ isLogin: true });
    }
    console.log(userData);
    console.log(user);
  }

  logout = e => {
    e.preventDefault();
    localStorage.clear();
    this.setState({ isLogout: true });
  };

  render() {
    if (this.state.isLogin === false || this.state.isLogout === true) {
      return (
        <header
          id="kr-header"
          className="kr-header cd-auto-hide-header kr-haslayout"
        >
          <div className="container">
            <div className="row">
              <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <strong className="kr-logo">
                  <Link to="/">
                    <img src="images/logo.png" alt="company logo here" />
                  </Link>
                </strong>
                <nav className="kr-addnav">
                  <ul>
                    <li>
                      <Link
                        id="kr-btnsignin"
                        className="kr-btn kr-btnblue"
                        to="login_register"
                      >
                        <i className="icon-smiling-face" />
                        <span>Join Now</span>
                      </Link>
                    </li>
                    <li>
                      <a
                        className="kr-btn kr-btngreen"
                        href="dashboardaddlisting.html"
                      >
                        <i className="icon-plus" />
                        <span>Add Listing</span>
                      </a>
                    </li>
                  </ul>
                </nav>
                <nav id="kr-nav" className="kr-nav">
                  <div className="navbar-header">
                    <button
                      type="button"
                      className="navbar-toggle collapsed"
                      data-toggle="collapse"
                      data-target="#kr-navigation"
                      aria-expanded="false"
                    >
                      <span className="sr-only">Toggle navigation</span>
                      <span className="icon-bar" />
                      <span className="icon-bar" />
                      <span className="icon-bar" />
                    </button>
                  </div>
                  <div
                    id="kr-navigation"
                    className="collapse navbar-collapse kr-navigation"
                  >
                    <ul>
                      <li>
                        <a href="dashboard.html">Dasboard</a>
                      </li>
                    </ul>
                  </div>
                </nav>
              </div>
            </div>
          </div>
        </header>
      );
    } else {
      return (
        <header
          id="kr-header"
          className="kr-header cd-auto-hide-header kr-haslayout"
        >
          <div className="container">
            <div className="row">
              <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <strong className="kr-logo">
                  <Link to="/">
                    <img src="images/logo.png" alt="company logo here" />
                  </Link>
                </strong>
                <nav className="kr-addnav">
                  <ul>
                    <li>
                      <Link
                        id="kr-btnsignin"
                        className="kr-btn kr-btnblue"
                        to="login_register"
                      >
                        <i className="icon-smiling-face" />
                        <span>{this.state.user.user.firstname}</span>
                      </Link>
                    </li>
                    <li>
                      <a
                        className="kr-btn kr-btngreen"
                        href="dashboardaddlisting.html"
                      >
                        <i className="icon-plus" />
                        <span>Add Listing</span>
                      </a>
                    </li>
                    <li>
                      <a onClick={this.logout} className="kr-btn kr-btngreen">
                        <i className="icon-plus" />
                        <span>Logout</span>
                      </a>
                    </li>
                  </ul>
                </nav>
                <nav id="kr-nav" className="kr-nav">
                  <div className="navbar-header">
                    <button
                      type="button"
                      className="navbar-toggle collapsed"
                      data-toggle="collapse"
                      data-target="#kr-navigation"
                      aria-expanded="false"
                    >
                      <span className="sr-only">Toggle navigation</span>
                      <span className="icon-bar" />
                      <span className="icon-bar" />
                      <span className="icon-bar" />
                    </button>
                  </div>
                  <div
                    id="kr-navigation"
                    className="collapse navbar-collapse kr-navigation"
                  >
                    <ul>
                      <li>
                        <a href="dashboard.html">Dasboard</a>
                      </li>
                    </ul>
                  </div>
                </nav>
              </div>
            </div>
          </div>
        </header>
      );
    }
  }
}

Below is login-register component code

import React, {Component} from 'react';
import { Link,Redirect ,withRouter } from 'react-router-dom';
import PropTypes from "prop-types";
import Otp from './otp';
import axios from '../api';

export default class LoginRegister extends Component {
    static contextTypes = {
        router: PropTypes.object
      }
    constructor(props,context){
        super(props,context);
        this.state = {
            fname:'',
            lname:'',
            emailaddress:'',
            password:'',
            mobile:'',
            user:'',
            login_pass:'',
            isLogin:false
        }
        this.regi_data = this.regi_data.bind(this);
        this.login_data = this.login_data.bind(this);
        // this.otpModalRef = React.createRef();
    }

    regi_data(e){
        this.setState({[e.target.name] : e.target.value}
        );
    }
    login_data(e){
        this.setState({[e.target.name] : e.target.value})
    }

    // otpModalRef = ({onOpenModal}) => {
    //    this.showModal = onOpenModal;
    // }

    componentDidMount(){
        if (localStorage.getItem('userData')) {
            this.context.router.history.push({
                        pathname:'/',

                    });
        }
    }




    login = (e) => {
        e.preventDefault();
         axios.post('/api/signin', { 
                        user:this.state.user,
                        password:this.state.login_pass,
                    })
          .then(res => {
                //console.log(res);
                localStorage.setItem('userData', JSON.stringify(res.data));
                this.context.router.history.push({
                        pathname:'/',

                    });
//                  window.location.reload();
                    this.setState({isLogin: true});
          })
          .catch(function (error) {
            console.log(error.message);
          })
    }

    register = (e) => {
        e.preventDefault(); 
        axios.post('/api/user/add', { 
                        firstname: this.state.fname,
                        lastname:this.state.lname,
                        email:this.state.emailaddress,
                        password:this.state.password,
                        mobile:this.state.mobile 
                    },              
                )
          .then(res => {
                console.log(res);
                // this.showModal();
                 this.context.router.history.push({
                        pathname:'/otp_validate',
                    });            
          }).catch(function(error){
            alert(error.message)
          })
    }



from Data not refreshing after login to homepage in reactjs

Swift Chart months at bottom

I'm integrating Chart in my app.

Using https://github.com/danielgindi/Charts

this have achieved: enter image description here

Expected Result: enter image description here

Code:

let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.minimumFractionDigits = 0
leftAxisFormatter.maximumFractionDigits = 1
leftAxisFormatter.negativePrefix = " $"
leftAxisFormatter.positivePrefix = " $"

chartView.xAxis.gridLineDashPhase = 0
chartView.leftAxis.enabled = false
chartView.xAxis.enabled = false

let rightAxis = chartView.rightAxis
rightAxis.enabled = true
rightAxis.labelFont = .systemFont(ofSize: 10)
rightAxis.labelCount = 4
rightAxis.valueFormatter = DefaultAxisValueFormatter(formatter: leftAxisFormatter)
rightAxis.axisMinimum = 0
rightAxis.drawZeroLineEnabled=true
rightAxis.labelPosition = .insideChart

chartView.leftAxis.drawZeroLineEnabled = true
chartView.legend.enabled = false

chartView.leftAxis.drawAxisLineEnabled = false
chartView.leftAxis.drawGridLinesEnabled = false
chartView.rightAxis.drawAxisLineEnabled = false
chartView.rightAxis.drawGridLinesEnabled = false
chartView.xAxis.drawAxisLineEnabled = false
chartView.xAxis.drawGridLinesEnabled = false
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
        chartView.xAxis.granularity = 1

What are other properties to achieve White vertical line on graph & Bottom Months in bottom.

Thanks in advance.



from Swift Chart months at bottom

Node.js & Gulp: Real piping sequence could differ from written '.pipe()'s chain?

In the below code, fileShouldBePreprocessedBySass() will be called before console.log('intercepted!'); execution. Also, in fileShouldBePreprocessedBySass(targetFileAbsolutePath), parameter targetFileAbsolutePath will be undefined:

let currentSourceFileAbsolutePath;

return gulp.src(entryPointsSourceFilesPathsOrGlobs)

    // "gulpPlugins.intercept" is "gulp-intercept"
    .pipe(gulpPlugins.intercept( sourceVynilFile => {
      console.log('intercepted!');
      currentSourceFileAbsolutePath = sourceVynilFile.path;
      console.log(currentSourceFileAbsolutePath); // OK here
      return sourceVynilFile;
    }))

    // "gulpPlugins.if" is "gulp-if"
    .pipe(gulpPlugins.if(
        // currentSourceFileAbsolutePath is undefined !!!
        fileShouldBePreprocessedBySass(currentSourceFileAbsolutePath),
        gulpPlugins.sass()
    ));

// ...

fileShouldBePreprocessedBySass(targetFileAbsolutePath) {

    console.warn('---');
    console.warn(targetFileAbsolutePath); // undefined!

    const targetFilenameExtension = Path.extname(targetFileAbsolutePath);
    let targetFilenameExtensionIsSupportedBySassPreprocessor = false;

    for (const filenameExtension of SUPPORTED_FILENAME_EXTENSIONS__SASS_PREPROCESSOR) {
      if (filenameExtension === targetFilenameExtension) {
        targetFilenameExtensionIsSupportedBySassPreprocessor = true;
        break;
      }
    }

    return targetFilenameExtensionIsSupportedBySassPreprocessor;
}

Really, original code written in TypeScript, but I rewrite it to JavaScript to allow more people to understand the code. I said about it because TypeScript compiler somehow understood, what in pipe(gulpPlugins.if(/*...*/)), parameter currentSourceFileAbsolutePath is not initialized, so TS2454: Variable 'currentSourceFileAbsolutePath' is used before being assigned. error occurred.

I am confused because I have similar task which works without error (in right sequence):

let currentSourceFileAbsolutePath: string;

return gulp.src(entryPointsSourceFilesPathsOrGlobs)

    .pipe(gulpPlugins.intercept(sourceVynilFile => {
      currentSourceFileAbsolutePath = sourceVynilFile.path;
      return sourceFile;
    }))

    .pipe(gulpPlugins.pug())
    .pipe(gulpPlugins.intercept(compiledHtmlFile => {
      // currentSourceFileAbsolutePath is NOT undefined!
      if (shouldValidateCompiledHtmlRespectiveToSourceFile(currentSourceFileAbsolutePath)) {
        HtmlValidator.validateHtml(compiledHtmlFile);
      }
      return compiledHtmlFile;
    }))

    .pipe(gulp.dest(() => (
      // currentSourceFileAbsolutePath is NOT undefined!
      getOutputDirectoryForPreprocessedMarkupEntryPointFileByRespectiveSourceFile(currentSourceFileAbsolutePath)
    )));

What wrong in the first task? I missed some async call?



from Node.js & Gulp: Real piping sequence could differ from written '.pipe()'s chain?

Can't receive Motion Events with Window.Callback

My task is receiving all motion events in android application with good embedding (library variant). I create my Window.Callback wrapper.

public class WindowCallback implements Window.Callback {

private final Window.Callback wrapper;

    public WindowCallback(Window.Callback callback) {        
        this.wrapper = callback;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
         return wrapper.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
         return wrapper.dispatchKeyShortcutEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {        
        return wrapper.dispatchTouchEvent(event);
    }

    // other methods omitted
}

Then, instantiate it in Activity:

final Window window = getWindow();
final Window.Callback windowCallback = window.getCallback();
final WindowCallback callbackWrapper = new WindowCallback(windowCallback);
window.setCallback(interceptCallback);

But when I have Toolbar in Activity, this Toolbar capture Window.Callback in method setActionBar(Toolbar) or setSupportActionBar(Toolbar). Code snippet from framework Activity:

if (toolbar != null) {
        final ToolbarActionBar tbab = new ToolbarActionBar(toolbar, getTitle(), this);
        mActionBar = tbab;
        mWindow.setCallback(tbab.getWrappedWindowCallback());

And ToolbarActionBar from support library:

ToolbarActionBar(Toolbar toolbar, CharSequence title, Callback windowCallback) {
    this.mDecorToolbar = new ToolbarWidgetWrapper(toolbar, false);
    this.mWindowCallback = new ToolbarActionBar.ToolbarCallbackWrapper(windowCallback);
    this.mDecorToolbar.setWindowCallback(this.mWindowCallback);
    toolbar.setOnMenuItemClickListener(this.mMenuClicker);
    this.mDecorToolbar.setWindowTitle(title);
}

Question is - How to check when Toolbar catch Window.Callback, but without creating base activity and extending from it. This check should execute not very frequently. (OnGlobalLayoutListener not our case)



from Can't receive Motion Events with Window.Callback

how to avoid using _siftup or _siftdown in heapq

I have no idea how to solve following problem efficiently without using _siftup or _siftdown:

How to restore the heap invariant, when one element is out-of-order?

In other words, update old_value in heap to new_value, and keep heap working. you can assume there is only one old_value in heap. The fucntion definition is like:

def update_value_in_heap(heap, old_value, new_value):

Here is _siftup or _siftdown version:

>>> from heapq import _siftup, _siftdown, heapify, heappop

>>> data = [10, 5, 18, 2, 37, 3, 8, 7, 19, 1]
>>> heapify(data)
>>> old, new = 8, 22              # increase the 8 to 22
>>> i = data.index(old)
>>> data[i] = new
>>> _siftup(data, i)
>>> [heappop(data) for i in range(len(data))]
[1, 2, 3, 5, 7, 10, 18, 19, 22, 37]

>>> data = [10, 5, 18, 2, 37, 3, 8, 7, 19, 1]
>>> heapify(data)
>>> old, new = 8, 4              # decrease the 8 to 4
>>> i = data.index(old)
>>> data[i] = new
>>> _siftdown(data, 0, i)
>>> [heappop(data) for i in range(len(data))]
[1, 2, 3, 4, 5, 7, 10, 18, 19, 37]

it costs O(n) to index and O(logn) to update. heapify is another solution, but less efficient than _siftup or _siftdown.

But _siftup and _siftdown are protected member in heapq, so they are not recommended to access from outside.

So is there a better and more efficient way to solve this problem? Best practice for this situation?

Thanks for reading, I really appreciate it to help me out. : )

already refer to heapq python - how to modify values for which heap is sorted, but no answer to my problem.



from how to avoid using _siftup or _siftdown in heapq

Twitter Error: Your credentials do not allow access to this resource

I'm working on twitter api's, some of api's getting response. But statuses/home_timeline.json api and other api's not getting response.

Getting error :

{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}

I'm getting access token successfully and using that access token for statuses/home_timeline.json and some other api's. But these are getting above error. Already i logged in with my account.

I found so many urls and i'm not getting answer from those urls.

My Accesstoken code is:

//Get twitter access token
func getAccessToken() {

    //RFC encoding of ConsumerKey and ConsumerSecretKey
    let encodedConsumerKeyString:String = "f4k***********0".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    let encodedConsumerSecretKeyString:String = "OD**************ln".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
    print(encodedConsumerKeyString)
    print(encodedConsumerSecretKeyString)
    //Combine both encodedConsumerKeyString & encodedConsumerSecretKeyString with " : "
    let combinedString = encodedConsumerKeyString+":"+encodedConsumerSecretKeyString
    print(combinedString)
    //Base64 encoding
    let data = combinedString.data(using: .utf8)
    let encodingString = "Basic "+(data?.base64EncodedString())!
    print(encodingString)
    //Create URL request
    var request = URLRequest(url: URL(string: "https://api.twitter.com/oauth2/token")!)  //oauth/access_token   oauth2/token
    request.httpMethod = "POST"
    request.setValue(encodingString, forHTTPHeaderField: "Authorization")
    request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
    let bodyData = "grant_type=client_credentials".data(using: .utf8)!
    request.setValue("\(bodyData.count)", forHTTPHeaderField: "Content-Length")
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
        print("error=\(String(describing: error))")
        return
        }

//            let responseString = String(data: data, encoding: .utf8)
//            let dictionary = data
//            print("dictionary = \(dictionary)")
//            print("responseString = \(String(describing: responseString!))")

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        do {
            let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
            print("Access Token response : \(response)")
//                print(response["access_token"]!)
//                self.accessToken = response["access_token"] as! String
            if let token = response["access_token"] {
                self.accessToken = token as! String
            }

        } catch let error as NSError {
            print(error)
        }
    }

    task.resume()
}

Twitter signing code :

//Twitter signin
@IBAction func onClickTwitterSignin(_ sender: UIButton) {

    //Login and get session
    TWTRTwitter.sharedInstance().logIn { (session, error) in

        if (session != nil) {
            //Read data
            let name = session?.userName ?? ""
            print(name)
            print(session?.userID  ?? "")
            print(session?.authToken  ?? "")
            print(session?.authTokenSecret  ?? "")

 //                self.loadFollowers(userid: session?.userID ?? "")

 //                let userid = session?.userID ?? ""
 //                let screenName = session?.userName ?? ""
 //                if userid != "" && screenName != "" {



             self.getStatusesUserTimeline(accessToken:self.accessToken)


 //                }

            //Get user email id
            let client = TWTRAPIClient.withCurrentUser()
            client.requestEmail { email, error in
                if (email != nil) {
                    let recivedEmailID = email ?? ""
                    print(recivedEmailID)
                } else {
                    print("error--: \(String(describing: error?.localizedDescription))");
                }
            }
            //Get user profile image url's and screen name
            let twitterClient = TWTRAPIClient(userID: session?.userID)
            twitterClient.loadUser(withID: session?.userID ?? "") { (user, error) in
                print(user?.profileImageURL ?? "")
                print(user?.profileImageLargeURL ?? "")
                print(user?.screenName ?? "")
            }



            let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
            self.navigationController?.pushViewController(storyboard, animated: true)
        } else {
            print("error: \(String(describing: error?.localizedDescription))");
        }
    }

}

Get twitter statuses/home_timeline.json : (I'm calling this function after login success)

func getStatusesUserTimeline(accessToken:String) {

    let userId = "10************56"
    let twitterClient = TWTRAPIClient(userID: userId)
    twitterClient.loadUser(withID: userId) { (user, error) in
        print(userId)
        print(user ?? "Empty user")
        if user != nil {


            //Get users timeline tweets
            var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json?")!)                


            request.httpMethod = "GET"
            request.setValue("Bearer "+accessToken, forHTTPHeaderField: "Authorization")
            print(request)

            let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
                }


                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }

                do {
                    let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String,Any>
                    print(response)
 //                        print((response["statuses"] as! Array<Any>).count)

                } catch let error as NSError {
                    print(error)
                }
            }

            task.resume()

        } else {
            print(error?.localizedDescription as Any)
        }
    }

}



from Twitter Error: Your credentials do not allow access to this resource

Socket.io not disconnecting through Cloudflare/Nginx

I have a small web app that's served with Express.js and connects to the backend with Socket.io. To make it public, I'm using Nginx as a reverse proxy and then Cloudflare at the very front. The app relies on the disconnect event firing when the it's closed or reloaded to keep track of online users among other things. When going through Nginx and Cloudflare the disconnect event never fires on the backend. It does when developing locally.

Here's my Nginx config file:

server {
    listen 80;
    server_name colab.gq;
    server_name www.colab.gq;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header X-Forwarded-For $remote_addr;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/colab.gq/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/colab.gq/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

And here's a snippet of my server-side code:

io.on('connection', (socket) => {
  // Stuff here

  socket.on('disconnect', () => {
    console.log('disconnected!')
    // Stuff that relies on the disconnect event
  })
})

When the user closes the tab or reloads the page the disconnect event should fire, but it never does when passing the connection through Nginx and Cloudflare. Thanks in advance for any help!

UPDATE: It seems like a few seconds after reloading/closing the disconnect event finally registers.



from Socket.io not disconnecting through Cloudflare/Nginx

Can't connect to websocket using ssl and apache

I am tying to connect my client to the server socket using socket.io. When I am using http all works fine but when I try to use https the client can't connect.

I try to create the server using http require('https') and using certificates but didn't work.

For now after a few code changes and tests this is how my code is:

Server, index.js

var https = require('https');
var app = express();
var options = {
  key: fs.readFileSync('./file.pem'),
  cert: fs.readFileSync('./file.crt')
};


var server = https.createServer(options, app);
var io = require('socket.io')(server);


server.listen(3003, function() {
        console.log('server up and running at %s port', 3003);
});
server.on('connection', function(client){
        console.log("NUEVO CLIENTE");
        client.on('event', function(data){});
        client.on('disconnect', function(){});
        client.on('room', function(room) {
                console.log('Room: '+room);
                        client.join(room);
    });
        client.on('leaveRroom', function(room) {
                        console.log('LeaveRroom: '+room);
                        client.leave(room);
    });

});

The server connection always success using port 3003.

Client

$scope.socket = io.connect('https://localhost:3003/', { transports: ['websocket'] });
$scope.socket.on('connect_error', function (data) {
                console.log(data);
    });

    $scope.socket.on('message', function(message) {
        $scope.getAttendance();
        $scope.clientDetails(message.user[0]);
    })


Browser logs:

VM2481:7 WebSocket connection to 'wss://localhost:3003/socket.io/?EIO=3&transport=websocket' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
r.doOpen @ VM2481:7
r.open @ VM2481:7
r.open @ VM2481:6
r @ VM2481:6
r @ VM2481:6
r.open.r.connect @ VM2481:6
(anonymous) @ VM2481:6
VM2481:6 engine.io-client:socket socket error {"type":"TransportError","description":{"isTrusted":true}} +93ms
VM2481:6 socket.io-client:manager connect_error +92ms
VM2481:6 socket.io-client:manager cleanup +4ms
access.js:45 Error: websocket error
    at r.onError (eval at <anonymous> (jquery.min.js:2), <anonymous>:7:8015)
    at WebSocket.ws.onerror (eval at <anonymous> (jquery.min.js:2), <anonymous>:7:23668)
VM2481:6 socket.io-client:manager reconnect attempt error +5ms
VM2481:6 socket.io-client:manager will wait 5000ms before reconnect attempt +2ms
VM2481:6 engine.io-client:socket socket close with reason: "transport error" +16ms
VM2481:6 socket.io-client:manager attempting reconnect +5s
VM2481:6 socket.io-client:manager readyState closed +3ms
VM2481:6 socket.io-client:manager opening https://localhost:3003/ +3ms
VM2481:6 engine.io-client:socket creating transport "websocket" +5s
VM2481:6 engine.io-client:socket setting transport websocket +3ms
VM2481:6 

For the ssl I am using load balancer for AWS.

I expect the client connect successfully with the server over https.



from Can't connect to websocket using ssl and apache

Can't connect to websocket using ssl and apache

I am tying to connect my client to the server socket using socket.io. When I am using http all works fine but when I try to use https the client can't connect.

I try to create the server using http require('https') and using certificates but didn't work.

For now after a few code changes and tests this is how my code is:

Server, index.js

var https = require('https');
var app = express();
var options = {
  key: fs.readFileSync('./file.pem'),
  cert: fs.readFileSync('./file.crt')
};


var server = https.createServer(options, app);
var io = require('socket.io')(server);


server.listen(3003, function() {
        console.log('server up and running at %s port', 3003);
});
server.on('connection', function(client){
        console.log("NUEVO CLIENTE");
        client.on('event', function(data){});
        client.on('disconnect', function(){});
        client.on('room', function(room) {
                console.log('Room: '+room);
                        client.join(room);
    });
        client.on('leaveRroom', function(room) {
                        console.log('LeaveRroom: '+room);
                        client.leave(room);
    });

});

The server connection always success using port 3003.

Client

$scope.socket = io.connect('https://localhost:3003/', { transports: ['websocket'] });
$scope.socket.on('connect_error', function (data) {
                console.log(data);
    });

    $scope.socket.on('message', function(message) {
        $scope.getAttendance();
        $scope.clientDetails(message.user[0]);
    })


Browser logs:

VM2481:7 WebSocket connection to 'wss://localhost:3003/socket.io/?EIO=3&transport=websocket' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
r.doOpen @ VM2481:7
r.open @ VM2481:7
r.open @ VM2481:6
r @ VM2481:6
r @ VM2481:6
r.open.r.connect @ VM2481:6
(anonymous) @ VM2481:6
VM2481:6 engine.io-client:socket socket error {"type":"TransportError","description":{"isTrusted":true}} +93ms
VM2481:6 socket.io-client:manager connect_error +92ms
VM2481:6 socket.io-client:manager cleanup +4ms
access.js:45 Error: websocket error
    at r.onError (eval at <anonymous> (jquery.min.js:2), <anonymous>:7:8015)
    at WebSocket.ws.onerror (eval at <anonymous> (jquery.min.js:2), <anonymous>:7:23668)
VM2481:6 socket.io-client:manager reconnect attempt error +5ms
VM2481:6 socket.io-client:manager will wait 5000ms before reconnect attempt +2ms
VM2481:6 engine.io-client:socket socket close with reason: "transport error" +16ms
VM2481:6 socket.io-client:manager attempting reconnect +5s
VM2481:6 socket.io-client:manager readyState closed +3ms
VM2481:6 socket.io-client:manager opening https://localhost:3003/ +3ms
VM2481:6 engine.io-client:socket creating transport "websocket" +5s
VM2481:6 engine.io-client:socket setting transport websocket +3ms
VM2481:6 

For the ssl I am using load balancer for AWS.

I expect the client connect successfully with the server over https.



from Can't connect to websocket using ssl and apache

TabLayout scrolls to unkown position after calling notifyDataSetChanged on PagerAdapter

I have sample project with TabLayout and PagerAdapter. Strange things happens with TabLayout when I call pagerAdapter.notifyDataSetChanged(); after tabLayout.setupWithViewPager(viewPager);

TabLayout is scrolling to unknown x position so the current tab is not visible. However if I scroll to left to expecting tab, this tab has indicator.

What is going on? Could anyone help me? I have spent on it too many time.

enter image description here

Below the code.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        final SampleFragmentPagerAdapter pagerAdapter = new SampleFragmentPagerAdapter(getSupportFragmentManager(), MainActivity.this);
        viewPager.setAdapter(pagerAdapter);

        // Give the TabLayout the ViewPager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);

        findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pagerAdapter.notifyDataSetChanged();
            }
        });
    }

}

I tested on nexus emulators and nexus real devices (api 21+)

Gradle settings:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "xx.xxx.myapplication4"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

Link to reported issue and ready to test project as attachment here



from TabLayout scrolls to unkown position after calling notifyDataSetChanged on PagerAdapter

JQuery Match Height Not Working on Rails 5.2

I'm getting the following error after trying to install Jquery Match Height on my Rails app.

enter image description here

I've tried using the Match Height Gem, simply copy-pasting the entire script into my application.js, and (currently) a CDN include on my application.html.erb:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.matchHeight/0.7.2/jquery.matchHeight.js" type="text/javascript"></script>

The same errors are generated regardless. I have these jquery-related gems installed:

gem 'jquery-rails'
gem 'jquery-ui-rails'

Here's how I'm trying to use Match Height:

<script>
  $(document).ready(function() {
    $('.card-img-top').matchHeight();
    $('.card-title').matchHeight();
    $('.card-text').matchHeight();
    $('.card-footer').matchHeight();
  });
</script>

Can anyone see what I'm doing wrong?



from JQuery Match Height Not Working on Rails 5.2

Friday 29 March 2019

3D scatterplot using custom image

I am trying to use ggplot and ggimage to create a 3D scatterplot with a custom image. It works fine in 2D:

library(ggplot2)
library(ggimage)
library(rsvg)

set.seed(2017-02-21)
d <- data.frame(x = rnorm(10), y = rnorm(10), z=1:10,
  image = 'https://image.flaticon.com/icons/svg/31/31082.svg'
)

ggplot(d, aes(x, y)) + 
  geom_image(aes(image=image, color=z)) +
  scale_color_gradient(low='burlywood1', high='burlywood4')

enter image description here

I've tried two ways to create a 3D chart:

  1. plotly - This currently does not work with geom_image, though it is queued as a future request.

  2. gg3D - This is an R package, but I cannot get it to play nice with custom images. Here is how combining those libraries ends up:

library(ggplot2)
library(ggimage)
library(gg3D)

ggplot(d, aes(x=x, y=y, z=z, color=z)) +
  axes_3D() +
  geom_image(aes(image=image, color=z)) +
  scale_color_gradient(low='burlywood1', high='burlywood4')

enter image description here

Any help would be appreciated. I'd be fine with a python library, javascript, etc. if the solution exists there.



from 3D scatterplot using custom image

Prevent window vertical scroll, until div's horizontal scroll reaches its end

I have a page that scrolls normal (vertically) and I'd like to have a div that scrolls horizontally on mousewheel down, then resumes vertical scrolling once the horizontal scrolling is done. Here's what I'm trying to accomplish.

  • Page scrolls normal (vertically)
  • Once I reach a the div #scroll, I'd like the page scrolling to stop and I'd like the content inside #scroll to scroll vertically
  • Once I scroll to the end of #scroll, I'd like the normal page scroll (vertically) to resume.

I have tried a few solutions but run in to the following problems

  • When I horizontal the #scroll content the vertical page scroll doesn't stop
  • When I stop the vertical scroll and get to the end of the horizontal scroll, I have to scroll like 50 times just to get out of that div.

Here's what I have so far...

var scroller = {};
scroller.e = document.getElementById("scroll");

if (scroller.e.addEventListener) {
    scroller.e.addEventListener("mousewheel", MouseWheelHandler, false);
    scroller.e.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
} else scroller.e.attachEvent("onmousewheel", MouseWheelHandler);

function MouseWheelHandler(e) {

    // cross-browser wheel delta
    var e = window.event || e;
    var delta = - 30 * (Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))));

    var pst = $('#scroll').scrollLeft() + delta;

    if (pst < 0) {
        pst = 0;
    } else if (pst > $('.box-wrap').width()) {
        pst = $('.box-wrap').width();
    }

    $('#scroll').scrollLeft(pst);

    return false;
}


var toolbox = $('#scroll'),
    height = toolbox.height(),
    scrollHeight = toolbox.get(0).scrollHeight;

toolbox.off("mousewheel").on("mousewheel", function (event) {
  var blockScrolling = this.scrollTop === scrollHeight - height && event.deltaY < 0 || this.scrollTop === 0 && event.deltaY > 0;
  return !blockScrolling;
});
#wrap {
  max-width: 600px;
  margin: 0 auto;
}

#scroll {
    width: 600px;
    border: 1px solid #111;
    padding: 0px;
    margin: 0px;
    overflow-x: scroll;
    overflow-y: hidden;
}

.box-wrap{
    padding: 0px;
    margin: 0px;
    height: 200px;
    width: 2040px;
}

.box {
    height: 200px;
    width: 200px;
    padding: 0px;
    background: #123;
    display: inline-block;
    color: #fff;
    font-size: 20px;
    text-align: center;
    line-height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrap">

  <h1>asl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdk</h1>

  <div id="scroll">
    <div class="box-wrap">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
      <div class="box">7</div>
      <div class="box">8</div>
      <div class="box">9</div>
      <div class="box">10</div>     
    </div>
  </div>

  <h1>asl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdkasl fjas fhljksa flkjsahf kjsah fkjlsa fkjshf kljsha fkljhs kjfhas kljfh sakjfhas fsdk</h1>

</div>

The problem with this solution is that the vertical page scroll doesn't stop when I get to the horizontal scroll section.

Does anyone have any suggestions on how to accomplish what I want? If I'm not explaining this right please let me know.

Thanks!



from Prevent window vertical scroll, until div's horizontal scroll reaches its end