text:
Q: Use regex to match only sequential (but not necessarily consecutive) matches I'm trying to match a regex with a string as long as possible. This is the string to look in:
"xxaxxbxxbxbxxbxxbxxbxxdxx"

The pattern to match is:
"bcda"

The pattern is to be interpreted as follows:

*

*b: There are several of them in the string. The first one should match.

*c: There isn't one in the string, so nothing is returned.

*d: There is just one near the end of the string. It should be returned.

*a: There is one at the beginning of the string. Since b, c, and d were sought first and results are returned, a will not be returned.

The expected return is:
"bd"

It may be that regex match is not the correct way to accomplish this, but I'd like to ask for assistance with one. The basic question is this: can I use regex to generically find a substring that represents as much of a an ordered, but not necessarily consecutive, sequence of candidate characters as it possibly can? If so, how?

A: As @sawa explained, you cannot do this with a single regex. Here is a recursive solution.
def consecutive_matches(str, pattern)
  return '' if str.empty? || pattern.empty?
  ch, pat = pattern[0], pattern[1..-1]
  i = str.index(ch)
  if i
    ch + consecutive_matches(str[i+1..-1], pat)
  else
    consecutive_matches(str, pat)
  end
end

str = "xxaxxbxxbxbxxbxxbxxbxxdxx"

consecutive_matches(str, "bcda") #=> "bd"
consecutive_matches(str, "abcd") #=> "abd"
consecutive_matches(str, "dabc") #=> "d"
consecutive_matches(str, "cfgh") #=> ""

A: It is impossible to do that with a single regex match. A capture in a regex must be a substring of the original string. bd here is not, so there is no way to match that as a single capture.


text:
Q: Force exerted by a charged ball on another one Consider two charged balls in space with radii $R_A$ and $R_B$, and total charge $Q_A$ and $Q_B=\rho_B\space V_B$. They are separated by a distance $D = \|\overrightarrow{AB}\|\geq R_A + R_B$.
I was wondering if it was possible to determine the force exerted by one ball on the other, e.g. $\overrightarrow{F}_{A\to B}$.
First I wasn't sure if it is possible to say that $\overrightarrow{dF}_{A\to B}=Q_B\space dV\space\overrightarrow{E}_A$ where $dV=r^2\space \sin{\theta}\space d\phi\space d\theta\space dr$. Then, if this is correct, it leads to
$$\overrightarrow{F}_{A\to B}=\frac{\rho_B\space Q_A}{4\space\pi\space\epsilon_0}\iiint_{V_B}\frac{\overrightarrow{AM}}{\|\overrightarrow{AM}\|^3}dV$$
Is it possible to "calculate" this integral in the general case or is it impossible? Thanks in advance

A:
I wasn't sure if it is possible to say that $\overrightarrow{dF_{A\to B}}=Q_B\space dV\space\overrightarrow{E_A}$

It isn't. This is dimensionally inconsistent: the left side has the dimensions of force but the right side has the dimensions of force times volume. The $Q_B$ should be $\rho_B$. You also don't know what $\overrightarrow{E_A}$ is without integrating over all the charges in ball $A$.
However, you are thinking in the right direction. You can write the force between two extended objects as a six-dimensional integral that sums up the infinitesimal forces between each infinitesimal element of charge in one body and each infinitesimal element of charge in the other body. For two spherically-symmetric balls this integral is doable analytically but rather messy. (Try it numerically! Then try it for cubes instead of balls.)
An equivalent two-part approach like what you were attempting is to consider one body, do a three-dimensional integral to compute its field everywhere, and another three-dimensional integral to compute the force that this field exerts on all the charges in the other body.
But, in general, it is easier to work with integrals for potential energy or potential, because these involve scalars rather than vectors. For example, you can compute the potential inside and outside a spherical shell of uniform surface charge density by doing a fairly easy integral. Once you know this potential, another easy integral gives you the potential energy of two shells. From this you can derive the potential energy for two spherically-symmetric balls, by considering the balls to be made up of concentric shells. From the potential energy, you can derive the force between the balls.
And, lo and behold, if the balls don't interpenetrate, the result will be that the spherically-symmetric balls behave as if they were simply point charges at their centers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing that a map on a tubular neighbourhood is a diffeomorphism Let $S$ be an embedded submanifold of a smooth manifold $M$. Then there exists a tubular neighbourhood $U$ of $S$ in $M$, that is, $U$ is the diffeomorphic image of $\exp$ restricted to the normal bundle $NS$ of $S$ of a subset $V \subseteq \mathcal{E} \cap NS$, where $\mathcal{E} \subseteq TM$ is the domain of the exponential map, of the form $$V = \{(x,v) \in NS : |v| < \delta(x)\}$$ for some positive continuous function $\delta : S \to \mathbb{R}$.
Let $0 \leq t \leq 1$. Then we can define $\psi_t : U \to U$ by $$\psi_t(\exp(x,v)) := \exp(x,tv).$$
Now the book Introduction to Symplectic Topology by McDuff and Salamon claims that this map is a diffeomorphism for $t > 0$. I do not quite see why. I mean, this map is injective and smooth, but I fail to see surjectivity or the explicit form of an inverse. Moreover, I guess that this map is a local diffeomorphism by considering its derivative. Can anyone help?

A: After a quick correspondence with the second author, the proof goes as follows: $\psi_t$ is a diffeomorphism onto its image, because $\psi_t$ is injective since $\exp_S$ is. Moreover, an explicit inverse is given by $\exp_S(x, tv) \mapsto \exp_S(x, v) $.


text:
Q: Using element object with jQuery method? I just started using jQuery. Now I want to use an jQuery method with an element object.
var element = document.elementFromPoint(x, y);
element.offset();

Of course this doesn't work because the variable element is not a jQuery selector, so the error message I get in Firebug is "element.offset is not a function".
Is there any general method I could use this element object with an jQuery selector?

A: You can turn a normal DOM element into a jQuery selection by wrapping it in $():
var element = document.elementFromPoint(x, y);
$(element).offset();

A: You need to wrap it into the jQuery constructor function, which returns a jQuery object.
jQuery(element).offset();

or shortcut method
$(element).offset();

http://api.jquery.com/jQuery/


text:
Q: Call an action from a Html.Dropdown onchange event in ASP.Net MVC 5 I'm trying to call the action in the controller when the dropdown selected item changes. Here is the code I am using but it is not working.
 @Html.DropDownList("UserID", null, new { @onchange = "location.href='@Url.Action("Action", "Controller")'" })

What is the correct syntax? I tried to call a javascript function and it works.
@Html.DropDownList("UserID", null, new { @onchange = "leaveChange(this);" })

leaveChange(control) is my javascript function.
However, I am unable to invoke the action of the controller. Also, How do I then pass the value of the selected item to the action?

A: You cannot call a C# method inside the htmlAttributes object where it expects a key value pair. Instead you could execute the Url.Action method and set the result(the url) on a parent element's data attribute and read from that in your javascript code
<div data-submit-url="@Url.Action("ApplyVacation","Jobs")">
    @Html.DropDownList("UserID",)
</div>

and in the change event, read it
$(document).ready(function ()
{
    $("#UserID").change(function ()
    {
        var $this = $(this);
        var url = $this.parent().data("submit-url") + "?userId=" + $this.val();
        window.location.href = url;
    });

});

When user make a selection on the SELECT, this code will navigate to the /Jobs/ApplyVacation url with querystring key userId and the selected option value as the value of that. Update the names as needed based on your code.

A: Try removing @ before onchange
 @Html.DropDownList("UserID", null, new { onchange = "location.href='@Url.Action("Action", "Controller")'" })

A: If you want to pass parameters to action you can use
@Html.DropDownList("UserID", null, new { onchange = "location.href='@Url.Action("Action", "Controller",

    new {name = "Test param", category = "Test1"})'" })

A: Here is what I did
 @Html.DropDownList("UserID", null,new {@id = "leve" })

Jquery code as below:
<script type="text/javascript">

                $('#leve').change(function () {
                    var url = "/UserRoles/TellMeDate";
                    var name = $('#leve').val();
                    $.get(url, { parameter: name }, function (data) {
                        alert(data);
                    });

                })

            });

        </script>

Controller:
public string TellMeDate(string parameter)
    {

            return DateTime.Today.ToString() +"-->>>"+ parameter + "!!!!";

    }

A: This code worked for me:
onchange = "location.href='" + @Url.Action("AdmissionRequirement", "Profile") + "'"


text:
Q: How to use ternary expression in setState ()? I have a fetch functional like this:
fetch('http://localhost:5000/kw-finder', {
      method: 'POST',
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
      body: JSON.stringify({'firstParam': this.state.value,
                            'secondParam' : this.state.audienceMax})
    }).then(response => {
        console.log(response)
        return response.json()
      })
      .then(json => {
        console.log(json)
        this.setState({queryResults: JSON.parse(json['query_results']),
                       dailyPreloadMetrics: JSON.parse(json['keyword_data']),
                       isLoading: false,
                       isHidden: false
                       })
      })

  }

This works; however, I want to conditionally set the value of isHidden state depending on the json results. So for example, I want to do something like this:
this.setState({queryResults: JSON.parse(json['query_results']),
                       dailyPreloadMetrics: JSON.parse(json['keyword_data']),
                       isLoading: false,
                       isHidden: (JSON.parse(json['keyword_data']) === '12') ? false : true
                       })

So basically if the JSON.parse(json['keyword_data']) === '12', then I want to change the value of the state. Is this possible?


text:
Q: Entity Framework and Iqueryable issue Given the Following basic Structure
public class Project
{
    public int ProjectId {get;set;}
    ICollection<SubProject> SubProjects {get;set;}

}

public class SubProject
{
    public int SubProjectId {get;set;}
    public int SubProjectId {get;set;}
    public int PrinterId {get;set;}
    public int AgencyId {get;set;}
    public int Status
    //Oodles more  properties
}

public class ProjectSearchResult
{
   public int ProjectId {get;set;}
   public int NoOfSubProjects {get;set;}
   //Loads more properties
}

I need to get a list of projects and a count of how many sub-projects they have, sometimes by Agency, Sometimes by Printer, and Sometimes by Status,
Instead of doing something like the below
public IQueryable<ProjectSearchResult> GetProjects(int? status, int? agencyId, int?     printerId)
{

    var projects = db.Projects.Include(x=>x.SubProjects);
    if(status.HasValue)
         return projects.Select(proj=> new ProjectSearchResult
                               {
                                  ProjectId = proj.ProjectId,
                                  NoOfSubProjects = proj.SubProjects.Count(s=>s.Status = status)

};

if(agency.HasValue)
         return projects.Select(proj=> new ProjectSearchResult
                               {
                                  ProjectId = proj.ProjectId,
                                  NoOfSubProjects = proj.SubProjects.Count(s=>s.AgencyId= agency)

};
if(printer.HasValue)
         return projects.Select(proj=> new ProjectSearchResult
                               {
                                  ProjectId = proj.ProjectId,
                                  NoOfSubProjects = proj.SubProjects.Count(s=>s.PrinterId= printer)

};

Is there any way I can make it more generic and keep it as an IQueryable, without returning all the sub projects and doing the count in memory?

A: You could do it like this:
public IQueryable<ProjectSearchResult> GetProjects(Expression<Func<SubProject, bool>> predicate)
{
    return
        from p in db.Projects
        select new ProjectSearchResult {
            ProjectId = p.ProjectId,
            NoOfSubProjects = p.SubProjects.Count(predicate),
        };
}

In case it's not obvious, you can then do something like this:
var projects = GetProjects(_ => _.Status == projectStatus);


text:
Q: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. usageLimits exceeded What does it mean?  I have used following scopes for accessing google drive.
    'https://www.googleapis.com/auth/drive.metadata.readonly',
    'https://www.googleapis.com/auth/plus.login',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile'

when I see in my console, it is showing errors ,

code: 403,
   domain: 'usageLimits',
   reason: 'dailyLimitExceededUnreg',
   message: 'Daily Limit for Unauthenticated Use Exceeded.
   }

What am I doing wrong ? However, I have changed my domain from http://localhost:3000 to http://localhost:3003 and all credentials also.
I didn't get any correct answer. please anyone help me.


text:
Q: Bootstrap col-md-3 class is not working Please find the following code snippet. Where col-md-3 class is not working. I have different styles for small, medium and large screens which is done by using media queries. But the trouble is arising only for col-md-3. Any ideas would be helpful.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Book Your Package

Select a date and a game and tell us your group numbers

We will do the Rest

We will organise premium seats, Aussie Rules 101 and direction booklet and home team merchandise

Receive the Box

Your package will be delivered to your hotel or home or you can pick it up at the stadium.

Get to the Game!

Read your new AFL rules guide and local tips booklet, put on your scarf and proceed to enjoy the game!

A: In media queries of bootstrap, medium devices' width is set to minimum 992px. To display your page to smaller device you could use col-sm-* classes.
https://getbootstrap.com/docs/3.3/css/#grid


text:
Q: How do I check that a Gjs class has already been defined? I am writing the preference view a GNOME shell extension and an facing issues when using the imports.lang function to write the application in an object oriented fashion.
const Gtk = imports.gi.Gtk
const Lang = imports.lang
Gtk.init(null)
const MyWindow = new Lang.Class({...})

Opening the preference window the first time works, but subsequent ones throw the following error: Error: Type name Gjs_MyWindow is already registered. Upon closing the window for the first time, I receive this error: TypeError: prefsModule.init is not a function.
The following more imperative code works:
const Gtk = imports.gi.Gtk
Gtk.init(null)
const window = new Gtk.Window({ type: Gtk.WindowType.TOPLEVEL })

Based on the errors thrown, my guess is that the class is being redefined. How can I avoid redefinition and receive the defined class otherwise? (Are there any docs I can refer to?)

A: Looks like the right answer is in this discussion.

If you extend a GObject class (anything from St, Clutter, Gtk, etc.), you're registering a new GType, and that's not possible for extensions.
...
Extensions are dynamic modules, and they can be loaded and unloaded - but that's not at all possible for GTypes.

So, don't extend GTypes. Instead, use the "delegate pattern", which looks like that.
const Class = new Lang.Class({
  Name: "Class",

  _init: function() {
    this.actor = new St.Button();
  }
)};

This being said, if you have a look at the extensions installed on your system and do something like grep -rn 'Extends: Gtk' /usr/share/gnome-shell/extensions/, you will see that some extensions still extend GTypes, and it doesn't cause any error. But you will notice that it's never done in the extension.js file...
Don't ask for more details here, that's all I know as of today !

A: If you want a solid rundown of GObject/Gtk classes in GJS, checkout testGObjectClass.js and testGtk.js (that whole directory is gold, actually).
If this is for prefs.js, you need a function called buildPrefsWidget() which should return a widget instance to be added to the window, not a Gtk.Window instance. Otherwise, you should define your class:
const MyWindow = new Lang.Class({
    Name: "MyWindow",
    Extends: Gtk.Window,

    _init: function (params) {
        this.parent(params);

        ...
    }
});

Then after defined, create an instance and use that:
Gtk.init(null);
let window = new MyWindow({ type: Gtk.WindowType.TOPLEVEL });
window.show_all();
Gtk.main();


text:
Q: Simple Flume agent hat some lag when logging to the console I have a simple Flume agent with the following configuration:
agent.sources = http-source
agent.sinks = logger-sink
agent.channels = logger-channel

# HTTP Source
###############################
agent.sources.http-source.type =  org.apache.flume.source.http.HTTPSource
agent.sources.http-source.channels = logger-channel
agent.sources.http-source.port = 81

# Logger Sink
###############################
agent.sinks.logger-sink.type = logger
agent.sinks.logger-sink.channel = logger-channel

# Channel
###############################

agent.channels.logger-channel.type = memory
agent.channels.logger-channel.capacity = 1000

The only thing that the Flume agent does, it to receive the HTTP POST request through the HTTP Source and logs the events using the Logger Sink.
The problem that I have is as follows: sometimes when I send the HTTP POST request to the Flume agent, It takes 1-5 second till I see the logs in the console. This is only the case for the first message being sent after starting the Flume agent. After sending several messages I see the logs immediately in the console.
My question is: is it a warm-up issues in Flume? It seems that if I do not send any message for a while, again I will have some delay seeing the logs in the console.
Notice that I start the Flume agent in a Docker container using a docker-compose file.

A: First check if the issue persists with the latest Flume agent available (release 1.7), using a recent image like mrwilson/docker-flume.
You can compare its docker-compose.yml with yours.
An  image like gilt/docker-flume is older and still in 1.5.


text:
Q: How to summarize pandas dataframe I have a pandas dataframe containing ~20,xxx records of bus boarding data. The dataset contains a cardNumber field which is unique for each passenger. There is a type field that identifies the type of boarding. There is a routeName column specifying which route the boarding took place on and finally a Date column which identifies when the boarding took place. I have provided a mock dataframe below.
df = pd.DataFrame(
    {'cardNumber': ['999', '999', '999', '999', '901', '901', '888', '888'],
     'type': ['trip_pass', 'transfer', 'trip_pass', 'transfer', 'stored_value', 'transfer', 'trip_pass',
              'trip_pass'],
     'routeName': ['1', '2', '2', '1', '20', '3', '4', '4'],
     'Date': ['2020-08-01 06:18:56 -04:00', '2020-08-01 06:46:12 -04:00', '2020-08-01 17:13:51 -04:00',
              '2020-08-01 17:47:32 -04:00', '2020-08-10 15:23:16 -04:00', '2020-08-10 15:44:45 -04:00',
              '2020-08-31 06:54:09 -04:00', '2020-08-31 16:23:41 -04:00']}
)
df['Date'] = pd.to_datetime(df['Date'])

What I would like to do is summarize the transfer activity. How many transfers, on average, occurred from Route 1 to Route 2 or from Route 2 to Route 1. There are eleven different routes in the dataset that transfers could happen between.
I would like the output to look something like (note that the output below was not generated from the sample provided above):
From   |   To     |   Avg. Daily
----------------------------------
 1     |   2      |     45.7
 1     |   3      |     22.6
 20    |   1      |     12.2

A: The following code works in the chunk data you provided. If it doesn't work in your actual data, pls let me know. There's probably better ways to do that, but I think it's a good starting point.
The general idea here is to group by passengers to figure out the route. Then, since you want the daily average, you gonna need to group by date, and then by destinations in order to calculate the daily mean.
# Define a function to get routes' relationship (origin vs destination)
def get_routes(x):
    if 'transfer' not in x.type.tolist(): # if no 'transfer' type in group, leave it as 0 (we'll remove them afterwards)
        return 0
    x = x[x.type == 'transfer'] # select target type
    date = df[df.cardNumber=='999'].Date.dt.strftime('%m/%d/%Y').unique()
    if date.size == 1: # if there is more than one date by passenger, you'll need to change this code
        date = date[0]
    else:
        raise Exception("There are more than one date per passenger, please adapt your code.")
    s_from = x.routeName[x.Date.idxmin()] # get route from the first date
    s_to = x.routeName[x.Date.idxmax()] # get route from the last date
    return date, s_from, s_to

# Define a function to get the routes' daily average
def get_daily_avg(date_group):
    daily_avg = (
        date_group.groupby(['From', 'To'], as_index=False) # group the day by routes
        .apply(lambda route: route.shape[0] / date_group.shape[0]) # divide the total of trips of that route by the total trips of that day
    )
    return daily_avg

# Get route's relationship
routes_series = df.groupby('cardNumber').apply(get_routes) # retrive routes per passenger
routes_series = routes_series[routes_series!=0] # remove groups without the target type

# Create a named dataframe from the series output
routes_df = pd.DataFrame(routes_series.tolist(), columns=['Date', 'From', 'To'])

# Create dataframe, perform filter and calculations
daily_routes_df = (
    routes_df.query('From != To') # remove routes with same destination as the origin
    .groupby('Date').apply(get_daily_avg) # calculate the mean per date
    .rename(columns={None: 'Avg. Daily'}) # set name to previous output
    .drop(['From','To'], axis = 1) # drop out redundant info since there's such info at the index
    .reset_index() # remove MultiIndex to get a tidy dataframe
)

# Visualize results
print(daily_routes_df)

Output:
         Date From To  Avg. Daily
0  08/01/2020    2  1         1.0

Here, the average is 1 since there's only one count per group. Note that only the "transfer" type has been taking into account. The ones without it, or with no changing route, were further removed.

A: If I got the question right, you would like to get the trip start and end out of your events and the first event corresponds with the starting point (the route name) and then calculate the number of tickets you have in your data set that have the same starting and endpoint.
If so, you can do this as follows
# srot the dataframe so you can use first/last
df_sorted= df.sort_values(['cardNumber', 'Date']).reset_index(drop=True)

# calculate the counts do the counts, but only
# from the defined types
indexer_trip_points= df_sorted['type'].isin(['transfer'])
df_from_to= df_sorted[indexer_trip_points].groupby('cardNumber').agg(
                  start_date=('Date', 'first'),
                  trip_start=('routeName', 'first'),
                  trip_end=('routeName', 'last'),
)

df_from_to['start_date']= df_from_to['start_date'].dt.date
df_counts= df_from_to.groupby(['trip_start', 'trip_end', 'start_date']).agg(
    count=('trip_start', 'count')
)
df_counts.reset_index(drop=False, inplace=True)
df_counts.groupby(['trip_start', 'trip_end']).agg(
    avg=('count', 'mean')
)

This results in:
                     avg
trip_start trip_end
2          1           1
3          3           1

As you can notice, the last entry has the same start- as endpoint. So probably you need to filter out trips, for which you don't have complete data yet. E.g. if in your case a route can never end with the same routeName as it started, you could simply filter them by comparing the two columns.


text:
Q: Simple Nginx 302 redirection not working I'm trying to get a simple redirect working on my nginx server. I am receiving the 302 response code back, but the Location header is not set. What am I missing?
My minimal case (with a hard coded image):
location /redirectme {
    return 302 https://www.google.com/logos/doodles/2016/childrens-day-2016-brazil-5739205150900224-hp2x.jpg;
}

My actual use case (redirect the user to the URL passed into the url query parameter):
location /redirectme {
  return 302 $arg_url
}

Another config that I tried (manually setting the Location header):
location /redirectme {
  add_header Location $arg_url;
  return 302;
}

None of these work in actually redirecting the client to the new URL (only returning the 302). The rest of my web app works great, just not this redirection piece. If it makes a difference, I'm working within an ssl server {...} block. Any ideas? Thanks!
----- UPDATE ------
Here is the entire server block...
server {
  listen   443;
  server_name myserver.com;
  access_log /path-to/myserver.com-ssl.access.log;

  ssl on;
  ssl_certificate /path-to/myserver.com.crt;
  ssl_certificate_key /path-to/myserver.com.key;

  ssl_client_certificate /path-to/clientkey.pem;
  ssl_verify_client on;
  ssl_verify_depth 1;

  keepalive_timeout 5;

  root /srv/www/myserver/public/;

  location /redirectme {
    return 302 $arg_url;
  }

  location / {
    try_files $uri/index.html $uri/index.htm @unicorn;
  }

  location @unicorn {
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-CLIENT-VERIFY $ssl_client_verify;
    proxy_redirect off;

    proxy_read_timeout 60;
    proxy_send_timeout 60;

    # If you don't find the filename in the static files
    # Then request it from the unicorn server
    if (!-f $request_filename) {
      proxy_pass http://unicorn_myserver.com;
      break;
    }
  }

  error_page 500 502 503 504 /500.html;
  location = /500.html {
    root /srv/www/myserver/public/;
  }
}

And the response from doing curl -i:
HTTP/1.1 302 Found
Content-Type: application/json
Content-Length: 0
Connection: keep-alive
Date: Fri, 14 Oct 2016 18:37:32 GMT
x-amzn-RequestId: 44e865b2-923d-11e6-a60a-5f6291eee9a8
X-Cache: Miss from cloudfront
Via: 1.1 aa89533ad2ec5e0edba466c9920bd000.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 7dzQ9JQK380hFD-nFyJxm6mIWT5D4mWzvCbSAhDaa-pHwpF4oZHszw==

It may also be relevant (I don't understand how, but maybe) that I have Amazon API Gateway sitting in front of my requests, directly proxying them to my server (note: the ssl_client_certificate /path-to/clientkey.pem; is configured to only accept requests from API Gateway).


text:
Q: PermissionError: [Errno 13] in python .webassets-cache So I got a 500 error after trying out a flask_assets Bundle. I have it working on my local machine, made to use Pyscss. But once I deployed I checked the error.log and saw that I had a PermissionError: [Errno 13] Permission denied: '.../app/static/.webassets-cache'
This is the script:
from flask import Flask
from flask_assets import Environment, Bundle

app = Flask(__name__)

assets = Environment(app)
assets.url = app.static_url_path
scss = Bundle('scss/main.scss', 'scss/bootflat.scss', 'scss/metro.scss', 'scss/responsive.scss', filters='pyscss', output='css/all.css')
assets.register('scss_all', scss)

And I used this on my html:
{% assets "scss_all" %}
<link rel=stylesheet type=text/css href="{{ url_for('static',filename='css/all.css') }}">
{% endassets %}

I'm guessing the permission error is due to webassets trying to update the all.css file.
My question is: How can I get around this permission error?


text:
Q: Unable to add buttons to custom scrollbar I changed the css properties of the scrollbar and the buttons disappeared. When I added this to my stylesheet:
::-webkit-scrollbar-button {
   display: block;
}

the scrollbar had two rectangles on the top and buttom but there were no arrows. When I tried clicking the top and bottom parts of each of the rectangles, it scrolled up and down. Is there a way to add only one button on each side (top and bottom) that have arrows?
CSS:
/* Properties of Scrollbar */
::-webkit-scrollbar {
    width: 15px;
}
::-webkit-scrollbar-track {
    background: #4d4d4d;
}
::-webkit-scrollbar-button {
    display: block;
}
::-webkit-scrollbar-thumb {
    background: #8d8d8d;
}
::-webkit-scrollbar-thumb:hover {
    background: #2b2b2b;
}

A: You're using ::-webkit-scrollbar-button wrong. It's supposed to be used like this:
::-webkit-scrollbar-button {
  background: blue;
}

This could also be found here


text:
Q: Do you have an open source example for saving data in RFID smart card reader I am starting an open source project by using RFID card readers for saving data from an hotel information system. heres my scenario, i will be using rfid to save the data from the database and store it into the rfid cards. and then they can use the card as an id to their room.
btw my platform is wpf vb2010

A: Not really an open source area, as it depends on the RFID system
Each one has it's own API/SDK and PHY (USB, RS232 etc)
Most manufacturers provide their own SDK usually free of charge

A: Well, it will depends which reader and which card technology you are using.
But you could be interested about our recently released open source RFID library which supports different standard an proprietary hardware. Could be addressed in DotNet (C#, VB.NET ...) using the COM wrapper.


text:
Q: Python logging FileHandler outputting blank file I'm trying to change all my overused prints, to logging.* mainly because i wanted to have a logfile.
logger = logging.getLogger(__name__)
formatter = logging.Formatter("{levelname}:{name}:{message}", style="{")

file_handler = logging.FileHandler("log.txt")
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

logger.setLevel(logging.DEBUG)

Thats the code i have for now, and it's printing to the console correctly but not outputting anything at all to the file. The file even gets created randomly, but but when it does, it's always empty.
I'm using logger.debug() and logger.info(), not the logging.* ones.
Update:
Just copying that same code to an empty script, and importing works as expected. Weird.
Update 2:
I found a question that has the same problem as me, he says he found a solution, but he doesn't share it :(
Update 3:
This is my source. The code gets called by uTorrent everytime the status of a torrent changes. This is the command i have setup in uTorrent:
py C:\Users\Gcq\Downloads\Torrent\torrent.py -n %N -d %D -f %F -p %P -c %S -s %M

py because i have  shebang at the top of my script that tells py to use python3. I have python2.7 installed too.
And the the commandline otions are the info that uTorrent exposes.

A: I'm not able to reproduce the problem (I have Python 3.3.0 installed rather than 3.3.2, but that shouldn't be relevant. See this screenshot:

The behaviour seems as expected, so I would look more closely at your Python installation/configuration, or any other part of your actual code which you haven't shown above.

A: I thought 'okay, i didn't told python where to put my output file' and indeed, it was on uTorrent base folder.
With all the expected output, so everything is working perfect now.


text:
Q: Getting header data with Sqoop import I'm importing Teradata table into HDFS which in then will be read by upstream(Datameer in my case).
Datameer expects headers in data before it can read the part files produced by Sqoop, I looked into Sqoop options but can't find anything that gives me data with headers(Column name).
Is it possible to get the table data with column names into HDFS? If not is there any workaround?

A: First, you don't need header names when importing files (header detection can be turned off in import jobs).
Second, Datameer supports direct Teradata import - no need to take the roundtrip via Sqoop.


text:
Q: VBA macro : find button by location and 'click' them I'm trying to du a macro. From a row index and a column index detect if there is one or more button on this cell and execute the code attached to this button.
I have not found a 'find_button_by_location' method nor a 'button.execute_as_clicked'
I wonder if anyone can help me with some suggestion.
Thank you

A: Something like this could work for you:
Sub ClickButton(ByVal arg_rCells As Range)

    Dim ws As Worksheet
    Dim oOLE As OLEObject
    Dim shp As Shape
    Dim hButtons As Object

    Set ws = arg_rCells.Parent
    Set hButtons = CreateObject("Scripting.Dictionary")

    'ActiveX buttons
    For Each oOLE In ws.OLEObjects
        hButtons.Add oOLE.Name, oOLE.Name
        If Not Intersect(arg_rCells, ws.Range(oOLE.TopLeftCell, oOLE.BottomRightCell)) Is Nothing Then
            Run "'" & ws.Parent.Name & "'!" & ws.CodeName & "." & oOLE.Name & "_Click"
        End If
    Next oOLE

    'Form Control buttons
    For Each shp In ActiveSheet.Shapes
        If Not hButtons.exists(shp.Name) Then
            hButtons.Add shp.Name, shp.Name
            If Not Intersect(arg_rCells, ws.Range(shp.TopLeftCell, shp.BottomRightCell)) Is Nothing Then
                Run shp.OnAction
            End If
        End If
    Next shp

End Sub

And here's an example of how to call it (this will click a button if one exists in cell C3):
Sub tgr()

    ClickButton ActiveSheet.Range("C3")

End Sub


text:
Q: How to stop Terraform being misused We have recently started using Terraform for IaC.
How do we make sure that Terraform is not misused by some member in the team by spinning hundreds of VMs costing the company $$$'s. How do we restrict users from doing this?
Thanks

A: Hashicorp offers a product named Sentinel, which allows you to write required policies for your Terraform organizations and users - note that this is a paid feature.
It's not clear which costs you're looking to restrict exactly, but with Sentinel, you could write a policy that restricts the total monthly cost of a Terraform plan like so:
# This policy uses the Sentinel tfrun import to restrict the
# proposed monthly cost that would be incurred if the current
# plan were applied

# Import common-functions/tfrun-functions/tfrun-functions.sentinel
# with alias "run"
import "tfrun-functions" as run
# The standard decimal import
import "decimal"

# Monthly Limit
limit = decimal.new(1000)

# Call the validation function
# Warnings will be printed for violations
cost_validated = run.limit_proposed_monthly_cost(limit)

# Main rule
main = rule {
  cost_validated
}

See the source of this policy here.

A: There are a variety of different answers to this question depending on the details of what you want to achieve and why.
The most thorough approach would be to ensure that you only grant your users access to perform operations that you consider acceptable within the target cloud platforms. As long as you configure the permissions correctly, the users won't be able to create objects they shouldn't regardless of whether they do it with Terraform or any other tool.
In practice though we typically need to trust to some extent that operators are acting in good faith, and think about including "guard rails" to discourage accidental misconfiguration, rather than trying to tightly control what individuals are allowed to do.
As long as folks are running Terraform directly on their own computers, they will have access to do whatever their credentials for the remote system permit them to do. Terraform is totally under the user's control in that case and so you can't control anything at the Terraform level, so any controls you introduce will need to be in the remote system instead.
However, typically teams using Terraform in production will run it in some sort of automation where the operators execute Terraform only indirectly, with Terraform itself running in a controlled remote environment similar to what's typically provided by CI/CD systems. In that case, you should still assume that terraform plan is effectively executing arbitrary code and so you can't use it as a hard security boundary, but you can create guardrails to help operators acting in good faith to avoid taking damaging actions.
To do that, make your automation system save a plan to a file, and then export it as JSON for consumption by external software:
terraform plan -out=tfplan
terraform show -json tfplan >tfplan.json

Then you can use software of your own design to consume tfplan.json, which is in the Terraform JSON output format, and implement whatever rules you deem appropriate to decide whether a particular plan is acceptable. If your program determines that the plan is not acceptable then you can halt the pipeline and prevent applying the plan.
If you consider the plan to meet policy then, after human approval, you can apply it from that file saved earlier, to ensure it'll take the same actions as you've checked:
terraform apply tfplan

There are some external systems which can help you write policies to check a JSON plan. For example, Open Policy Agent is open source software which can integrate with Terraform plans, and the higher pricing tiers of Terraform Cloud include "Team Management and Governance", which is a hosted version of this model using a HashiCorp-specific policy language called Sentinel. Other open source projects and vendors have similar offerings.


text:
Q: Testing mongoose pre-save hook I am quite new to testing nodejs. So my approach might be completely wrong. I try to test a mongoose models pre-save-hook without hitting the Database. Here is my model:
// models/user.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

UserSchema = new Schema({
    email: {type: String, required: true},
    password: {type: String, required: true}
});

UserSchema.pre('save', function (next) {
    const user = this;
    user.email = user.email.toLowerCase();
    // for testing purposes
    console.log("Pre save hook called");
    next();
});

module.exports = mongoose.model("User", UserSchema);

As I said, I do not want to hit the Database with my test, so I tried using a sinon stub of the Users save() method:
// test/models/user.js
const sinon = require("sinon");
const chai = require("chai");
const assert = chai.assert;

const User = require("../../models/user");

describe("User", function(){
    it("should convert email to lower case before saving", (done) => {
        const user = new User({email: "Valid@Email.com", password: "password123"});
        const saveStub = sinon.stub(user, 'save').callsFake(function(cb){ cb(null,this) })

        user.save((err,res) => {
            if (err) return done(err);
            assert.equal(res.email,"valid@email.com");
            done();
        })
    })
});

However, If I do it like that the pre-save hook will not be called. Am I on the wrong path or am I missing something? Or is there maybe another way of triggering the pre-save hook and testing its outcome? Thanks very much in advance!

A: Before we start: I'm looking for the same thing as you do and I've yet to find a way to test the different hooks in Mongoose without a database. It's important that we distinguish between testing our code and testing mongoose.

Validation is middleware. Mongoose registers validation as a pre('save') hook on every schema by default. http://mongoosejs.com/docs/validation.html

Considering that validate will always be added to the model and I wish to test the automated fields in my model, I've switched from save to validate.
UserSchema = new Schema({
  email: {type: String, required: true},
  password: {type: String, required: true}
});

UserSchema.pre('validate', function(next) {
  const user = this;
  user.email = user.email.toLowerCase();
  // for testing purposes
  console.log("Pre validate hook called");
  next();
});

The test will now look like:
it("should convert email to lower case before saving", (done) => {
    const user = new User({email: "VALID@EMAIL.COM", password: "password123"});
    assert.equal(res.email,"valid@email.com");
}

So What About the Pre Save Hook?
Because I've moved the business logic for automatic fields from 'save' to 'validate', I'll use 'save' for database specific operations. Logging, adding objects to other documents, and so on. And testing this only makes sense with integration with a database.

A: I just faced the same issue and managed to solve it by extracting the logic out of the hook, making it possible to test it in isolation. With isolation I mean without testing anything Mongoose related.
You can do so by creating a function, that enforces your logic, with the following structure:
function preSaveFunc(next, obj) {
  // your logic
  next();
}

You can then call it in your hook:
mySchema.pre('save', function (next) { preSaveFunc(next, this); });

This will make the reference to this available inside the function, so you can work with it.
The extracted part can then be unit tested by overwriting the next function to a function without a body.
Hope this will help anyone as it actually was a pain to solve this with my limited knowledge on Mongoose.


text:
Q: \multicolumn in a booktabs table I'm having a few problems with a table which uses \multicolumn and the booktabs package.
This is what I've done:
\documentclass[12pt]{article}
\usepackage[margin=1.8cm]{geometry}
\geometry{a4paper}
\usepackage[parfill]{parskip}
\usepackage{booktabs}
\usepackage{multirow}

\begin{document}

\begin{center}

  \begin{tabular}{*{7}{c}}
    \toprule
    & \multicolumn{2}{c}{\textsc{sg}} &
\multicolumn{2}{c}{\textsc{du}} & \multicolumn{2}{c}{\textsc{pl}} \\
    \cmidrule(lr){2-3}
    \cmidrule(lr){4-5}
    \cmidrule(lr){6-7}
    & \textsc{m} & \textsc{n} & \textsc{m} & \textsc{n} & \textsc{m} &
\textsc{n} \\
    \midrule
    \textsc{nom} & \textit{s} & \textit{m} \\
    \textsc{acc} & \multicolumn{2}{c}{\textit{m}} \\
    \textsc{ins} & \multicolumn{2}{c}{\textit{-a} $\to$ \textit{ena}} \\
    \multirow{2}{*}{\textsc{dat}} & \multicolumn{2}{c}{\textit{aya}} \\
    & \multicolumn{2}{c}{\textit{-a} $\to$ \textit{\={a}ya}} \\
    \textsc{abl} & \multicolumn{2}{c}{\textit{t} (\textit{-a} $\to$ \textit{\={a}})} \\
    \textsc{gen} & \multicolumn{2}{c}{\textit{sya}} \\
    \multirow{2}{*}{\textsc{loc}} & \multicolumn{2}{c}{\textit{i}} \\
    & \multicolumn{2}{c}{\textit{-a} $\to$ \textit{e}} \\
    \bottomrule
  \end{tabular}

\end{center}

\end{document}

I think it's pretty clear that the horizontal centring is off where I've used \multicolumn. The M and N beneath SG are not equidistant from SG, the m in the ACC row seems to be nicely centred under SG but is woefully out of alignment with the s and m of the NOM row above.

A: Contents in your table is still perfectly centered, however, their width is changed according to width of \multicolumn{2}{c}{... cells. If it is wider than your "normal" column, than additional width is added to the second column. This you can see, if you add the vertical lines to your table.
One of possible solutions is the following. Lets assume, that multicolumn cells width is not larger than 6em. Than you can solve your problem with:
\documentclass[12pt]{article}
    \usepackage[a4paper,margin=1.8cm]{geometry}
    \usepackage[parfill]{parskip}
    \usepackage{array,booktabs,multirow}

\begin{document}
\begin{center}
  \begin{tabular}{>{\scshape}r*{6}{>{\centering\arraybackslash}p{3em}}}
    \toprule
    & \multicolumn{2}{c}{\textsc{sg}} &
\multicolumn{2}{c}{\textsc{du}} & \multicolumn{2}{c}{\textsc{pl}} \\
    \cmidrule(lr){2-3}
    \cmidrule(lr){4-5}
    \cmidrule(lr){6-7}
    & \textsc{m} & \textsc{n} & \textsc{m} & \textsc{n} & \textsc{m} &
\textsc{n} \\
    \midrule
nom & \textit{s} & \textit{m} \\
acc & \multicolumn{2}{c}{\textit{m}} \\
ins & \multicolumn{2}{c}{\textit{-a} $\to$ \textit{ena}} \\
\multirow{2}{*}{dat}
    & \multicolumn{2}{c}{\textit{aya}} \\
    & \multicolumn{2}{c}{\textit{-a} $\to$ \textit{\={a}ya}} \\
abl & \multicolumn{2}{c}{\textit{t} (\textit{-a} $\to$ \textit{\={a}})} \\
gen & \multicolumn{2}{c}{\textit{sya}} \\
\multirow{2}{*}{loc}
    & \multicolumn{2}{c}{\textit{i}} \\
    & \multicolumn{2}{c}{\textit{-a} $\to$ \textit{e}} \\
    \bottomrule
    \end{tabular}
\end{center}
\end{document}

I little bit optimize your code (see difference in the first column). That code can works, I add package array.


text:
Q: Can someone please explain the syntactic rules at work here? I'll use an example statement that's currently being used in a radio commercial for American Family Insurance (paraphrased.)

They all told me that I couldn't build my dream home by myself; but, I didn't.

Can someone please lex this to identify why but, I didn't is referring to the fact that the dream home was built and it was not build by myself; whereas and, I didn't would introduce ambiguity as to whether the dream home was built or not; or that it was built but not by myself.
To state my question another way: if I were to attempt to automate a lexical analysis of this statement -exactly as it has been provided- to conclude that the house was built with the help of others, what rules would I need to consider?
Apart from bare assertions that the sentence parses a different way, can anyone see any alternative interpretations?
[Edit]
I see the but as an adverbial conjunction and that's why my parsing is conflicting with that of others who are seeing it as a coordinating conjunction.

They all told me that I couldn't build my dream home by myself, only I didn't.

With this understanding, it is clear to see that this is the structure they are using.  The question now is...is that the proper structure of an adverbial but?  It feels natural to me, but by the responses below, others seem to disagree.

A: There's actually a bit of a problem here - the sentence, as provided, without context or a follow-up, is indeed ambiguous.
I'll illustrate first:

They all told me that I couldn't build my dream home by myself; but, I
  didn't.

This is how you resolved the sentence, with the meaning that the person built the home but had help - but this isn't the only way to interpret the sentence!

They all told me that I couldn't build my dream home by myself; but, I
  didn't.

Here the speaker actually didn't build the house at all. What did they do? Well, they could have grown the house, as in living in some sort of organic structure. They could have found the house of their dreams - perhaps abandoned or lost in some hidden or rarely visited area. They could have also just bought the dream home, and this is actually just a clever add for a real estate agent. Or they could have inherited or been given it, and perhaps this is an ad for one of those lost-property services or a lawyer/estate planning service.
And actually, this isn't the only way to interpret the sentence either!

They all told me that I couldn't build my dream home by myself; but, I
  didn't.

Here the speaker is referring to the fact that they themselves didn't build the dream home at all. This could even be combined with emphasis from the previous interpretation for another similar set of interpretations. Maybe their spouse did it, or their kid, or their grandparent - all are very possible introductions to a potentially interesting story.

So, what set of grammatical/syntactic rules are at work? In short: contextual re-interpretation, where ambiguity is resolved with additional information.
The purpose of the sentence is to provide a momentary pause, of confusion, not only because it violates a common template (They said...but I did, or They said...and so I didn't) but also because it is actually ambiguous. No rule leads us to only one interpretation, because it isn't the only valid one. It requires multiple re-readings to get a guess as to what the author might have meant, when no context is available.
Now, you could argue that proximity of "by myself" made the given interpretation more likely, and this is indeed a common enough sentence structure that it's a reasonable heuristic. You could also note that the specificity also made this part of the sentence stand out more, as we assume that all detail in a sentence is necessary for the meaning. For instance:

I told you I didn't want you driving at night; but you did it anyway.

Here we tend to assume that the problem was the "at night", and not the more general "driving" at all, due to both proximity to the objection and due to the specificity. If the speaker objected to driving generally, why did they specify at night? Well, this would also be somewhat ambiguous - because "at night" might have been intended as an intensifier!
Returning to the example sentence, let's look at it again:

They all told me that I couldn't build my dream home by myself; but, I
  didn't.

Now, why would "by myself" have been included if it wasn't important to the sentence? If they had said instead:

They all told me that I couldn't build my dream home; but, I didn't.

This is valid, but takes the natural emphasis away due to proximity and reduces our heuristic certainty. It could still be about going it alone, as they could follow with "my spouse and I built it together". But this seems like the less likely intent now.
However, as with my made-up example sentence, what if "by myself" was intended as an intensifier? The speaker was poor or physically disabled, so "they" said that not only could the speaker not build their own dream home, but they thought it was even more absurd that they'd be able to do it by themselves!
Ultimately, there is no syntactic rule that eliminates ambiguity from this sentence simply because there is still ambiguity. Multiple meaning and intentions are possible, and a reading agent can apply heuristic rules to find more or less statistically likely meanings - but no agent would be able to attain certainty.

A:
They all told me that I couldn't build my dream home by myself; but, (the thing is,) I didn't (try to do it, I had help).

He's saying they were wrong to assume I was trying to build it by myself.
EDIT:
The conjunction AND, unlike BUT, doesn't always provide contrast. Therefore, you might be right in saying that using and is ambiguous here. It could mean:

They all told me that I couldn't build my dream home by myself; and (they were right), I didn't.

But I think that even here, the interpretation that the house wasn't built at all is far-fetched. If the speaker wanted to say that, they'd be more likely to say:

They all told me that I couldn't build my dream home by myself; and (they were right), I couldn't.

A:
They all told me that I couldn't build my dream home by myself; but, I
  didn't.
They all told me that I couldn't build my dream home by myself; but, I
  didn't build my dream home by myself.

They were wrongheaded to warn (or predict) that I would be unable to build the dream house on my own because it was never my intention to act alone.
The "but" denies "their" premise, the very basis for their warning or prediction. It does not deny the truth-content of the warning or prediction itself.
P.S. Consider:

They all warned me that I wouldn't make it to the wedding on time if I
  took the tunnel, so I didn't.
They all warned me that I wouldn't make it to the wedding on time if I
  took the tunnel; but, I didn't.

"So" makes perfectly logical sense. He did not take the tunnel because he had been warned of the traffic.
"But" does not make logical sense unless we understand "I didn't" to mean "I did not take the tunnel and never intended to take the tunnel." The "but" means "they had no need to warn me".  It does not deny that the tunnel would have been a bad idea.  It is the dramatic context of the conversation which is the referent of "but", not heavy traffic in the tunnel.

A: There is little difference between these two ellipses:

They all told me that I couldn't ( build my dream home by myself;) but
I didn't (build my dream home by myself.)>
They all told me that I couldn't ( build my dream home by myself;) and
I didn't (build my dream home by myself.)

It is a matter of Rhetoric: possibly Suggestio falsi 1 (Wickipedia), that you hear it as

They all told me that I couldn't ( build my dream home by myself;) but
I didn't.

Or Psycholinguistics Compare Wikipedia.Garden_path_sentence

A garden path sentence is a grammatically correct sentence that starts
in such a way that a reader's most likely interpretation will be
incorrect; the reader is lured into a parse that turns out to be a
dead end. Garden path sentences are used in psycholinguistics to
illustrate the fact that when human beings read, they process language
one word at a time. "Garden path" refers to the saying "to be led down
the garden path", meaning "to be misled".2

A: I see this as holding a very strict context with one and only one possible valid interpretation.
A statement was made by "all" at some point in the past that has a truth value.

They all told me that I couldn't build my dream home by myself

If I merely believe that I could build a dream home by myself, I would have a weak disagreement with their assertion because both would be hypothetical. If I built a dream home by myself, I would have a strong conclusion to negate their assertion. If I attempted and failed to build a dream home by myself, I would have a strong conclusion to affirm their assertion.
I contend that the addition of "by myself" is not merely an intensifier that tries to add that "I can't build my dream home [even with help] and I especially can't build it by myself." That statement would be

They all told me that I couldn't build my dream home, especially not by myself

An intensifier of this structure requires a conjunctive adverb.
Without the conjunctive adverb, by myself is the major component of the premise.
Carrying through the semicolon, the context of all's statement is imported for the concluding one.  To move past the conjunction for a moment, the didn't decorates that conjunction and applies to the couldn't from the premise made by all. Usage of a word that does not directly coincide with all's usage of couldn't necessarily imparts a tone of deflection.  Usage of didn't denies that all's premise was ever under consideration.
To discuss alternatives first to address other potential, invalid, interpretations:
If assessment of the statement made by all was being evaluated by myself for consideration when building a dream home, the word could or couldn't would instead be used.

;and, I couldn't

would be used to state "they were right" but place the statement of the conclusion in an ambiguous temporal setting.
It could potentially mean that the assessment made by all was agreed with, and no attempt to build a dream home by myself has been made.
It could potentially mean that the assessment made by all was disagreed with, but a failed attempt to build a dream home by myself was made.
At any rate, and I couldn't would be used for these, not the structure as provided.

but, I could

would be used to state that I reject their notion that I could build it by myself but carry no truth value of whether the dream home was built.  It would be perfectly valid to interpret this as but, I (know I) could to indicate subjective disagreement with all but no objective truth to the statement.

but, I couldn't

makes no logical sense within the context I am currently discussing.  It only applies to a very novel interpretation of the statement that They all told me, but I couldn't tell myself.

and, I could

exists in the same vein as but, I couldn't It means They all told me, and I could tell myself although this is fairly weak.

and, I couldn't

is perfectly consistent with the assessment made by all. It very clearly means that I either tried to build my dream home by myself and failed or I agreed with their assessment and did not try to build my dream home by myself.

Usage of did implies something very different.

but, I did

means something very clear. They all told me that I couldn't build my dream home by myself. But I did, in fact, build it by myself.

and, I did

is weird. I'm not certain that it is even valid given the logical structure. I see it only working with a very specific addition, consistent with the novel approach.  They all told me that I couldn't build my dream home and, I [told myself that as well].

and, I didn't

is slightly ambiguous but has one strong and one weak meaning. The strong meaning is that they told me that I couldn't build my dream home by myself. I tried to build my dream home by myself and I failed.  The weak meaning is that they told me that I couldn't build my dream home by myself and I did not tell that to myself.

but, I didn't

The but is used here as an adverbial conjunction.  That's why the and versions of the statements seem clumsy and why but, I did seems very clear. The perceived discomfort with this version likely comes from the way the sentence was ended with an unfamiliar sounding phrase and the way the structure makes it sound somewhat as if the but is used as a simple conjunction.

They all told me that I couldn't build my dream home by myself; only I didn't.


text:
Q: Mocking UnitOfWork / GenericRepository Implementation I followed this SO answer to a similar question, (the below is an implentation of the 2nd answer)
I'm trying to figure out how to test:
 public async Task<string> DoWork()
        {
            return await _testRepository.GetAsync(); <-- how do I test here???
        }

Example Class
using System.Threading.Tasks;
using Test.DataAccess.Core;
using Test.DataAccess.Repository;

namespace Test.DataAccess
{
    public class TestManager : ITestManager
    {
        private IUnitOfWork _unitOfWork;
        private ITestRepository _testRepository;

        public TestManager(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _testRepository = _unitOfWork.GetRepository<TestRepository>();
        }

        public async Task<string> DoWork()
        {
            return await _testRepository.GetAsync();
        }

    }
}

Example Repo Link:
Class Link
Repo Link

A: It depends. What are you trying to test? If you need to mock your ITestRepository that is being built by your IUnitOfWork, with NSubstitute you can do something like:
public class SomeTestClass
{
    public void SomeTest()
    {
        var repository = Substitute.For<ITestRepository>();
        var unitOfWork = Substitute.For<IUnitOfWork>();
        unitOfWork.GetRepository<TestRepository>().Returns(repository);
    }
}

In that case you`ll mock both repository and uow and make the uow return the mock repo.


text:
Q: How do I refer to any object in MainActivity from other class? and how do I avoid NullPointerException for referencing to any object onPostExecute()-NullPointerException: Attempt to invoke v.method'android.view.Window$Callback android.view.Window.getCallback()'on a null object ref.
Null pointer Exception(onPostExecute()-NullPointerException: Attempt to invoke v.method'android.view.Window$Callback) on set method(MainActivity) or on postExecute
methode(img load) appears.

I was trying to load an image and set it to the imageview in mainactivity. but I cant refer to that imageview.
I can't refer to that imageview from imageload class but I can refer to that from any method in mainactivity.

Here is MainActivity :
public class MainActivity extends AppCompatActivity {

ImageView imageView;
Context context;

TextView textView;

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

    imageView = (ImageView) findViewById(R.id.imageView);

    textView = (TextView) findViewById(R.id.textView);
}

    public void network(View view) {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            // fetch data
            Toast.makeText(this, "Network detected", Toast.LENGTH_SHORT).show();

            String stringUrl = "http://www.lorempixel.com/420/240/";
            new imgLoad().execute(stringUrl);

        } else {
            // display error

            Toast.makeText(this, "No network detected", Toast.LENGTH_SHORT).show();
//            textView.setText("No network connection available.");

        }

    }
public void set(Bitmap bitmap) {
    textView = (TextView) findViewById(R.id.textView);
    if (textView != null) {
        textView.setText("setting image..");
    }
    Toast.makeText(this, "setting..,", Toast.LENGTH_SHORT).show();

    if (imageView != null) {
        Toast.makeText(this, "good", Toast.LENGTH_SHORT).show();
        textView.setText("image not null..");

        imageView.setImageBitmap(bitmap);
    }else {
        textView.setText("null");
    }
}

Here references on set method are null and cant get reference on below class for ImageView.
Here is Imageloader class:
public class imgLoad extends AsyncTask<String, Void, Bitmap> {

@Override
protected Bitmap doInBackground(String... params) {
    return load(params[0]);

}

@Override
protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);
    MainActivity m = new MainActivity();
//        ImageView c = m.x();
            m.set(bitmap);
//        Toast.makeText(MainActivity.getContext(), "downloaded", Toast.LENGTH_SHORT).show();
//        if (c!=null) {
//            c.setImageBitmap(bitmap);
//        }

}

private Bitmap load(String param) {
    Bitmap bitmap = null;
        InputStream inputStream;
        try {
            URL url = new URL(param);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("Get");
            httpURLConnection.setConnectTimeout(4000);
            httpURLConnection.setReadTimeout(2000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);

        } catch (MalformedURLException e) {

            Log.e("error", "wrong url : " + e.getMessage());

//            e.printStackTrace();
            } catch (IOException e) {
//            e.printStackTrace();
            Log.e("error", "failed : " + e.getMessage());
        }
    return bitmap;
}
}

Here is the Logcat:
12-13 10:15:53.234 28054-28127/com.facebook.mahmud.r.pixels E/error: failed : Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get
12-13 10:15:53.347 28054-28054/com.facebook.mahmud.r.pixels D/AndroidRuntime: Shutting down VM
12-13 10:15:53.364 28054-28054/com.facebook.mahmud.r.pixels E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.facebook.mahmud.r.pixels, PID: 28054
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:145)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:186)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:170)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:502)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:174)
at com.facebook.mahmud.r.pixels.MainActivity.set(MainActivity.java:151)
at com.facebook.mahmud.r.pixels.imgLoad.onPostExecute(imgLoad.java:35)
at com.facebook.mahmud.r.pixels.imgLoad.onPostExecute(imgLoad.java:20)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
12-13 10:15:56.700 28054-28054/com.facebook.mahmud.r.pixels I/Process: Sending signal. PID: 28054 SIG: 9

TIA.

A: Let's put your problem in proper format. When you ran your application you created an object for MainActivity. Let us call that mainActivityObject1. From mainActivityObject1 you created an object for imgLoad class. In that after downloading the image you created yet another object for MainActivity (let's call it mainActivityObject2). Now you are trying to call the method mainActivityObject2.set(bitmap); where you should be calling mainActivityObject1.set(bitmap);.
You can solve this problem couple of ways. But the most basic one is by passing the activity context.
Create a constructor in imgLoad class and change your onPostExecute method like this:
private MainActivity mainActivityContext;
public imgLoad(MainActivity passedActivityContext){
    this.mainActivityContext = passedActivityContext;
}
@Override
protected Bitmap doInBackground(String... params) {
    return load(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
    super.onPostExecute(bitmap);
    mainActivityContext.set(bitmap);
}

From your MainActivity class when you do instantiate imgLoad pass your activity context like this:
new imgLoad(MainActivity.this).execute(stringUrl);

Now you when you call set(Bitmap bitmap) from imgLoad class it should call the original MainActivity object that created the imgLoad object.
Note:

I also noticed you are not calling network method in your MainActivity class that you posted in here. Do call it to test properly.


text:
Q: C# HTML.Actionlink strange behaviour on server If someone can help, I would be very thankful.
I'm using C# in VS 2017 for an ASP.net Application.
In a razor view, I have this code:

        @for (var i = 1; i <= ViewBag.SearchMetaData.SearchNumberOfPages; i++)
        {
            if (ViewBag.SearchMetaData.SearchCurrentPage == @i)
            {

 @Html.ActionLink(@i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", new { id = @i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)

            }
            else
            {

 @Html.ActionLink(@i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", "Home", new { id = @i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)

            }
        }

}
It works great on my development machine.  The actionlinks never fail.
However, when I publish to the server, I can click on the links 3 or 4 times and they work.  After the 4th time, it is like the variables are forgotten.  When I view the page source the links appear to correct.  It seems to me something on the server is being reset.  Does anyone have any ideas?
Here is more code:
____________EDIT AFTER THIS LINE__________________
Controller:
 public ActionResult CI_SequenceBlocks()
    {
        string strIP = "";
        string strSRCHString = "";
        string strSRCHstringQry = "";
        int intSRCHRequestedPage = 1;
        int intSRCHPageSize = 10;
        if (TempData["CI_SequenceBlocks_InstitutionProgram"] == null)
        {
            strIP = "0";
            strSRCHString = "";
        }
        else
        {
            strIP = TempData["CI_SequenceBlocks_InstitutionProgram"].ToString();
            strSRCHString = TempData["CI_SequenceBlocks_SRCHString"]?.ToString() ?? "";
        };
        ViewData["listInstitutionPrograms"] = new SelectList(MSSQL_CI_Repository.ListInstitutionProgramsForComboBoxes(), "Value", "Text");
        ViewData["SelectedInstitutionProgram"] = strIP;
        ViewData["inSRCHString"] = strSRCHString;
        ViewBag.SRCHString = strSRCHString;
        //ViewBag.InstitutionalProgram = strIP;
        if (strSRCHString == "") { ViewBag.SRCHDescriptor = "NO_SEARCH_TERM"; } else { ViewBag.SRCHDescriptor = strSRCHString?.ToString() ?? "NO_SEARCH_TERM"; }
        if (strSRCHString.Trim() == "")

        {
            strSRCHstringQry = "rttyghujmgdddh";
        }
        else
        {
            strSRCHstringQry = strSRCHString;
        }
        if(TempData["CI_SequenceBlocks_RequestedPage"] != null)
        {
            intSRCHRequestedPage = Convert.ToInt32(TempData["CI_SequenceBlocks_RequestedPage"]);
        }
        vm_CI_SequenceBlocksWithSearchMetaData obj = MSSQL_CI_Repository.ListCI_SequenceBlocksByInstitutionalProgramForFullTextSearch(Convert.ToInt32(strIP), strSRCHstringQry,intSRCHPageSize,intSRCHRequestedPage);
        ViewBag.SearchMetaData = obj.SearchMetaData;
        var model = obj.lstSequenceBlocks;
        return View(model);
    }

    [HttpPost]

    public ActionResult CI_SequenceBlocks_FullTextSearch(FormCollection form)
    {
        TempData["CI_SequenceBlocks_InstitutionProgram"] = form["HidInstitutionProgram"].ToString();
        TempData["CI_SequenceBlocks_SRCHString"] = form["SRCHString"].ToString();
        TempData["CI_SequenceBlocks_RequestedPage"] = 1;
        return RedirectToActionPermanent("CI_SequenceBlocks");
    }

    public ActionResult CI_SequenceBlocks_Edit_Form_Handler(int id, string value, int inInstitutionProgramID)
    {
        TempData["CI_SequenceBlocks_InstitutionProgramID"] = inInstitutionProgramID;
        TempData["CI_SequenceBlocks_SequenceBlockID"] = id;
        if (value == "Edit_SequenceBlock_ID")
        {
            return RedirectToAction("CI_SequenceBlock_Edit");
        }
        else if (value == "Maintain_SequenceBlock_ID")
        {
            return RedirectToAction("CI_SequenceBlock_Maintain");
        }
        else
        {
            TempData["CI_SequenceBlocks_InstitutionProgram"] = inInstitutionProgramID;
            return RedirectToAction("CI_SequenceBlocks");

        }

        }

    public ActionResult CI_SequenceBlocks_Pager_Form_Handler(int id, string value, int inInstitutionProgramID)
    {
        TempData["CI_SequenceBlocks_InstitutionProgram"] = inInstitutionProgramID;
        TempData["CI_SequenceBlocks_SRCHString"] = value;
        TempData["CI_SequenceBlocks_RequestedPage"] = id;
        return RedirectToActionPermanent("CI_SequenceBlocks");
    }

    [HttpPost]

    public ActionResult CI_SequenceBlocks_ProgramChange(FormCollection form)
    {
        TempData["CI_SequenceBlocks_InstitutionProgram"] = form["SelectedInstitutionProgram"].ToString();
        return RedirectToActionPermanent("CI_SequenceBlocks");
    }

RouteConfig.cs
  public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}/{id2}/{id3}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional, id3 = UrlParameter.Optional }
            );
}

Full Razor Code:
@model IEnumerable<UTCI_Manager.Models.vm_CI_SequenceBlock>

@{
    ViewBag.Title = "CI_SequenceBlocks";
}

CI_SequenceBlocks

@using (Html.BeginForm("CI_SequenceBlocks_ProgramChange", "Home", FormMethod.Post, new { id = "submitForm" }))
{

    @Html.DisplayNameFor(model => model.InstitutionProgramID)
    @Html.DropDownList("SelectedInstitutionProgram", (SelectList)ViewData["listInstitutionPrograms"], new { onchange = "this.form.submit();" })

}
@using (Html.BeginForm("CI_Sequenceblocks_FullTextSearch", "Home", FormMethod.Post, new { id = "submitForm" }))
{
    if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
    {

            @Html.Hidden("HidInstitutionProgram", ViewData["SelectedInstitutionProgram"]?.ToString() ?? "0")
            @Html.TextBox("SRCHString", ViewData["inSRCHString"].ToString(), new { @class = "form-control", @placeholder = "Search" })

                <button class="btn btn-info" type='submit' value="Search">Search</button>

    }
}

                @*
                @Html.DisplayNameFor(model => model.SequenceBlockID)

                @Html.DisplayNameFor(model => model.InstitutionProgramID)

                *@

                    @Html.DisplayNameFor(model => model.Title)

                    @Html.DisplayNameFor(model => model.SequenceBlockDescription)

                    @Html.DisplayNameFor(model => model.SequenceBlockRequired)

                @*
                @Html.DisplayNameFor(model => model.Minimum)

                @Html.DisplayNameFor(model => model.Maximum)

                *@

                    @Html.DisplayNameFor(model => model.SequenceBlockTimingMethod)

                    @Html.DisplayNameFor(model => model.Duration)

                    @Html.DisplayNameFor(model => model.StartDate)

                    @Html.DisplayNameFor(model => model.EndDate)

                    @Html.DisplayNameFor(model => model.ClerkshipModel)

                    @using (Html.BeginForm("CI_SequenceBlocks_AddSequenceBlock", "Home", FormMethod.Post, new { id = "submitForm" }))
                    {
                        if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
                        {
                            @Html.Hidden("HidInstitutionalProgram", ViewData["SelectedInstitutionProgram"].ToString())
                            <input type="submit" value="Add Sequence Block" class="btn btn-sm" />
                        }
                    }

            @foreach (var item in Model)
            {

                    @Html.HiddenFor(modelItem => item.SequenceBlockID)

                    @Html.HiddenFor(modelItem => item.InstitutionProgramID)

                    @Html.HiddenFor(modelItem => item.Minimum)

                    @Html.HiddenFor(modelItem => item.Maximum)

                        @Html.DisplayFor(modelItem => item.Title)

                        @Html.DisplayFor(modelItem => item.SequenceBlockDescription)

                        @Html.DisplayFor(modelItem => item.SequenceBlockRequired)

                        @Html.DisplayFor(modelItem => item.SequenceBlockTimingMethod)

                        @Html.DisplayFor(modelItem => item.Duration)

                        @Html.DisplayFor(modelItem => item.StartDate)

                        @Html.DisplayFor(modelItem => item.EndDate)

                        @Html.DisplayFor(modelItem => item.ClerkshipModel)

                        @Html.ActionLink("Edit", "CI_SequenceBlocks_Edit_Form_Handler", new { id = item.SequenceBlockID, value = "Edit_SequenceBlock_ID", inInstitutionProgramID = item.InstitutionProgramID }) |
                        @Html.ActionLink("Maintain", "CI_SequenceBlocks_Edit_Form_Handler", new { id = item.SequenceBlockID, value = "Maintain_SequenceBlock_ID", inInstitutionProgramID = item.InstitutionProgramID })

            }

    @if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
    {

                @for (var i = 1; i <= ViewBag.SearchMetaData.SearchNumberOfPages; i++)
                {
                    if (ViewBag.SearchMetaData.SearchCurrentPage == @i)
                    {

 @Html.ActionLink(@i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", new { id = @i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)

                    }
                    else
                    {

 @Html.ActionLink(@i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", "Home", new { id = @i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)

                    }
                }

    }

@using (Html.BeginForm("CI_SequenceBlocks_AddSequenceBlock", "Home", FormMethod.Post, new { id = "submitForm" }))
{
    if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
    {

                    @Html.Hidden("HidInstitutionProgram", ViewData["SelectedInstitutionProgram"].ToString())

                Add Sequence Block:
                 <input type="submit" value="Add Sequence Block" class="btn btn-sm" />

    }
}

____________NEW UPDATE____________
Found the issue:
I changed RedirectToActionPermanent to RedirectToAction.  No more problems!
Thanks,
James


text:
Q: vue-tables-2 event emit not registering for custom filter I'm getting this error: "TypeError: Event.$emit is not a function" whenever the watcher fires.
I can console log the Event object since I imported it in my main.js file.
I use a named prop because I have 3 different client tables on 1 page. I named the table as rmTable
<v-client-table name="rmTable" :data="filteredRMInvData" :columns="rmColumns" :options="rmOptions" v-if="rmInventoryData.length">

In my watcher:
materialType(value) {
    Event.$emit('vue-tables.rmTable.filter::materialtype', value)
}

This is my customFilters in my rmOptions variable:
customFilters: [{
    name: 'materialtype',
    callback(row, query) {
        console.log(row)
        console.log(query)
        return query.code.includes(row.material_group)
    }
}],

How can I do this correctly? At least I should be able to see the row and query logs. I checked the guide on the github page and it seems I followed it correctly.

A: Assuming you have
Vue.use(VueTables.Event);

Then
materialType(value) {
    VueTables.Event.$emit('vue-tables.rmTable.filter::materialtype', value)
}

Event is already a browser interface, which I'm guess is the reason it doesn't work.


text:
Q: jQuery seems to not be loaded when using Chrome Web Console The following script run successfully via the Chrome Web Console for months is suddenly not working.
// Override site's disabling of the console.log function
console.log = console.__proto__.log

// get the DOM ready to process
$(document).ready()
function doThisThing(){
  window._waitWindow = setInterval(function(){

    // start looking for items not 'ready to go'
    items = $("div.Catalogitem-content");
    $.each(items, function(index){

           if($(items[index]).find(".Catalogitem-stager").text().includes("ready to go") || index < lastitemCount){
              $(this).css("background-color", "#84f784");
            } else {
                $(this).css("background-color", "#ff7089");
                $(this).find(".engage-cycle-btn").click();
              }
         });
        window.scrollTo(0, document.body.scrollHeight);
    }, 10000);
  return window._waitWindow;
}

function stopit() {
  clearInterval(window._waitWindow);
  console.log("Just executed clearInterval.");
}

The error thrown is:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[object HTMLDocument]' is not a valid selector.

The offending line is:

$(document).ready()

Actions I took:

*

*I checked to see if jQuery had been loaded properly.  The results of the following commands led me to believe jQuery wasn't loaded properly... maybe I'm wrong?

Command 1
$(document).ready(function($){ });

Uncaught DOMException: Failed to execute 'querySelector' on
  'Document': '[object HTMLDocument]' is not a valid selector.

Command 2
console.log($())

null

Command 3
$().jquery

Uncaught TypeError: Cannot read property 'jquery' of null(…)

Command 4
jQuery.jquery

Uncaught ReferenceError: jQuery is not defined(…)

Command 5
$('.class');

null

*Tried to load jQuery by running the following code in the Web Browser:
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
Got this error:

VM711:3 Refused to load the script
  'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'
  because it violates the following Content Security Policy directive:
  blah blah blah.

Been combing the internet for a solution, but feel I'm in a deep rabbit hole.
Is it that jquery's not loaded?
Is it that the site I'm processing data from has added a new layer of security to thwart my automation?
I'm at a loss.  Thanks in advance.

A: You posted the answer. Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' because it violates the following Content Security Policy - jQuery is not loading properly. Try changing https://ajax to just //ajax

A: This has been asked before, perhaps the answer to the following question will address your issue:
A subsite was referencing an older version of jQuery


text:
Q: Using/Compiling C++ with Cython I am working on a project which required a large number of dictionary lookups in cython. To try improve the speed I attempted to replace the dictionaries with unordered_maps from libcpp.
#!python
#cython: boundscheck=False, wraparound=False, infer_types=True,cdivision = True
from libcpp.unordered_map cimport unordered_map

However when I attempt to compile with gcc on the command line the compilation fails with
CAStar2.c:482:19: fatal error: utility: No such file or directory
 #include <utility>
                   ^
compilation terminated.

It seems the compiler cannot find multiple required files.
How would I point it to those files?

A: The cython generated C file needs to be compiled by a setuptools Extension.
If compiling manually all the include and lib directories that setuptools would otherwise use need to be also specified manually.
See cython setuptools documentation here and here for a minimal compile from cmd line example.

A: I turns out the issue was my compiler not activating support for c++11 which cython seems to produce. Adding the option -std=c++11 everything compiled normally.
Thanks though to everyone who helped.


text:
Q: number or size of python igraph communities I am using the python igraph package for community detection. Currently, I am using community_multilevel
communities = ig.Graph.community_multilevel(g)

However, the detected communities are too large, making them less informative. Is there a way to either specify the number of communities or restrict the size of the communities so they are smaller? I am not opposed to using other community detection algorithms available in igraph.
I know there was a similar question asked here: Python community module, restrict size of each community?, but it was never answered. I appreciate any feedback.

A:
Is there a way to either specify the number of communities or restrict the size of the communities so they are smaller?

The answer is pretty disappointing: no, there isn't; none of the community detection algorithms in igraph let you specify the number of communities in advance or restrict their sizes.


text:
Q: How to use xcopy with /exclude in a network path with spaces? I want to use xcopy on a network path. I actually do.
The problem is that I wanted to use an /exclude option. But the file would be in a network path. But the network path has spaces (s:\my path).
So this is what I'm using and it's working right now without /exclude (S: is a mapped network file):
xcopy "S:\TI\My Path" "C:\Path" /S /I /D /Q /Y

I've tried adding an /exclude file locally and it works fine (figured out I must use the 8.3 name):
xcopy "S:\TI\My Path" "C:\Path" /S /I /D /Q /Y /exclude:c:\MyConf~1\cfg.txt

But the same didn't work when I move to a network path. I think the main reason is that network path doesn't have a 8.3 name according to  dir /x.
xcopy "S:\TI\My Path" "C:\Path" /S /I /D /Q /Y /exclude:s:\MyConf~1\cfg.txt

Impossible to read the file: s:\MyConf~1\cfg.txt

The line above was translated by me from Brazilian Portuguese and may not be exactly what xcopy returns. But I think you get it.
I've tried to use a not mapped version, which is not practical actually and didn't work.
xcopy "S:\TI\My Path" "C:\Path" /S /I /D /Q /Y /exclude:\\server\MyConf~1\cfg.txt

Is there a way I can achieve this with xcopy? Is there any equivalent who does not need an install in every PC?

A: I figured out a not so elegant solution with help of an idea the user S. Brottes gave me in the comments.
I found a code to see the full UNC path associated with the letter here and made some changes.
My code finds the full UNC path of the letter I've already had mapped (in this case s:) gets the full UNC path and concatenates.
After that I map it to an unused letter and use it in the exclude parameter:
@REM Get the full UNC path, maps it to a letter, use the letter in the exclude parameter and exludes the mapped letter
cls

@set _NetworkPath=
@set _newLetterDrive=y

@REM finds the complete network path mapped to s:
@pushd "s:"

@for /f "tokens=2" %%i in ('wmic path win32_mappedlogicaldisk get deviceid^, providername ^| findstr /i "%CD:~0,2%"') do @(set _NetworkPath=%%i%CD:~2%)

@REM concatenates the actual network path with the added folder I need
@REM @echo. Debug info %_NetworkPath%

@set _newPath="%_NetworkPath%TI\My configs"

@REM maps deep into the folder to a known not used letter
net use %_newLetterDrive%: %_newPath%

@REM finally call the xcopy with the exclude file pointed out directly by y:
@REM @echo Debug info %_newPath%

xcopy "S:\TI\My Path" "C:\Path" /S /I /D /Q /Y /exclude:%_newLetterDrive%:\cfg.txt

@REM removes the used letter
net use %_newLetterDrive%: /delete /yes


text:
Q: Redirect all sub-directories but not parent I want to redirect all folders after a subdirectory:
example.com/sub/sub2/some-place
example.com/sub/sub3/some-place
example.com/sub/subY/some-place

to a subdomain:
sub.example.com/sub2/some-place
sub.example.com/sub3/some-place
sub.example.com/subY/some-place

This is the rule I'm using and it works:
RewriteRule ^sub/(.*)$ http://sub.example.com/$1 [R=302,L]

However, I don't want the example.com/sub/ directory to be redirected.
User visits example.com/sub/ should stay at /sub/
User visits example.com/sub/ANYTHINGELSE should be redirected to sub.example.com/ANYTHGINELSE
Thanks in advance.
EDIT: Question: How do I add an exclusion to the rule? Example: I want
example.com/sub/sub2/some-place
example.com/sub/sub3/some-place
example.com/sub/subY/some-place

to redirect as above but
example.com/sub/thispageshouldnotredirect

to NOT redirect. I tried adding this rule:
RewriteCond %{REQUEST_URI} !^/thispageshouldnotredirect

EDIT #2: This is working for me currently:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/sub/thispageshouldnotredirect/?$
RewriteRule ^sub/(.+)$ http://sub.example.com/$1 [R=302,L]

A: Use .+ in place of .* to make sure there are 1 more characters after /sub/:
RewriteRule ^sub/(.+)$ http://sub.example.com/$1 [R=302,L]


text:
Q: Does whole subtree rebuilds on setState in flutter I am new to flutter and really wondering if all the subtree of widgets gets rebuild when we call setState.
Subtree here means all the widget tree below that widget (including that widget as root node).
When we call setState function, the build method is called on the root node of the subtree, which triggers the build methods on its child. Say a branch (here MyWidget1) of a subtree (a child of that widget) is independent of the state variables. I noticed that even independent branches are rebuilt on setState called in the parent node.
class _MyAppState extends State<MyApp> {
  int count=0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: <Widget>[ MyWidget1(),MyWidget2(count),],),
      floatingActionButton: FloatingActionButton(onPressed: ()=>setState((){count++;}),),
    );
  }
}

class MyWidget1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) { print("widget builds 1");
    return Container(height: 100, color: Colors.orange,);
  }
}
class MyWidget2 extends StatelessWidget {
  final int count;
  MyWidget2(this.count);
  @override
  Widget build(BuildContext context) { print("widget builds 2");
    return Text(count.toString());
  }
}

Here we can see that MyWidget1 is independent of the state variable (here count), so generally, setState should have no impact on it.
I was wondering if there should be any optimization to avoid that useless build of MyWidget1 on the call of setState function. As the tree below MyWidget1 can be too big, that too will be rebuild again.
My Questions:

*

*Is it Ok for this Independent Widget (here MyWidget1) to build again on setState?

*Is there a better way to deal with this situation to avoid its rebuild.
Note: I have read this question
In this question, there is a way to avoid useless build by creating an instance of the independent branch outside the build method,
My doubt is :
Is this the WAY to deal with this situation or some other better way or this situation isn't that big at all as tree builds in O(n) time (which I think shouldn't be the answer because building tree might be O(n) operation but it may include many time-consuming operations which may not be optimization friendly to call again and again uselessly).

A: Yes, MyWidget1 is rebuilt upon that setState. Just trust the code. After you call setState, build is called, which calls the constructor of MyWidget1. After each setState, the entire subtree is rebuilt. Old widgets are thrown away. States are not thrown away, though. State instances live on, they are not recreated (see didUpdateWidget).
So, yes. After each setState, the entire subtree is rebuilt.
This is OK, don't worry.
The widget classes here are very lightweight classes. Dart's garbage collector is optimized to instantiate many such objects and throw them away together.
This tree that you get to recreate again and again is just a facade. There are two more parallel trees that are not lightweight and are not recreated. Your widget trees are diff'ed together to find how the actual ui elements should be modified by the system.
Why all this trouble, you may ask. Because creating trees is easy and maintaining them is difficult. This reactive declarative framework lets us get away with only creating the tree and not maintaining it.
There are some resources about Flutter internals that you can read more about this. One such resource is this video: https://www.youtube.com/watch?v=996ZgFRENMs

A: class _MyAppState extends State<MyApp> {
  int count=0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(children: <Widget>[ const MyWidget1(),MyWidget2(count),],),
      floatingActionButton: FloatingActionButton(onPressed: ()=>setState((){count++;}),),
    );
  }
}

class MyWidget1 extends StatelessWidget {
  const MyWidget1();
  @override
  Widget build(BuildContext context) { print("widget builds 1");
  return Container(height: 100, color: Colors.orange,);
  }
}
class MyWidget2 extends StatelessWidget {
  final int count;
  MyWidget2(this.count);
  @override
  Widget build(BuildContext context) { print("widget builds 2");
  return Text(count.toString());
  }
}

when the constructor starts with a "const" keyword, which allows
you to cache and reuse the widget.
When calling the constructor to initiate the widget, use the "const" keyword. By calling with the "const" keyword, the widget does not rebuild when any parent widgets change
their state in the tree. If you omit the "const" keyword, the widget will be build every time the parent
widget redraws.


text:
Q: Keras - First batch norm layer shown as input to every other batch norm layer in tensorboard, why is this the case? Sorry if this is something obvious that I'm missing, I've tried /r/learnmachinelearning and they're of no help so I thought I'd try here.
I am using this:
    def cnn_block_1(inp, filt, kernal, b_num):
        # Layer Names
        c1_left, b1_left, a1_left, c2_left, b2_left, a2_left, c3_left, b3_left, a3_left, p_left = \
        "c1_left_" + b_num, "b1_left_" + b_num, "a1_left_" + b_num, "c2_left_" + b_num, \
        "b2_left_" + b_num, "a2_left_" + b_num, "c3_left_" + b_num, "b3_left_" + b_num, \
        "a3_left_" + b_num, "p_left_" + b_num,

        # Block
        c1_l = Conv2D(filters=filt, kernel_size=kernal, padding="same", name=c1_left)(inp)
        bn1_l = BatchNormalization(name=b1_left)(c1_l)
        a1_l = Activation("relu", name=a1_left)(bn1_l)
        c2_l = Conv2D(filters=filt, kernel_size=kernal, padding="same", name=c2_left)(a1_l)
        bn2_l = BatchNormalization(name=b2_left)(c2_l)
        a2_l = Activation("relu", name=a2_left)(bn2_l)
        c3_l = Conv2D(filters=filt, kernel_size=kernal, padding="same", name=c3_left)(a2_l)
        bn3_l = BatchNormalization(name=b3_left)(c3_l)
        a3_l = Activation("relu", name=a3_left)(bn3_l)
        p_l = MaxPooling2D(padding="same", name=p_left)(a3_l)

        return p_l

    left_arm_blocks = 6
    filter_value = 2

    x1 = Sequential()
    x1.add(Embedding(vocab_char_size, embedding_char_size, input_length=maxlen, mask_zero=True,         weights=[e_char], name='embedding_1', trainable=False))
    x1.add(Lambda(lambda xo: K.expand_dims(xo, axis=3)))

    x2 = Sequential()
    x2.add(Embedding(vocab_word_size, embedding_word_size, input_length=maxlen, mask_zero=True,     weights=[e_word], name='embedding_2', trainable=False))
    x2.add(Lambda(lambda xo: K.expand_dims(xo, axis=3)))

    c = Concatenate(axis=3)([x1.output, x2.output])
    left_string = list()
    left_string.append(c)
    f_value = filter_value
    for i in range(left_arm_blocks):
        c = cnn_block_1(left_string[-1], f_value, kernal_value, str(i))
        left_string.append(c)
        f_value *= 2

    x = Lambda(lambda xq: xq, output_shape=lambda s: s)(left_string[-1])
    flat1 = Flatten()(x)
    #etc....

To string together a bunch of predefined CNN blocks. I am saving the output of each call to the function in a list and using the last output in the list as the input for the next layer etc. (I originally was just using the previous output as an input but made a list so I could ensure I wasn't going crazy in that capacity)
When I load the model on tensorboard to have a look at the architecture though, something bizarre is happening: https://i.imgur.com/zhjOkhe.png
Here's that node expanded: https://i.imgur.com/7ujMDVX.png & closer up: https://i.imgur.com/HpNgK4V.png
This one with no function and just the CNN layers: https://i.imgur.com/4G3IPgu.png
For some reason it shows that the first batch norm layer or "b1_left_0" is being used  as an input to every other batch norm layer in my entire model, including an entire other "right" arm of the model that is only connected to this via a concatenate layer much later on.
I'm assuming I'm missing something obvious here and am being dumb but I'm at a loss for how to try to work this out further as everything in my code seems to be working as intended.
Thanks in advance for any advice.

A: The graph is correct - that's how Keras represents certain operations like batch norm.
It creates a node in the graph that performs the operation (it keeps the first one encountered, the b1_left_0 in your case) and references is in every other node that performs the same operation.
The tensorboard visualization is not suited for a graph created with keras, hence in your case is better to refer to the model.summary() method to see if keras built the graph correctly.


text:
Q: undefined method `each' for "MySQL. Versions 5.0+ are recommended.":String in rails cloned the application from my friend I am getting this error, but in his machine working fine(same os), and deleted the database and trying to recreate but same issue.
mysql version: 5.7.19-0ubuntu0.16.04.1
my database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: root
  password: password
  socket: /var/run/mysqld/mysqld.sock

development:
  <<: *default
  database: timeline_sheet
test:
  <<: *default
  database: timeline_sheet_test

here is my gem file
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.7'
gem 'mysql2', '>= 0.3.13', '< 0.5'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc

gem 'simple_form'
gem 'jquery-ui-rails', '~> 4.2.1'
gem 'bootstrap-datepicker-rails', '~> 1.6', '>= 1.6.1.1'
gem 'carrierwave'
gem 'prawn'
gem 'pdfkit', '0.5.0'
gem 'wkhtmltopdf-binary'
gem 'passenger', '~> 5.0', '>= 5.0.30'
gem 'simple_format'
gem 'webrick', '~> 1.3.1'
group :development, :test do
  gem 'byebug'
end

group :development do
  gem 'web-console', '~> 2.0'
  gem 'spring'
end

application trace:
This error occurred while loading the following files:
   active_record/base

Framework trace:
activerecord (4.2.7) lib/active_record/connection_adapters/connection_specification.rb:150:in `resolve_all'
activerecord (4.2.7) lib/active_record/connection_handling.rb:69:in `resolve'
activerecord (4.2.7) lib/active_record/core.rb:46:in `configurations='
activerecord (4.2.7) lib/active_record/railtie.rb:117:in `block (2 levels) in <class:Railtie>'
activesupport (4.2.7) lib/active_support/lazy_load_hooks.rb:38:in `instance_eval'
activesupport (4.2.7) lib/active_support/lazy_load_hooks.rb:38:in `execute_hook'
activesupport (4.2.7) lib/active_support/lazy_load_hooks.rb:45:in `block in run_load_hooks'
activesupport (4.2.7) lib/active_support/lazy_load_hooks.rb:44:in `each'
activesupport (4.2.7) lib/active_support/lazy_load_hooks.rb:44:in `run_load_hooks'
activerecord (4.2.7) lib/active_record/base.rb:315:in `<module:ActiveRecord>'
activerecord (4.2.7) lib/active_record/base.rb:26:in `<top (required)>'
activesupport (4.2.7) lib/active_support/dependencies.rb:274:in `require'
activesupport (4.2.7) lib/active_support/dependencies.rb:274:in `block in require'
activesupport (4.2.7) lib/active_support/dependencies.rb:240:in `load_dependency'
activesupport (4.2.7) lib/active_support/dependencies.rb:274:in `require'
activerecord (4.2.7) lib/active_record/migration.rb:383:in `connection'
activerecord (4.2.7) lib/active_record/migration.rb:370:in `call'