How to Adding Background Image using jQuery

A guide on adding background image using jQuery


With jQuery, you can change the background-image CSS property by using the css() method. The method is used to set or retrieve one CSS property value.

The syntax of css() method is as follows:

css("propertyName", "value");

You can set the background-image property, to any element you’ve selected using jQuery selector method:

$('.imgEl').css('background-image', 'url(./assets/image.png)');

Finally, you can also set other CSS properties to make the background looks good on your page, such as background-repeat, background-position, and height properties as follows:

$('.imgEl').css('background-image', 'url(./assets/image.png)');
$('.imgEl').css('background-repeat', 'no-repeat'); // do not repeat the image
$('.imgEl').css('background-position', 'center'); // center the image
$('.imgEl').css('height', '500px'); // sets the height

And that’s how you can change background image using jQuery 😉

Original article source at: https://sebhastian.com/

#jquery #background #image 

How to Adding Background Image using jQuery

Guide on changing background color using jQuery

How to change background color using jQuery.

A guide on changing background color using jQuery


When you need to change the background color of an element using jQuery, you can use the css() method of jQuery to set the background-color CSS property of the element.

For example, suppose you have an HTML <body> tag as follows:

<body style="background-color: yellow;">
  <h1>jQuery change background color</h1>
</body>

You can change the <body> background color by first selecting the element using jQuery selector $() and chain it with the css() method as follows:

$("body").css("background-color","blue");

The code above will change the background color from yellow to blue. You can also trigger the color change when a <button> element is clicked by using the .click() event handler method from jQuery.

Here’s an example code for that:

<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="background-color: yellow;">
  <h1>jQuery change background color</h1>
  <button id="btn">Change background</button>
  <script>
    $("#btn").click(function(){
      $("body").css("background-color","blue");
    })
  </script>
</body>

The click() method will execute the function you passed into it when the selected element is clicked.

Original article source at: https://sebhastian.com/

#jquery #background #color 

Guide on changing background color using jQuery

A Flutter Plugin to Handle Phone Call State in Background

Caller

A flutter plugin to handle Phone Call state and execute a Dart callback in background.
 

Warning

This package is under development and since I'm not keen on native Android development, there may be a lot of work to do, so any PR are welcome.


 

IOS Implementation

Unfortunately I'm not familiar with IOS development neither with Switf/ObjC languages, so if you wish to help any PR will be welcome.


 

Android

Add the following permissions to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />

Also, apparently it is necessary to register the broadcast receiver manually, otherwise an error will be throw saying that our receiver does not exist inside the app:

<receiver android:name="me.leoletto.caller.CallerPhoneServiceReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>


 

Getting started

All you need to start using our package after installing it, is defining a callback which must be a top level function or static function, that will be called by our plugin when any incoming call events are detected.

void callerCallbackHandler(CallerEvent event, String number, int duration)

This callback handler must accept 3 arguments:

CallerEvent: The event type detect by our plugin in background.

Number: The incoming number that is triggering the phone state call.

duration: An integer that represents the duration of the call in seconds.

The CallerEvent is an enum with four possible values:

Event ValueDescription
incomingIndicates an incoming call.
outgoingIndicates an outgoing call.

Since all this process happens in background in a Dart Isolate, there's no guarantee that the current OS will call the registered callback as soon as an event is triggered or that the callback will ever be called at all, each OS handle background services with different policies. Make sure to ask user permission before calling the Caller.initialize method of our plugin. Check the example to see a simple implementation of it.

Breaking changes

If you were using the previous version 1.x.x of this package, be aware that some breaking changes have been made.

  • Intermediate events won't be fired anymore, a single event will be fired when the call is ended, indicating the type (incoming/outgoing), the duration and the phone number.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add caller

With Flutter:

 $ flutter pub add caller

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  caller: ^2.0.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:caller/caller.dart'; 

example/lib/main.dart

import 'package:caller/caller.dart';
import 'package:flutter/material.dart';

/// Defines a callback that will handle all background incoming events
Future<void> callerCallbackHandler(
  CallerEvent event,
  String number,
  int duration,
) async {
  print("New event received from native $event");
  switch (event) {
    case CallerEvent.incoming:
      print(
          '[ Caller ] Incoming call ended, number: $number, duration $duration s');
      break;
    case CallerEvent.outgoing:
      print(
          '[ Caller ] Ougoing call ended, number: $number, duration: $duration s');
      break;
  }
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  /// Run your app as you would normally do...
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Caller Plugin Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Caller Plugin Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool? hasPermission;

  @override
  void initState() {
    super.initState();

    _checkPermission();
  }

  Future<void> _checkPermission() async {
    final permission = await Caller.checkPermission();
    print('Caller permission $permission');
    setState(() => hasPermission = permission);
  }

  Future<void> _requestPermission() async {
    await Caller.requestPermissions();
    await _checkPermission();
  }

  Future<void> _stopCaller() async {
    await Caller.stopCaller();
  }

  Future<void> _startCaller() async {
    if (hasPermission != true) return;
    await Caller.initialize(callerCallbackHandler);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(hasPermission == true ? 'Has permission' : 'No permission'),
            ElevatedButton(
              onPressed: () => _requestPermission(),
              child: Text('Ask Permission'),
            ),
            ElevatedButton(
              onPressed: () => _startCaller(),
              child: Text('Start caller'),
            ),
            ElevatedButton(
              onPressed: () => _stopCaller(),
              child: Text('Stop caller'),
            ),
          ],
        ),
      ),
    );
  }
} 

Download Details:

Author: Paradoxu

Source Code: https://github.com/Paradoxu/Caller

#flutter #background #call 

A Flutter Plugin to Handle Phone Call State in Background
Lawson  Wehner

Lawson Wehner

1660932720

Parallax_bg: Create Beautiful & interactive Parallax Backgrounds

parallax_bg

Create beautiful & interactive parallax backgrounds for your apps and games.

Example Image

You can find another working example in SlideIT Mobile Game

Usage

Add following command in your pubspec.yaml & install package

parallax_bg:2.0.0

Import in your dart page

import 'package:parallax_bg/parallax_bg.dart';

Add following to create background wrapper

    ParallaxBackground(
      backgroundImage: "assets/images/galaxy.jpg",
      parallaxType: _parallaxType,
      foregroundChilds: [
        ParallaxItem(
            child: Image.asset("assets/images/planet.png"),
            offset: _planetOffset),
        ParallaxItem(
            child: Image.asset("assets/images/meteor.png"),
            offset: _meteorOffset),
      ],
      // fallback: true,
    );

Change/Add/Remove ParallaxItem for foreground items

    ParallaxItem(
    child: Image.asset("assets/images/meteor.png"),
    offset: _meteorOffset),

ParallaxBackground

PROPERTYTYPEREQUIREDDETAILS
backgroundImagestringyesImage path from asset folder
foregroundChildsListyesWidgets to create foreground layers
childWidgetnoChild widget to draw over all parallax widgets
reversebooleannoMove foreground items in reverse direction. Default false
fallbackbooleannoIf true render the items normally when there are no sensors available. If false, it will show a error message in visible area. Default false

ParallaxItem

PROPERTYTYPEREQUIREDDETAILS
childWidgetyesChild widget to draw over background as parallax item
offsetbooleannoOffset values to calculate distance to move items when moving device. Need separate value for each item. Default 5

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add parallax_bg

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  parallax_bg: ^2.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:parallax_bg/parallax_bg.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:parallax_bg/parallax_bg.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  double _planetOffset = 1;
  double _meteorOffset = 5;

  bool _loading = false;

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIOverlays([]);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        // appBar: AppBar(
        //   title: const Text('Sample App'),
        // ),
        body: Column(mainAxisSize: MainAxisSize.max, children: [
          Expanded(
              child: _loading
                  ? Center(child: CircularProgressIndicator())
                  : _parallaxBody()),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              children: [
                Text("Planet"),
                Expanded(
                  child: Slider(
                    value: _planetOffset,
                    onChanged: (val) {
                      setState(() {
                        _planetOffset = val;
                      });
                    },
                    min: 1,
                    max: 10,
                  ),
                ),
                Text(_planetOffset.toStringAsFixed(0)),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Row(
              children: [
                Text("Meteor"),
                Expanded(
                  child: Slider(
                    value: _meteorOffset,
                    onChanged: (val) {
                      setState(() {
                        _meteorOffset = val;
                      });
                    },
                    min: 5,
                    max: 20,
                  ),
                ),
                Text(_meteorOffset.toStringAsFixed(0)),
              ],
            ),
          ),
        ]),
      ),
    );
  }

  _parallaxBody() {
    return ParallaxBackground(
      backgroundImage: "assets/images/galaxy.jpg",
      foregroundChilds: [
        ParallaxItem(
            child: Image.asset("assets/images/planet.png"),
            offset: _planetOffset),
        ParallaxItem(
            child: Image.asset("assets/images/meteor.png"),
            offset: _meteorOffset),
      ],
      // fallback: true,
    );
  }
}

Download Details:

Author: Kumar-aakash86
Source Code: https://github.com/kumar-aakash86/parallax_bg 
License: MIT license

#flutter #dart #background 

Parallax_bg: Create Beautiful & interactive Parallax Backgrounds
Rocio  O'Keefe

Rocio O'Keefe

1660778580

Flutter Background Location Plugin for android & IOS

Background Location

A Flutter plugin to get location updates in the background for both Android and iOS (Requires iOS 10.0+). Uses CoreLocation for iOS and FusedLocationProvider for Android

Getting Started

1: Add this to your package's pubspec.yaml file:

dependencies:
  background_location: ^0.8.1

2: Install packages from the command line:

$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

How to use

Import the package where you wanna use it.

import 'package:background_location/background_location.dart';

Request permissions from the user. You can use permission_handler for this

Set the notification title, message and icon (Android only). Use await or .then if you wanna start the location service immediatly after becuase its an asynchronous method

BackgroundLocation.setAndroidNotification(
    title: "Notification title",
        message: "Notification message",
        icon: "@mipmap/ic_launcher",
);

Set the interval between localisations in milliseconds (Android only). Use await or .then if you wanna start the location service immediatly after becuase its an asynchronous method

BackgroundLocation.setAndroidConfiguration(1000);

Start the location service. This will also ask the user for permission if not asked previously by another package.

BackgroundLocation.startLocationService();

Start location service by specifying distanceFilter. Defaults to 0 if not specified

BackgroundLocation.startLocationService(distanceFilter : 10);

You can also force the use of Android LocationManager instead of Google's FusedLocationProvider by setting the forceAndroidLocationManager property to true. If not specified, this defaults to false, which uses FusedLocationProvider if it is available, treating LocationManager as a fallback. This setting has no effect on iOS devices.

BackgroundLocation.startLocationService(forceAndroidLocationManager: true);

getLocationUpdates will trigger everytime the location updates on the device. Provide a callback function to getLocationUpdates to handle location update.

BackgroundLocation.getLocationUpdates((location) {
  print(location);
});

location is a Class exposing the following properties.

double latitude;
double longitude;
double altitude;
double bearing;
double accuracy;
double speed;
double time;
bool isMock;

To stop listening to location changes you can execute.

BackgroundLocation.stopLocationService();

Make sure to delcare all required permissions for both your android and ios app

info.plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location.</string>
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>location</string>
</array>

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/> 

  Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add background_location

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  background_location: ^0.8.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:background_location/background_location.dart';

example/lib/main.dart

import 'package:background_location/background_location.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String latitude = 'waiting...';
  String longitude = 'waiting...';
  String altitude = 'waiting...';
  String accuracy = 'waiting...';
  String bearing = 'waiting...';
  String speed = 'waiting...';
  String time = 'waiting...';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Background Location Service'),
        ),
        body: Center(
          child: ListView(
            children: <Widget>[
              locationData('Latitude: ' + latitude),
              locationData('Longitude: ' + longitude),
              locationData('Altitude: ' + altitude),
              locationData('Accuracy: ' + accuracy),
              locationData('Bearing: ' + bearing),
              locationData('Speed: ' + speed),
              locationData('Time: ' + time),
              ElevatedButton(
                  onPressed: () async {
                    await BackgroundLocation.setAndroidNotification(
                      title: 'Background service is running',
                      message: 'Background location in progress',
                      icon: '@mipmap/ic_launcher',
                    );
                    //await BackgroundLocation.setAndroidConfiguration(1000);
                    await BackgroundLocation.startLocationService(
                        distanceFilter: 20);
                    BackgroundLocation.getLocationUpdates((location) {
                      setState(() {
                        latitude = location.latitude.toString();
                        longitude = location.longitude.toString();
                        accuracy = location.accuracy.toString();
                        altitude = location.altitude.toString();
                        bearing = location.bearing.toString();
                        speed = location.speed.toString();
                        time = DateTime.fromMillisecondsSinceEpoch(
                                location.time!.toInt())
                            .toString();
                      });
                      print('''\n
                        Latitude:  $latitude
                        Longitude: $longitude
                        Altitude: $altitude
                        Accuracy: $accuracy
                        Bearing:  $bearing
                        Speed: $speed
                        Time: $time
                      ''');
                    });
                  },
                  child: Text('Start Location Service')),
              ElevatedButton(
                  onPressed: () {
                    BackgroundLocation.stopLocationService();
                  },
                  child: Text('Stop Location Service')),
              ElevatedButton(
                  onPressed: () {
                    getCurrentLocation();
                  },
                  child: Text('Get Current Location')),
            ],
          ),
        ),
      ),
    );
  }

  Widget locationData(String data) {
    return Text(
      data,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 18,
      ),
      textAlign: TextAlign.center,
    );
  }

  void getCurrentLocation() {
    BackgroundLocation().getCurrentLocation().then((location) {
      print('This is current Location ' + location.toMap().toString());
    });
  }

  @override
  void dispose() {
    BackgroundLocation.stopLocationService();
    super.dispose();
  }
}

Download Details:

Author: Almoullim
Source Code: https://github.com/Almoullim/background_location 
License: View license

#flutter #dart #background #location 

Flutter Background Location Plugin for android & IOS
Royce  Reinger

Royce Reinger

1658197680

Sneakers: A Fast Background Processing Framework for Ruby & RabbitMQ

Sneakers

      __
  ,--'  >
  `=====

A high-performance RabbitMQ background processing framework for Ruby.

Sneakers is being used in production for both I/O and CPU intensive workloads, and have achieved the goals of high-performance and 0-maintenance, as designed.

Installation

Add this line to your application's Gemfile:

gem 'sneakers'

And then execute:

$ bundle

Or install it yourself as:

$ gem install sneakers

Documentation

A quick start guide is available in the section below.

Visit the wiki for more detailed documentation and GitHub releases for release notes.

A change log is also available.

Quick start

Set up a Gemfile

source 'https://rubygems.org'
gem 'sneakers'
gem 'json'
gem 'redis'

How do we add a worker? Firstly create a file and name it as boot.rb then create a worker named as Processor.

touch boot.rb

require 'sneakers'
require 'redis'
require 'json'

$redis = Redis.new

class Processor
  include Sneakers::Worker
  from_queue :logs

  def work(msg)
    err = JSON.parse(msg)
    if err["type"] == "error"
      $redis.incr "processor:#{err["error"]}"
    end

    ack!
  end
end

Let's test it out quickly from the command line:

$ sneakers work Processor --require boot.rb

We just told Sneakers to spawn a worker named Processor, but first --require a file that we dedicate to setting up environment, including workers and what-not.

If you go to your RabbitMQ admin now, you'll see a new queue named logs was created. Push a couple messages like below:

{
   "type": "error",
   "message": "HALP!",
   "error": "CODE001"
}

Publish a message with the bunny gem RabbitMQ client:

require 'bunny'

conn = Bunny.new
conn.start

ch = conn.create_channel
ch.default_exchange.publish({ type: 'error', message: 'HALP!', error: 'CODE001' }.to_json, routing_key: 'logs')

conn.close

And this is the output you should see at your terminal.

2013-10-11T19:26:36Z p-4718 t-ovqgyb31o DEBUG: [worker-logs:1:213mmy][#<Thread:0x007fae6b05cc58>][logs][{:prefetch=>10, :durable=>true, :ack=>true, :heartbeat_interval=>2, :exchange=>"sneakers"}] Working off: log log
2013-10-11T19:26:36Z p-4718 t-ovqgyrxu4 INFO: log log
2013-10-11T19:26:40Z p-4719 t-ovqgyb364 DEBUG: [worker-logs:1:h23iit][#<Thread:0x007fae6b05cd98>][logs][{:prefetch=>10, :durable=>true, :ack=>true, :heartbeat_interval=>2, :exchange=>"sneakers"}] Working off: log log
2013-10-11T19:26:40Z p-4719 t-ovqgyrx8g INFO: log log

We'll count errors and error types with Redis.

$ redis-cli monitor
1381520329.888581 [0 127.0.0.1:49182] "incr" "processor:CODE001"

We're basically done with the ceremonies and all is left is to do some real work.

Looking at metrics

Let's use the logging_metrics provider just for the sake of fun of seeing the metrics as they happen.

# boot.rb
require 'sneakers'
require 'redis'
require 'json'
require 'sneakers/metrics/logging_metrics'
Sneakers.configure(metrics: Sneakers::Metrics::LoggingMetrics.new)

# ... rest of code

Now push a message again and you'll see:

2013-10-11T19:44:37Z p-9219 t-oxh8owywg INFO: INC: work.Processor.started
2013-10-11T19:44:37Z p-9219 t-oxh8owywg INFO: TIME: work.Processor.time 0.00242
2013-10-11T19:44:37Z p-9219 t-oxh8owywg INFO: INC: work.Processor.handled.ack

Which increments started and handled.ack, and times the work unit.

From here, you can continue over to the Wiki

Docker

If you use Docker, there's some benefits to be had and you can use both docker and docker-compose with this project, in order to run tests, integration tests or a sample worker without setting up RabbitMQ or the environment needed locally on your development box.

  • To build a container run docker build . -t sneakers_sneakers
  • To run non-integration tests within a docker container, run docker run --rm sneakers_sneakers:latest
  • To run full integration tests within a docker topology including RabbitMQ, Redis (for integration worker) run scripts/local_integration, which will use docker-compose to orchestrate the topology and the sneakers Docker image to run the tests
  • To run a sample worker within Docker, try the TitleScraper example by running script/local_worker. This will use docker-compose as well. It will also help you get a feeling for how to run Sneakers in a Docker based production environment
  • Use Dockerfile.slim instead of Dockerfile for production docker builds. It generates a more compact image, while the "regular" Dockerfile generates a fatter image - yet faster to iterate when developing

Compatibility

  • Sneakers 2.7.x and later (using Bunny 2.9) - Ruby 2.2.x
  • Sneakers 1.1.x and later (using Bunny 2.x) - Ruby 2.x
  • Sneakers 1.x.x and earlier - Ruby 1.9.x, 2.x

Contributing

Fork, implement, add tests, pull request, get my everlasting thanks and a respectable place here :).

Thanks:

To all Sneakers Contributors - you make this happen, thanks!

Author: jondot
Source Code: https://github.com/jondot/sneakers 
License: MIT license

#ruby #rabbitmq #background 

Sneakers: A Fast Background Processing Framework for Ruby & RabbitMQ
Royce  Reinger

Royce Reinger

1658190240

Qu: A Ruby Library for Queuing and Processing Background Jobs

Qu

Qu is a Ruby library for queuing and processing background jobs. It is heavily inspired by delayed_job and Resque.

Qu was created to overcome some shortcomings in the existing queuing libraries that we experienced at Ordered List while building SpeakerDeck, Gaug.es and Harmony. The advantages of Qu are:

  • Multiple backends (redis, mongo)
  • Jobs are requeued when worker is killed
  • Resque-like API

Information & Help

Installation

Rails 3 and 4

Decide which backend you want to use and add the gem to your Gemfile.

gem 'qu-rails'
gem 'qu-redis'

That's all you need to do!

Rails 2

Decide which backend you want to use and add the gem to config.gems in environment.rb:

config.gem 'qu-redis'

To load the rake tasks, add the following to your Rakefile:

require 'qu/tasks'

Usage

Jobs are defined by extending the Qu::Job class:

class ProcessPresentation < Qu::Job
  def initialize(presentation_id)
    @presentation_id = presentation_id
  end

  def perform
    Presentation.find(@presentation_id).process!
  end
end

You can add a job to the queue by calling create on your job:

job = ProcessPresentation.create(@presentation.id)
puts "Created job #{job.id}"

The job will be initialized with any parameters that are passed to it when it is performed. These parameters will be stored in the backend, so they must be simple types that can easily be serialized and unserialized. Don't try to pass in an ActiveRecord object.

Processing the jobs on the queue can be done with a Rake task:

$ bundle exec rake qu:work

You can easily inspect the queue or clear it:

puts "Jobs on the queue:", Qu.size
Qu.clear

Queues

The default queue is used, um…by default. Jobs that don't specify a queue will be placed in that queue, and workers that don't specify a queue will work on that queue.

However, if you have some background jobs that are more or less important, or some that take longer than others, you may want to consider using multiple queues. You can have workers dedicated to specific queues, or simply tell all your workers to work on the most important queue first.

Jobs can be placed in a specific queue by setting the queue:

class CallThePresident < Qu::Job
  queue :urgent

  def initialize(message)
    @message = message
  end

  def perform
    # …
  end
end

You can then tell workers to work on this queue by passing an environment variable

$ bundle exec rake qu:work QUEUES=urgent,default

Note that if you still want your worker to process the default queue, you must specify it. Queues will be process in the order they are specified.

You can also get the size or clear a specific queue:

Qu.size(:urgent)
Qu.clear(:urgent)

Configuration

Most of the configuration for Qu should be automatic. It will also automatically detect ENV variables from Heroku for backend connections, so you shouldn't need to do anything to configure the backend.

However, if you do need to customize it, you can by calling the Qu.configure:

Qu.configure do |c|
  c.logger = Logger.new('log/qu.log')
  c.graceful_shutdown = true
end

Tests

If you prefer to have jobs processed immediatly in your tests, there is an Immediate backend that will perform the job instead of enqueuing it. In your test helper, require qu-immediate:

require 'qu-immediate'

Why another queuing library?

Resque and delayed_job are both great, but both of them have shortcomings that can be frustrating in production applications.

delayed_job was a brilliantly simple pioneer in the world of database-backed queues. While most asynchronous queuing systems were tending toward overly complex, it made use of your existing database and just worked. But there are a few flaws:

  • Occasionally fails silently.
  • Use of priority instead of separate named queues.
  • Contention in the ActiveRecord backend with multiple workers. Occasionally the same job gets performed by multiple workers.

Resque, the wiser relative of delayed_job, fixes most of those issues. But in doing so, it forces some of its beliefs on you, and sometimes those beliefs just don't make sense for your environment. Here are some of the flaws of Resque:

  • Redis is a great queue backend, but it doesn't make sense for every environment.
  • Forking before each job prevents memory leaks, but it is terribly inefficient in environments with a lot of fast jobs (the resque-jobs-per-fork plugin alleviates this)

Those shortcomings lead us to write Qu. It is not perfect, but we hope to overcome the issues we faced with other queuing libraries.

Contributing

If you find what looks like a bug:

  1. Search the issues on GitHub to see if anyone else has reported issue.
  2. If you don't see anything, create an issue with information on how to reproduce it.

If you want to contribute an enhancement or a fix:

  1. Fork the project on GitHub.
  2. Make your changes with tests.
  3. Commit the changes without making changes to the Rakefile, Gemfile, gemspec, or any other files that aren't related to your enhancement or fix
  4. Send a pull request.

Author: Bkeepers
Source Code: https://github.com/bkeepers/qu 
License: MIT license

#ruby #background #jobs 

Qu: A Ruby Library for Queuing and Processing Background Jobs
Nat  Grady

Nat Grady

1658152500

SpaceEye: Live Satellite Imagery for Your Desktop Background

SpaceEye

Live satellite imagery for your Mac or Windows desktop background.

App running on macOS

Install

Mac

Windows

  • Recommended: Download from the Microsoft Store by clicking the link above (Microsoft account not needed).
  • Alternative: Follow the installation instructions to download and run the installer from the latest GitHub release.
    • Note: You will have to dismiss warnings about the download being potentially dangerous with this method.

About

SpaceEye is an open source desktop app which sets live, publicly available satellite imagery as your desktop background.

New images are downloaded approximately every 10 minutes to an hour (depending on the view), giving an up-to-date, high resolution view of the Earth from space.

Currently, the app provides 12 views of the Earth from 5 different geostationary weather satellites: Himawari-8, GOES-17 (West), GOES-16 (East), Meteosat-8, and Meteosat-11. This list will hopefully be expanded in the future.

Acknowledgements

Special thanks to NOAA STAR and the Regional and Mesoscale Meteorology Branch (RAMMB) of NOAA/NESDIS (located at Colorado State University) for providing the satellite imagery.

Issues

If you encounter a bug or have a feature request, please create an issue on the Issues page.

Development

Requirements

VS Code is recommended for development, but not required. The repo includes configs and recommended extensions.

Setup

git clone https://github.com/KYDronePilot/SpaceEye.git
cd SpaceEye
yarn
yarn run build

Start in dev mode

Opens Chromium dev tools and watches renderer files.

yarn run start-dev

Package the app

Builds and packages app for distribution.

If on macOS, creates DMG and ZIP files, or if on Windows, creates NSIS executable installer.

yarn run dist

Privacy

The only data collected are server logs when downloading the satellite config file. This config file contains metadata and links to the satellite images provided by NOAA and RAMMB.

Author: KYDronePilot
Source Code: https://github.com/KYDronePilot/SpaceEye 
License: MIT license

#electron #desktop #background #mac #windows 

SpaceEye: Live Satellite Imagery for Your Desktop Background

Cakephp-queuesadilla: CakePHP Queuesadilla Plugin 4.0

CakePHP Queuesadilla Plugin 4.0

This plugin is a simple wrapper around the Queuesadilla queuing library, providing tighter integration with the CakePHP framework.

Requirements

  • CakePHP 4.x
  • PHP 7.2+
  • Patience

Documentation

For documentation, please see the docs.

Author: josegonzalez
Source Code: https://github.com/josegonzalez/cakephp-queuesadilla 
License: MIT license

#php #cakephp #background 

Cakephp-queuesadilla: CakePHP Queuesadilla Plugin 4.0

D3.sketchy: A tool To Create Sketchy Backgrounds, Shapes and Lines

d3.sketchy

A tool to create sketchy backgrounds, shapes and lines

Sketchy Rectangles

The library can draw rectangles and circles

Sketchy Circle

Custom shapes defined by an array of points.

Sketchy Shape

Which can be drawn automatically or with custom path functions

Sketchy Shape

And of course outlines for rectangles

Sketchy Rectangle Stroke

and circles

Sketchy Circle Stroke

The density, angle and sketchiness can be customized through parameters and the thickness of the lines through css.

Here is an interactive customizer that lets you play around with the parameters.

For in-depth documentation take a look at the docs, there are also various examples.

The library was inspired by Handy by Jo Wood et al. The circle strokes use code from http://codepen.io/spencerthayer/pen/nhjwu by Spencer Thayer

Author: Sebastian-meier
Source Code: https://github.com/sebastian-meier/d3.sketchy 
License: MIT license

#javascript #d3 #tool #background 

D3.sketchy: A tool To Create Sketchy Backgrounds, Shapes and Lines
Lawson  Wehner

Lawson Wehner

1652516220

A Flutter Plugin for Execute Dart Code in Background

background_service

A flutter plugin for execute dart code in background.

Android

  • No additional setting required.
  • Support notify for bt, gps state

iOS

  • Register plugins (optional)
import UIKit
import Flutter
import flutter_background_service // add this

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    /// add this
    static func registerPlugins(with registry: FlutterPluginRegistry) {
        GeneratedPluginRegistrant.register(with: registry)
    }

    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        AppDelegate.registerPlugins(with: self)
        SwiftBackgroundServicePlugin.setPluginRegistrantCallback { registry in
            AppDelegate.registerPlugins(with: registry)
        }

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}
  • Playing audio continously

Info.plist

...
    <key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
        ...
    </array>
...

Then use audioplayer plugin to play audio.

...
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  BackgroundService.initialize(onStart);

  runApp(MyApp());
}

void onStart() {
  WidgetsFlutterBinding.ensureInitialized();

  final audioPlayer = AudioPlayer();

  String url =
      "https://www.mediacollege.com/downloads/sound-effects/nature/forest/rainforest-ambient.mp3";

  audioPlayer.onPlayerStateChanged.listen((event) {
    if (event == AudioPlayerState.COMPLETED) {
      audioPlayer.play(url); // repeat
    }
  });

  audioPlayer.play(url);
}
..

Usage

  • Follow the example.

Warning

The code will executed in isolated process, you can't share reference between UI and Service. Use sendData and onDataReceived to communicate between service and UI.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add background_service

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  background_service: ^1.1.5

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:background_service/background_service.dart';

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:background_service/background_service.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  BackgroundService.initialize(onStart);

  runApp(MyApp());
}

void onStart() {
  WidgetsFlutterBinding.ensureInitialized();
  final service = BackgroundService();
  service.onDataReceived.listen((event) {
    if (event!["action"] == "setAsForeground") {
      service.setForegroundMode(true);
      return;
    }

    if (event["action"] == "setAsBackground") {
      service.setForegroundMode(false);
    }

    if (event["action"] == "stopService") {
      service.stopBackgroundService();
    }
  });

  // bring to foreground
  service.setForegroundMode(true);
  Timer.periodic(Duration(seconds: 1), (timer) async {
    if (!(await service.isServiceRunning())) timer.cancel();
    service.setNotificationInfo(
      title: "My App Service",
      content: "Updated at ${DateTime.now()}",
    );

    service.sendData(
      action: DateTime.now().toIso8601String(),
    );
  });
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String text = "Stop Service";
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Service App'),
        ),
        body: Column(
          children: [
            StreamBuilder<Map<String, dynamic>?>(
              stream: BackgroundService().onDataReceived,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }

                final data = snapshot.data!;
                DateTime? date = DateTime.tryParse(data["current_date"]);
                return Text(date.toString());
              },
            ),
            ElevatedButton(
              child: Text("Foreground Mode"),
              onPressed: () {
                BackgroundService().sendData(action: "setAsForeground");
              },
            ),
            ElevatedButton(
              child: Text("Background Mode"),
              onPressed: () {
                BackgroundService().sendData(action: "setAsBackground");
              },
            ),
            ElevatedButton(
              child: Text(text),
              onPressed: () async {
                var isRunning = await BackgroundService().isServiceRunning();
                if (isRunning) {
                  BackgroundService().sendData(
                    action: "stopService",
                  );
                } else {
                  BackgroundService.initialize(onStart);
                }
                if (!isRunning) {
                  text = 'Stop Service';
                } else {
                  text = 'Start Service';
                }
                setState(() {});
              },
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            BackgroundService().sendData(action: "world");
          },
          child: Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}

Author: jin-develop
Source Code: https://github.com/jin-develop/background_service 
License: View license

#flutter #dart #background 

A Flutter Plugin for Execute Dart Code in Background

Dynamically Changing Status Bar Color Based on The Background

Dynamic status bar plugin

Features

A Flutter package for dynamically changing status bar color based on the background. Can be set up to automatically change the color whenever the current route is changed. It is also possible to manually refresh the color.

Usage

Place StatusbarzCapturer above your MaterialApp widget:

void main() {
  runApp(
    StatusbarzCapturer(
      child: MaterialApp(
        home: Container(),
      ),
    ),
  );
}

Now you can manually refresh status bar color by calling:

Statusbarz.instance.refresh();

Or alternatively you can refresh automatically when the current route changes. To do this, simply add Statusbarz.instance.observer to your MaterialApps navigatorObservers:

void main() {
  runApp(
    StatusbarzCapturer(
      child: MaterialApp(
        navigatorObservers: [Statusbarz.instance.observer],
        home: Container(),
      ),
    ),
  );
}

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add statusbarz

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  statusbarz: ^1.0.8

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:statusbarz/statusbarz.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:statusbarz/statusbarz.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StatusbarzCapturer(
      child: MaterialApp(
        navigatorObservers: [Statusbarz.instance.observer],
        title: 'Statusbarz example',
        home: RouteA(),
      ),
    );
  }
}

class RouteA extends StatelessWidget {
  const RouteA({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.black,
      child: Center(
        child: ElevatedButton(
          child: Text('Change screen to B'),
          onPressed: () {
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => RouteB()));
          },
        ),
      ),
    );
  }
}

class RouteB extends StatelessWidget {
  const RouteB({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.white,
      child: Center(
        child: ElevatedButton(
          child: Text('Change screen to A'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
} 

Download Details:

Author: Mapventure

Source Code: https://github.com/Mapventure/statusbarz

#flutter #background #bar 

Dynamically Changing Status Bar Color Based on The Background
Raja Tamil

Raja Tamil

1650888000

CSS Make Background Image Full Screen

Learn how to set an image of any size as the background of an HTML element full screen in CSS!

Create A Container Div Element

Create a div or any block-level HTML element with the class name called .bg-container where I’m going to add a background image into.

<div class="bg-container"></div>

Make The Container Div Full Screen

Then, make the div full screen so that the background image fits the full screen of the browser window.

Note: You can change the size of the container div if you do not want the image to fill the whole screen because the background image will only be visible based on the size of the container div.

There are a few ways to make a div full screen but I’m going to use the height:100% CSS property to achieve it this time.

This is a two-step process.

  1. Add a couple of CSS properties to the html and body selectors. Setting the margin to 0 will get rid of any white space around the browser window and set the height to 100%.
html, body {
  margin:0;
  height:100%;
}

2. Add three properties to the .bg-container selector.

.bg-container {
  width:100%;
  height:100%;
  border:5px solid red;
}

I’ve explicitly set the width to 100%, but we do not have to because div is a block-level element and its default width is stretched to its parent width, in this case, body.

Then, set height:100% which will stretch the height of the .bg-container to the bottom edge of the browser viewport. In order to get the height to work, make sure you’ve added the height:100% to the html and body selector above, otherwise, it won’t work.

To see that .bg-container, add the border with 5px width, solid style, and red color.


At this stage, I have an issue that the scroll bars appear on the right and bottom which hide the red border.

Let’s fix that.

To hide the scroll bar, add overflow: hidden to the html and body CSS selectors.

html, body {
  margin:0;
  height:100%;
  overflow:hidden;
}

As you can see from the below picture, the scroll bar is gone but the border at the bottom and right are still hidden.

This is because when you give a border to the element that is already 100% width, the border will be added to the container in addition to the 100% width on both left and right sides. That’s why the border on the right and bottom stretched beyond the edge of the browser viewport.

To bring the border back in, in other words, include the border within the 100% width, all I have to add is the box-sizing:border-box CSS property to the .bg-container.

.bg-container {
  width:100%;
  height:100%; 
  border:5px solid red;
  box-sizing:border-box;
}

This way, I know if I add an image as a background image to this container it will be visible to the full screen.

Recommended
Design Cool Registration Form Using HTML & CSS

Add Background Image Full Screen

Let’s add the background image to the .bg-container.

For that, all I have to do is add the background-image CSS property to the .bg-container with the image URL path which will normally be the image location of your project folder or any web image URL.

Continue Reading…

#HTML #CSS #coding #background #image 

CSS Make Background Image Full Screen
Rocio  O'Keefe

Rocio O'Keefe

1650406020

Flutter_uploader: Background Upload Plugin for Flutter

Flutter Uploader

A plugin for creating and managing upload tasks. Supports iOS and Android.

This plugin is based on WorkManager in Android and NSURLSessionUploadTask in iOS to run upload task in background mode.

This plugin is inspired by flutter_downloader. Thanks to Hung Duy Ha & Flutter Community for great plugins and inspiration.

iOS integration

  • Enable background mode.

AppDelegate changes

The plugin supports a background isolate. In order for plugins to work, you need to adjust your AppDelegate as follows:

import flutter_uploader

func registerPlugins(registry: FlutterPluginRegistry) {
    GeneratedPluginRegistrant.register(with: registry)
}

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    SwiftFlutterUploaderPlugin.registerPlugins = registerPlugins

    // Any further code.
  }
}

Optional configuration:

  • Configure maximum number of connection per host: the plugin allows 3 simultaneous http connection per host running at a moment by default. You can change this number by adding following codes to your Info.plist file.
<!-- changes this number to configure the maximum number of concurrent tasks -->
<key>FUMaximumConnectionsPerHost</key>
<integer>3</integer>
  • Configure maximum number of concurrent upload operation: the plugin allows 3 simultaneous upload operation running at a moment by default. You can change this number by adding following codes to your Info.plist file.
<!-- changes this number to configure the maximum number of concurrent tasks -->
<key>FUMaximumUploadOperation</key>
<integer>3</integer>
  • Configure request timeout: controls how long (in seconds) a task should wait for additional data to arrive before giving up Info.plist file.
<!-- changes this number to configure the request timeout -->
<key>FUTimeoutInSeconds</key>
<integer>3600</integer>

Android integration

Optional configuration:

  • Configure maximum number of concurrent tasks: the plugin depends on WorkManager library and WorkManager depends on the number of available processor to configure the maximum number of tasks running at a moment. You can setup a fixed number for this configuration by adding following codes to your AndroidManifest.xml:
 <provider
     android:name="androidx.work.impl.WorkManagerInitializer"
     android:authorities="${applicationId}.workmanager-init"
     android:enabled="false"
     android:exported="false" />

 <provider
     android:name="com.bluechilli.flutteruploader.FlutterUploaderInitializer"
     android:authorities="${applicationId}.flutter-upload-init"
     android:exported="false">
     <!-- changes this number to configure the maximum number of concurrent tasks -->
     <meta-data
         android:name="com.bluechilli.flutterupload.MAX_CONCURRENT_TASKS"
         android:value="3" />

     <!-- changes this number to configure connection timeout for the upload http request -->
     <meta-data android:name="com.bluechilli.flutteruploader.UPLOAD_CONNECTION_TIMEOUT_IN_SECONDS" android:value="3600" />
 </provider>

Usage

Import package:

import 'package:flutter_uploader/flutter_uploader.dart';

Configure a background isolate entry point

First, define a top-level function:

void backgroundHandler() {
  // Needed so that plugin communication works.
  WidgetsFlutterBinding.ensureInitialized();

  // This uploader instance works within the isolate only.
  FlutterUploader uploader = FlutterUploader();

  // You have now access to:
  uploader.progress.listen((progress) {
    // upload progress
  });
  uploader.result.listen((result) {
    // upload results
  });
}

The backgroundHandler function needs to be either a static function or a top level function to be accessible as a Flutter entry point.

Once you have a function defined, configure it in your main FlutterUploader object like so:

FlutterUploader().setBackgroundHandler(backgroundHandler);

To see how it all works, check out the example.

Create new upload task:

multipart/form-data:

final taskId = await FlutterUploader().enqueue(
  MultipartFormDataUpload(
    url: "your upload link", //required: url to upload to
    files: [FileItem(path: '/path/to/file', fieldname:"file")], // required: list of files that you want to upload
    method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
    headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
    data: {"name": "john"}, // any data you want to send in upload request
    tag: 'my tag', // custom tag which is returned in result/progress
  ),
);

binary uploads:

final taskId = await FlutterUploader().enqueue(
  RawUpload(
    url: "your upload link", // required: url to upload to
    path: '/path/to/file', // required: list of files that you want to upload
    method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
    headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
    tag: 'my tag', // custom tag which is returned in result/progress
  ),
);

The plugin will return a taskId which is unique for each upload. Hold onto it if you in order to cancel specific uploads.

listen for upload progress

final subscription = FlutterUploader().progress.listen((progress) {
  //... code to handle progress
});

listen for upload result

final subscription = FlutterUploader().result.listen((result) {
    //... code to handle result
}, onError: (ex, stacktrace) {
    // ... code to handle error
});

when tasks are cancelled, it will send on onError handler as exception with status = cancelled

Upload results are persisted by the plugin and will be submitted on each .listen. It is advised to keep a list of processed uploads in App side and call clearUploads on the FlutterUploader plugin once they can be removed.

Cancel an upload task:

FlutterUploader().cancel(taskId: taskId);

Cancel all upload tasks:

FlutterUploader().cancelAll();

Clear Uploads

FlutterUploader().clearUploads()

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_uploader

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_uploader: ^1.2.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_uploader/flutter_uploader.dart';

example/lib/main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_uploader/flutter_uploader.dart';
import 'package:image_picker/image_picker.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart';

const String title = "FileUpload Sample app";
const String uploadURL =
    "https://us-central1-flutteruploader.cloudfunctions.net/upload";

const String uploadBinaryURL =
    "https://us-central1-flutteruploader.cloudfunctions.net/upload/binary";

void main() => runApp(App());

class App extends StatefulWidget {
  final Widget child;

  App({Key key, this.child}) : super(key: key);

  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: title,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: UploadScreen(),
    );
  }
}

class UploadItem {
  final String id;
  final String tag;
  final MediaType type;
  final int progress;
  final UploadTaskStatus status;

  UploadItem({
    this.id,
    this.tag,
    this.type,
    this.progress = 0,
    this.status = UploadTaskStatus.undefined,
  });

  UploadItem copyWith({UploadTaskStatus status, int progress}) => UploadItem(
      id: this.id,
      tag: this.tag,
      type: this.type,
      status: status ?? this.status,
      progress: progress ?? this.progress);

  bool isCompleted() =>
      this.status == UploadTaskStatus.canceled ||
      this.status == UploadTaskStatus.complete ||
      this.status == UploadTaskStatus.failed;
}

enum MediaType { Image, Video }

class UploadScreen extends StatefulWidget {
  UploadScreen({Key key}) : super(key: key);

  @override
  _UploadScreenState createState() => _UploadScreenState();
}

class _UploadScreenState extends State<UploadScreen> {
  FlutterUploader uploader = FlutterUploader();
  StreamSubscription _progressSubscription;
  StreamSubscription _resultSubscription;
  Map<String, UploadItem> _tasks = {};

  @override
  void initState() {
    super.initState();
    _progressSubscription = uploader.progress.listen((progress) {
      final task = _tasks[progress.tag];
      print("progress: ${progress.progress} , tag: ${progress.tag}");
      if (task == null) return;
      if (task.isCompleted()) return;
      setState(() {
        _tasks[progress.tag] =
            task.copyWith(progress: progress.progress, status: progress.status);
      });
    });
    _resultSubscription = uploader.result.listen((result) {
      print(
          "id: ${result.taskId}, status: ${result.status}, response: ${result.response}, statusCode: ${result.statusCode}, tag: ${result.tag}, headers: ${result.headers}");

      final task = _tasks[result.tag];
      if (task == null) return;

      setState(() {
        _tasks[result.tag] = task.copyWith(status: result.status);
      });
    }, onError: (ex, stacktrace) {
      print("exception: $ex");
      print("stacktrace: $stacktrace" ?? "no stacktrace");
      final exp = ex as UploadException;
      final task = _tasks[exp.tag];
      if (task == null) return;

      setState(() {
        _tasks[exp.tag] = task.copyWith(status: exp.status);
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _progressSubscription?.cancel();
    _resultSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(height: 20.0),
            Text(
              'multipart/form-data uploads',
              style: Theme.of(context).textTheme.subhead,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  onPressed: () => getImage(binary: false),
                  child: Text("upload image"),
                ),
                Container(width: 20.0),
                RaisedButton(
                  onPressed: () => getVideo(binary: false),
                  child: Text("upload video"),
                )
              ],
            ),
            Container(height: 20.0),
            Text(
              'binary uploads',
              style: Theme.of(context).textTheme.subhead,
            ),
            Text('this will upload selected files as binary'),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  onPressed: () => getImage(binary: true),
                  child: Text("upload image"),
                ),
                Container(width: 20.0),
                RaisedButton(
                  onPressed: () => getVideo(binary: true),
                  child: Text("upload video"),
                )
              ],
            ),
            Expanded(
              child: ListView.separated(
                padding: EdgeInsets.all(20.0),
                itemCount: _tasks.length,
                itemBuilder: (context, index) {
                  final item = _tasks.values.elementAt(index);
                  print("${item.tag} - ${item.status}");
                  return UploadItemView(
                    item: item,
                    onCancel: cancelUpload,
                  );
                },
                separatorBuilder: (context, index) {
                  return Divider(
                    color: Colors.black,
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _uploadUrl({bool binary}) {
    if (binary) {
      return uploadBinaryURL;
    } else {
      return uploadURL;
    }
  }

  Future getImage({@required bool binary}) async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      final String filename = basename(image.path);
      final String savedDir = dirname(image.path);
      final tag = "image upload ${_tasks.length + 1}";
      var url = _uploadUrl(binary: binary);
      var fileItem = FileItem(
        filename: filename,
        savedDir: savedDir,
        fieldname: "file",
      );

      var taskId = binary
          ? await uploader.enqueueBinary(
              url: url,
              file: fileItem,
              method: UploadMethod.POST,
              tag: tag,
              showNotification: true,
            )
          : await uploader.enqueue(
              url: url,
              data: {"name": "john"},
              files: [fileItem],
              method: UploadMethod.POST,
              tag: tag,
              showNotification: true,
            );

      setState(() {
        _tasks.putIfAbsent(
            tag,
            () => UploadItem(
                  id: taskId,
                  tag: tag,
                  type: MediaType.Video,
                  status: UploadTaskStatus.enqueued,
                ));
      });
    }
  }

  Future getVideo({@required bool binary}) async {
    var video = await ImagePicker.pickVideo(source: ImageSource.gallery);
    if (video != null) {
      final String savedDir = dirname(video.path);
      final String filename = basename(video.path);
      final tag = "video upload ${_tasks.length + 1}";
      final url = _uploadUrl(binary: binary);

      var fileItem = FileItem(
        filename: filename,
        savedDir: savedDir,
        fieldname: "file",
      );

      var taskId = binary
          ? await uploader.enqueueBinary(
              url: url,
              file: fileItem,
              method: UploadMethod.POST,
              tag: tag,
              showNotification: true,
            )
          : await uploader.enqueue(
              url: url,
              data: {"name": "john"},
              files: [fileItem],
              method: UploadMethod.POST,
              tag: tag,
              showNotification: true,
            );

      setState(() {
        _tasks.putIfAbsent(
            tag,
            () => UploadItem(
                  id: taskId,
                  tag: tag,
                  type: MediaType.Video,
                  status: UploadTaskStatus.enqueued,
                ));
      });
    }
  }

  Future cancelUpload(String id) async {
    await uploader.cancel(taskId: id);
  }
}

typedef CancelUploadCallback = Future<void> Function(String id);

class UploadItemView extends StatelessWidget {
  final UploadItem item;
  final CancelUploadCallback onCancel;

  UploadItemView({
    Key key,
    this.item,
    this.onCancel,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final progress = item.progress.toDouble() / 100;
    final widget = item.status == UploadTaskStatus.running
        ? LinearProgressIndicator(value: progress)
        : Container();
    final buttonWidget = item.status == UploadTaskStatus.running
        ? Container(
            height: 50,
            width: 50,
            child: IconButton(
              icon: Icon(Icons.cancel),
              onPressed: () => onCancel(item.id),
            ),
          )
        : Container();
    return Row(
      children: <Widget>[
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Text(item.tag),
              Container(
                height: 5.0,
              ),
              Text(item.status.description),
              Container(
                height: 5.0,
              ),
              widget
            ],
          ),
        ),
        buttonWidget
      ],
    );
  }
}

Author: fluttercommunity
Source Code: https://github.com/fluttercommunity/flutter_uploader 
License: MIT License

#flutter #dart #background 

Flutter_uploader: Background Upload Plugin for Flutter

ズームの背景を毎日変更するスクリプトを作成する

過去数か月の間に、ハイキング中に撮った写真の新しい用途を見つけました。ズーム仮想背景として使い始めました。

あなたが私のようなもので、たくさんの写真を撮るなら、どれがよく見えるかを決めるのは難しいかもしれません。そして、私はそれらすべてを別の日に使用することにしました。

残念ながら、Zoomには組み込み機能としてこれがありません。そのため、ソフトウェア開発者である私は、ランダムなズーム仮想背景を毎日選択するプロセスを自動化する必要がありました。

スクリプトは何をしますか?

Zoomには、毎日背景を変更するために使用できるAPIがありますが、それはこのタスクには大変な労力のように思えました。ソフトウェア開発者は怠惰に生まれていますよね?:)

代わりに、Zoomアプリケーションが、設定フォルダーで選択された背景のコピーを作成し、それを参照していることがわかりました。スクリプトはランダムなファイルを取り込んで、それをこのバックグラウンドファイルに置き換えます。そして出来上がり!別のズーム仮想背景が表示されます。

次に、これをcronジョブに入れて、毎日(または任意の頻度で)実行して、バックグラウンドを定期的に変更できます。

セットアップする

背景として使用したいすべての画像をユーザーディレクトリのフォルダに入れました。私はにい/zoom/bgpictures/ます、そしてそれは私がスクリプトで使用するものです。しかし、それはあなたが望むものに変更できる変数です。

次に、アプリケーションでズーム仮想背景を設定します。どの背景を選択してもかまいません。必要なのは、Zoomがこの背景に割り当てる一意のIDだけです。

ディレクトリにすでにいくつかのファイルがある可能性がありますが、別のファイルを置き換えないように、アップロードしたばかりの画像に対応するファイルを選択する必要があります。

ディレクトリは次の場所にあります~/Library/Application Support/zoom.us/data/VirtualBkgnd_Custom。ファイル名は次のようになります。9WAE197F-90G2-4EL2-9M1F-AP784B4C2FAD

スクリプトの書き方

使用した画像をbashスクリプトで置き換えます。このスクリプトを、背景画像用に作成したZoomフォルダーに配置します。繰り返しますが、好きな名前を付けることができます–私は私の名前を付けてい~/zoom/zoombg.shます。

スクリプトは次のとおりです。

#!/bin/bash
# The name of file that we copied before and will be replaced with
OG_BG="9WAE197F-90G2-4EL2-9M1F-AP784B4C2FAD";

# Directory where Zoom keeps the backgrounds
ZOOM_DIR="/Users/$USER/Library/Application Support/zoom.us/data/VirtualBkgnd_Custom/";

# Directory of our images
BGPATH="/Users/$USER/zoom/bgpictures/";

# Picking a random file
NEW_BG=$(find "$BGPATH" -type f | sort -R | head -1);

# Replacing the file
cp -R "$NEW_BG" "$ZOOM_DIR/$OG_BG";

ディレクトリに別のパスを選択する場合は、変数でパスを変更してください。次のコマンドを実行して、このスクリプトを実行可能にする必要があります。

chmod 755 ~/zoom/zoombg.sh

ズームの背景をランダムに変更する方法

スクリプトの準備ができました。必要なのは、組み込みの時間ベースのジョブスケジューラであるcronジョブに配置することだけです。ズーム仮想背景を変更する頻度のスケジュールを決定する必要があります。私の会議は午前10時に始まるので、私は毎日午前9時55分に私のことをします。

cronジョブを初めて使用する場合は、ジェネレーターを使用して支援できます。私が使う:

55 9 * * 1-5 /Users/saranshkataria/zoom/zoombg.sh > /dev/null 2>&1

最初の部分(55 9 * * 1–5)は、スケジュールに従ってカスタマイズする必要があるものです。2番目の部分は、その時点で何をすべきかをOSに指示するだけです。bashスクリプトに別の場所を選択した場合は、パスを更新する必要があります。

cronジョブに入れるには、次のように入力します。

crontab -e

そして、viを使用してエディターを開きます。キーボードのIキーを押して挿入モードに入り、行を貼り付け、Escapeキーを押してから「:wq」を押してEnterキーを押して保存して終了します。

これですべてです。これで、毎日ランダムなズーム仮想背景が表示されます(または頻繁に選択します)。

Windowsを使用している場合は、それに応じてスクリプトを変更でき、使用するのはかなり簡単です。

ご不明な点がございましたら、お気軽にお問い合わせください。

出典:https ://www.freecodecamp.org/news/how-to-write-a-script-to-change-zoom-background/

#zoom #background #script 

ズームの背景を毎日変更するスクリプトを作成する