text:
Q: Blank page when building Angular 8 project but works perfectly using "ng serve" My project is working with "ng serve" command but shows just a blank screen when building. And this message is shown in the console:

Angular is running in the development mode. Call enableProdMode() to enable the production mode.

No route is loaded and there is just an empty  tag in the middle of the template.
I tried both AOT and JIT. production and development modes. All blank
I just published the project here: https://razesheydaei.ir
This is my angular.json file:
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ui": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ui",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": [
              "src/assets/bower_components/bootstrap/css/bootstrap.min.css",
              "src/assets/icon/themify-icons/themify-icons.css",
              "src/assets/css/jquery.mCustomScrollbar.css",
              "src/assets/pages/chart/radial/css/radial.css",
              "node_modules/@fortawesome/fontawesome-free/css/all.min.css",
              "node_modules/ngx-toastr/toastr.css",
              "src/assets/css/style.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ui:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ui:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ui:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.css"],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": ["**/node_modules/**"]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ui:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ui:serve:production"
            }
          }
        }
      }
    }
  },
  "defaultProject": "ui"
}

And the tsconfig.json:
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

And the routes:
const routes: Routes = [
  {
    path: '',
    component: MainComponent,
    canActivate: [AuthGuard],

    children: [
      {
        path: 'user',
        loadChildren: () => import('./systems/user/user.module').then(mod => mod.UserModule)
      },
      {
        path: 'usergroup',
        loadChildren: () => import('./systems/user-group/user-group.module').then(mod => mod.UserGroupModule)
      },
      {
        path: 'flight',
        loadChildren: () => import('./systems/flight/flight.module').then(mod => mod.FlightModule)
      }
    ]
  },
  {
    path: '',
    component: SimpleComponent,
    children: [
      {
        path: '',
        component: LoginComponent
      },
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  },
  {
    path: '**',
    component: LoginComponent
  }
];

A: I think the problem is your app server
if you using nginx try this config
      worker_processes  1;

      events {
          worker_connections  1024;
      }

      http {
          server {
              listen 80;
              server_name  localhost;
              access_log off;

              root   /usr/share/nginx/html;
              index  index.html index.htm;
              include /etc/nginx/mime.types;

              gzip on;
              gzip_min_length 1000;
              gzip_proxied expired no-cache no-store private auth;
              gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

              location / {
                  try_files $uri $uri/ /index.html;
              }
          }
      }

and try with docker here is dockerfile
FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf

WORKDIR /usr/share/nginx/html
COPY dist/out-tsc/ .


text:
Q: Pagination function that adds data to StreamController - Flutter I am trying to implement pagination in my app but it's not working very well. So far, the code works to get the first 10 posts and their users but after that, it goes downhill. When a user reaches the last post, the getData() function is called again to add ten more. Although I only call it once, a loop is somehow created, which results in all of the data being added at once, defeating the point of pagination. What's even more strange is that, as I see the range printing many times, I can see that the range skips by tens of numbers (example: Range: [1021, 1030] => Range: [1051, 1060]). Another issue is that when I open the app switcher, the app goes in the background and the data list is cleared which makes postsList and usersList empty, messing up the pagination.
Here is the code that I am using:
class FloatingTabBarView extends StatefulWidget {
  const FloatingTabBarView({Key? key}) : super(key: key);

  @override
  State<FloatingTabBarView> createState() => _FloatingTabBarViewState();
}

class _FloatingTabBarViewState extends State<FloatingTabBarView> with AutomaticKeepAliveClientMixin<FloatingTabBarView> {
  @override
  bool get wantKeepAlive => true;

  List<Post> currentUserPosts = [];
  Profile currentProfile = Profile(
    ProfileInfoObject(
      Supabase.auth.currentUser!.userMetadata!['photoURL'].toString(),
      Supabase.auth.currentUser!.userMetadata!['displayName'].toString(),
    ),
    [],
  );

  static int lastRange = 0;
  static var data = [[], []];

  static var controller = StreamController<List>.broadcast();
  static void getData() async {
    List<UserSearchResult> usersList =
        data.first.map<UserSearchResult>((e) => e).toList();
    List<Post> postsList = data.last.map<Post>((e) => e).toList();

    print('Getting/Updating data');

    List<int> range() {
      if (lastRange == 0) {
        lastRange = 10;
        return [0, 10];
      } else {
        // Example 0, 10 => 11, 20
        int newMin = lastRange + 1;
        int newMax = lastRange + 10;
        lastRange = newMax;
        return [newMin, newMax];
      }
    }

    print('Range: ${range()}');

    final postsDocs = await Supabase.db
        .from('posts')
        .select()
        .order('date', ascending: false)
        .range(range().first, range().last);
    List<Post> newPostsList =
        postsDocs.map<Post>((postDoc) => Post.fromJson(postDoc)).toList();

    for (var post in newPostsList) {
      postsList.add(post);

      if (usersList.where((u) => u.uid == post.uid).isEmpty) {
        try {
          final userDoc =
          await Supabase.db.from('profiles').select().eq('uid', post.uid).single();

          ProfileInfoObject profileInfo = ProfileInfoObject.fromJson(userDoc);
          print('New profile: $profileInfo');
          Profile profile = Profile(profileInfo, []);
          profile.posts.add(post);
          List blockedUsers = userDoc['blockedUsers'] as List;
          UserSearchResult user = (UserSearchResult(
              profile, userDoc['uid'].toString(), blockedUsers));

          usersList.add(user);
        } catch (e) {
          print('Failed getting user: $e');
        }
      } else {
        final posts = usersList.where((u) => u.uid == post.uid).first.profile.posts;

        if (posts.where((p) => p.postId == post.postId).isEmpty) {
          posts.add(post);
        }
      }
    }

    controller.add([usersList, postsList]);
  }

  @override
  void initState() {
    PermissionsService.checkPermissions(context);
    getData();
    super.initState();
  }

  @override
  void dispose() {
    lastRange = 0;
    super.dispose();
  }

  Widget floatingTabBarPageView() {
    List<TabItem> tabList(List<UserSearchResult> users, List<Post> posts) {
      currentProfile = Profile(
        ProfileInfoObject(
          Supabase.auth.currentUser!.userMetadata!['photoURL'].toString(),
          Supabase.auth.currentUser!.userMetadata!['displayName'].toString(),
        ),
        posts
            .where((post) => post.uid == Supabase.auth.currentUser!.id)
            .toList(),
      );
      List blockedUsers =
          Supabase.auth.currentUser!.userMetadata!['blockedUsers'] ?? [];
      UserSearchResult currentUser = UserSearchResult(
        currentProfile,
        Supabase.auth.currentUser!.id,
        blockedUsers,
      );
      List<TabItem> list = [
        TabItem(
          icon: const Icon(Icons.home_outlined, size: 35),
          selectedIcon: const Icon(Icons.home, size: 35),
          label: "Home",
          tabWidget: HomeScreen(usersMap: users, postsList: posts),
        ),
        TabItem(
          icon: const Icon(Icons.travel_explore_outlined, size: 35),
          selectedIcon: const Icon(Icons.travel_explore, size: 35),
          label: "Explore",
          tabWidget: ExploreScreen(usersMap: users, postsList: posts),
        ),
        if (!kIsWeb)
          if (Platform.isIOS || Platform.isAndroid)
            const TabItem(
              icon: Icon(CupertinoIcons.add_circled, size: 35),
              selectedIcon: Icon(CupertinoIcons.add_circled_solid, size: 35),
              label: "Post",
              tabWidget: CreatePostScreen(),
            ),
        TabItem(
          icon: const Icon(CupertinoIcons.person_alt_circle, size: 35),
          selectedIcon:
              const Icon(CupertinoIcons.person_alt_circle_fill, size: 35),
          label: "Account",
          tabWidget: ProfileScreen(
            user: currentUser,
          ),
        ),
      ];
      return list;
    }

    return StreamBuilder<List>(
        stream: controller.stream,
        builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
          List<UserSearchResult> users = [];
          if (snapshot.data?[0] != null) {
            users = snapshot.data![0];
          }
          List<Post> posts = [];
          if (snapshot.data?[1] != null) {
            posts = snapshot.data![1];
          }
          print('Snapshots: $users, $posts');
          if (!snapshot.hasData) {
            return const Scaffold(
              body: Center(child: GlowingIcon()),
            );
          } else {
            return FloatingTabBar(
              activeColor: const Color(0xFF7157A0),
              inactiveColor: const Color(0xFFadc0ff),
              tabItemList: tabList(users, posts),
              isFloating: true,
              titleTapNavigationRouteWidget: HomeScreen(
                usersMap: users,
                postsList: posts,
              ),
              title: 'GLOBE',
              showTabLabelsForFloating: true,
            );
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    return floatingTabBarPageView();
  }
}

A: The first two issues were caused by the fact that I had the range as a function. Since that function used the same variable that it updates, that started the loop of the ranges. Below is the new code for that which creates the range without a function and separated updates the lastRange.
List<int> range = lastRange == 0 ? [0, 10] : [lastRange + 1, lastRange + 10];
lastRange = range.last;

Now, the biggest issue was the data clearing. I thought that the data list was getting reset but it turns out I never updated it in the function. The fix for this was simple.
Before:
controller.add([usersList, postsList]);

After:
data = [usersList, postsList];
controller.add(data);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Clojure define functions with redundancy in parameter clauses
Possible Duplicate:
Why clojure's vector function definition is so verbose?

To clarify my question, let's take the definition of list* as example.
(defn list*
  "Creates a new list containing the items prepended to the rest, the
  last of which will be treated as a sequence."
  {:added "1.0"
   :static true}
  ([args] (seq args))
  ([a args] (cons a args))
  ([a b args] (cons a (cons b args)))
  ([a b c args] (cons a (cons b (cons c args))))
  ([a b c d & more]
    (cons a (cons b (cons c (cons d (spread more)))))))

My question is, why not define list* like this:
(defn list*
  "Creates a new list containing the items prepended to the rest, the
  last of which will be treated as a sequence."
  {:added "1.0"
   :static true}
  ([args] (seq args))
  ([a & more] (cons a (spread more))))

A: The main reason is performance.
It can help the Clojure compiler to create more optimised code if you explicitly provide a few extra versions with small arities (especially since the small arity cases are the most commonly used)
This is particularly true if the overloaded versions avoid the need to process a variable length argument list (& more), since processing a variable-length argument list results in more overhead than normal positional parameters.


text:
Q: Is the sum of a subspace with itself that same subspace? Quick question. Let $U$ be a subspace of a vector space $V$. I was asked to

Express $U + U$ in terms of $U$.

My thought process is that, by definition, any linear combination $c\alpha + \beta$ of vectors $\alpha, \beta \in U$ belongs to $U$. In other words, every linear combination within $U$ maps to vectors within $U$. It seems to follow that
$$U + U = U$$
since $U + U$ is simply every possible linear combination of vectors within $U$. Is this correct?

A: You are basically correct. To make it more formal, we can show $U + U = U$ by showing that both sides of the equation are subsets of the other.
First, it's fairly trivial to see that $U \subseteq U + U$ but just in case notice that if $u \in U$ is an arbitrary vector from $U$ then $u = u + 0 \in U + U$ and hence $U \subseteq U + U$.
Then, as you've noted, if $u, v \in U$ and $\alpha, \beta \in \mathbb{F}$ (the underlying field) then $\alpha u + \beta v$ represents an arbitrary vector from $U + U$, but because $U$ is a subspace of $V$ it's clear that $\alpha u + \beta v \in U$, and hence $U + U \subseteq U$.
Then since $U \subseteq U + U$ and $U + U \subseteq U$, we have $U = U + U$.


text:
Q: How to access form input variable values with multiple inputs using a loop in php? Let's say I have a "fieldname" that has multiple form inputs in an HTML form.  In the form, name="fieldname[]".
I then set a fieldname variable:
 $fieldname = $_POST['fieldname'];

I would then use a loop to access each value:
 foreach ( $_POST['fieldname'] as a_name ) {
     echo $a_name;
 }

I want to use each value in "fieldname" in my below $email_body variable and then in a mail function.
I have an email_body variable which is used in my mail function:
     $email_body = "Auto Quote\n From: $email \n $address, $carrier"
Would I just include the email_body in the squiggly brackets of the foreach loop?  And then put the $a_name variable in the quotes?  Or would it be better to use it in my(not shown) mail function?

A: If I understand correctly, you're not sure how to use the $a_name variables in your message body. How to do this of course depends on where in the message body you want to place the form input, but the following could work:
$fieldname = $_POST['fieldname'];
$email_body = "Auto Quote\n From: $email \n $address, $carrier \n"

foreach ($_POST['fieldname'] as $a_name ) {
    $email_body .= $a_name . "\n";
}

This will append the input in the "fieldname" forms to your message body. If you want to place the input in a different place, you should clearly just switch things around. ;)

A: You did almost everything. $_POST['fieldname'] is an array, so after $fieldname = $_POST['fieldname'];, a copy of the array is in $fieldname, no need to use $_POST['fieldname'] anymore.
To add each content to your mail body:
$body = 'Whatever text before: ';

foreach ($fieldname as $index => $value ) {
  $body .= $index . ': ' . $value . ';';
}

$body .= 'text after.';

//send your e-mail

You can use $_POST['fieldname'] directly without $fieldname variable.
I put an index that you can ignore if you want, see PHP foreach documentation if needed http://php.net/manual/en/control-structures.foreach.php.
As the text from client is being used, You must be aware of the fact that a dot by itself on a line ends the e-mail body, I don`t know how PHP mail functions handle this, may be some testing is appropriate.


text:
Q: Counter in WP7 Silverlight application I am writting minesweeper game in c# silverlight.
1. How can I add a counter (counting seconds only) to this application?
2. How can I stop counter when application goes to the background (middle button, search button, incoming call etc.)?
3. How can I do something when WP7 is closing my application process? For example save current game to isolated storage.

A: 1) You need to use Timer
        timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
        timer.Interval = (1000) * (10);             // Timer will tick evert 10 seconds
        timer.Enabled = true;                       // Enable the timer
        timer.Start();                              // Start the time

void timer_Tick(object sender, EventArgs e)
        {
           //Do something
        }

2) You need to handle OnNavigatedFrom Event:
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    //Do something
}

3) Here You have a 4 useful events:
    // Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
    //Do something
}

// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
    //Do something
}

// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    //Do something
}

// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
    //Do something
}

Here You can read more about handle this events: http://msdn.microsoft.com/en-us/library/hh821027.aspx


text:
Q: Java Reading Text File Currently Open For Writing I am wondering what the best way to read from a file that is currently open for writing.
The program handles read / write requests.
In the program, a PrintWriter is used to write to the file.
PrintWriter serverLog = new PrintWriter(new FileWriter("server"+processID+".log"));
serverLog.println("arbitrary text");

I have a function that is accessed that needs to read from the file. No writes will be performed when I need to access the file for reading.
Using the Scanner or BufferedReader methods for reading don't appear to work.
The only option I can think of is to close the PrintWriter, read the file, and then re-open the PrintWriter with 'append' mode, but that seems like a very poor option.

A: Consider java.io.RandomAccessFile. This class can both read and write from an open file. Not very convenient to read / write text though.

A: I think you can't perform two modes(read and write) at the same time.


text:
Q: My program isnt adding a record to a table in a database   var
    sName, sSurname, sUsername, sPassword, sPassword2: string;
begin
  sName:=edtName.Text;
  sSurname:=edtSurname.Text;
  sUsername:=edtUsername.Text;
  sPassword:=edtPassword.Text;
  sPassword2:=edtPassword2.Text;
  if sPassword=sPassword2 then
    with DataModule1 do
     begin
       tblLogInInfo.Open;
       tblLogInInfo.Last;
       while NOT tblLogInInfo.Eof do
         begin
           tblLogIniNfo.Insert;
           tblLogInInfo.FieldByName('Name').Value:=sName;
           tblLogInInfo.FieldByName('Surname').Value:=sSurname;
           tblLogInInfo.FieldByName('Username').Value:=sUsername;
           tblLogInInfo.FieldByName('Password').Value:=sPassword;
           tblLogInInfo.Post;
         end;
       ShowMessage('You have successfully created an account!');
       Form2.Close;
       Form1.Show;
     end
  else
    begin
      ShowMessage('Your passwords did not match. Please try again.');
    end;

This is the code I use to add a record, but it doesn't add the record. I've tried various other methods but it doesn't work.
I'm at the point where I'd like to restart the entire program, and I wouldn't like to do that due to the fact that I already have over 1,000 lines of code.

A: You are moving to the last record then doing a while not EOF. That is creating an infinite loop that would create the same record for ever.  Remove the WHILE and change the Insert to an Append.  Also, doing things this way is fine, but if you are using an SQL database that supports stored procedures you should look into using a stored procedure to do the insert instead.


text:
Q: SQL IF statement for unique rows I am working in Excel and Im trying to make an if sql statement:
="INSERT INTO Roles (Role Type, Role, Trade) VALUES ("&A1&", '"&B1&"');"
In my C column I have a numbers in the first 13 rows and then I have string in rows 14 to 19. I am trying to make an If statement so that the first 13 rows are treated as a number and rows 14 to 19 are treated as a string. Thanks in advance!


text:
Q: Hide Add To cart Button in WordPress Woocommerce I am trying to hide Addtocart button in all pages when user is not login in the site.
Also, I used this code for hiding the Price and AddtoCart.
if (!is_user_logged_in()) {
    /****** REMOVE THE ADD TO CART BUTTON ****/
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10);

    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
   /*********** REMOVE PRICE FROM ALL PLACES *******/
    add_filter( 'woocommerce_variable_sale_price_html', 'theme_remove_prices', 10, 2 );
    add_filter( 'woocommerce_variable_price_html', 'theme_remove_prices', 10, 2 );
    add_filter( 'woocommerce_get_price_html', 'theme_remove_prices', 10, 2 );
}

function theme_remove_prices( $price, $product ) {
    $price = '';
    return $price;
}

but unfortunately it did not work in all situations.
I need to hide AddtoCart in these pages which I showed in the images.

and this one

I was wondering If you could help me to solve this problem.
Thanks in advance.

A: Another possible way is to make the product unpurchasable for not logged in user.
add_filter( 'woocommerce_is_purchasable', '__return_false' );

Even if you wish you can hide the button through custom CSS.
li.product .add_to_cart_button, .single-product form.cart{
    display: none;
}


text:
Q: Is there a method to set limits on scipy's generating a random variable set? Basically I'm trying to create a curve using scipy's random variable state but I'd like to set limits for the random value generated.
Basically I'm looking for something like:
from scipy import stats

data = stats.gamma.rvs(2, loc=1.5, scale=2, size=10000, min=800, max=1000)

Or is it something that you preface in scipy?

A: You cannot set boundaries for a gamma distribution but you can clamp resulting values to [minimum, maximum]
import numpy as np
from scipy import stats

data = stats.gamma.rvs(2, loc=1.5, scale=2, size=10000)
print(data) # [1.55651126 7.25914918 5.03753265 ... 5.56524255 3.05888237 2.17275238]

# clamp to [minimum, maximum]
minimum = 3
maximum = 5
# assert minimum < maximum

data = np.where(data < minimum, minimum, data)
data = np.where(data > maximum, maximum, data)
print(data) # [3.         5.         5.         ... 5.         3.05888237 3.        ]

Adjusting for your comment: if you want to sample n elements in [minimum, maximum] without clamping you could do something like:
from scipy import stats

minimum = 3
maximum = 5

sampled, n = [], 10_000
while len(sampled) != n:
    data = stats.gamma.rvs(2, loc=1.5, scale=2, size=n - len(sampled))
    sampled.extend(data[(minimum <= data) & (data <= maximum)])


text:
Q: Swift generic with Any type I have a such classes:
class Base<T> {
}

class First:Base<Int> {
}

class Second:Base<Double> {
}

How can I declare type Base to be able to assign to it First object
When I try with Any it doesn't work:
class Test {

    var base:Base<Any>

    init(_ base: Base<Any>) {
        self.base = base
    }

}

Test(First())

It gives me:
Cannot convert value of type 'First' to expected argument type 'Base<Any>' (aka 'Base<protocol<>>')

A: Simple solution
If you want Base to have First as generic type then why are you using Any?
This code will work
class Test {
    var base:Base<First> // <- this must be First instead of Any
    init(_ base: Base<First>) {
        self.base = base
    }
}

More
However if you want Test to accept different kinds of Base<T> you should declare your class like follow
class Test<T> {
    var base:Base<T>
    init(_ base: Base<T>) {
        self.base = base
    }
}

Test
Test<Base<Int>>(Base())

Please see the comment below by @sargeras for more ways to use my code.


text:
Q: ERROR string variable is receiving 0x603270 besides an alphabetic value When I type an text, like: "The quick brown fox.", as an input, the debugger shows the value from the variable text is: 0x603270 "The quick brown fox" and the type is an string.
Because of that when it start the for loop, the if statement ISALPHA recive this error: "Process received SIGSEGV: Segmentation fault".
code:
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>

int main (void)
{
    // ask the user input
    string text = get_string("Text: ");

    // take the text and count how many letters there is (uppercase and lower case)
    for (int i = 0; ;i++)
    {
        if(isalpha(text))
        {
            i++;
            return 0;
        }
        else if(isspace(text))
        {
            return 1;
        }
    }

some one can help me?
why it's showing 0x603270 ? before the correct input ?

A: The program crashes at
isalpha(test)

Cause you declared
string text

the parameter there is a pointer of type string. But isalpha only accepts an int parameter, so just write it as
isalpha(text[i])

Same for isspace.


text:
Q: Handling Spring/Tomcat initialization failures Currently, if the database of our Spring app hosted on Tomcat is unavailable, context initialization fails and all requests return a 404.
What would be a good way to overcome this problem? Instead of the app being unavailable until the next Tomcat, I would like it to show an error message to the user while unavailable and automatically recover when the database is available (like it would if a database failure occurs while Tomcat is already running).
I can set all beans to lazy-init, but I'm not sure that's the best solution? Can't Tomcat retry the initialization every x seconds/requests and show a decent error page in the meantime? Any ideas on this?
An example of the errors thrown on startup when the DB is unavailable:
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128)
at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy$LazyConnectionInvocationHandler.getTargetConnection(LazyConnectionDataSourceProxy.java:401)
at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy$LazyConnectionInvocationHandler.invoke(LazyConnectionDataSourceProxy.java:376)
at com.sun.proxy.$Proxy43.getMetaData(Unknown Source)
at com.googlecode.flyway.core.dbsupport.DbSupportFactory.getDatabaseProductName(DbSupportFactory.java:103)
... 67 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525)
... 72 more
Mar 28, 2013 11:19:47 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Mar 28, 2013 11:19:47 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors

A: From the exception stack trace I see that you are using c3p0 connection pool. Look at http://www.mchange.com/projects/c3p0/#configuring_recovery where you can configure your pool to retry for connection.
But this would keep the http thread active and imagine if you have high load your system will go down.
Its best to show an error page to the user. In this case i would show a 503 error. You can do this by putting Apache web server in front of your tomcat where you host the 503 page. There could be other ways to achieve this also.
Since your webapp itself will not start you cannot serve the error page from your webapp unless you configure it to be lazy init.
You can also try auto refresh on the error page every X seconds for the url user was trying to visit.


text:
Q: If conditional that expresses two of what you think will happen Is it okay? For example you are talking to someone sad, and you want him to wear a happy mask, you'd say

*

*If you wear this mask, you will seem like you're happy, but you're crying inside.

*If you wear this mask, it will silently kill you, but you'll still choose to hide.

In 1, I expect that he will seem like happy but will still be crying under the mask.
In 2, I expect that the mask will silently kill him eventually figuratively, but I also expect that he'll still choose to hide.
Are these grammatically correct? And did I punctuate them correctly? With commas before buts.

A: The sentences in quotation marks are grammatically correct, and it is fine to put a comma before the 'but' in those cases. However, the crying part may be unclear. It is fine in informal English, but if you want to make sure people understand that it is part of your prediction, then you might want to say "you'll be crying inside" instead.
There are slight grammatical mistakes in the rest of your post. Also, it is not very clear what you are asking. I hope I guessed right.


text:
Q: Position View on top of Drawable inside ImageView I have an ImageView like this:
        <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"/>

This stretches each image to maximum width or height, depending on drawable ratio of width and height.
ImageView takes the whole screen but actual Image doesn't. I would like to position a View on top of that ImageView. View should always be in right corner on top of drawable inside ImageView.
If I just put gravity to right for that View it will always be on the right side of ImageView but not on top of that drawable which is inside ImageView.
Any ideas? Thank you.

A: You can play with the sizes anyway you like, including using wrap_content, fill_parent and match_parent
<FrameLayout
    android:layout_width="96dp"
    android:layout_height="96dp">

    <ImageView
        android:layout_width="96dp"
        android:layout_height="96dp" />

    <ImageView
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="end|bottom"
        android:gravity="center|bottom" />

</FrameLayout>

A: You can display image on top right corner with below code...
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

      <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"/>

</RelativeLayout>


text:
Q: Make Post Api Call from HTML I want to make a post API call from a anchor HTML tag and URL will be included in the href.
How can i attach the body parameters.

And in this I want to send the body parameters in the call as well.
I want to find a way to include this in the html tag itself, not in the javascript file.
Help will be appreciated.

A: Links are designed to GET a URL. You cannot make a POST request directly with them.
Use a form with a submit button instead.

A: Thats what forms are for. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
Just create a form with a submit button. You can also specify if you want to open the requested URL in a new tab with the target attribute.

A: This is a way you could do it
 <form  method="POST" action="/api/PostFile">

</form>

A: there's only one way for you to POST data with a link... you would need to wrap the code in a <form> and use that link to submit the form, for example:
<form id="frm" ation="http:/test_url:5002/api/GetFile">
  <input type="hidden" name="param1" value="value_for_param1" />
  ...

  ...
</form>

any input can be used to append parameters to the <form>, as an example, the hidden is used
now, remember that you shouldn't use http:/test_url:5002 just minimize to /api/getfile or you would most likely get caught into CORS issues


text:
Q: How to get instance root volume id in CloudFormation template? Is there a way to get instance root volume id in CloudFormation template? Instance was created from AMI image. I want to specify volume id for Cloudwatch Alarm. Fn::GetAtt function can't return it, after reading documentation a lot i found only one way to do it: "custom resource", but it's too complicated.

A: You should try creating the volume first (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html) and then attaching it to /dev/sda1 (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html).
Although the doc doesn't rule this out, I'm not completely confident it will work. I assume you will at least need the right snapshot ID from the desired AMI.
If it happens to work, the example under the second link shows how to then reference and get the volume id. And to suggest an alternative, I do believe instance metrics provide aggregate IO for ephemeral disks (see EC2 under http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/ec2-metricscollected.html).
I realize you're not asking for ideas in reengineering your stack... but depending on what this disk IO actually represents, you might realize additional benefits by switching to instance store (free and very fast) or additional EBS (many down-the-road benefits when e.g. mounted for data directories for databases). Both of these would also solve your immediate problem.


text:
Q: How to read date values seperated with slash from csv files with pandas? Hello I want to read date values seperated with / in csv file and convert it datetime format in python. In this example my date values day/month/year/hour/minute/second under the Tarih column:

A: You may try this.
import datetime

# 1st argument: actual date
# 2nd argument: format of date
mDate = datetime.datetime.strptime("1/1/2012/1/1/1", "%d/%m/%Y/%H/%M/%S")
print(mDate)

A: I think need to_datetime with parameter format define in http://strftime.org/:
df['date'] = pd.to_datetime(df['Tarih'], format='%d/%m/%Y/%H/%M/%S')
print (df)
            Tarih          Veri                date
0  1/1/2012/1/1/1   6.028350798 2012-01-01 01:01:01
1  1/1/2012/1/1/2  7.072969987  2012-01-01 01:01:02
2  1/1/2012/1/1/3   1.76o4o2oes 2012-01-01 01:01:03
3  1/1/2012/1/1/4  -3.345437166 2012-01-01 01:01:04
4  1/1/2012/1/1/5  -5.209516549 2012-01-01 01:01:05
5  1/1/2012/1/1/6  -3.730161144 2012-01-01 01:01:06
6  1/1/2012/1/1/7  -10.80188385 2012-01-01 01:01:07


text:
Q: String with Variables Concatenation Issue #include<stdio.h>
int main() {
    char R_FPD[] = "+00393E33mm/go";
    char R_FPH[] = "+00393E33mm/go";
    char R_Vel[] = "+00393E33mm/go";
    char R_Tot[] = "+00393E33mm/go";
    char str_msg[] = "{"+"flow_rate_per_day"+":"+R_FPD+","+"flow_rate_per_hour"+":"+R_FPH+","+"velocity"+":"+R_Vel+","+"totalizer"+":"+R_Tot+"}";

    printf("%s", str_msg);

    return 0;
}

i want to make it like a json object but its not working

A: Arrays in C decay to pointers to their first elements and adding pointers is not defined in C standard.
The simplest way to concatenate string like this is using sprintf function. It works like printf but it prints into a C-string.
In your case the pattern could be following:
char str_msg[BIG_ENOUGH];
sprintf(str_msg, "{flow_rate_per_day:%s,flow_rate_per_hour:%s,velocity:%s,totalizer:%s}", R_FPD,R_FPH,R_Vel,R_Tot);

BIG_ENOUGH should be larger then the longest string that can be formed. 256 should be enough in your case.
Alternatively you can use asprintf function that will automatically allocated a buffer of the right size. Remember to use free when the buffer is no longer needed.
char *str_msg;
asprintf(&str_msg, "{flow_rate_per_day:%s,flow_rate_per_hour:%s,velocity:%s,totalizer:%s}", R_FPD,R_FPH,R_Vel,R_Tot);
... use str_msg

free(str_msg);


text:
Q: Include dygraphs for R in Jupyter I have an R notebook that I am trying to make into a Jupyter notebook using IRkernel, which I downloaded via Anaconda.
Everything works fine except when I try to use dygraphs, which just won't display the graph.
The only thing close to an answer I could find online is: https://doc.dataiku.com/dss/latest/R/dygraphs.html but I am not able to download the dataiku library for some reason.
I tried using conda install -c r r-dygraphs but it has made no difference.
On the dygraphs website they don't mention anything about using it in a Jupyter notebook so I'm not sure what to do. If it isn't supported on Jupyter, can someone point me to a close alternative to dygraphs that will work on Jupyter? The time series visualisation is really great on it which is why I want to implement it in my Jupyter notebook.
Thanks in advance!

A: If your error is something like:
ERROR while rich displaying an object: Error in file(file, "rb"): invalid 'description' argument

Then I think it's referring to not being able to plot the dygraphs in Jupyter. I would suggest checking out the "using" section on the documentation for R dygraphs. Although it doesn't strictly mention using dygraphs in Jupyter notebooks, it gives pointers for using them in R Console, R Markdown, and R Shiny. Lately I've been using them in an R shiny application and they've worked flawlessly, just as long as you set them up correctly. Also, just use:
install.packages('dygraphs')

in Jupyter notebooks to ensure successful installation and use. I've noticed that there are inconsistencies when running conda install commands (i.e. whether or not the package will end up working in Jupyter notebooks, RStudio, or both).

A: I think the problem is not in the install dygraphs, but it depends on jupyter notebook, this one can't appear dynamic graphic such as in RMarkdown.


text:
Q: Boot messages on both VGA and serial console I use RHEL6 (with GRUB and upstart from Ubuntu) and want to put boot messages on my normal VGA console as well on serial port.
I got GRUB to put messages on one of them, but not on both at same time.
Any suggestions?


text:
Q: std::move to a function I have this example code:
#include <iostream>

class Struct {
public:
   Struct() { std::cout << "0" << std::endl; }
   Struct(Struct&) { std::cout <<"1"<<std::endl;}
   Struct(const Struct&) { std::cout << "2" << std::endl; }
};

class Struct2 {
public:
    Struct s;

    Struct2() {}
    void setMember(const Struct& aux) { s = aux; }
};

int main()
{
    Struct s;
    Struct2 s2;
    s2.setMember(s);
}
// http://coliru.stacked-crooked.com/a/dd57e8af23f6db4b

Doubt 1:
It is printting two 0, because the constructor in the main and the construct of the member of Struct2.
The thing is, I was expecting three 0, because the "setMember" is receiving a copy of 's', right? What is happening then?
Doubt 2:
I was thinking in putting this:
s2.setMember(std::move(s));

As I won't use 's' again, but the setMember does not have '&&' specified, is it ok? Do i have to also do this? :
s = std::move(aux);

Or with just the main one is enough?
Doubt 3 :
std::vector<A> vectorA;

int main()
{
    A a;
    // modifies a ...
    vectorA.push_back(std::move(a));
}

Is it correct? Am I optimizing anything moving 'a'? It will not be used anymore and I want to keep it in the vector
Thanks

A:
because the "setMember" is receiving a copy of 's', right?

Well, no. It's receiving a const& and copies on assignment operator. Since you haven't overloaded the assignment operator, nothing is printed out.

s2.setMember(std::move(s));

This won't solve anything; std::move will just cast s to rvalue, but inside of the function it's still a const&.

Rule of thumb: pass-by-value, move out inside:
void setMember(Struct aux) { s = std::move(aux); }

That way it will "automagically" work; copying lvalues on interface / moving rvalues into the parameter value, and then moving the parameter value into the actual object member.
Of course to make optimal use of that machinery, you need an rvalue passed there, so...
Struct s;
Struct2 s2;
s2.setMember(std::move(s));

Or perhaps...
s2.setMember(Struct());

That being said, your old code won't break.

As for the third example, yes, this is OK, altough I'd probably either

*

*move the change to a to another function and push_back(function())

*move the changes to a to As constructor and use emplace_back


text:
Q: How to replace key string in dictionary with Python and regex? How to replace a key string extracting data from it using regex with Python, example :
{"root['toto']": {'new_value': 'abcdef', 'old_value': 'ghijk'}}

I'd like to replace root['toto'] with something easier to read, like toto and my object might have several key like this, that I'd like to extract inside root[''].

A: You could use the following regular expression:
mydict = {
    "root['toto']": {'new_value': 'abcdef', 'old_value': 'ghijk'},
    "test['aaa']": {'new_value': 'abcdef', 'old_value': 'ghijk'},
    "root['bb']": {'new_value': 'abcdef', 'old_value': 'ghijk'},
    "ccc": {'new_value': 'abcdef', 'old_value': 'ghijk'}
    }

for key, value in mydict.items():
    new_key = re.sub(r"(\w+\[')(\w+)('\])", r"\2", key)

    if new_key != key:
        mydict[new_key] = mydict.pop(key)  # Remove the old entry and add the entry back with new key

print mydict

Giving you an updated mydict containing:
{'aaa': {'new_value': 'abcdef', 'old_value': 'ghijk'},
'bb': {'new_value': 'abcdef', 'old_value': 'ghijk'},
'toto': {'new_value': 'abcdef', 'old_value': 'ghijk'},
'ccc': {'new_value': 'abcdef', 'old_value': 'ghijk'}}

A: If your key all have type 'root[*]', you can use :
newkey = oldkey.replace("['"," ").replace("']","").split()[1]

A: d={ k[6:-2] if k[:6]=="root['" else k :v for k,v in d.items() }

where d is your dictionary object
example
d={"root['abc']":2,'3':4}
d={ k[6:-2] if k[:6]=="root['" else k :v for k,v in d.items() }
print(d)

output
{'abc': 2, '3': 4}

explanation
we use dictionary comprehension to create a new dictionary.
breaking down the line:-
{                                    #Start dictionary construction
k[6:-2] if k[:6]=="root['" else k    # this is our new key
:                                    # key value separator
v                                    #Keep the same value as the old one.
for k,v in d.items()                 #Do this for all key,values in my old dictionary.
}                                    #End dictionary construction

without using dict comprehension
d={"root['abc']":2,'3':4}                 #d is our old dict
nd={}                                     #nd is new dict
for k,v in d.items():                     #iterating over each key,value k,v
  nk= k[6:-2] if k[:6]=="root['" else k   #nk is our new key
  nd[nk]=v                                #setting nk:v in nd
print(nd)                                 #print final dict

output
{'abc': 2, '3': 4}


text:
Q: Testing an AngularJS factory with Karma (Jasmine) I'm struggling with testing an AngularJS factory using Karma + Jasmine.
I am unable to inject my factory to OfficerValidationService variable.
What am i doing wrong?
Note: the file is loaded properly
Factory:
'use strict';

angular.module('darthvader').factory('OfficerValidationService', [function(){

  var OfficerValidationService = {};

  OfficerValidationService.something = function() {
    return true;
  };

  return OfficerValidationService;

}]);

Code:
'use strict';

(function() {
  describe('OfficerValidationService Spec', function() {

    var OfficerValidationService;

    beforeEach(function() {
      angular.module('darthvader');
    });

    beforeEach(module('darthvader', function($provide) {
      $provide.value('OfficerValidationService', OfficerValidationService);
    }));

    it('is very true', inject(function(OfficerValidationService){
      alert('=====' + OfficerValidationService + '=====');
      var output = OfficerValidationService.something();
      expect(output).toBeTruthy();
    }));

  });
}());

Output:
Running "karma:unit" (karma) task
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Mac OS X)]: Connected on socket yc_qTseOCArRtZLAXSTZ with id 97647403
ALERT: '=====undefined====='
PhantomJS 1.9.7 (Mac OS X) OfficerValidationService Spec is very true FAILED
    TypeError: 'undefined' is not an object (evaluating 'OfficerValidationService.something')
        at /Users/chuck/Desktop/sandbox/dashboard.darthvader/test/karma/unit/services/officerValidationService.js:25
        at invoke (/Users/chuck/Desktop/sandbox/dashboard.darthvader/public/lib/angular/angular.js:3917)
        at workFn (/Users/chuck/Desktop/sandbox/dashboard.darthvader/public/lib/angular-mocks/angular-mocks.js:2155)
    undefined
PhantomJS 1.9.7 (Mac OS X): Executed 28 of 28 (1 FAILED) (0.102 secs / 0.131 secs)

A: To add to martynas' answer, here is a simplified version:
module() is the shorthand of angular.mock.module
inject() is the shorthand of angular.mock.inject (same as $injector)
'use strict';

(function() {
  describe('OfficerValidationService Spec', function() {
    var OfficerValidationService;

    beforeEach(module('darthvader'));
    beforeEach(inject(function (OfficerValidationService) {
      OfficerValidationService = OfficerValidationService;
    }));

     it('OfficerValidationService should exist', function() {
        expect(OfficerValidationService).toBeTruthy();
    });

  });
}());

A: You need to call angular.injector:
'use strict';

(function() {
  describe('OfficerValidationService Spec', function() {

    var OfficerValidationService;

    beforeEach(function() {
      angular.module('darthvader');
    });

    beforeEach(inject(function() {
      var $injector = angular.injector(['darthvader']);
      OfficerValidationService = $injector.get('OfficerValidationService');
    }));

    it('is very true', function(){
      var output = OfficerValidationService.something();
      expect(output).toBeTruthy();
    });

  });
}());


text:
Q: How to disable automatic linting of imported classes from modules? In my project, I'm importing a series of different other modules/classes, for instance like this:
from my_project.filesystem import create_dir
from my_project.filesystem import file_size
from my_project.hashing import hash_from_file
from my_project.multiprocessing import max_workers_for
from my_project.multiprocessing import multiprocessing

When saving the file, Python extension automatically is linting those lines into:
from my_project.filesystem import create_dir, file_size
from my_project.hashing import hash_from_file
from my_project.multiprocessing import max_workers_for, multiprocessing

In settings, I have tried disabling auto linting:
{
    "python.linting.lintOnSave": false,
    "python.linting.enabled": false,
    "python.linting.pylintArgs": [
        "--disable=all"
    ]
}

For clarity, I prefer to have my imports separate, but now I'm faced with a daunting task to "fix the fix" before committing any changes.
Is there a way to disable this feature (bar disabling the whole extension, which works but removes other features of the extension which I'd prefer to continue using)?

A: I think that your imports get sorted by isort. You might be able to solve the issue by passing a custom argument to it. The "force_single_line" option mentioned here seems to be what you want. To pass this configuration option to isort, add the following line to your vs code config:
"python.sortImports.args": ["-sl"]
Let me know if that solves the issue.


text:
Q: dd is writing indefinitely until disk is full I want to dd my microSD card, 32 GB, on which I installed RasberryPiOS.
I plugged my 2TB SSD with 150GB space left, and send the following command:
sudo dd if=/dev/sda1 of=/media/pi/Samsung_T5/raspi2.sda1.img

But the process stops when raspi2.sda1.img is 149 GB.
How can it be? Since my microSD card is only 32GB, with 25GB free space left?
I also tried the following, overnight:
sudo dd if=/dev/sda1 | gzip -c >/media/pi/Samsung_T5/raspi2.sda1.img.gz

And this morning it was 70GB already!!
Also, I determined the partition name using parted, if that can be of any help to answer the question.
Thanks.


text:
Q: R: Centering a map in ggplot2 I would like to center the outline of Jersey in the middle of the bounding box (See attached image below)

This is what the shapefile looks like before using the coord_cartesian(xlim=c(200000.732,905000.646), ylim=c(-5812.321,900000.543))

Code is as follows:
graph1<-ggplot()+
  geom_polygon(data=middlestates,colour="black",fill="#D3D3D3",aes(x=long,y=lat,group=group))+
  geom_polygon(data=df,colour="black",aes(x=long,y=lat,group=group,fill=ALG))+
  ggtitle("Figure 2.2A: Assessment Results for\nGeneral Aquatic Life Use, Spatial Extent")+
  xlab("")+
  ylab("")+
  coord_cartesian(xlim=c(200000.732,905000.646), ylim=c(-5812.321,900000.543))+
  ggsn::scalebar(df,location="bottomleft",dist = 50,st.dist=0.02,st.size=3, height=0.01)+
  scale_fill_manual("Aquatic Life Designated\nUse 2014 Assessment",values=c((values=c(colors))))+
  cowplot::background_grid(major= "none",minor = "none") +
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(),
        axis.text.y = element_blank(), axis.ticks.y = element_blank(),
        axis.line = element_blank(),
        panel.background = element_blank(),
        legend.position=c(0.8,0.2),
        panel.border = element_rect(fill=NA),
        legend.background = element_blank(),
        legend.text = element_text(size=12),
        legend.title = element_text(colour="black", size=12, face="bold"),
        plot.title=element_text(size=15, face="bold",hjust=0.5))

pdf(file="Figure 2.2A.pdf",width=13,height=12,paper="a4")
north2(graph1, x = 0.10, y = 0.89, scale = 0.1, symbol = 3)
dev.off()

Is there anyway to do this without changing the
coord_cartesian(xlim=c(200000.732,905000.646), ylim=c(-5812.321,900000.543))

line??
I would like to keep the way the map looks.
Any help or feedback would be greatly appreciated! Thanks!

A: Here's a mockup of similar shapefiles. I'm using sf, because it's great for quickly filtering or analyzing spatial data, works like dplyr but for shapes, and because it plots easily with the newest version of ggplot2 (might need to use the github version). If your shapefiles are in Spatial* formats, you can use st_as_sf to create an sf object.
To get an sf of states and an sf of New Jersey towns, I used functions from tigris that download shapefiles from the Census. That was just the easiest way I had to get the shapefiles; you use whatever ones you're already working with.
I filtered the mid_sf object, which is an sf of the states in the region, for just New Jersey, then piped it into st_buffer to place a small buffer around it, then st_bbox to get its bounding box.
There are two plots: one without the coordinate limits set, and one with them set based on nj_bbox.
library(tidyverse)
library(sf)

us_sf <- tigris::states(class = "sf", cb = T)

mid_sf <- us_sf %>%
    filter(NAME %in% c("New York", "New Jersey", "Pennsylvania", "Connecticut", "Delaware", "Rhode Island", "Massachusetts", "Maryland", "Virginia", "West Virginia"))

nj_towns_sf <- tigris::county_subdivisions(state = "NJ", class = "sf", cb = T)

# dist is in degrees latitude & longitude
nj_bbox <- mid_sf %>%
    filter(NAME == "New Jersey") %>%
    st_buffer(dist = 0.15) %>%
    st_bbox()
#> Warning in st_buffer.sfc(st_geometry(x), dist, nQuadSegs): st_buffer does
#> not correctly buffer longitude/latitude data

nj_bbox
#>      xmin      ymin      xmax      ymax
#> -75.70961  38.77852 -73.74398  41.50742

nj_map <- ggplot() +
    geom_sf(data = mid_sf, color = "gray40", fill = "white", size = 0.5) +
    geom_sf(data = nj_towns_sf, color = "gray20", fill = "tomato", alpha = 0.7, size = 0.25)

nj_map

nj_map +
    coord_sf(ndiscr = 0, xlim = c(nj_bbox$xmin, nj_bbox$xmax), ylim = c(nj_bbox$ymin, nj_bbox$ymax))

Created on 2018-05-02 by the reprex package (v0.2.0).

A: I think it should be something like this.
library(ggplot2)
library(ggmap)
library(maps)
library(mapdata)

states <- map_data("state")
dim(states)
#> [1] 15537     6

head(states)

nj_df <- subset(states, region == "new jersey")
head(nj_df)

counties <- map_data("county")
nj_county <- subset(counties, region == "new jersey")
head(nj_county)

nj_base <- ggplot(data = nj_df, mapping = aes(x = long, y = lat, group = group)) +
  coord_fixed(1.3) +
  geom_polygon(color = "black", fill = "gray")
nj_base + theme_nothing()

bj_base + theme_nothing() +
  geom_polygon(data = nj_county, fill = NA, color = "white") +
  geom_polygon(color = "black", fill = NA)  # get the state border back on top


text:
Q: Automate Human Activity software Anyone know any softwares that can simulate human interaction on desktop browser specifically by clicking or entering some data and run some report and print automatically obviously with some programming behind this. Main, it will be used for reducing business process steps on human interaction day to day activity (possibly testing purpose in the future).
I am appreciated your comment or input.
Thanks

A: I tried a few different automation tools myself when trying to automate desktop software, one is AutoIt which is one of the most complete in my opinion. It helps to automate small tasks, ie: select a window and press a button to do the rest. It even has a macro recorder to get you started.

A: Telerik WebUI Test Studio
Watir
Selenium
...to name a few

A: To keep up with the namedropping, here's 2 APIs for Java:
Robot
Abbot (Built on top Robot)


text:
Q: Mean Squared error for complex Weibull Model Can anyone give me a hand here. I have been trying to solve this problem for weeks, but lead me no where. I want to find the roots of the following function
$f(d_1, d_2)=$$\sum_{i=0}^n{[P(e_i)-P_i^L]^2+[P(e_i)-P_i^u]^2}$$
Where:
$P(e_i)=\frac{1-e^-(\frac{a_i}{d_2})^d_1}{1-e^-(\frac{b}{d_2})^d_1}$
I can take the derivative of the function with respect to both d1 and d2 without any problem, but I don't know which kind of numerical method to apply. Can anyone point me in the right direction, please


text:
Q: no puedo comparar Estoy creando un código para "comparar" el nombre de unos medicamentos, pero no se bien los métodos dentro de los if  (en este caso son los métodos GetText y SetText), y no puedo arreglarlo.
Según vi, para variables tipo String debo usar el método .equals(), lo cual ya hice, al igual que los dos iguales para comparar (==), pero aún así no logro hacerlo funcionar
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class VentanaMedicamentos extends JFrame implements ActionListener{

    private Jlabel label1, label2, label3, label4;
    private JLabel labelNoHay;
    private JTextArea area1, area2, area3;
    private JButton boton1, boton2;
    Int medic;
    String med1, med2, med3;
    String descr1, descr2, descr3;
    JScrollPane scroll1, scroll2, scroll3;

    public VentanaMedicamentos(){
        setLayout(null);
        setTitle("Medicamentos");
        getContentPane().setBackground(new Color(0,0,255));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        VentanaUno mensajero = new VentanaUno();
        num_med = mensajero.medic;
        VentanaUno mensaje = new VentanaUno();
        med_1 = mensaje.med1;
        VentanaUno iris = new VentanaUno();
        med_2 = iris.med2;
        VentanaUno hermes = new VentanaUno();
        med_3 = hermes.med3;

        label1 = new JLabel ("hemos detectado " + num_med + " medicamentos" );
        label1.setBounds(50,50,300,50);
        label1.setFont(new Font("Calibri", 3, 16));
        label1.setForeground(new Color(0,0,0));
        add(label1);

        label2 = new JLabel (med_1);
        label2.setBounds(110,50,300,50);
        label2.setFont(new Font("Calibri", 3, 16));
        label2.setForeground(new Color(0,0,0));
        add(label2);

        label3 = new JLabel (med_2);
        label3.setBounds(300,50,300,50);
        label3.setFont(new Font("Calibri", 3, 16));
        label3.setForeground(new Color(0,0,0));
        add(label3);

        label4 = new JLabel (med_4);
        label4.setBounds(500,100,300,50);
        label4.setFont(new Font("Calibri", 3, 16));
        label4.setForeground(new Color(0,0,0));
        add(label4);

        area1 = new JTextArea (descr1);
        area1.setBounds(110,150,300,50);
        area1.setFont(new Font("Calibri", 3, 16));
        area1.setForeground(new Color(0,0,0));
        area1.setEditable(false);
        scroll1 = new JScrollPane(area1);
        add(scroll1);

        area2 = new JTextArea (descr2);
        area2.setBounds(300,150,300,50);
        area2.setFont(new Font("Calibri", 3, 16));
        area2.setForeground(new Color(0,0,0));
        area2.setEditable(false);
        scroll2 = new JScrollPane(area2);
        add(scroll2);

        area3 = new JTextArea (descr3);
        area3.setBounds(500,150,300,50);
        area3.setFont(new Font("Calibri", 3, 16));
        area3.setForeground(new Color(0,0,0));
        area3.setEditable(false);
        scroll3 = new JScrollPane(area3);
        add(scroll3);

        boton1 = new JButton("volver");
        boton1.setBounds(100,700,300,50);
        boton1.setBackground(new Color(255,0,0));
        boton1.setFont(new Font("Calibri", 3, 16));
        boton1.setForeground(new Color(255,255,255));
        boton1.setEnabled(true);
        boton1.addActionListener(this);
        add(boton1);

        boton2 = new JButton("continuar");
        boton2.setBounds(700,700,300,50);
        boton2.setBackground(new Color(255,0,0));
        boton2.setFont(new Font("Calibri", 3, 16));
        boton2.setForeground(new Color(255,255,255));
        boton2.setEnabled(true);
        boton2.addActionListener(this);
        add(boton2);

        labelNoHay = new JLabel ();
        labelNoHay.setBounds(700,1200,300,50);
        labelNoHay.setFont(new Font("Calibri", 3, 16));
        labelNoHay.setForeground(new Color(0,0,0));
        add(labelNoHay);

        if (label1.getText().equals(levotiroxina)){

            area1.setText();

        }if (label1.getText().equals(metformina)){

            area1.setText();

        }if (label1.getText().equals(enalapril)){

            area1.setText();

        }if (label1.getText().equals(aspirina)){

            area1.setText();

        }if (label1.getText().equals(amlodipino)){

            area1.setText();

        }if (label2.getText().equals(levotiroxina)){

            area2.setText();

        }if (label2.getText().equals(metformina)){

            area2.setText();

        }if (label2.getText().equals(enalapril)){

            area2.setText();

        }if (label2.getText().equals(aspirina)){

            area2.setText();

        }if (label2.getText().equals(amlodipino)){

            area2.setText();

        }if (label3.getText().equals(levotiroxina)){

            area3.setText();

        }if (label3.getText().equals(metformina)){

            area3.setText();

        }if (label3.getText().equals(enalapril)){

            area3.setText();

        }if (label3.getText().equals(aspirina)){

            area3.setText();

        }if (label3.getText().equals(aspirina)){

            area3.setText();

        }else{

            labelNoHay.setText("lo sentimos, hay un medicamento que aun no está en nuestro sistema");

        }
    }

    public void actionPerformed(ActionEvent e){

            if (e.getSource() == boton1){

                VentanaUno ventana1 = new VentanaUno();
                ventana1.setBounds(0,0,2000,2000);
                ventana1.setVisible(true);
                ventana1.setResizable(false);
                ventana1.setLocationRelativeTo(null);

            }if (e.getSource() == boton2) {

        }
    }
}

A: con el método equals de java debería bastar para comparar 2 String, por lo que te recomiendo validar los valores que se están ingresando por pantalla, como buena practica de programacion te recomiendo usar la contantes antes de la variables al comparar ejemplo.
if (aspirina.equals(label2.getText())){
  area2.setText();
}

por otra parte, tambien existe el metodo equalsIgnoreCase
El método equalsIgnoreCase () compara dos cadenas independientemente del caso (lower or upper) de la cadena. Este método devuelve verdadero si el argumento no es nulo y representa un caso de ignorar String equivalente, de lo contrario es falso.
saludos.

A: Creo que hubiera sido más fácil con switch:
String medicamento=label1.getText();

if(medicamento.equals(""))
{
  JOptionPane.showMessageDialog(null,"lo sentimos, hay un medicamento que aun no está en nuestro sistema");
} else {
switch(medicamento)
          {
           case "levotiroxina": area1.setText(); break;
             .
             .
             .
           case N : area1.setText(); break;
          }
      }


text:
Q: How to add vertical scroll in HTML DataList tag I have a datalist with lot of option, The list goes too long I want to give it vertical scroll.
<input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
<option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
<option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>

Here the demo Problem
FIDDLE

A: Unfortunately, there's not much you can do with the datalist attribute. The datalist does not currently support any CSS styling, and specific visual characteristics are browser-specific. Some browsers may choose to add scrollbars for long lists.
If this isn't acceptable, you may have to forget the datalist and implement a dropdownlist and set the list size as per your needs.


text:
Q: Converting std::string to const char*, getting errors #include <iostream>
#include <sstream>

template <typename T>
const char* numberToString(T number) {
    std::ostringstream ss;
    ss << number;
    return ss.c_str();
}

int main() {
    printf(numberToString(123));
    return 0;
}

My error:
1>d:\programming\euler\problem 4\problem 4\problem 4\source.cpp(8): error C2039: 'c_str' : is not a member of 'std::basic_ostringstream<char,std::char_traits<char>,std::allocator<char>>'
1>          d:\programming\euler\problem 4\problem 4\problem 4\source.cpp(26) : see reference to function template instantiation 'const char *numberToString<int>(T)' being compiled
1>          with
1>          [
1>              T=int
1>          ]

Why doesn't this work?

A: c_str is a member of std::string, not ostringstream. If you want to get a string out of the stream, use str(). Note, however, that returning a const char* from that string is wrong - the string will go out of scope before you can use the const char*. Therefore, have your function return a string (or have it get a buffer to write to):
template <typename T>
std::string numberToString(T number) {
    std::ostringstream ss;
    ss << number;
    return ss.str();
}

A: c_str() does not exist for std::ostringstream.  What you meant was:
template <typename T>
const char* numberToString(T number)
{
    std::ostringstream ss;
    ss << number;
    return ss.str().c_str();
}

After you make that change, you will have another problem:  you will be returning a pointer to a buffer that was just destroyed.  To fix that, you should return a std::string:
template <typename T>
std::string numberToString(T number)
{
    std::ostringstream ss;
    ss << number;
    return ss.str();
}

Which you can do with std::to_string already, so it is really pointless to write your own function.

A: That's because c_str() is the member function of std::string which returns a const char*.
To get the underlying string of  a strinstream, you must use str().
The error was pretty much self explanatory:

error C2039: 'c_str' : is not a member of 'std::basic_ostringstream

Note however that you're returning a pointer to something (the underlying data of the temporary string returned by str()) that will not exist after the return statement (i.e. in the calling code) and that manipulating that pointer will quite sureley end up in undefined behavior.
As you are in C++, you could rather return the std::string directly, and output it with
std::cout << numberToString(123);

which would be safer.

A: You want to do:
template <typename T>
std::string numberToString(T number) {
    std::ostringstream ss;
    ss << number;
    return ss.str();
}

int main() {
    std::cout << numberToString(123);
    return 0;
}

To get the underlying std::string in std::ostringstream, and then the resulting c-style string in std::string. As others have pointed out, the pointer returned by c_str goes out of scope, and therefore you must copy it to a buffer or to another std::string. If you insist on using printf, then use c_str on the function call:
printf("%s", numberToString(123).c_str());

For more information, see Is it a good idea to return " const char * " from a function?

Depending on what somestlstring is and what is being done there.
If it is a local variable you are returning a pointer into memory that
  is being released when GetSomeString completes, so it is a dangling
  pointer and an error.
It all boils down to the lifetime of somestlstring and the operations
  you perform on it. The pointer returned by .c_str() is guaranteed to
  be valid only up to the next mutating operation in the string. So if
  something changes somestlstring from the call to .c_str() and before s
  is constructed you will be in undefined behavior land.

However, you can simply use std::to_string.
std::string s = std::to_string(123);


text:
Q: Size of divs in HTML I want to reduce the size of these divs so that every row contain 3 cards at most. As I change the measurements in the CSS, it gets smaller and smaller. PS I'm not allowed to use Bootstrap! I tried using different measurements and also the grid feature but it was of no help.
This is the screenshot of the divs on my website

.locations .box-container {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  grid-template-rows: auto;
}

.locations .box-container .box {
  overflow: hidden;
  box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.1);
  border: 1rem solid #fff;
  border-radius: 0.5rem;
  flex: 1 1 30rem;
  height: 25rem;
  position: relative;
}

.locations .box-container .box img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

.locations .box-container .box .card-body {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  text-align: center;
  background: rgba(0, 0, 0, 0.7);
  padding: 2rem;
  padding-top: 5rem;
}

.locations .box-container .box .card-body .card-btn {
  display: inline-block;
  margin-top: 1rem;
  background: orange;
  color: #fff;
  padding: 0.8rem 3rem;
  border: 0.2rem solid orange;
  cursor: pointer;
  font-size: 1.7rem;
}

.locations .box-container .box .card-body .card-btn:hover {
  border: 2px solid orange;
  color: orange;
  background: transparent;
  transition: 0.4s ease;
}

.locations .box-container .box .card-body .card-btn:focus {
  outline: none;
}

.locations .box-container .box .card-body h5 {
  font-size: 2.5rem;
  color: orange;
}

.locations .box-container .box .card-body p {
  font-size: 1.5rem;
  color: #eee;
  padding: 0.5rem 0;
}

Locations

"Adventure is out there."

Murree

Some quick example text to build on the card title and make up the bulk of the card's content.

          View

A: I simplified your HTML and CSS a bit, but this solution should work. This will give you 3 cards per row, and will fill the rows below it. I removed some of your styling for brevity, so you'll need to add that back, but this should give you the structure you need.

.locations .box-container
{
  display: flex;
  flex-wrap: wrap;
}

.locations .box-container .box
{
  overflow: hidden;
  box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.1);
  border: 1rem solid #fff;
  border-radius: 0.5rem;
  height: 25rem;
  flex: 1 0 25%;
  margin: 0.5rem;
  box-sizing: border-box;
}

.locations .box-container .box .card
{
  height: 100%;
  width: 100%;
  text-align: center;
  background: rgba(0, 0, 0, 0.7);
  padding: 2rem;
}

.locations .box-container .card h5
{
  font-size: 2.5rem;
  color: orange;
}

.locations .box-container .card p
{
  font-size: 1.5rem;
  color: #eee;
  padding: 0.5rem 0;
}

.locations .box-container .card a
{
  display: inline-block;
  margin-top: 1rem;
  background: orange;
  color: #fff;
  padding: 0.8rem 3rem;
  border: 0.2rem solid orange;
  cursor: pointer;
  font-size: 1.7rem;
}

Title

Card content.

      View

Title

Card content.

      View

Title

Card content.

      View

Title

Card content.

      View

Title

Card content.

      View


text:
Q: using packagemaker on mac os i want to make the installation package on the mac os of my java application using the package maker. is there any one having the link that will show step by step guidance for performing this.

A: See Java Deployment Options for Mac OS X on the Apple Developer site. Here's an ant build.xml file with targets to compose a Mac application bundle and create a .dmg disk image. Alternatively, consider using Java Web Start, also supported by that project.


text:
Q: How to Change the code from For Loops to FoldLeft,Fold or FoldRight on Data frames in Scala I'm trying to Compare two datasets(DS1 and DS2). So, I got them pulled into two dataframes and now I want to compare each and every Column of (DS1) with each and every Column of DS2.
Before comparing each and every record from each column, I would like to reduce my data by performing GroupBy, so I can decrease the number of records to compare.
I will pass this records to compare from both datasets to my Algorithm which will return a score back.
I did it using for loops, the results are good, but it is taking a lot of time.
Below is my code using 4 nested for Loops,
// StringDS1 and StringDS2 are Dataframes
var s1= stringDS1.columns
var s2= stringDS2.columns
var contentString = ofDim[Double](s1.size,s2.size)
var ds1StringCount = stringDS1.count()
var ds2StringCount = stringDS2.count()
for (i <- 0 to s1.size-1) {
  println("entered 1st for Loop")
  var ds1s =stringDS1.groupBy(s1(i)).count() // GroupBy of every column before comparing on DS1
  ds1s.show()
  for(j <- 0 to s2.size-1) {
    var totalScore:Double=0
    println("entered 2nd for loop")
    var ds2s = stringDS2.groupBy(s2(j)).count() //GroupBy of every column before comparing on DS1
    ds2s.show()
    var score = new Array[Double](ds2s.count().toInt)
    var maxScore = new Array[Double](ds1s.count().toInt)
    var m:Int=0
    for(row <- ds1s.rdd.collect()) {

      println("entered 3rd for loop")
      var key1 = row(0).toString
      var value1 = row(1).toString
      println("Key1 is " + key1 + " value is " + value1)
      var s = 0 //Score Array iterator
      for (row <- ds2s.rdd.collect()) {
        println("entered 4th for loop")

        var key2 = row(0).toString
        var value2 = row(1).toString
        println(" key2 is " + key2 + "value 2 is " + value2)
        //println(ds1StringCount + " " + ds2StringCount)
        println("size is " + score.size)
        score(s) = contentAlgoString(key1, key2, value1, value2)  // ContentAlgoString is the Method for the Algorithm where it
                                              // returns a score and that score is stored in an array
        s = s + 1
      } // Loop for k1 -> k2

      maxScore(m) = score.max        // maxScore(m) is an array that stores the max value from the Score Array
      println("Max Score is " + maxScore(m))
      totalScore = totalScore + (maxScore(m) * (value1.toDouble / ds1StringCount.toDouble))
      println("Total Score is " + totalScore)
      m = m + 1

    } // loop for all k1's -> all k2's

    contentString(i)(j)= totalScore  // Total Score is stored in this Array
  }
}

By removing "FOR Loops" and using "Foldleft" instead can I optimize my code and retrieve faster results.
Is there any other approach other than folds to improve my results or get faster results.
Any help is appreciated.


text:
Q: Application Updating Error I Upload A New Version Android App in Google Play store , But Not successfully , I See Error , That Error is Bellow , Please Help Me ?
Upload failed
You uploaded an APK that is signed with a different certificate to your previous APKs. You must use the same certificate. Your existing APKs are signed with the certificate(s) with fingerprint(s):
[ SHA1: 27:7C:DC:76:0B:18:AE:F8:30:3A:48:CA:08:9C:6B:23:44:E6:E4:D2 ]
and the certificate(s) used to sign the APK you uploaded have fingerprint(s):
[ SHA1: 1B:93:3C:5E:55:F5:41:15:8D:64:CC:18:48:0C:A8:4D:7B:47:1B:FD ]

A: You have to use the same keystore to sign your APK that you used to sign in the first time


text:
Q: Where can I configure "erase mac" iCloud offers the service to remotely wipe (erase) a mac, as you can remotely erase an iPhone.
Where can I change this setting, e.g. disable it?

A: The Find My Mac feature can be enabled and disabled in the iCloud settings (System Preferences → iCloud)

You cannot disable just the "erase" feature: the locate, lock and erase features must be managed as a single option.


text:
Q: Django Social Auth - Google: AttributeError: 'NoneType' object has no attribute 'provider' I am receiving this error when trying to login via google, I've tried just about everything I can think of and similar issues on SO don't seem to help. I have a custom user model setup as such:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class Departments(models.Model):
    name = models.CharField(max_length=255, unique=True)
    def __str__(self):
        return self.name

class AlluredUser(AbstractUser):
    departments = models.ManyToManyField(Departments)
    def __str__(self):
        return self.username

forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import AlluredUser

class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = AlluredUser
        fields = ('username', 'email')

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = AlluredUser
        fields = ('username', 'email')

Social Auth Pipeline
SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.social_auth.associate_by_email',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details'
)

Error Traceback
AttributeError at /auth/complete/google-oauth2/
'NoneType' object has no attribute 'provider'

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/auth/complete/google-oauth2/?state=8XLcbxz6sPSPOwJfOIXWOud88UJ5YtL2&code=4/twHRVLHTMzBV99K-VvektvJfjGuJYGBvqi254dWTuA2dLmbNFw3fIp8l5pdYSqKK89ONPGrxInG39pH8Wf-fpas&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20openid&authuser=0&hd=allured.com&session_state=2403f8348307b18b8ab460026d3c88b1b18d759f..5dbb&prompt=none

Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['user.apps.UserConfig',
 'issue_tracker.apps.IssueTrackerConfig',
 'ytd_reports.apps.YtdReportsConfig',
 'stats.apps.StatsConfig',
 'scheduler.apps.SchedulerConfig',
 'submissions.apps.SubmissionsConfig',
 'dash_app.apps.DashAppConfig',
 'contact.apps.ContactConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.humanize',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'social_django']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'social_django.middleware.SocialAuthExceptionMiddleware',
 'dashboard.middleware.loginRequired.LoginRequiredMiddleware']

Traceback:

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\utils.py" in wrapper
  49.             return func(request, backend, *args, **kwargs)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\views.py" in complete
  33.                        *args, **kwargs)

File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_core\actions.py" in do_complete
  71.                                          social_user.provider)

Exception Type: AttributeError at /auth/complete/google-oauth2/
Exception Value: 'NoneType' object has no attribute 'provider'

I'm guessing it has something to do with the custom user model I created since I didn't have this problem beforehand. Any help would be much appreciated.

A: The error on the link doesn't match what you mention in the title.
For the traceback, the solution is just to add this:
SESSION_COOKIE_SECURE = False


text:
Q: Vim imaps stopped working on Mac? I was using an older version of vim on Windows, then I switched to a Mac computer and MacVim and brought over my imap files and vimrc, but the imaps no longer work. When I open a file it gives me an "Error detected while processing .. etc. ftplugins/html_imaps.vim" for example:
line    1:
E15: Invalid expression: ";"^M

The line in question in the imap file says:
let maplocalleader=";"

Is there a reason this doesn't work anymore? It was also giving me an error on each empty line. I deleted the empty lines so those errors went away, but I haven't been able to do anything about maplocalleader line.
Thanks for any suggestions.

A: Because your .vimrc file came from a Windows machine, it has \r\n line endings, so you need to get rid of the \r (which shows up as ^M). It looks like my Mac doesn't have dos2unix, so you'll probably want to just use tr:
tr -d '\r' <~/.vimrc >tmp
mv tmp ~/.vimrc

Or from within vim itself:
:%s/\r//g

On the off-chance you have \rs you actually want to keep,
:%s/\r$

With the implied //


text:
Q: Why does `clear` create that much whitespace on top in the macOS Terminal.app? I was wondering about the functionality of the clear (https://invisible-island.net/ncurses/man/clear.1.html) command, that I can evoke with CtrlL in my Terminal.app on macOS.
When executed, it should move my cursor to the top of the screen - what it does. That's great.
But it has a side effect as well: It creates a whole lot of white space (depending on the screen size) on top of the command.
For example look at this command line history:
➜  ~ some command
command
output
➜  ~ clear

➜  ~ # the input line is now on top; but there is a lot of whitespace in the history as well

This is kind of bloating my command line history, when I scroll back. So I'm wondering, why is this white-space on top created?


text:
Q: Как ускорить поиск совпадений в DOM элементе через цикл? Есть ниже упрощенный пример, в реальности рабочий код сложнее и скорость сильно медленей.
Без прерывания цикла!
Можно ли как то его ускорить?

let html = '';
for (let i = 0; i < 100000; i++) {
  html += `<div class="item">${i}</div>`;
}
document.querySelector('.content').innerHTML = html;

function search(e) {
  const start = new Date().getTime();
  document.querySelectorAll('.item').forEach(e => e.classList.remove('active'));
  let value = e.target.value.toUpperCase().trim();
  if (value) {
    document.querySelectorAll('.item').forEach(item => {
      if (item.innerText === value) {
        item.classList.add('active');
      }
    });
  }
  console.log(`Go: ${new Date().getTime() - start}ms`);
}

document.querySelector('[name="search"]').addEventListener('keyup', e => {
  search(e)
});
.content .item {
  display: none;
}

.content .item.active {
  display: block;
}
<input name="search">

A:

let html = '';
for (let i = 0; i < 100000; i++) {
  html += `<div class="item">${i}</div>`;
}
document.querySelector('.content').innerHTML = html;

const lookup = {};
document.querySelectorAll('.content .item').forEach(i => {
  (lookup[i.textContent] || (lookup[i.textContent] = [])).push(i);
});

function search(e) {
  const start = new Date().getTime();
  document.querySelectorAll('.content .item.active').forEach(e => e.classList.remove('active'));
  let value = e.target.value.toUpperCase().trim();
  if (value && lookup[value]) {
    lookup[value].forEach(i => i.classList.add('active'));
  }
  console.log(`Go: ${new Date().getTime() - start}ms`);
}

document.querySelector('[name="search"]').addEventListener('keyup', search);
.content .item {
  display: none;
}
.content .item.active {
  display: block;
}
<input name="search">

A: Основная проблема вашего кода - два одинаковых цикла. Так как циклы повторяются, то гораздо проще вынести все условия в один цикл. А в теле этого цикла через условие проверить все необходимые данные.

let html = '';
for (let i = 0; i < 100000; i++) {
  html += `<div class="item">${i}</div>`;
}
document.querySelector('.content').innerHTML = html;

function search(e) {
  const start = new Date().getTime();
  document.querySelectorAll('.item').forEach(e => {

    let value = e.target?.value?.toUpperCase()?.trim();
    if (value && e.innerText === value) {
      e.classList.add('active');
    } else {
      e.classList.remove('active');
    };

  });

  console.log(`Go: ${new Date().getTime() - start}ms`);
}

document.querySelector('[name="search"]').addEventListener('keyup', e => {
  search(e)
});
.content .item {
  display: none;
}

.content .item.active {
  display: block;
}
<input name="search">


text:
Q: Can a Solenoid be driven from one of the pins of a Servo controller? Would it be possible to operate a solenoid (e.g. this Plastic Water Solenoid Valve - 12V - 1/2" Nominal, suggested for use with "a TIP120 or N-Channel power FET with a 1N4001 kickback diode to drive from a microcontroller pin.") from one of the pins of a Servo Controller (e.g. this Pololu Micro Maestro 6-channel USB Servo Controller)?

Or am I overthinking it- for my solenoid ought I just use whatever relay I need on top of a simple breakout board such as this:

A: Go for the simple relay control. Try this one from the same site you linked to:
http://www.robotshop.com/en/devantech-2-channel-usb-relay.html
The servo driver ouputs a pulse train to control the servo position. Seems like an overcomplicated way of doing things by modifying it as an on/off controller.


text:
Q: Creating dynamic documents in Flask-MongoAlchemy I'm using Flask-MongoAlchemy for a personal project. I have some .cfg input files that I want to parse and make into mongodb document entries. Unfortunately, the .cfg files are flat and I want to make multiple different documents from each file. I'd like to define the structure I want to use in one place (in a separate .cfg file) and 1) convert the input files into this format while parsing it, and 2) create the MongoAlchemy document classes using this structure. I'm only having troubles with #2, but I am open to alternative implementations that solve both goals.
Here's my input .cfg file. I'd like to make this into multiple mongodb documents.
[foo]
a = val1
b = val2
c = val3
d = val4

Here's documents.cfg that defines the structure. The values are numbers to distinguish types.
[foo]
    [[bar]]
    a = 1
    b = 1
    [[baz]]
    c = 2
    d = 1

Here are the class definitions
class Bar(db.Document):
    # add class attributes from kwargs
    @classmethod
    def init(cls, **kwargs):
        for k, v in kwargs.items():
            if v == 1:
                setattr(cls, k, db.IntField(min_value=0))

class Baz(db.Document):
    # add class attributes from kwargs
    @classmethod
    def init(cls, **kwargs):
        for k, v in kwargs.items():
            if v == 1:
                setattr(cls, k, db.IntField(min_value=0))
            elif v == 2:
                setattr(cls, k, db.StringField())

I parse documents.cfg to create two dicts:
bar_dict = {'a': '1', 'b': '1'}
baz_dict = {'c': '2', 'd': '1'}

I then pass these to the respective init() methods
Bar.init(**bar_dict)
Baz.init(**baz_dict)

This successfully adds the attributes. However, when creating an instance of Bar (or Baz) I get this error.
mongoalchemy.exceptions.ExtraValueException: a

My guess is that this has to do with the fact that the MongoAlchemy fields should be class attributes, not instance attributes. Any help?

A: class Bar(db.Document):
    config_extra_fields = 'ignore'
    ...

class Baz(db.Document):
    config_extra_fields = 'ignore'
    ...


text:
Q: Magento 2 : Get values defined in env.php into script Is their any way we can get env variables values in custom script ?

A: Have a look at \Magento\Framework\App\DeploymentConfig:
Inject a deployment config object of \Magento\Framework\App\DeploymentConfig in your code and then retrieve the value like this:
$deploymentConfig->get('db/connection/default/host');

For Example:
$deploymentConfig->get('your/custom/value');

Courtesy: Magento 2. Retrieve information from env.php programmatically


text:
Q: How to convert CAML query results to JSON with JSOM without looping Below JSOM code is iterating through sharepoint list items. This will not be efficient if the CAML query results are in thousands. Is there any way to convert the query results directly into JSON without looping and REST queries.
while (listItemEnumerator.moveNext())
{
  var oListItem = listItemEnumerator.get_current();
  listItemInfo += '\nID: ' + oListItem.get_id() +
             '\nTitle: ' + oListItem.get_item('Title') +
             '\nDLastName: ' + oListItem.get_item('DLastName') +
             '\nDLastName: ' + oListItem.get_item('DLastName');
}

A: Umh, afaik that's not possible. I don't know your reasons for why you can't use REST, but you could try looking into the onExecutingWebRequest etc on the SP.ClientContext object and abort the initial request, and then do your own request with the payload JSOM have generated. Never used it like that myself, but I have a simple example of what I'm talking about that you could play around with:
(function() {

    var ctx = SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getByTitle("ListTitle");
    var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
    ctx.load(items, "Include(ID, Title)");

    // abort the request
    ctx.set_requestTimeout(1);

    ctx.onExecutingWebRequest = function(webRequest,e) {
        console.log(webRequest)
        var waitForExecutor = setInterval(function() {
            if(typeof  webRequest.get_webRequest() != null) {
                clearInterval(waitForExecutor);

                 $.ajax({
                    url: webRequest.get_webRequest().get_url(),
                    data: webRequest.get_webRequest().get_body(),
                    type: "POST",
                    headers: {
                        "Content-Type": webRequest.get_webRequest().get_headers()["Content-Type"],
                        "X-RequestDigest": webRequest.get_webRequest().get_headers()["X-RequestDigest"]
                    },
                    success: function(data) {
                        console.log(data)
                        if(data.length) {
                            var collection = data.filter(function(item) {
                                if(item._ObjectType_ === "SP.ListItemCollection") {
                                    return item._Child_Items_;
                                }
                            });
                            if(collection.length) {
                                var json = JSON.stringify(collection[0]._Child_Items_);
                                console.log(json);
                            }
                        }
                    },
                    error: function(err) {
                        console.log("ERR")
                    }
                });
            }
        },10);

    }

    ctx.executeQueryAsync( function() {
        console.log("Should not enter this function")
    }, function(s,a) {
        console.log("Should enter if aborted");
        console.log(a.get_message())
    });

})();


text:
Q: Passing Stack to Function So I'm playing around with stacks and I've filled one in my main function, but now I want to pass it to my other functions so I can traverse through it. I'm not sure what kind of data type to put into the prototype though so that it accepts it. Suggestions? Here's what I have:
Main.cpp
#include <iostream>
using namespace std;
#include "stack.h"

void displayStack(char &stackRef);

int main()
{
    Stack<char> stack;
    stack.push('a');
    stack.push('b');
    stack.push('c');

    return 0;
};

void displayStack(char starRef)
{
    // Cannot Get here - Errors!
};

It's telling me I have too many arguments and it doesn't match argument list.

A: This should suffice:
void displayStack(const Stack<char>& stack);

A: The name DisplayStack indicates that the function only displays the stack, not changing it in any way. So then the argument can be a reference to const. However, the suffix Stack in the name is redundant since it is implied by the argument, so I'd do it like this:
#include <iostream>
using namespace std;
#include "stack.h"

typedef Stack< char > CharStack;

void display( CharStack const& stack )
{
    // ... Display the stack
}

int main()
{
    CharStack stack;

    for( auto const ch : { 'a', 'b', 'c' } )
    {
        stack.push( ch );
    }
    display( stack );
}

Note that …

*

*The function has been moved above main. No silly pure declaration required then, less work. DRY: Don't Repeat Yourself.

*Incorrect semicolons after the function definitions, have been removed. Well, at least I think they're incorrect. Whether they are or not, they're totally superfluous.

*Superfluous return 0; in main has been removed, because that is the default. However, some programmers prefer to have it explicit.
On the downside, while the C++11 loop compiles nicely with g++ 4.7.2, it causes an Internal Compiler Error (ICE) with Visual C++ 11.0:

[d:\dev\test]
> cl foo.cpp
foo.cpp
foo.cpp(7) : warning C4100: 'stack' : unreferenced formal parameter
foo.cpp(16) : error C2059: syntax error : '{'
foo.cpp(16) : error C2143: syntax error : missing ';' before '}'
c1xx : fatal error C1063: INTERNAL COMPILER ERROR
         Please choose the Technical Support command on the Visual C++
         Help menu, or open the Technical Support help file for more information

[d:\dev\test]
> _

Oh well.
Do that your way. ;-)
Compiler bug reported to Microsoft.

A: If you do not want to modify contents of the stack inside the function:
void displayStack(const Stack<char> &starRef)

If you want to modify the contents of the stack inside the function:
void displayStack(Stack<char> &starRef)

Points to note:

*

*The type of the variable being passed must be the type you mention in function prototype.

*In C/C++, by default all arguments to function are passed by copy, i.e: A copy of the argument rather than the argument itself is passed to the function. The overhead is the copy. You pass by reference to avoid overhead of a copy of variable being passed.

*You use const qualifier on the argument if you want the passed variable to be immutable in the function.

A: Change your displayStack function to:
void displayStack(Stack<char> &stackRef)