text:
Q: Unity: How to apply rotation on object's velocity? I am making top-down shooter on Unity and I need to implement shotgun, which will release 5 rounds at a time, each next will have rotation 10 degrees less than previous (from 20 to -20 in total). Instantiating the bullet on firepoint, the velocity is applied to it by bullet script, attached to bullet prefab. I apply the rotation in instantiating method too, but the bullet just rotates around itself, not to direction it flying.
Shooting code:
Vector2 mouseScreenPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (mouseScreenPosition - (Vector2) transform.position).normalized;
transform.up = direction;

GameObject newBullet1 = Instantiate(bullet, firePoint.position, Quaternion.Euler(0f, 0f, 20f)) as GameObject;
newBullet1.GetComponent<Bullet>().direction = direction;
GameObject newBullet2 = Instantiate(bullet, firePoint.position, Quaternion.Euler(0f, 0f, 10f)) as GameObject;
newBullet2.GetComponent<Bullet>().direction = direction;

Bullet code:
public Vector3 direction;
public float bulletSpeed;

void Update () {
    GetComponent<Rigidbody2D>().velocity = new Vector3 (direction.x, direction.y, transform.position.z) * bulletSpeed;
}

A: You need to apply the rotation to the direction vector for each bullet. Formula for the rotation of a vector is...
x1 = x0*cos(angle) - y0*sin(angle);
y1 = x0*sin(angle) + y0*cos(angle);
    Vector2 direction10 = new Vector2(direction.x*Mathf.cos(10*Mathf.Deg2Rad) - direction.y*Mathf.sin(10*Mathf.Deg2Rad), direction.x*Mathf.sin(10*Mathf.Deg2Rad) + direction.y*Mathf.cos(10*Mathf.Deg2Rad));
    Vector2 direction20 = new Vector2(direction.x*Mathf.cos(20*Mathf.Deg2Rad) - direction.y*Mathf.sin(20*Mathf.Deg2Rad), direction.x*Mathf.sin(20*Mathf.Deg2Rad) + direction.y*Mathf.cos(20*Mathf.Deg2Rad));

    newBullet2.GetComponent<Bullet>().direction = direction10;
    newBullet3.GetComponent<Bullet>().direction = direction20;
    ... //etc

Can probably do this cleaner with a loop.


text:
Q: Adding Cordova Plugins to Meteor Project with command line arguments In my Meteor project a Cordova Plugin needs to be added. While this is documented in
https://github.com/meteor/meteor/wiki/Meteor-Cordova-Phonegap-integration
the problem here is that the Plugin needs a command line argument, meaning in a common Cordova project it would be added like so:

cordova plugin add pluginName --variable varName="VAR_VALUE"

So how can I add a variable in Meteor?
Just adding the argument gives back: "--variable: unknown option"
Without the argument I get the error "Failed to install Plugin:Error: Variable is missing.."
Another way would be to clone the project, upload it to my Github-account and then put in the variables by hand.

meteor add cordova:pluginName@https://github.com/myName/prjName/tarball/SHA-ID

Here the error is "Must declare exact version of dependency". But how shoud I?

meteor add cordova:pluginName@x.y.z@https://github.com/myName/prjName/tarball/SHA-ID
  doesn't work either?

Or can one add a Plugin to a Meteor project manually, meaning adding the sourcefiles to the .meteor-directory?
Any help would be appreciated.

A: I couldn't make it work the way Slava posted. I don't know why actually.
The way it worked on my system with the plugin was to git clone the Plugin from Github, fill in the KEYS, push it to my Github account and add it with meteor add cordova:plugin@https://github.com/myacc/prj/tarball/sha
Edit:
It does work, but you also have to put the variable in single quotation marks, like so
App.configurePlugin('plugin.google.maps', {
  'API_KEY_FOR_ANDROID': 'YOUR_API_KEY'
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter: MissingPluginException(No implemention found for method currentUser on channel plugins.flutter.io/firebase_auth) for iOS I don't know what it exception, id did't show in the past, but now it's showing!
this code on StartPage, it's checking if user signIn or not by cheking uid if null or not, if he signIn it convert to HomePage else to SignInPage.
I can't solve this problem with my self, I try more than one thing to solve this bug.
My app is broken because of this bug.

  Widget build(BuildContext context) {
    return FutureBuilder<User>(
        future: setUser(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.uid != null) {
              return DefaultTabController(
                length: 2,
                child: Scaffold(
                  appBar: _buildAppBar(),
                  body: _buildTabView(context),
                ),
              );
            }
            return HomePage(
              user: snapshot.data,
            );
          }
          return Scaffold(
            backgroundColor: Colors.white,
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  !snapshot.hasError
                      ? SpinKitCircle(
                          color: Theme.of(context).primaryColor,
                          size: 50,
                        )
                      : Icon(
                          Icons.warning,
                          color: Theme.of(context).primaryColor,
                          size: 50,
                        ),
                  Text(
                    !snapshot.hasError
                        ? "يرجى الانتظار..."
                        : "مشكلة!" + "\n${snapshot.error.toString()}",
                    style: TextStyle(color: Colors.black54),
                    textDirection: TextDirection.rtl,
                    textAlign: TextAlign.center,
                  )
                ],
              ),
            ),
          );
        });
  }

setUser method:

Future<User> getUserData() async {
    User user;
    final FirebaseUser authUser = await FirebaseAuth.instance.currentUser();
    String uid = authUser.uid;
    DocumentSnapshot ds = await Firestore.instance.collection('Users').document('$uid').get();
    user = User(
      name: ds['name'],
      email: ds['email'],
      hospital: ds['hospital'],
      password: ds['password'],
      phoneNumber: ds['phone'],
      rank: ds['rank'],
      uid: uid,
    );
    return user;
  }

A: https://github.com/flutter/flutter/issues/36958

solution: I copied the AppDelegate.m from the firebase app setup page. This works fine if there are no plugins but causes the MissingPluginException as soon as you start adding plugins. Correct code is:

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
@import UIKit;
@import Firebase;

@implementation AppDelegate

(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[FIRApp configure];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application
didFinishLaunchingWithOptions:launchOptions];
//return YES;
}


text:
Q: Urgent help! What statistical test to use (dental thesis) The primary aim of this study is to compare tongue posture and function in children with an unilateral posterior crossbite UPCB who were treated with maxillary expansion in combination with orofacial myofunctional therapy (OMT) versus children who received maxillary expansion only.
Secondly, the effect of maxillary expansion only on tongue posture and function will be evaluated.
All subjects included are evaluated for tongue posture and function. The children with an infantile swallowing pattern are randomly assigned to two groups: The experimental group (EXP + OMT) (receiving orthodontic maxillary expansion and OMT) or the control group (EXP) (receiving orthodontic maxillary expansion only). The children presenting a normal swallowing pattern, are assigned to a third group (CtEXP) (orthodontic maxillary expansion only).
Data registration takes place at different timepoints. The first registration moment is at baseline before any treatment has taken place (pre-treatment, T0). After the active expansion phase and before start of the retention phase, with or without OMT, new data is collected (post-treatment, T1). Once OMT is completed (this takes on average 10-20 weeks) and the patient has been in retention for at least 3 months the post-retention data were collected (T2). The data that are collected at the before mentioned time points, is tongue posture and -function.
To acquire tongue posture, conventional 2DUS imaging can be used. The transducer is placed in the midsagittal plane. The participants are asked to remain still and relaxed while no further instructions are given. Once a stable posture of the tongue is obtained, at least two images are acquired. After image acquisition in the midsagittal plane, the same process is repeated, but with the transducer positioned in the frontal plane.
Tongue function during swallowing can be visualized using two-dimensional B- and M-mode ultrasonography. The transducer is placed in the midsagittal plane and the M-line is positioned through the tongue tip. Patients are asked to remain still. Once the M-line is almost flat and constant, the patients are asked to swallow. This is repeated at least 3 times. If a patient has difficulties with swallowing, they are given a small amount of water to drink. However, only empty swallows are to be evaluated. The range of movement of a certain point on the scanning line will be determined in millimetres. The swallowing pattern can be diagnosed according to the action of the genioglossus muscle, as described by Peng et al. (2003).
The images will be exported to a personal computer for QUALITATIVE analysis of tongue posture and QUANTITATIVE analysis of tongue function.
Would be great to hear your advice, I can't wrap my head around it.
Kind regards


text:
Q: Functional Programming - Does Knowing It Help Job Prospects? The main language that I use at the moment is C# and I am the most comfortable with it. However, I have started dabbling in F# and Haskell and really enjoy those langauges. I would love to improve my skills in either of those languages over time since it truly is fun for me to use them (as opposed to Ruby, which is hyped as "fun", I just don't get where the fun is, but I digress...). My question is directed at those who have hired/interviewed for programming positions (junior/mid-level): if you see a functional programming language on a resume, does it affect your opinion (whether positive or negatively) of that candidate?
My rationale for knowledge of functional programming affecting the view of a candidate is because it can show that the candidate can adapt to different methodologies and take a mulit-dimensional approach to problems rather than the "same old OO approach". (This may be off-base, please let me know if this assumption is as well!)

A: My personal view (no experience in the matter) would be that it would depend on the job you are interviewing for and if it depends on having specific experience in a language paradigm. If you're interviewing for a Java role (or C# in your case), they wouldn't hire you for your functional programming skills and vice versa. However, if you're going for a programming role and you can program multiple languages, that can only be seen as a good sign, i.e. you are a good computer scientist with a broad range of experience.

A: Knowing the functional paradigm makes you a better programmer. Dabbling in languages like Haskell shows that you're interested in having more than one instrument in your mental toolbox.
That should have a concrete boost in your attractiveness as a hire. (If it doesn't, I wouldn't be interested in working for that company.)

A: I was the technical guy helping with interviews for C# / ASP.NET developers recently, and I can tell you that if any of them were dabbling with functional languages - or indeed anything clearly removed from their work experience - that it would have earned them a definite tick from me. I think there's a huge correlation between enjoying learning and dabbling with new things and being one of the upper echelon of naturally talented programmers.
Specifically to functional programming: I think LINQ is one of the most significant additions to the C# language, we use it heavily, and while it doesn't come naturally to everyone, I can't imagine anyone with functional experience finding it difficult to work with.

A: Absolutely. Industry are now crying out for F# programmers and are willing to pay top-dollar. Note that this is no different from other upcoming technologies like LINQ, TPL, Silverlight etc.


text:
Q: subprocess open file and pipe awk command This is my input file format:
@SRR2056440.1 1 length=100
TGTAGGTCTGAGCAGCTTGTCCTGGCTGTGTCCATGTCAGAGCAACGGCCCAAGTCTGGGTCTGGGGGGGAAGGTGTCATGGAGCCCCCTACGATTCCCA
+SRR2056440.1 1 length=100
BCBFFFEFHHHHHJJJJJJIJJJJJJJJIJHHIJJIIJJJJJIJJIJJJJJJJJFHIJJJHHHHHHFDDDBDDD>>ACDEDDDDDDDDDDDDDDDDDEDD
@SRR2056440.2 2 length=100
CTGCCGCCACCGCAGCAGCCACAGGCAGAGGAGGACGAGGACGACTGGGAATCGTAGGGGGCTCCATGACACCTTCCCCCCCAGACCCAGACTTGGGCCA
+SRR2056440.2 2 length=100
CCCFFFFFHHHHHJJJJJJJJJJJIJIJIGJGGIGGJIJJEHFEDDDDDDDDDDABDDDDDDDDDDDDDDADDDDDDDDDDDCDDDDDDBBDDCDDBDD@
@SRR2056440.3 3 length=100
TCTGCCGCCACCGCAGCAGCCACAGGCAGAGGAGGACGAGGACGACTGGGAATCGTAGGGGGCTCCATGACACCTTCCCCCCCAGACCCAGACTTGGGCC
+SRR2056440.3 3 length=100
CCCFFFFFHGHHHJJJJJIJJJJJJIJJIJJJIJJIIIGIJ<CDBCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDCDDDDDDDDDDDDDDDDDDCDCBDD

This is the command I want to execute:
cat input.fq | awk 'NR%4==2{sum+=length($0);nr++;sumsq+=length($0)*length($0)}END{printf"%.1f\t%.1f\n",sum/nr,sqrt(sumsq/nr-(sum/nr)**2)}'

And the output of the command:

100.0 0.0

I want to execute that command inside a python script using subprocess. I have done several attempts but I can't figure out, this is my last try:
awk_comm = r"""'NR%4==2{sum+=length($0);nr++;sumsq+=length($0)*length($0)}END{printf"%.1f\t%.1f\n",sum/nr,sqrt(sumsq/nr-(sum/nr)**2)}'"""
cmd = ['cat', 'input.fq', '|', 'awk', awk_comm]
p2 = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out1, err = p2.communicate()

EDIT:
I can't see any error in the output. It gets stuck, running forever.

A: The following works for me.
>>> awk_comm = r"""cat input.fq | awk 'NR%4==2{sum+=length($0);nr++;sumsq+=length($0)*length($0)}END{printf"%.1f\t%.1f\n",sum/nr,sqrt(sumsq/nr-(sum/nr)**2)}'"""
>>> p2 = subprocess.Popen(awk_comm, stdout=subprocess.PIPE,shell=True)
>>> res = p2.communicate()
>>> res
('100.0\t0.0\n', None)

A: There's no point to shell=True here. Just set up your subprocess.Popen object to do everything you'd otherwise use the shell for:
# the original awk code, with whitespace added for readability
awk_command = r"""
NR%4==2 {
  sum+=length($0);
  nr++;
  sumsq+=length($0)*length($0)
}
END {
  printf "%.1f\t%.1f\n", sum/nr, sqrt(sumsq/nr-(sum/nr)**2)
}
"""

p2 = subprocess.Popen(
  ['awk', awk_command],
  stdin=open('input.fq', 'r'),  # pass a file handle to input.fq directly on awk's stdin
  stdout=subprocess.PIPE,
  stderr=subprocess.PIPE)
out1, err = p2.communicate()

A: By default, Python doesn't use the shell to run commands...but pipes are evaluated by the shell!! You need to pass shell=True:
p2 = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

A: You can use the commands module to achieve this:
import commands
awk_comm = r"""'NR%4==2{sum+=length($0);nr++;sumsq+=length($0)*length($0)}END{printf"%.1f\t%.1f\n",sum/nr,sqrt(sumsq/nr-(sum/nr)**2)}'"""
p1 = commands.getoutput('cat input.fq | awk ' + awk_comm)
print p1

Hope this helps


text:
Q: How does FusedLocationProviderClient.getCurrentLocation work? CancellationToken I'm trying to request the current location, and if the task goes wrong, call if location is on.
private void getCurrentLocation() {
    fusedClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, new CancellationToken() {
        @Override
        public boolean isCancellationRequested() {
            return false;
        }

        @NonNull
        @Override
        public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) {
            Log.d("CurrentLocation", "CancelRequest");
            createLocationSettingRequest();
            return null;
        }
    }).addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null) {
                Log.d("CurrentLocation", location.toString());
                mapFragment.getMapAsync(MapsActivity.this)
            }
        }
    });
}

The problem is code in onCancelationRequested executes twice; I tried with CancellationTokenSource but I had same results.

A: According to docs only the first call to cancel() will have an effect. You can check it by adding addOnCanceledListener() which would be called only once.


text:
Q: Javascript Sleep Function in For, While for(i=0;i<10;i++) {
//codes
sleep(500);
}

This code working finely with php , how to write this code with js ? help me please

A: You'll have to use the setTimeOut() function. Here's how the basic usage goes :
setTimeOut(function(){ /*Your code */},500);

Also note that the time is in milliseconds.
Here are some more examples to help you.


text:
Q: What does z* represent in statistics? Could somebody please give me an explanation as to what Z-star means for statistics, where it's used, and how to calculate it?  My book is very confusing and I don't really know what it means.  Even a link to a website would be helpful.
Main questions I need to answer:
What does $z^{∗}$ represent? What is the value of $z^{∗}$ for a 95% and 90% confidence interval? Include a sketch.
Thank you very much.

A: It means the "critical value of $z$."
This is taken from wikipedia:

In statistics, z* and t* are given critical points for z-distributions
  and t-distributions, respectively.

I appreciate it but that doesn't really help as I have a huge
  background in calculus where a "critical point" probably has a totally
  different meaning. Maybe an example problem and answer?

Certainly. In hypothesis testing, e.g. comparing a mean to a fixed number, we used the data to generate a z-statistics, and then we will see if that z-value is at the extreme tails of a normal distribution that is based on the premise that the null hypothesis is true. If the observed z-value is more extreme than that "critical value," we will reject the null hypothesis.
The critical value depends on your preset type I error rate. Most of the time it's 5% (corresponding to a 95% confidence interval), and we will then make the left and right side 2.5% area under the normal distribution our "rejection zone." The value that defines the starting of that rejection zone is the critical value.
For instance, in a two-tailed test, the critical value for 95% is 1.96 (which means if your observed z-score is bigger than 1.96 or smaller than -1.96 you'll reject the null.) For one-tailed, it'd be 1.64 at the right OR -1.64 at the left.

A: z* means the critical value of z to provide region of rejection
if confidence level is 99%, z* = 2.576
if confidence level is 95%, z* = 1.960
if confidence level is 90%, z* = 1.645


text:
Q: laravel error 500 (browser) after change of php version Yesterday I had to update the version of PHP 7.4 to 8.0.13.
Since then, when I access my site, I get a 500 (browser) error.
The error occurs on the line:
require __DIR __. '/ .. / vendor / autoload.php';
in the public / index.php file.
Does anyone have (any idea please? please
I have already tried all the basic commands:
php artisan config: clear
php artisan cache: clear
compose dump-autoload
...
delete the vendor directory and recreate it
...
check the rights on the directories
UPDATE 10:13
I just saw in /var/logs/apache2/error.log
PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /var/www/welrdv/vendor/composer/autoload_static.php on line 2501
UPDATE 10:18
I didn't have it before but I put memory_limit = -1 in /Etc/php/8.0/apache2/php.ini.
Is this the correct method?

A: memory_limit = -1 is a value PHP understands as unlimited. It can use up most of the RAM and even swap to disk. This could be useful only in dev environments to test purposes.
Just increase this value enough: memory_limit = 128MB


text:
Q: Just in time schema in Cloudkit I want to use private database of cloudkit for my app, so for designing i was looking for something which would easily map my model classes to cloudkit without any extra efforts.
so i came across something interesting in the apple document where it is written,

During development, it's easy to create a schema using CloudKit APIs.
  When you save record objects to a database, the associated record
  types and their fields are automatically created for you. This feature
  is called just-in-time schema and is available only when you use the
  development environment which is not accessible by apps sold on the
  store. For example, during development you can populate a CloudKit
  database with test records stored in a property list.

But i am not able to exactly understand the concept of the same or not able to find any reliable tutorial where this has been achieved.

A: In the development environment, you have two options for defining the DB schema. First, you can use the web portal and manually create new record types (adding field types as you go). Or, you can use the "just in time" route, meaning that you simply create new records in your code, add the desired fields and then save the record. In the development environment, that will automatically add the record type to the schema and save the data you provided in the new record.
That doesn't work in the production environment, though. You can't create new schema in the prod environment. The web portal will not allow you to manually create new record types. If you try to create a new record (or add new fields to an existing record) and save it in the prod environment, you'll get an error.
The only way to add a new record type (or add a new field to an existing record type) in the prod environment is to first create the change you want in the dev environment, then publish the changes from the dev environment to the prod environment.
In short, the dev environment schema is malleable and can be modified simply by creating new records and saving them. The prod environment schema is fixed, and can only be changed by modifying the dev env and then publishing the changes to prod.


text:
Q: Django is taking the templates from virtualenv not from /templates for application I am using Django 3.2.10 and I also use a template for frontend and for admin panel. My problem is that the website is loading the templates from virtualenv and not from the template folders in the applications. My current configuration is:
INSTALLED_APPS = [
'django.contrib.admindocs',
'apps.admin_volt.apps.AdminVoltConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.app',
'apps.crypto',
'apps.taskmgr',
'django_celery_results',
'apps.home',
'apps.authentication',
'debug_toolbar',]

CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates")  # ROOT dir for crypto

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
...

STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles')
STATIC_URL = 'static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(CORE_DIR, 'core/static'),
    os.path.join(CORE_DIR, 'apps/admin_volt/static'),
    os.path.join(CORE_DIR, 'apps/static'),
)

How can I change my configuration to ensure that the templates are taken from app/admin_volt/templates/admin and not from venv\Lib\site-packages\admin_volt\templates\admin
Thank you


text:
Q: How does gedit edit and save a large file before the file is finished loading? I wanted to edit just the first line of a 4 MB file. When I open files this large in gedit, it takes a minute or two to load the file but displays and allows you to edit the part that it has loaded so far. So I opened the file, quickly edited the first line, saved the file, and closed gedit all before it was even close to finishing loading the file.
How was it able to save the file before loading it completely? The only way I know of editing files is to load it into memory, edit the copy in memory, then write the whole thing back to the file.

A: 4MB is not terribly large. It really shouldn't take a minute or two just to load that. It's possible that it loads it all into memory, but then takes a while to get round to displaying it all - the UI widgets may take a while to populate. (Not a minute for a 4MB file, I'd hope, but...)
Maybe that's how it's letting you edit the start and save it quickly - it's finished loading the file, but not finished displaying it.


text:
Q: Resizable img within a p tag, that has a larger width than container I am using Ghost Blogging Platform, and when I insert a image it automatically wraps a image in a p tag. I have a max-width setup for the container wrapping the p tag and the img. I want the img to be larger than the container. I can set a width for the img which is larger with width: 62rem; However it no longer is responsive vs width: 100%;
I want the img to resize as I resize the browser, I was hoping to do it without media queries but if necessary I will do so.
I am already changing the size of all the p tags so that my blockquote is the size of the container section, and I want my image to do the same, but it is just the size of the p tag. My main concern is making the img responsive and larger, I can already make it larger on its own with a specified width, but it no longer stays responsive.
Thanks in advance.
CODE
HTML

Design and Development Process for a technolgy service and repair company.

Sketching is the first part of my process, sometimes I just play around in code, there is no exact process that I   follow, often my creative mood will push me in different directions.

For Tech Basics I started playing in the browser, below is the evolution of the design.

Always I will setup my site under a github repository, so I can see my changes as I go and have a good backup of my code.

After debating for a while of whether to use a Zurbs Foundation, I have decided to go with html5 boiler plate custom, I want the site to be as minimal as possible and it is simple enough I dont need a massive template to still to rapid development, however it is nice to have the goodies bundled with html5 boiler plate have the option to remove the stuff that I dont need. Below is a list of what I used and why.

I am using docpad for this project, docpad is like static pages on steroids. So far I am loving it for fast development. I am using the no template and building from scratch, plopping in my custom html5 boiler plater contents.

I read this article http://alistapart.com/article/the-infinite-grid and it is a great starting point for creating a responive site. It really hits home the theory, and not so much specifics about a one fit solution for a website.

CSS
/* line 1, ../scss/screen.scss */
body {
  font-size: 16px;
  font-family: 'Cabin', sans-serif;
}

/* line 6, ../scss/screen.scss */
a {
  color: #FA7FB5;
  text-decoration: none;
}

/* line 16, ../scss/screen.scss */
#postSelect {
  max-width: 82rem;
  margin: auto;
}
/* line 20, ../scss/screen.scss */
#postSelect .tag-case-study {
  max-width: 62rem;
  margin: auto;
}
/* line 26, ../scss/screen.scss */
#postSelect .post-header {
  position: fixed;
  left: 1rem;
  top: 1rem;
}

/* line 41, ../scss/screen.scss */
#postSelect .share {
  text-align: center;
}
/* line 43, ../scss/screen.scss */
#postSelect .share a {
  padding: 1rem;
}
/* line 48, ../scss/screen.scss */
#postSelect .author {
  text-align: center;
  font-variant: small-caps;
  letter-spacing: 0.2rem;
  font-size: 3rem;
}
/* line 55, ../scss/screen.scss */
#postSelect .post-title {
  font-size: 1rem;
  font-weight: 900;
  font-style: italic;
  text-align: center;
}
/* line 62, ../scss/screen.scss */
#postSelect .post-meta {
  font-size: 1rem;
  font-weight: 900;
  font-style: italic;
  text-align: center;
  display: block;
}
/* line 70, ../scss/screen.scss */
#postSelect p {
  max-width: 42rem;
  margin: auto;
  font-size: 1.5rem;
  font-weight: 300;
  line-height: 3rem;
  padding: 2rem 0 2rem 0;
}
/* line 78, ../scss/screen.scss */
#postSelect p img {
  width: 100%;
  border: 1rem solid #fff;
}
/* line 84, ../scss/screen.scss */
#postSelect blockquote {
  margin: 0;
  padding: 2rem;
}
/* line 88, ../scss/screen.scss */
#postSelect blockquote p {
  max-width: 60rem;
  margin: 0;
  text-align: center;
}
/* line 94, ../scss/screen.scss */
#postSelect blockquote:before {
  content: url("../img/quote.png");
}
/* line 98, ../scss/screen.scss */
#postSelect blockquote:after {
  content: url("../img/quoteB.png");
  margin-left: 97.4%;
}
/* line 102, ../scss/screen.scss */
#postSelect ul {
  max-width: 42rem;
  margin: auto;
  line-height: 3rem;
  padding: 0;
}
/* line 107, ../scss/screen.scss */
#postSelect ul li {
  list-style-type: square;
  font-size: 1.5rem;
  margin: 0;
}
/* line 114, ../scss/screen.scss */
#postSelect .post-content h1 {
  font-size: 2.5rem;
  letter-spacing: 0.1rem;
  text-align: center;
  color: #69BDFF;
}

A: You are setting 100% width too image, but also giving it borders. This causes problem.
You need to subtract amount of border from image.
Try:
#postSelect p img {
    width: calc(100% - 2rem);
    border: 1rem solid #fff;
}

Fiddle here.

A: I don't think you should have a div of a certain size and and then an element within that which then breaks out of the div because you've set it to be larger then the .container
First thing I would do is reorganize the way that container works. Here is a FIDDLE of some basic html to reference.
The second thing I would do - is ask a more targeted question about removing the automatic p tag from the image in a ghost forum (assuming they exist by now).
In WordPress this happens by default as well. It looks something like this with a function running a regular expression search and replace. I bet there is something like this for ghost, or there will be really really soon - because it's a huge pain - and almost no one actually puts images inline anymore. And if they did, they would want to control when this happens.
function filter_ptags_on_images($content) {
  // do a regular expression replace...
  // find all p tags that have just
  //
maybe some white space then maybe whitespace

  // replace it with just the image tag...
  return preg_replace('/
(\s*)()(\s*)<\/p>/iU', '\2', $content);
}

// we want it to be run after the autop stuff... 10 is default. ? ? ?
add_filter('the_content', 'filter_ptags_on_images');

Good luck! I hope to play with Ghost soon and I bet this will be the first problem I run into as well.


text:
Q: Converting GeoTIFF file into NetCDF file in Python and file is empty I am trying to convert a GeoTIFF file into NetCDF file (still remains all the information) using either rioxarray or xarray in python. The file is just empty. But when I checked the GeoTIFF file it looks fine to me. I now have no idea why it is not successfully converted and cannot find the solutions. Below are the ones that I have tried:
With rioxarray.open_rasterio() and to_netcdf()
raster = rioxarray.open_rasterio("example_raster.tiff")
raster.to_netcdf("example_raster.nc")

With rioxarray.open_rasterio() and rio.to_raster()
raster = rioxarray.open_rasterio("example_raster.tiff")
raster.rio.to_raster("example_raster.nc")

With xarray.open_rasterio() and rio.to_raster()
raster = xarray.open_rasterio("example_raster.tiff")
raster.rio.to_raster("example_raster.nc")

With xarray.open_dataset() and to_netcdf()
raster = xarray.open_dataset("example_raster.tiff")
raster.to_netcdf("example_raster.nc")

They all give the empty outputs (when I put them into QGIS to see).
Do you know how to solve this problem?
Here is the file https://ufile.io/ztjbk8pt (choose Free Download --> Slow Speed).

A: I looked at this and it appears there is a bug in how the x/y coordinates are generated internally in xarray/rioxarray.
Fix oncoming: https://github.com/corteva/rioxarray/pull/401


text:
Q: Cocoa Scripting: "whose clause" cannot access certain properties I am working on making my application scriptable. I struggle with the "whose" filter clause.
I want to make this work, but while name can be used, country can not:
tell application "myapp"
    get every city whose name is "Berlin" -- works
    get every city whose country is "Germany" -- error -1700 (Can't make country into type specifier)
end tell

The relevant parts of the sdef look like this:
<class name="application" code="capp">
    <cocoa class="NSApplication"/>
    <element type="city">
        <cocoa key="allCities"/>
        <accessor style="index"/>
    </element>
    <class name="city" code="Citi" plural="cities">
        <cocoa class="ScriptableCity"/>
        <property name="name" code="pnam" type="text" access="r">
            <cocoa key="name"/>
        </property>
        <property name="country" code="Ctry" type="text" access="r">
            <cocoa key="country"/>
        </property>
    </class>

What must I do to make country work with "whose" as well? Apparently, the "whose" clause wants a type specifier, not a property name, but I can't make sense of this.
I have implemented indicesOfObjectsByEvaluatingObjectSpecifier:, but that only gets called for name, not for country.

A: Oh, I had it all wrong. My program code is fine. The issue is caused by the fact that I also have a class named country. So AppleScript, looking at the outmost scope for the identifier first, finds the class country and tries to use that for the comparison. Had the error message included the word "class", this would have been easier to detect, probably.
There are now two solutions:

*

*Rename the property in the Sdef so that it does not clash with the class name any more, e.g. to country name.

*Use of it in order to change the scope for the lookup of the identifier, like this:
get every city whose country of it is "Germany"

It is also important to make sure that if the same property name is used in several classes, they all use the same 4-char type code. Otherwise this problem can surface as well.


text:
Q: Shortest Path With Limitations on Node Visitation I have a variant on the classic 'shortest path' problem and I don't know how to approach it. My graph topology is as such:
There is one source and one sink.
Other nodes are designated by a letter and subscript integer (e.g., A1,B1,C1,A2,B2,C2,....A30,B30,C30). There is one node per possible letter/integer combination.
There is one zero-cost directed edge from the source to each of A1, B1, C1. There is one zero-cost directed edge from each of the nodes with the largest integer to the sink (e.g., when the integers go up to 30, there is one zero-cost directed edge from A30 to the 'Final Destination Node', and an identical edge from B30 and from C30).
From each node there is a directed, weighted edge to one other node of each of the other letters with a larger integer.
For example, there may be a directed weighted edge from A1 to B3 and from A1 to C10; however you won't see edges from A1 to both B3 and B5 because the destinations are both 'B' edges.
There are no edges that move from one node with a letter, to another node with a letter (e.g., no B3 to B10) and no edges that move from a node with a higher integer to one with a lower integer (e.g., no B30 to C10).
I know that I can use Djikstra's algorithm to find a singular shortest path from origin to destination, but my goal is somewhat different. I want to:
1) Find a single shortest path from source to sink that visits each of the 'letters' once and only once. Any group of integers will work as long as I visit all the letters. Eg. visiting the node set A1, B22, and C27 between the source and sink is acceptable; visiting A10, A15, B22 is not. 2) Find two paths that, combined, visit each of the letters once and only once. If the 'letter set' was ABCDEF, one route could visit ABD and the other CEF; but we couldn't have one route visit ABCD and the other visit DEF, because D would overlap. The goal is to identify two paths that find the minimal longer route - I don't care about the total time as much as about this minimax. 3) Same question as #2 but with 3 paths, 4 paths, etc.
I assume I could make a very complicated integer program but didn't know if there were shortest-path algorithms already available to solve this. Bonus points if it's ready-made in an R package.
Ralph


text:
Q: How do I remove the title bar of my app? I want to remove the title bar of the application, that is run out of that bar black with the name of the App.
Have followed the examples but always gives error initializing:
Example 1
 <application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

Example 2
android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen"

My XML
  <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

A: this works for me:
in style.xml:
<style name="AppTheme" parent="android:Theme.NoTitleBar">
</style>

in AndroidManifest.xml
<application
    android:theme="@style/AppTheme"
    ...>


text:
Q: How to Integrate fingerprint scanner in Java web application I am fresher and I want to use fingerprint facility in my web application. I tried neurotechnology API but that API give me an error that no scanner found. Demo application which is given by device manufacturer is working successfully but not my application.
So please suggest me which API is useful and easy API to integrate fingerprint scanner in my application.

A: I have not worked on it but by doing google and access some other resources i have found one source which will provide you fingerprint scanner api, please try it and also let me know if it is working fine.
Here is the link:- griaulebiometrics


text:
Q: Recive Value from RecyclerViewAdapter Class I got an RecyclerView in my Main Activity, where the Items got a Like Button. In my RecyclerViewAdapter Class I got the OnClickListener which receives the ID of the Item.
What I want to do is:
Pass the ID of the Item to the MainActivity. I tried it with Intents in the OnClickMethod of the RecycerViewAdapter Class, but if I would use it like this I would need something like a Listener for the Intent in the MainActivity. The other Idea was to set an OnClickListener for the Button in the MainActivity. But I cant set an OnClickListener for an Item of the RecyclerView in the Main Acitivity.
Does someone know how I can solve my Problem?

A: There are two straightforward ways I can think of:

*

*Use a Handler

*Define an interface and pass the instance to the Adapter. Then call the appropriate method when the click is performed.
BTW, why do you want to pass the value back to the Activity? Can't you perform the work withing the adapter?


text:
Q: Datatables Simple Join Query I am putting together a simple join query using Datatables Editor however am getting errors which I don't understand. My code is below:
HTML

                    <legend id="lgdActions">Actions</legend>

Javascript
             Actions Datagrid
            $('#tblActions').DataTable({
                dom: "Tfrtip",
                lengthChange: false,
                bAutoWidth: false,
                jQueryUI: true,
                bProcessing: true,
                bServerSide: true,
                ajax: {
                    url: "dataGridQuery.php",
                    data: { "gridNumber": 2 },
                    type: 'POST'
                },
                columns: [
                    { title: "Action ID", data: "tblActions.actionID", width: "10%" },
                    { title: "Time", data: "tblActions.actionTime" },
                    { title: "Action Taken", data: "tblActions.actionTaken" },
                    { title: "User", data: "tblUsers.userID" }
                ]
                tableTools: {
                    sRowSelect: "os",
                    aButtons: [
                        { sExtends: "editor_create", editor: editor1 },
                        { sExtends: "editor_edit",   editor: editor1 },
                        { sExtends: "editor_remove", editor: editor1 }
                    ]
                }
            });

PHP
            // Obtain Action Grid
            if(isset($_GET['gridNumber']) && $_GET['gridNumber']==2){
            //
            $data = Editor::inst( $db, 'tblActions' )
                ->field(
                    Field::inst( 'tblActions.actionID' ),
                    Field::inst( 'tblActions.actionTime' ),
                    Field::inst( 'tblActions.actionTaken' ),
                    Field::inst( 'tblActions.actionUserID' ),
                    Field::inst( 'tblUsers.userID' )
                )
                ->leftJoin( 'tblUsers', 'tblUsers.userID', '=', 'tblActions.actionUserID' )
                ->process($_POST)
                ->data();
            //
            if ( ! isset($_POST['action']) ) {
                // Get a list of sites for the `select` list
                $data['tblUsers'] = $db
                    ->selectDistinct( 'tblUsers', 'userID as value, userID as label' )
                    ->fetchAll();
            }
            // Echo
            echo json_encode( $data );
            }

The errors I receive when running this code are:

*

*Errors {"error":"SQLSTATE[42S22]: Column not found: 1054 Unknown
column 'tblActions.id' in 'field
list'","data":[],"tblUsers":[{"value":"1","label":"1"},{"value":"2","label":"2"}]}

*DataTables warning: table id=tblActions - Invalid JSON response. For
more information about this error, please see
http://datatables.net/tn/1.

This code was from a sample provide when downloading the Editor v1.3.1.  I am somewhat familiar with the plug-in however find it perplexing when such an error occurs.  Any help would be much appreciated.
Thanks :)

A: You have to change the name of the primary key.
I think if you add the following somewhere.
 "idSrc": "actionID",

http://datatables.net/forums/discussion/19199/custom-primary-key
This also may work
        $data = Editor::inst( $db, 'tblActions' )
            ->pkey( 'actionID' )


text:
Q: How to change IP address using perl (something like ipconfig release/renew) I am beginner to Perl and I have to write a script which could change the IP address after every 1 hour.
I want to change it because I receive some data from a dongle from a website and that website has some time limit to receive that data, so currently we need to unplug the connecting device and use another to
change IP address. (I mean I have to request DHCP for another IP.)
But currently I am asked to write a script using Perl. Could someone please help me how to do that?
My try to do it is :
#!/usr/bin/perl
# Simple DHCP client - sending a broadcasted DHCP Discover request

use IO::Socket::INET;
use Net::DHCP::Packet;
use Net::DHCP::Constants;

use POSIX qw(setsid strftime);

# sample logger
sub logger{
    my $str = shift;
    print STDOUT strftime "[%d/%b/%Y:%H:%M:%S] ", localtime;
    print STDOUT "$str\n";
}

logger("DHCPd tester - dummy client");

logger("Opening socket");
$handle = IO::Socket::INET->new(Proto => 'udp',
                                Broadcast => 1,
                                PeerPort => '67',
                                LocalPort => '68',
                                PeerAddr => '255.255.255.255',
                )
      || die "Socket creation error: $@\n";     # yes, it uses $@ here

# create DHCP Packet DISCOVER
$discover = Net::DHCP::Packet->new(
                      Xid => 0x12345678,
                      DHO_DHCP_MESSAGE_TYPE() => DHCPDISCOVER(),
                      DHO_VENDOR_CLASS_IDENTIFIER() => 'foo',
                      );
logger("Sending DISCOVER to 127.0.0.1:67");
logger($discover->toString());
$handle->send($discover->serialize())
              or die "Error sending:$!\n";

logger("Waiting for response from server");
$handle->recv($buf, 4096) || die("recv:$!");
logger("Got response");
$response = new Net::DHCP::Packet($buf);
logger($response->toString());

# create DHCP Packet REQUEST
$request = Net::DHCP::Packet->new(
                      Xid => 0x12345678,
                      Ciaddr => $response->yiaddr(),
                      DHO_DHCP_MESSAGE_TYPE() => DHCPREQUEST(),
                      DHO_VENDOR_CLASS_IDENTIFIER() => 'foo',
                      DHO_DHCP_REQUESTED_ADDRESS() => $response->yiaddr(),
                      );

logger("Sending REQUEST to 127.0.0.1:67");
logger($request->toString());

$handle->send($request->serialize())
              or die "Error sending:$!\n";
logger("Waiting for response from server");
$handle->recv($buf, 4096) || die("recv:$!");
logger("Got response");
$response = new Net::DHCP::Packet($buf);
logger($response->toString());

It's output on terminal is :
C:\shekhar_Axestrack_Intern\IpAddressChangeScripts>test6.pl
[08/Jan/2015:18:01:01] DHCPd tester - dummy client
[08/Jan/2015:18:01:01] Opening socket
[08/Jan/2015:18:01:01] Sending DISCOVER to 127.0.0.1:67
[08/Jan/2015:18:01:01] op = BOOTREQUEST
htype = HTYPE_ETHER
hlen = 6
hops = 0
xid = 12345678
secs = 0
flags = 0
ciaddr = 0.0.0.0
yiaddr = 0.0.0.0
siaddr = 0.0.0.0
giaddr = 0.0.0.0
chaddr =
sname =
file =
Options :
 DHO_DHCP_MESSAGE_TYPE(53) = DHCPDISCOVER
 DHO_VENDOR_CLASS_IDENTIFIER(60) = foo
padding [0] =

[08/Jan/2015:18:01:01] Waiting for response from server
//And it is stuck here since last 45 minutes....

My idea to do it is:
I will send a request to server (DHCP) (I think DHCPREQUEST() do that)that please provide me new IP  adress.
Could some one please let me know if my last line will print ID adress or not ? I mean :
$response = new Net::DHCP::Packet($buf);
logger($response->toString());

EDIT:
I also tried this on suggestion by the experienced guys below but it still do not change IP adress (even i tried to run this perl code 4 times without success in IP change-Even i tried to run manually ipconfig /renew but still the IP is same all the time).
my $ipconfig = `ipconfig /renew`;
my $ipcfg_success = $?;
print $ipconfig;
if ($ipcfg_success == 0) {
    do print "n succesfully runned \n";
} else {
    do "\n succesfully NOT sunned \n";
}

A: This more of a comment but it grew too long.
Just have your script call ipconfig /release and ipconfig /renew with a few seconds in between. That will request a new IP from the DHCP server, just as your script apparently tries to do.
Of course you are not exactly guaranteed a new IP that way, that depends on the configuration of the DHCP server but you are dependent on that either way. If the possible range of addresses is very small and you are afraid you might get the old IP by bad luck, check and renew again if it happened. If you get the same IP every time, it most likely means that the server recognizes you (by MAC or hostname) and assigns your static IP to you. In that case all you can do is talk to your network adminstrator (a course of action i would suggest anyways).
If you really need a guarantee, then you have to ditch DHCP and set your own IP. That however requires that you have some range of IPs reserved just for you. Otherwise your network administrator might hunt you down with their crossbow.
Be aware that depending on what that dongle is for and who set up that time limit, they may do anyways.

A: Writing a DHCP client isn't going to change your system's IP address. You need to use the system's client.
system('ipconfig /release & ipconfig /renew');

You're not guaranteed to get a new address, though. It causes less headaches if machines always have the same IP address, so DHCP servers tend to always give the same address to a machine.


text:
Q: GPU-based Laplacian Pyramid I have implemented an image blending method for seamless blending using plain C++. Now I want to convert this code for GPU (using OpenGL ES 2 Shaders for mobile devices). Basically the method creates Gaussian and Laplacian Pyramides for each image which are then combined from low-resolution to top (see also the paper "The Laplacian Pyramid as a Compact Image Code" from Burt et.al. 1983).
My problem is that the Laplacian pyramid levels can have negative values but my devices do not support float or integer type textures (using the ORB_texture_float extension e.g.).
I already looked for papers dealing with GPU-based pyramids but without finding something really useful.

*

*How can I implement such a pyramid efficiently for a GPU?

*Is it possible to calculate a Gaussian/Laplacian pyramid level without iterating through the preceding levels?

Regards,
EDIT
It seems as if there is no "good" way to calculate Laplacian Pyramids completely on GPU except using two passes (one for signs, one for values) which do not have support for either signed types (for instance ARB_texture_float) or types larger than byte when the the image's data range is between [0..255]. My Laplacian Pyramid runs perfectly on GPUs with ARB_texture_float extension but without the extension (and some adjustments to compress the range) the pyramid gets "wrong" due to range compression.

A: *

*The safest way for you to implement a Laplacian pyramid if your textures are unsigned integers is to store two pyramids - one pyramid that contains the gradient magnitude of the Laplacian and another pyramid that stores the sign of the pixel at that location.

*Yes.  Any level in a Gaussian or Laplacian pyramid has a closed form solution based on the sigma value that you want to compute.  Consider the base case of a LoG pyramid computed at intervals of sigma = (2/3).  The first level of the pyramid has sigma 2/3 and is produced simply by convolving with a 5x5 LoG filter with sigma 2/3.  The second convolution with the same filter produces an LoG image with sigma 4/3, and finally the third has sigma 6/3, or 2, so we subsample the image to produce the next integer level of the pyramid.  If you want to compute the LoG of an image at sigma 2, the levels at sigma 2/3 and 4/3 are not necessary - simply subsample the image one time and convolve with an LoG filter with sigma 1.
If you want to compute the LoG at sigma = 20, quad-subsample the image (16 pixel blocks become 1 pixel) to give you a sigma 16 image, then convolve once with a sigma 4/3 LoG filter.


text:
Q: Mysql table format lost when passed into a pipe [root@tokyo-b ~]# mysql -e 'select NOW();'
+---------------------+
| NOW()               |
+---------------------+
| 2019-09-05 21:35:49 |
+---------------------+

VS
[root@tokyo-b ~]# mysql -e 'select NOW();' | cat
NOW()
2019-09-05 21:34:51

Table format lost.. anyone can explain this?

A: The mysql command probably detects it being run as part of a pipe and it removes the formatting on purpose.
Many Unix/Linux command line utilities do this to make it easier for a subsequent commands in the pipe to extract the data without having to worry about the additional formatting characters.


text:
Q: Golang end function after any go routine finishes I have a main function that looks like so:
func main() {
    go SyncRealTime()
    go SyncStale()
}

Both of these functions are supposed to continue indefinitely. I'd like for main to:

*

*Not terminate as long as both Goroutines are running.

*Terminate if either one of the Goroutines terminates (i.e. errors)

What is the idiomatic way of doing that in Go?

A: This is a way of doing it:
func main() {
    c := make(chan string)
    go func() {
        SyncRealTime()
        c <- "SyncRealTime"
    }()

    go func() {
        SyncStale()
        c <- "SyncStale"
    }()

    firstDone := <-c
    fmt.Println(firstDone + " exited")
    // done
}


text:
Q: How to set the cursor in text box on page init I am doing a mobile application in jquery mobile. When the first page is loading it have an init function. My requirement is that when the first page is loaded the cursor should point to the text box. I tried:
  $('#txtdemo').focus();

and
   var txtBox=document.getElementById("txtdemo");
   txtBox.focus();

but both are not working. Please let me know a good approach to do this.

A: In mobile site, it is impossible to focus in textbox and open keyboard using programming. it is one type of usability issue. In desktop site you can do this with
$('#txtdemo').focus();

$('#txtdemo').select();

$('#txtdemo').trigger('focus');

$('#txtdemo').trigger('click');

A: It can be done only during the pageshow event. It must be pageshow because page is fully formed only at that point. If you dont know what pageshow is take a look at my ARTICLE regarding jQuery Mobile page events. Also this will only work on a desktop browsers, it will not work on mobile browsers. In a case of mobile browsers input field will be under focus but this will not trigger keyboard to show.
$(document).on('pageshow', '#index', function(){
    $('#some-input').focus();
});

Working example:
<!DOCTYPE html>
http://jsfiddle.net/Gajotres/PMrDn/#update

        <title>jQM Complex Demo</title>
        <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />

Index page

                <input type="text" value="" id="some-input"/>


text:
Q: performance stringbuf vs string When we have to work with string manipulation, is there any significants performance difference between std::string and std::stringbuf, and if yes why.
More generally when it is good to use std::stringbuf over std::string ?

A: A std::stringbuf uses a string internally to buffer data, so it is probably a bit slower. I don't think the difference would be significant though, because it basically just delegation. To be sure you'd have to run some performance-tests though.
std::stringbuf is useful when you want an IO-stream to use a string as buffer (like std::stringstream, which uses a std::stringbuf by default).

A: First of all, a std::stringbuf does not necessarily (or even ordinarily) use an std::string for its internal storage. For example, the standard describes initialization from an std::string as follows:

Constructs an object of class basic_stringbuf ... Then copies the content of
  str into the basic_stringbuf underlying character sequence [...]

Note the wording: "character sequence" -- at least to me, this seems to be quite careful to avoid saying (or even implying) that the content should be stored in an actual string.
Past that, I think efficiency is probably a red herring. Both of them are fairly thin wrappers for managing dynamically allocated buffers of some sort of character-like sequence. There's a big difference in capabilities (e.g., string has lots of searching and insertion/deletion in the middle of a string that are entirely absent from stringbuf). Given its purpose, it might make sense to implement stringbuf on top of something like a std::deque, to optimize the (usual) path of insertion/deletion at the ends, but this is likely to be insubstantial for most uses.
If I were doing it, I'd probably be most worried by the fact that stringbuf is probably only tested along with stringstream, so if I used it differently than stringstream did, I might encounter problems, even if I'm following what the standard says it should support.

A: std::stringbuf extends std::string container, for reading and writing to std::string.
Generally, there is no significant performance difference between std::string and std::stringbuf.
Because std::streambuf <- std::stringbuf, both because:
typedef basic_stringbuf<char> stringbuf;
typedef basic_string<char> string;

Read this for more details.


text:
Q: On transitive actions on the sphere A theorem of Borel asserts that $\mathbf{Sp}(n)\mathbf{Sp}(1)$ and $\mathbf{Sp}(n)\mathbf{U}(1)$ act  transitively in the sphere $\mathbb{S}^{4n-1}$. How can we describe these actions? Is there some resource where I can learn more about these groups and their actions in $\mathbb{S}^{4n-1}\subset \mathbb{H}^n$?

A: The definitions are in Morton Curtis, Matrix Groups, p. 27. The group $Sp(n)$ is the group of quaternionic linear transformations of a quaternionic vector space, which preserve a quaternionic bilinear positive definite form (all made precise by Curtis). The group $Sp(n)Sp(1)$ is the group of real linear transformations of a quaternionic vector space induced by those of $Sp(n)$ and by the group $Sp(1)$ of unit quaternion scalars. The subgroup $Sp(n)U(1)$ uses only the unit complex scalars. These all act by linear transformations, by definition, and preserve the real part of the quaternionic bilinear form, i.e. the real inner product. (Again, Curtis has all of the details.) Therefore they preserve the unit sphere in the quaternionic vector space. Moreover, already $Sp(n)$ acts transitively, which is easy to see by looking at the subgroup stabilizing a particular vector $e_1$, and then induction.


text:
Q: Bootstrap collapse panel in reactjs render method I want to collapse few columns in the ReactJS table row. Please find the code that am trying.
render() {
    return (

            <button className="btn btn-primary" type="button"
            data-toggle="collapse"
            data-target="#collapseExample"
            aria-expanded="false"
            aria-controls="collapseExample">
            +
            </button>
            { this.state.item.line_number }
            { this.state.item.product_code }

            { this.state.item.net_price }
            { this.state.item.discount }

          )
        }

I want to open the panel (collapse panel) once i clicked on the "+" button. But am getting error on the 2nd  tag. Am not able to render two  tag in render() method.
How i can achieve this solution.?

A: Am using ReactJS 15.6.1 version and in this version return() method wont support multiple
 tags to render. From ReactJS 16+ version we can able to return() array of components. So, its possible with ReactJS 16+ version.


text:
Q: Datadog: how to get redis cpu usage metrics? Taking a look at Redis metrics for Datadog , we can see that redis.cpu.sys refers to System CPU consumed by the Redis server. But this is metric for CPU usage time, not CPU usage.
How do we do if we want to create alerts based on the actual CPU usage?


text:
Q: Salesforce CRM and Marketing Cloud - Data Extensions I have a client who has a bunch of data in their Salesforce CRM.
We (my company) are passing data specifically to their Marketing cloud data extension, and NOT to their crm.
I have reason to believe that these leads are coming from the extension table because many of the leads contain fields that we are passing to Marketing cloud.  The client is saying that it is not case.  I don't believe him.
The question is: For customer data passed into their Marketing cloud data extension, is an entry automatically created for the customer in the CRM?  Is there some type of setting that is in control of this? In what way would that data be getting in there?

A: If you are using Marketing Cloud Connect data that you are seeing in you Marketing Cloud instance are in read-only mode, as synchronisation is not working in both directions in the same way.
You can easily bring all Salesforce objects into Marketing Cloud as Synchronised Data Extensions, but they are in read-only mode. You can't modify them from Marketing Cloud level. As we can read in Marketing Cloud documentation:

Synchronized Data Sources allows you to access data from the Sales and Service Clouds within the Marketing Cloud for use in your marketing activities. As changes occur in the Sales or Service Clouds, the Marketing Cloud receives those updates.

Back to the SalesForce you can push tracking and analytics, both as individual stats as well as aggregated reports.


text:
Q: jQuery keyboard arrow navigation not working on autocomplete dropdown list I have an autocomplete list populated via an ajax call, which makes a call to the API each time a key is pressed in the textbox.
This works fine, and the list is displayed with the desired results. The problem is, I want to add keyboard navigation with the up/down arrow keys and scroll through the list items, changing the class to "selected" for the current item.
The code to scroll through the list works on its own, but stops working in conjunction with the ajax call. I'm assuming there must be some kind of conflict going on which resets something each time the ajax call is made, stopping the index values of the list items from being properly recognised? is this code correct?
THE HTML:
<form method="post" action="" autocomplete="off">
    <input type="text" id="textBox" autocomplete="off" />

test

test2

test3

 </form>

THE JQUERY
var $listItems = $('#predictiveList li');

$('#textBox').live('keyup', function(e)
{
    var key = e.keyCode,
    $selected = $listItems.filter('.selected'),
    $current;

    $listItems.removeClass('selected');

    if ( key == 40 ) // Down key
    {
        if ( ! $selected.length || $selected.is(':last-child') ) {
            $current = $listItems.eq(0);
        }
        else {
            $current = $selected.next();
        }
    }
    else if ( key == 38 ) // Up key
    {
        if ( ! $selected.length || $selected.is(':first-child') ) {
            $current = $listItems.last();
        }
        else {
            $current = $selected.prev();
        }
    }

     $current.addClass('selected') ;
});

$('#textBox').live('keyup', function(e) {
    $.ajax({
        type: 'GET',
        dataType:'jsonp',
        url: 'http://www.apiCallurlhere.js?callback=displayOptions'
    });
});

/******** Generates dropdown from results of AJAX call ***********/

function displayOptions(data){

    $('#predictiveList').show();
    var obj = data.results;
    var dropdownOptions = '';

    //generate list of options for dropdown menu
    $.each( obj, function( i, v ) {
        dropdownOptions += '
' + v.place + '
';

    });
    $('#predictiveList').html(dropdownOptions);

}

as I said, both work fine independently, but when the AJAX call is included in the page at the same time as the keyboard nav, the arrow navigation stops working (though the list still shows up and populates as expected)
Any tips appreciated!

A: Ah, do not use keyup event to fetch the autocomplete list.
When you press up or down arrows, it calls the ajax to refresh the list, and probably ".selected" class is getting removed.
So instead, use change event:
$('#textBox').live('change', function(e) {
    $.ajax({
        type: 'GET',
        dataType:'jsonp',
        url: 'http://www.apiCallurlhere.js?callback=displayOptions'
    });
});

However, .live() method is deprecated in 1.7 and REMOVED in 1.9. So you really should use .on() method instead:
$(document).on('change', '#textBox', function(e) {
    $.ajax({
        type: 'GET',
        dataType:'jsonp',
        url: 'http://www.apiCallurlhere.js?callback=displayOptions'
    });
});

Try my first solution with .live() method first. If it works, then try my second solution to avoid using deprecated .live() method.


text:
Q: Resizing an Array with a Dedicated Method in Java I am at my wit's end with this one. I need to create an array and then use a separate method to resize it and then print it using yet another method. Here is the code I have so far:
import java.util.Scanner;

public class Lab07 {

public static void main(String[] args)
{
    //Variables
    int userSize;
    int newSize;
    int diff;

    //Scanner
    @SuppressWarnings("resource")
    Scanner kb = new Scanner(System.in);

    do{
        System.out.println("Input an array size: ");
        userSize = kb.nextInt();
    }while(!(userSize>0));

double[] userNums = new double[userSize];

    System.out.println("Now please enter "+userSize+" numbers.");

    //Gathering Input
    for(int i= 0; i < userNums.length; i++)
    {
        System.out.println("Input a number into your array: ");
        userNums[i] = kb.nextDouble();

    }
    //Print Array
    System.out.println("Here are all the numbers in your array:");
    printArray(userNums);

    //New Size
    System.out.println();

    do{
        System.out.println("Input a new size: ");
        newSize = kb.nextInt();
    }while(!(newSize>userSize));
    diff = newSize-userSize;
    System.out.println("You need to add "+diff+" new values.");

    //Resize
    arrayResize(userNums, newSize);

    //New input
    for(int i= userNums.length; i <= newSize; i++)
    {
        System.out.println("Input a number into your array: ");
        newArray[i] = kb.nextDouble();
    }
    printArray(newArray);
}

public static void printArray(double[] arr)
{
    System.out.print("[");
    for(int j=0; j<arr.length; j++){
        if(!(j==(arr.length-1)))
            {
            System.out.print(+arr[j]+", ");
            }
        else{
            System.out.print(+arr[j]);
        }
    }
    System.out.print("]");

}

public static double[] arrayResize(double[] oldArray, int newSize)
{
    double[] newArray = new double[newSize];

    for(int i=0; i<newArray.length; i++)
    {
        if(i<oldArray.length)
        {
        newArray[i] = oldArray[i];
        }
        else
        {
            newArray[i] = 0.0;
        }
    }
    return newArray;

I need my result to look like this:
Input an array size: 5

Now please enter 5 numbers
Input a number into your array: 10.0
Input a number into your array: 6.5
Input a number into your array: 4.4
Input a number into your array: 0.0
Input a number into your array: 15.0
Here are all the numbers in your array:
[10.0, 6.5, 4.4, 0.0, 15.0]

Input a new size: 7
You need to add 2 values
Input a number to add to your array: 42.42
Input a number to add to your array: 84.99
Here are all the numbers in your new array:
[10.0, 6.5, 4.4, 0.0, 15.0, 42.42, 84.99]

My problem is when it comes time to call arrayResize. I have no idea how to get the new values into the array and I don't know how I can use it with printArray. I can't move any of the code from one method to another, either.

A: You need to assign the result of arrayResize(userNums, newSize);. You are returning a value but doing nothing with it, so userNums remains the same as it was before the call to your resize method. Try this:
userNums = arrayResize(userNums, newSize);

A: If you need to replace the current userNums with the resized array just do:
userNums = arrayResize(userNums, newSize);

In your arrayResize() method, there is no need to fill the rest of newArray with 0.0, because this is already the default value when you create a double[] array. Also, you only need to loop up to oldArray.length, since there are no more elements to add to newArray after that.
public static double[] arrayResize(double[] oldArray, int newSize) {
    double[] newArray = new double[newSize];
    for(int i = 0; i < oldArray.length; i++) {
        newArray[i] = oldArray[i];
    }
    return newArray;
}

You could implement this method easily using System.arraycopy():
static double[] arrayResize(double[] oldArray, int newSize) {
    double[] newArray = new double[newSize];
    System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
    return newArray;
}

Example:
double[] old = {1.5, 2.5, 3.5};
double[] resized = arrayResize(old, 6);
printArray(resized);

Output:
[1.5, 2.5, 3.5, 0.0, 0.0, 0.0]


text:
Q: Can anyone help give an example that $x^HAx > 0$ for any non-zero $x$ but $A$ is non-Hermitian? Can anyone help give an example of a complex matrix $A \in \Bbb C^{n\times n}$ such that $x^HAx > 0$ for any non-zero $x\in \Bbb C^n$ but $A$ is non-Hermitian? Here $x^H$ denotes the conjugate transpose of $x$. Thanks!

A: No such example exists. If $x^HAx$ is real for all $x\in\mathbb{C}^n$, then $A$ is Hermitian.
Proof: Let $S=\frac{1}{2}(A+A^*)$ and $T=\frac{1}{2i}(A-A^*)$. Observe that
$$S^*=\overline{\left(\frac{1}{2}\right)}(A+A^*)^*=\frac{1}{2}(A^*+A)=S$$
and
$$T^*=\overline{\left(\frac{1}{2i}\right)}(A-A^*)^*=-\frac{1}{2i}(A^*-A)=T,$$
that is, $S$ and $T$ are Hermitian, hence $x^HSx$ and $x^HTx$ are real for all $x\in\mathbb{C}^n$. Since $A=S+iT$ we have
$$x^HAx=x^HSx+i(x^HTx),$$
so if $x^HAx$ is real then $x^HTx=0$ for all $x\in\mathbb{C}^n$. This implies $T=0$, so $A=S$ is Hermitian.


text:
Q: What is the difference among kubernetes_sd_config (within prometheus) and metrics-server and kube-state-metrics? I've read some pages about monitoring k8s, and I found kubernetes_sd_config (within prometheus), metrics-server (took the place of heapster) and kube-state-metrics. All of them could provides metrics, but what's the difference?

*

*Does kubernetes_sd_config (within prometheus) provide all the data those I can get using metrics-server and kube-state-metrics?

*Is kubernetes_sd_config just enough for monitoring?

*Is metrics-server just for providing data (less than kubernetes_sd_config) to the internal components(such as hpa controller)?

*Is kube-state-metrics just for the objects (pod, deployment...) in k8s?

*what is their own target respectively?

A: 1 Metrics-server is a cluster level component which periodically scrapes container CPU and memory usage  metrics from all Kubernetes nodes served by Kubelet through Summary API.
The Kubelet exports a "summary" API that aggregates stats from all pods.
$ kubectl proxy &
Starting to serve on 127.0.0.1:8001
$ NODE=$(kubectl get nodes -o=jsonpath="{.items[0].metadata.name}")
$ curl localhost:8001/api/v1/proxy/nodes/${NODE}:10255/stats/summary

Use-Cases:

*

*Horizontal Pod Autoscaler.

*kubectl top --help:  command.

2 kube-state-metrics

is focused on generating completely new metrics from Kubernetes' object state (e.g. metrics based on deployments, replica sets, etc.). It holds an entire snapshot of Kubernetes state in memory and continuously generates new metrics based off of it

Use-Cases

*

*count the number of k8s Objects.

*How many namespaces are there ?

sysdig-k8s-state-metrics provide the further Information.
3 Prometheus Node_Exporter − Gets the host level matrices and exposes them to Prometheus.
Use-Cases

*

*User and Kernel Space level information.

Lastly, kubernetes_sd_config is the configuration file defines everything related to scraping targets.
You can decide in the config file what kind of information you want to gather and from whom.


text:
Q: Jquery change icon I want to change the icon on the left of the link when the user clicks on it, but I can't get the code to work. I think I may have the wrong element selected by JQuery.
HTML

Danh mục sản phẩm

Laptop

Máy tính bảng

Điện thoại di động

Bộ đàm

Phụ kiện

Tổng đài

Router

Javascript
$(document).ready(function(){
    $('.panel_sanpham > li').toggle(function(){
        $('.panel_sanpham > i').removeClass('.glyphicon-play').addClass('.glyphicon-ok');
    }, function(){
        $('.panel_sanpham > i').removeClass('.glyphicon-ok').addClass('.glyphicon-play');
    })
});

A: toggle() is using for display or hide an element, it will toggle between display state. You can use toggleClass() with space separated class names. It will toggle the class

$('.panel_sanpham li').click(function() {
  $(this).find('i').toggleClass('glyphicon-play glyphicon-ok');
});
.glyphicon-play {
  display:inline-block;
  width: 10px;
  height: 10px;
  background: red;
}
.glyphicon-ok {
  display:inline-block;
  width: 10px;
  height: 10px;
  background: black;
}

Danh mục sản phẩm

Laptop

Máy tính bảng

Điện thoại di động

Bộ đàm

Phụ kiện

Tổng đài

Router

A: You can use ToggleClass() for this:
Your Working Demo at http://jsfiddle.net/z3kt0dey/
$('.panel_sanpham li').click(function() {
 $(this).find('i').toggleClass('glyphicon-play glyphicon-ok');
});

A: Now i want to change the icon when click but the rest of the links still remain the same i have my jquery code like this:
$('.panel_sanpham li').click(function(){
            $('.panel_sanpham li').find('i').removeClass('glyphicon-ok').addClass('glyphicon-play');
            $(this).find('i').removeClass('glyphicon-play').addClass('glyphicon-ok');
        })

can my code be more cleaner?


text:
Q: How to store the same image twice with additional smaller variant of the original photo I'm using jQuery Fancybox Plugin which works pretty good. The problem is that I don't like the fact that on page load the original image with its size is loaded. I need to somehow load a smaller variant of this picture on page load and when clicked to show the original one. It's very easy to do when it comes to fancybox. But the storing process of the smaller variant is confusing me. On upload, I'll store 2 images - the original, and the resized (smaller variant) one. The div that is containing the smaller variant of the photo is set to max-width:500px;max-height:150px; and that's how the smaller variant photo should be resized. Max width of 500px and Max height of 150px. Another question is how will I save the aspect ratio of the image? And how will I determine whether there is a need to store a second (smaller) photo at all. I'm so confused. I'm waiting for you replies. Thanks in advance.
smaller variant

original variant - fancybox opened

I'm using Image Intervention.
My project is on Laravel 8.

A: Yes, you need to store 2 images on your storage.
You need to define either width or height to main aspect ratio of the image. Check the below code
// open an image file
$img = Image::make('public/foo.jpg');

// now you are able to resize the instance with maintaining aspect ratio
$img->resize(300, null, function ($constraint) { $constraint->aspectRatio(); });

// finally we save the image as a new file
$img->save('public/foo_sm.jpg');

I personally like spatie media package (Which uses image intervention in behind). It handles media on separate table using polymorphic relation.
Have a look into the docs, it's amazing
https://spatie.be/docs/laravel-medialibrary/v10/introduction


text:
Q: Printing Daemonic Thread Exceptions in Python Python does not print traceback messages from exceptions raised in daemon threads.
For example, this code creates a daemonic thread and raises an exception in the new thread:
def error_raiser():
    raise Exception

import threading
thread = threading.Thread(target=error_raiser)
thread.daemon = True
thread.start()

but does not print a traceback.  (It gives no output).
However, if the thread is not set as a daemon thread, Python will print the traceback.  Here is the same code with one line commented out:
def error_raiser():
    raise Exception

import threading
thread = threading.Thread(target=error_raiser)
# thread.daemon = True
thread.start()

and the output:
Exception in Thread-1:
Traceback (most recent call last):
  File "C:\Python26\lib\threading.py", line 525, in __bootstrap_inner
    self.run()
  File "C:\Python26\lib\threading.py", line 477, in run
    self.__target(*self.__args, **self.__kwargs)
  File "test.py", line 2, in error_raiser
    raise Exception
Exception

Executing this code in both Python 2.6.2 and Python 3.0.1 and gives the same results.  Interestingly, however, if I execute the code by importing it in the IPython shell, the exception is displayed whether the thread is daemonic or not.
According to the documentation, the only significance of the 'daemon' flag is that "the entire Python program exits when only daemon threads are left."  This would make me believe that not printing a traceback after an exception is a bug in Python, unless I missed something in the documentation.
Is this a bug, or did I miss something in the documentation and this behavior is intentional?  If it is intentional, how can I force Python to print the traceback in daemon threads without using IPython?

A: According to Wikipedia, by definition a daemon should detach itself from the controlling tty, so I think it's correct that no exception is shown (and after all, a daemon should keep working even if you close the shell that launched it)..
See here.
As for how to print the traceback, I think that a simple try/except_then_log_to_file would do the trick :)

A:
Is this a bug, or did I miss something in the documentation and this behavior is intentional?

You have basically stated the reason yourself, without realising it:

According to the documentation, the only significance of the 'daemon' flag is that "the entire Python program exits when only daemon threads are left."

If you have a non-daemonic thread, Python waits for it after thread.start(). This waiting includes anything it does, including raising and handling exceptions.
If you have a daemonic thread, Python does not wait for it after thread.start(). Instead, in the absence of further instructions Python exits immediately. That means your thread never has a chance to raise or handle the exception.

If it is intentional, how can I force Python to print the traceback in daemon threads without using IPython?

For a daemon thread, it is inconsequential what your thread is supposed to do. If it was instructed to print something, the same would have happened.
That also means you have no way to conditionally wait for an action of the daemon. Either you set thread.daemon = False and get all tracebacks - as well as all prints, I/O, and other actions. Or you set thread.daemon = True and get no traceback - and no prints, I/O or other actions - after all other threads are dead.

Interestingly, however, if I execute the code by importing it in the IPython shell, the exception is displayed whether the thread is daemonic or not.

The thing about shells is that they never exit unless you kill them. Since the shell's interpreter does not exit while it waits for your input, any daemon threads started remain alive.


text:
Q: Is there a shorter version of a regex? I have these strings
C910 C918 C920 C924 C925 C926 C928 C929 C930 C937 C940 C942 C943 C947 C950
and this regex works
^(C9[1-5]0|C9[12]8|C94[237]|C92[4569]|C937)$

but can it be made shorter and more elegant?

A: Try this, bring C9 out as its common to all terms you require.
 ^(C9)([1-5]0|[12]8|4[237]|2[4569]|37)$


text:
Q: Who can explain the meaning of this scala code I am reading this code for a long time. I typed it into REPL and it works as well.
but I don't have any idea of what's going on here. Why and how does this even work!!!
import shapeless._

case class Size[L <: HList](get : Int)
object Size {
    implicit val hnilSize = Size[HNil](0)
    implicit def hconsSize[H, T <: HList](implicit tailSize: Size[T]) =
        Size[H :: T](1 + tailSize.get)
    def apply[L <: HList](l : L)(implicit size: Size[L]) : Int = size.get
}

Size(1 :: "Foo" :: true :: HNil)

Can someone explain this step by step and help me understand what is going on here.

A: Yeah, that's pretty thick stuff.
The mind-bender here is that hconsSize is recursive without actually being self referential.
Both apply and hconsSize pull in an implicit of type Size[X].  There are only two implicits that could fit that bill:

*

*hnilSize, but only if X is type HNil

*hconsSize itself

So apply pulls in the hconsSize implicit, which adds 1 to the stack and pulls in another hconsSize implicit (not necessarily in that order).  This continues until we encounter an element of type HNil.  Then the hnilSize implicit is pulled in, the get is zero, the stack is unrolled and all those 1's are added up.
Result: number of elements in the shapeless HList.


text:
Q: postgres $HOME directory unproperly set in Docker container created from official postgres Dockerfile I've created a PostgreSQL 9.1 Docker container using this official Dockerfile.
To create my container, I've done this:
Step 1: create a volume for permanent postgres data
docker volume create --name postgres_data

Step 2: Start the postgres instance
docker run --name my_postgres_container -e POSTGRES_PASSWORD=my_password -v postgres_data:/var/lib/postgresql/data -d postgres:9.1

My instance starts correctly, and I can connect with it, but:
Problem 1: No logs
docker logs my_postgres_container --> returns nothing

Problem 2: Improperly configured $HOME directory
docker exec -it my_postgres_instance /bin/bash --> enter as root
# su postgres --> change to postgres user

$ psql --> ok, can connect to my cluster
psql (9.1.20)
Type "help" for help.

postgres=#

$ pwd
/ --> Why do I directly go to / instead to /var/lib/postgresql/data ?

$ export
export HOME='/home/postgres'
export PGDATA='/var/lib/postgresql/data'

Why is HOME configured to that value? I was expecting $HOME equal to $PGDATA. Am I wrong?


text:
Q: Provide an array of origins to builder.WithOrigins in AddCors I thought there would already be an answer to this, but I could not find any.
I have a CORS setup like this, in my API server.
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder => {
            builder.WithOrigins(AddCorsOrigin1LocalHost,
                                AddCorsOrigin2ProductionSite,
                                AddCorsOrigin3DevOrTestOrSomethingElseSite);
            builder.AllowAnyMethod();
            builder.AllowAnyHeader();
            builder.AllowCredentials();
        });
    });

I am adding the sites that I want, one by one, using a local string. This works as long as I only have 3 origins to use. I can keep changing the origins when I want.
However, if I have a 4th origin or more origins, I have to add a new local string and update it in the above code block.
I am curious, is there anyway, I can simply send a string collection of array or list. that way, when I have to add or remove origins, I could simply manipulate the string collection.

A: You can set the sites in appsettings.json:
Here is a demo:
appsettings.json(I add Origins to it):
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Origins": "http://example.com,http://www.contoso.com"
}

Startup.cs(change Origins to a string[]):
string[] s = Configuration["Origins"].Split(",");
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins(s);
                                  });
            });

result:


text:
Q: How to multithread a session? I am trying to multithread my python script, which works with mysql via sqlalchemy with "threading" module
from threading import Thread

But multiple calls are crushing mysql.
If I get it right, the cause of this is the fact that the session object is designed to take  care of only one call at the  time,  so I tied to implement a scoped session approach with the following code:
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

s_session = scoped_session(sessionmaker(bind=engine))
session = s_session()

Now I get the following error:

"Lost connection to MySQL server during query")
  sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, >'Lost connection to MySQL server during query')

How to fix the problem?

*

*maybe I need multiple engines to implement scoped_session?

*maybe I need to close session?

Thank you!


text:
Q: How to rebuild whats apps main menu (viewpager with fab) Is in whats app the floating action button part of each fragment (chats, status, calls and so on) or is the fab part of the enclosing main layout that encapsulates the fragments?
Because the fab does not scroll sideways away with the fragment contents i tend to the latter case but then again i just started android programming and know nothing about layout flags or options that might cause this behaviour...

A: Yes, the FloatingActionButton (fab) seems to be a part of the Activity layout.  The Activity likely has a ViewPager beneath the TabLayout - this is a pretty common approach to building these types of layouts.  The ViewPager/TabLayout combination is set up to link the pages as you either scroll or tap the tabs to Fragments that each have their own logic and implementation associated with them.  The fab sits at the Activity level so it is unaffected by the changing of pages.  However the Fragments definitely modify the fab visually (you can see the icons change when you change pages) and logically so when the view is clicked it performs the correct action depending on the currently shown page.
Take a peak at this article to see a simple implementation to get your hands dirty with some of the code: https://medium.com/@Abdulkadir98/android-sliding-tabs-with-viewpager-851f9c996cb5


text:
Q: multiple records in sharepoint workflow I would like like to send an email to user when my criteria meets, but I can only get the workflow designer to return one record.
I have two lists and I have data something like below.
List A:
**col1**                **col2**
abc@a23.com             This is subject

List B:
Col1            Key1                  Key2
abc@123.com     orange               apple
abc@123.com     banana               subject

Iam writing the condition
if col1(A) equals col1(B)
and col1(A) contains key1 or key2
do something.
But it looks like only first row is getting selected all the time and nothing is happening as it not matching with keyword column. IS there a way to implement this in sharepoint designer as there is a limitation that only first row will be selected if multiple rows returned. Plz help me. Let me know if I am unclear.
Thanks,

A: There's no way to do this in SharePoint Designer, they way I've duct taped this together in the past was to create another list that is a one for your many... based upon your list a and list b
Create a new list as such.
List C
Col 1              Key1        Key2     Key1-1      Key2-1    Key1-2     Key2-2
abc@a23.com        Lookup to List B   Lookup to List B    Lookup to List B    http://www.fiddler2.com/fiddler2/
With  the new list created you update it based upon Column1 1 (you'll have to manually update Key1 with the values from the lookups.  From there your workflow can successfully query and email based upon list C (I'd probably put the workflow on list C and have it trigger when the appropariate number of items have been added.

A: I am working on a task that is running into this problem as well. Email all contacts where the record has a particular flag.
Example List:
Record | Group A | Group B | Group C | Contacts
-----------------------------------------------
1       [Checked]           [Checked]  Names
2                 [Checked] [Checked]  Names
3       [Checked]                      Names

While I have not succeeded in getting this to work. I did move one step closer today. Namely, I have two Workflow Variables - Collector and Bucket.
I am using the following:
Set Variable:Bucket to [%Variable: Bucket%][%Variable: Collector%]

The above line has allowed me to append emails to a single variable.  Now if we can combine this with a way to check "each" record.  Then we will have a solution.


text:
Q: Hierarchical Bayesian Distance Sampling based on Sollmann et al 2015 I'm working to adapt code from a paper by Sollman et al (2015) that uses distance sampling to correct for imperfect bird detection using species-specific and community parameter estimates for multiple species (https://doi.org/10.1111/2041-210X.12518). This code is also similar to that of Kery and Royle's HM textbook, though Kery and Royle only estimate single species.
I'm encountering errors with a variable 'fct[s,j,k]', which is a matrix with dimensions equal to the number of species (s), number of sites (j), and number of distance intervals (k), and is used in the code to connect detection probabilities with the observation model. The error I am getting states that node fct[1,3,2] has "Invalid parent values".
The full code (including data prep above the model) is as follows. I'm using a reduced dataset of six sites and five species, modeled by one detection covariate and one process covariate for the purposes of testing:
###########################################################
# Load Packages --------------------------------------------------------------
library(tidyverse)
library(jagsUI)
###########################################################
# Set WD --------------------------------------------------------------
setwd("/Users/colinsweeney/Documents/Documents/PhD/Chapter1/2017_DistanceModel_Test/Models")

Y<- matrix(as.integer(c(0,0,3,0,0,0, 0,0,0,0,3,1, 0,0,0,1,0,0,  1,0,0,0,0,0, 0,1,0,0,0,0)), nrow=6, ncol=5)
colnames(Y)<- c(1,2,3,4,5)

Nin=Y+1

nsp=5 # number species
species=c(4, 5, 1, 3, 2, 2, 1, 2, 1, 2) # species index
nG=2 # number of distance bins, previously: nD=nD,
pix=c(0.25, 0.75) # % area covered by each category
midpt=c(62.5, 187.5) # previously: midpt=midpt,
nsites=6
nVAR=1
nOBSVAR=1
VAR = matrix(c( 1.40683409, -0.33717511, -0.91851151,2.07537095,-0.14824078, 0.05522696,-0.91851151,-0.14824078,-0.91851151,-0.14824078), nrow=10, ncol=1)
colnames(VAR)<- c("elevation")
OBSVAR=matrix(c(1.42884613,1.26074658,0.08404977,0.08404977,-1.26074658, 0.75644795, 0.08404977,-1.26074658,0.08404977,-1.26074658),nrow=10, ncol=1)
colnames(OBSVAR)<-c("cloudcover")
dclass=c(2, 2, 1, 1, 1, 2, 1, 1, 1, 1)
y=Y
nind=10
site=c(1, 2, 3, 4, 5, 6, 3, 5, 3, 5)

# Bundle and summarize data set
str(win.df_NEON <- list(spec=nsp,
                        species=species,
                        nG=nG,
                        pix=pix,
                        midpt=midpt,
                        nsites=nsites,
                        nVAR=nVAR,
                        nOBSVAR=nOBSVAR,
                        VAR = VAR,
                        OBSVAR=OBSVAR,
                        dclass=dclass,
                        y=y,
                        nind=nind,
                        site=site) )

##################################################################################################
##################### JAGS model code for community DS model: NEON Adaptated ####################
cat(" # commented out just for the purposes of editing code (delete before running)
model{
  #################################### Priors #######################
  mu_s~dnorm(0,0.01) # part of asig: species specific covariate
  sig_s~dunif(0,100) # part of tau_s, which is part of asig: species specific covariate
  tau_s<-1/(sig_s*sig_s) # part of asig: species specific covariate

  mu_a~dnorm(0,0.01) # part of alpha: species specific covariate
  tau_a~dgamma(0.1,0.1)# part of sig_a, which is part of alpha: species specific covariate
  sig_a<-1/sqrt(tau_a) # part of alpha: species specific covariate

  r.N~dunif(0,100) # community hyperparamter: used in rho.N

  ########################################################
  # community hyperpriors
  ########################################################

  for (k in 1:nVAR){
    mu_b[k]~dnorm(0,0.01)
    sig_b[k]<-1/sqrt(tau_b[k]) # This doesn't appear to be used anywhere??
    tau_b[k]~dgamma(0.1,0.1)
  }

  for (k in 1:nOBSVAR){ # NEW: Trying to rework bsig (Observation covariates): treat it like beta
    mu_bsig[k]~dnorm(0,0.01)
    tau_bsig[k]~dgamma(0.1,0.1)
    sig_bsig[k]<-1/sqrt(tau_bsig[k])
  }

  ########################################################
  ### draw species-specific parameters from hyperdistribution
  ########################################################
  for (s in 1:spec){
    for (k in 1:nVAR){
      beta[s,k]~dnorm(mu_b[k],tau_b[k])
    }

    ########   ############   ############
    for (k in 1:nOBSVAR){ # NEW Trying to rework bsig (Observation covariates): treat it like beta
         bsig[s,k]~dnorm(mu_bsig[k],tau_bsig[k]) # community hyperparameter for detection model
       }

    asig[s] ~dnorm(mu_s, tau_s) # detection model species specific intercept

    alpha[s]~dnorm(mu_a,tau_a)  # ecological model species specific intercept
  }

#########################################################################################
### Main HM - > parallel structure to Kery and Royle
#########################################################################################

#########################################################################################
    for (s in 1:spec){ # New

    for (j in 1:nsites){ # number of sites

      ########### linear model for detection (Detection model) #######
      sigma[s,j]<- exp(asig[s] + inprod(bsig[s,],OBSVAR[j,]) )

      ### construct detection probabilities by distance class w/ half-normal model
      for(k in 1:nG){ # nG: number of distance intervauls (nG is db-1 in length)
        log(p[s,j,k])<- -midpt[k]*midpt[k]/(2*(sigma[s,j]*sigma[s,j])) # half-normal detection

        fc[s,j,k]<- p[s,j,k]*pix[k] # pix: proportion of area of each intervaul
        fct[s,j,k]<- fc[s,j,k]/sum(fc[s,j,1:nG])  # swap pcap for it's value AND fsc -> fst

      }

      pcap[s,j]<-sum(fc[s,j,1:nG])                   # overall detection probability

      ############ Part 2 of HM   ################
      y[j,s]~ dbin(pcap[s,j],N[j,s])

      ############ Part 3 of HM   ################
      N[j,s]~dpois(lambda.star[j,s])

        ########### linear model for abundance (Ecological model) #######
        log(lambda[j,s])<- alpha[s] + inprod(beta[s,],VAR[j,])

        rho.N[j,s]~dgamma(r.N,r.N)

        lambda.star[j,s]<-lambda[j,s]*rho.N[j,s]
    }
  }

  for(i in 1:nind){

    ############ Part 1 of HM   ################
    dclass[i] ~ dcat(fct[species[i],site[i],1:nG])

    # distance class of individual distributed by catagorical distribution of binned probabilites
    # nG: number of distance bins
  }
  ################################################################################################
  ### monitor total abundance
  for (i in 1:spec){
    Nspec[i]<-sum(N[1:nsites,i])
  }
}
    ",fill=TRUE, file="MultispeciesDist_2017NEON_ver1.txt")

################################## MCMC Settings #########################
# Inits --------------------------------------------------------------
# Initial values to start run at

inits<-function(){list(N=Nin,
                       # Shape paramters
                       mu_a=runif(1,0,1), # alpha
                       tau_a=runif(1,0,1), # alpha

                       mu_b=runif(nVAR,0,1), # beta
                       tau_b=runif(nVAR,0,1), # beta

                       mu_bsig=runif(nOBSVAR,0,1), # NEW: bsig (OBSVAR)
                       tau_bsig=runif(nOBSVAR,0,1), # NEW: bsig (OBSVAR)

                       asig=runif(nsp,0,1), # OBSVAR
                       mu_s = runif(1, 0, 1), # asig (OBSVAR) ~ like alpha
                       sig_s=runif(1) )} # asig (OBSVAR) ~ like alpha

# Params --------------------------------------------------------------
# Params to save: list of parameters to save (variables of interest)

params<-c('asig', # species specific parameter, used in detection model
          'mu_s', # species specific shape parameter for asig (detection model )
          'sig_s', # species specific shape parameter for asig (detection model )
          'mu_a', # species specific shape parameter for alpha (ecological model)
          'alpha', # species specific covariate, ecological model (intercept)
          'sig_a', # species specific shape parameter for alpha (ecological model)
          'mu_b', # species specific shape parameter for beta (ecological model)-VAR
          'sig_b', # species specific: beta parameter(ecological model)-VAR
          'beta', # species specific covariate, ecological model
          'Nspec', # abundance for each species
          'r.N', # community hyper parameter
          'mu_bsig', # NEW
          'sig_bsig', # NEW
          'bsig' # MODIFIED # new format to match beta's format
)

# MCMC chain settings--------------------------------------------------------------
# ni: number of iterations in MCMC chain
# nb: burn in period
# nt: thinning
# nc: number of chains

ni <- 52000   ;   nb <- 2000   ;   nt <- 2   ;   nc <- 3

# TEST ONLY
ni <- 300   ;   nb <- 200   ;   nt <- 2   ;   nc <- 3

###########################################################
# Make sure wd is correct--------------------------------------------------------------
setwd("/Users/colinsweeney/Documents/Documents/PhD/Chapter1/2017_DistanceModel_Test/Models")
# Make sure the txt file is exported to the correct folder

###########################################################
# Run MCMC (Gibbs Sampler) in JAGS --------------------------------------------------------------
##### Run JAGS and summarize posteriors.
# jagsUI
MultiSp_FullTest_1 <- jags(win.df_NEON,
                           inits,
                           params,
                           "MultispeciesDist_2017NEON_ver1.txt",
                           n.thin=nt,
                           n.chains=nc,
                           n.burnin=nb,
                           n.iter=ni)

I've tried to modify initial values and priors but that hasn't appeared to make a difference with the "invalid parent values" error. Any thoughts are appreciated.

A: This almost always means you are not specifying priors/joint likelihoods that "respect" the support of your prior distributions/joint likelihood. This can happen, for example, if you (implicitly) try to sample from distributions with negative variances, Poisson distributions with negative lambda, or divide by zero. My understanding is that jags does not allow improper priors as well.
While I don't have an exact solution for you because your example isn't a minimal example, here's what I recommend:

*

*Start with a simpler version of the model and add in complexity one component at a time to ensure you are getting sensible estimates, things converge, etc. This will also help you identify where you are passing unsupported value of parameters or allowing the sampler to move into those spaces.

*Move from the top of the hierarchical structure to the unit observations to ensure that everything is supported and appropriately constrained. For example,  sig_s ~ dunif(0, 100) imposes a uniform prior on the closed interval [0, 100].  You then divide 1 by this value when defining tau_s as follows: tau_s <- 1 / (sig_s * sig_s). tau_s is then the precision (1/var) of a normal distribution (asig). If sig_s = 0 then you're asking jags to (a) set tau_s to 1/0 and (b) give the normal distribution asig a variance of 1/(1/0). Infinite variance is not a sensible prior and will produce a bunch of issues if jags doesn't just throw an error like this.

*Take a look at the jags forums, which will be much better-suited for this question. This error appears in over 1,331 posts on those forums, so I am quite sure you will find a solution there in conjunction with the other parts of this.