text:
Q: Building Phantom Dancers
Disclaimer: I realize that most build questions have a, well, questionable presence on Arqade, I feel that my question is different enough in that it can have a definite answer.

I had an argument with a friend regarding build sequence, specifically to stacking Phantom Dancers on an AD carry. All things being equal, suppose that a typical AD carry has a Zeal. Should this AD carry turn this Zeal into a Phantom Dancers and then begin on another Zeal later or should the AD carry buy another Zeal and then upgrade either of them at later time?
I argued that buying another Zeal would be cost-effective as Zeal costs 1195G, as opposed to 1650G for the upgrade to Phantom Dancers. However, my friend argued that the first Phantom Dancers offers improved MS and AS as opposed to a second Zeal.

A: Your friend is correct. From a strict "gold per stat" cost analysis, Phantom Dancer's upgrade cost gives more bang for the buck than Zeal. I break down each stat on its own merit, but you have to take the composite (which is even more in PD's favor) to get the full picture.
Attack Speed
Zeal provides 20% Attack Speed. Phantom Dancer provides 55%, meaning that the upgrade over Zeal is 35% Attack Speed for the cost of the item. The price per stat then looks like:

*

*Zeal: 1195 Gold / 20% ASPD = 59.75 Gold per Percent ASPD

*Phantom Dancer Upgrade: 1650 Gold / 35% ASPD = 47.14 Gold per Percent ASPD

It is worth noting that two Zeals still gives the same Gold to Percent ASPD ratio. ASPD is also not multiplicative as far as items go, meaning that you do not get a higher final Attack Speed from two Zeals due to two multiplications by 1.20 instead of one by 1.55. (1.20 squared is still lower than 1.55, regardless.)
Critical Strike Chance
Zeal provides 10% Crit Chance. Phantom Dancer provides 30% - this makes Phantom Dancer an upgrade of 20% Crit Chance for the cost. This gives us a price per stat comparison of:

*

*Zeal: 1195 Gold / 10% Crit Chance = 119.50 Gold per Percent Crit

*Phantom Dancer Upgrade: 1650 Gold / 20% Crit Chance = 82.50 Gold per Percent Crit

Again, much like ASPD, two Zeals has the same price per stat point, and still doesn't compare to a Phantom Dancer. Crit chance is also additive.
Movement Speed
Movement speed is where Zeal earns a slight edge over the Phantom Dancer. Zeal's MS bonus is 6%; Phantom Dancer's is 12%, meaning the upgrade is merely another 6%. Price per point thus looks like:

*

*Zeal: 1195 Gold / 6% MS = 199.16~ Gold per Percent Movespeed

*Phantom Dancer Upgrade: 1650 Gold / 6% MS = 275 Gold per Percent Movespeed

It is important to note that, when considering Movement Speed, there are numerous soft caps/diminishing returns plateaus. Detailed on League Wiki, the gist is that any movespeed above 415 is reduced by 20%, and any movespeed above 490 is reduced by 50% (not cumulative). With Berserker Greaves and Zeal, any champion with base 320 or 330 movement speed is bumping into that 415 cap - both a second Zeal and their Phantom Dancer would be hit with the reduction. Most AD carries tend to be between 300 and 310 base MS, however, but quite a few have things that boost that, like Vayne, Sivir, or any carry that is running with Nunu support.
Conclusions
With the exception of Movement Speed - which in quite a few cases is already decayed by diminishing returns and is not really the hallmark stat of Zeal or Phantom Dancer, it is (from a gold perspective) almost always a better buy to upgrade Zeal into PD, as opposed to purchasing a second. Raven Dreamer's point about item slot efficiency is also important to consider - item space is often more precious than gold to an AD carry, due to the number of tools they need to succeed (Berserker Greaves, Infinity Edge, Last Whisper, some sort of Lifesteal item, and some sort of defensive item). The popularity of multiple early-game Doran's Blades for early game durability merely compounds this issue, and makes the advantage even more favorable for the singular, more cost-efficient item - the Phantom Dancer.

A: Ask Mr. Robot is a really neat tool for comparing builds.  Since questions like this can depend a lot on the specifics, I recommend you have a play with it yourself.
I did a quick comparison of the standard graves build (not exactly how I would build him, but close enough!) versus the same thing replacing the BT for a second Phantom Dancer.  Where build 1 completes his PD, build 2 picks up a second zeal instead.  Have a look at the DPS graph:

Obviously there are other, harder-to-quantify benefits such as movespeed and lifesteal.  And there's a billion assumptions about target armor and other things that you'd have to decide on from game to game.  Still; interesting!
Have a look at the setup here.

A: There are two things to consider here.
The first is that Movespeed has diminishing returns. So the second Zeal will often provide less movespeed than the first, so that should not be considered.
The bigger question is, do you have the inventory space for it?
With only 6 slots, one of which is going to be boots, buying a second zeal limits your options. Especially if you're in the process of building an IE, Blood Thirster / Sanguine Blade, or another big-cost, multi-component item, you may be shooting yourself in the foot if you run out of inventory space before you can spend the gold. (A common scenario would be having the BF Sword and Pickaxe of an IE, a doran's blade, and two zeals vs. the same with one phantom-dancer).
Gold banked but not spent isn't doing you any good, and if you buy a 2nd doran's blade, or a vamp scepter for early life steal, your inventory is at even more of a premium (to say nothing of buying health potions or wards).
If you've got the room for it, by all means, buy a zeal, but just realize by purchasing a 2nd zeal before buying, say, an Infinity Edge, or a BF Sword, you might actually be lowering your damage potential if you can't buy more damage later on. (A crit with 100 AD isn't nearly as impressive as a crit with 200+!)


text:
Q: How to test whether component contains string? I am trying to get my head around jest. This is my test:
test('whether contains className', () => {

    let list = [
        {
            id: 12,
            name: 'two',
            completed: true
        }
    ];

    const wrapper = shallow(
        <Todos todos={list}>
        </Todos>
    );

    expect(wrap).toMatch(/strikethrough/);
});

How can I check whether a component contains a (sub)string inside the component?

A: You can also use
expect('Something').toContain('thing');

A: You need to get the rendered text of the current render tree with .text() method.
expect(wrapper.text()).toMatch(/strikethrough/)

A: jest-extended package has extension toInclude
 expect('hello world').toInclude('ell');
  expect('hello world').not.toInclude('bob');

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting field to string with leading zeroes using Python Parser of ArcGIS Field Calculator? I would like to create an expression using the field calculator in ArcMap to be able to convert an Int field to a string and add leading zeroes.
I am able to do it in a python window with an example
x=450
print str(x).zfill(4)
>>>0450

I have tried:
!Time!.str().zfill(4)

but that gives me invalid syntax errors.

A: str is a class, not a method, so you need to do:
str(!Time!).zfill(4)

This should work if the Time field is an integer. If it's a float or other type, you will need to recast it as an int.


text:
Q: Show/hide navigation header depending upon platform in react-native I want to show/hide header depending upon a platform in react-native. I have done this
  const RNApp = createStackNavigator(
  {
    Menu: {
      screen: Menu,
      navigationOptions: {
        gesturesEnabled: false,
        headerBackground: (
          <Image
            style={[
              StyleSheet.absoluteFill,
              {
                width: Metrics.screenWidth * 0.5,
                height: Metrics.navBarHeight * 0.6,
                marginTop:
                  Platform.OS === "ios"
                    ? Metrics.navBarHeight * 0.45
                    : Metrics.navBarHeight * 0.2,
                marginLeft: Metrics.screenWidth * 0.25,

                resizeMode: "contain"
              }
            ]}
            source={images.icons.headerimage}
          />
        )
      }
    },
    WebViewScreen: {
      screen: WebViewScreen,
      navigationOptions: {
        headerVisible: Platform.OS === "ios" ? true : false,
        gesturesEnabled: false
      }
    }
  },
  {
    headerMode: "screen",
    initialRouteName: "Menu"
  }
);

This works if the platform is ios just like I want since there is no hardware back button there must be a header to navigate back. But with the above code the header is still visible in case of android too even with the condition I've given. How to solve this problem?

A: There isn't a property headerVisible. The property that you are looking for is header:

header
React Element or a function that given HeaderProps returns a React
  Element, to display as a header. Setting to null hides header.

In your case it has to be:
import { Header } from 'react-navigation'; // import the default header to use it for iOS

...

navigationOptions: {
    header: (headerOptions) => Platform.OS === 'android' ? null : <Header {...headerProps} />,
    gesturesEnabled: false
}

See also here.


text:
Q: MASS Package in R: "lower" of fitdistr(x,"weibull",lower=T) Is "lower" changing the densfunction to
y=shape/scale*(x/scale)^(shape-1) *e^((T^shape-x^shape)/(scale^shape))?

A: No, it changes the range within which the function searches for optimal parameter values. The distribution remains (from ?dweibull):

f(x) = (a/b) (x/b)^(a-1) exp(- (x/b)^a)

As usual, one of the best ways to figure this stuff out is to experiment.  Simulate some data and fit:
set.seed(101)
library(MASS)
z <- rweibull(1000,shape=2,scale=5)
fitdistr(z,"weibull")
##     shape        scale
##   1.99894352   5.06797419
##  (0.04950087) (0.08437483)

Now set a lower bound, but one that is non-binding - i.e. the estimated parameters are both above the lower bound:
fitdistr(z,"weibull",lower=c(1,4))
##     shape        scale
##  1.99894311   5.06797394
## (0.04950086) (0.08437484)

The answer is practically identical.
Now set a binding lower bound for one of the parameters:
fitdistr(z,"weibull",lower=c(2.5,4))
##      shape        scale
##  2.50000000   5.32522699
## (0.05815129) (0.07329413)

It seems as though you might be looking for a truncated Weibull distribution:
library("sos")
findFn("{truncated weibull}")


text:
Q: How to use validates_uniqueness_of with ActiveModel? I'm using ActiveModel to make my tableless models feel like ActiveRecord models. I'm using a custom store and I need to be able to validate uniqueness of a record.
How can I implement the required uniqueness check using ActiveModel?

A: I ended up doing something like this:
class Theme < Base

  include ActiveModel::Validations

  attr_accessor :id, :name
  validate      :uniqueness_of_theme_name, :on => :create

  def initialize(attrs = {})
    attrs.each do |name, value|
      send("#{name}=", value)
    end
  end

  def uniqueness_of_theme_name
    errors.add(:name, "name is already in use") unless Theme.find_by_name(name).nil?
  end

  def self.find_by_name(name)
    return store.find({ 'name' => "/^#{name}$/i" }).any?
  end

  def self.create(attributes = {})
    theme = Theme.new(attributes)
    theme.save

    return theme
  end

  def persisted?
    id && !id.nil?
  end

  def save()
    # only call validation during create context
    context = persisted? :update : :create
    false if invalid?(context)
    store.save(self)
    true
  end

  def self.create(attrs = {})
    theme = Theme.new(attrs)
    theme.save
    theme
  end

end

Maybe someone can tell me if this was the correct way to go about it

A: Check this railscasts, it might help
http://railscasts.com/episodes/193-tableless-model
once you do your model, add the validations and then @model.valid?

A: ActiveModel can be used with according to another railscasts, which is more suitable for that use-case.
class Theme

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :id, :name

  validates :name, uniqueness: true, on: :create

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end


text:
Q: Laravel Passport API call always return Unauthenticated So I have setup my API with Passport and tried to make GET request for almost a week now but still getting the response bellow :
{
"message": "Unauthenticated."
}

Below are my configuration :
Auth.php
'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

'guards' => [
    'web' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        //'hash' => true,
    ],
],

AuthServiceProvider.php
public function boot()
{
    $this->registerPolicies();

    //
    Passport::routes();
    Passport::tokensExpireIn(Carbon::now()->addDays(7));

   Passport::refreshTokensExpireIn(Carbon::now()->addDays(14));

}

RouteServiceProvider
 protected function mapApiRoutes()
{
    Route::prefix('api')
         ->middleware('auth:api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

Controller : Token request function using user credentials as per laravel doc
public function callback(Request $request)
{
     $http = new Client();
    $token_url=url('oauth/token');

$response = $http->post($token_url, [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => $this->client_id,
        'client_secret' => $this->client_secret,
        'username'=>'my-username',
        'password'=>'my-password',
        'scope' =>'*',
    ],
]);

return json_decode((string) $response->getBody(), true);
}

Which returns an access_token that I use in my request in my request .  I tried all the solution listed below and none of them worked :
.htaccess
# Handle Authorization Header
 RewriteCond %{HTTP:Authorization} .
 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Passport.php line 167
 public static function tokensExpireIn(DateTimeInterface $date = null)
{
    if (is_null($date)) {
        return static::$tokensExpireAt
                        ? Carbon::now()->diff(static::$tokensExpireAt)
                        : new DateInterval('P1Y');
    }

    static::$tokensExpireAt = $date;

    return new static;
}

Please help , I'm desperate now :)

A: The problem is how you authenticate and which token you are using.
There are 2 ways to generate token

*

*Users login and you use create token to get the token if user is authenticated.

*Generate a client and use PRE built routes by passport to get token

Now in the API routes you have to tell in your method how you are authenticating for example
// Below one is for authenticating Client token
Route::get('/test', 'Api\TestController@index')->middleware('client_credentials');

// Below one is for the User token
Route::get('/test', 'Api\TestController@index')->middleware('auth:api');

And Remember if you are using client authentication, you have to add the below line in routemiddleware in App/http/kernel.php
'client_credentials' => \Laravel\Passport\Http\Middleware\CheckClientCredentials::class
I hope that solves issues

A: Try creating a new password grant client with:
php artisan passport:client --password

You'll get an output like:
What should we name the password grant client? [Laravel Password Grant Client]:
 >

Password grant client created successfully.
Client ID: 4
Client secret: WlRYEbA5lt5esbi0MuFyJPzPDmHDGsk3iC5QGw7d

Use those credentials to fill your client id and secret.  Standard client credentials created through the Vue component interface do not work for password grants.


text:
Q: Android Plot for String Parameters My app requires the Y-axis to have strings like 'Charging', 'Discharging' and 'Charging Failed'. Is it possible to plot a graph with this and have the parameter in question depicted in accordance with these strings on Android Plot?

A: I'm still not 100% sure I'm understanding the desired visualization but here are the basic steps I would suggest:
To start, you're going to need to convert your CSV data in to XYSeries data.  To accomplish this, you'll need to map your current X/Y string values to numbers.  I'd suggest creating a method that looks something like this:
// parses a CSV string into an XYSeries
// for example, DISCHARGE = 1, MPPT = 2
public XYSeries convertCSVToXYSeries(String csvContent) {...}

Next, setup your Plot etc. pretty much the same way you would for any other XYPlot as shown in the Androidplot Quickstart Tutorial.
When you add the XYSeries you get back from convertCSVToXYSeries to your plot, use an XYStepFormatter:
StepFormatter stepFormatter  = new StepFormatter(Color.BLUE, Color.BLUE);
stepFormatter.setVertexPaint(null); // don't draw individual points
plot.addSeries(series, stepFormatter);

Finally, add a custom range value formatter to print your status strings instead of the int values they've been mapped to:
        // create a custom getFormatter to draw our state names as range tick labels:
        plot.setRangeValueFormat(new Format() {
            @Override
            public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
                Number num = (Number) obj;
                switch(num.intValue()) {
                    case 1:
                        toAppendTo.append("DISCHARGE");
                        break;
                    case 2:
                        toAppendTo.append("MPPT");
                        break;
                    default:
                        toAppendTo.append("Unknown");
                        break;
                }
                return toAppendTo;
            }

            @Override
            public Object parseObject(String source, ParsePosition pos) {
                return null;
            }
        });


text:
Q: How can I disable jquery validation on readonly fields? The product I am working for uses JQuery validation with MVC3 working behind the scenes.  I have a field that I toggle as read only (based on whether or not a dropdown's value is > 0) or not.
The trick is, this field needs to be required when it is not read-only, and needs to submit without errors when it is read-only, whether or not it has data.
How should I go about doing this?

A: $.validator.setDefaults({
    ignore: ':hidden, [readonly=readonly]'
});

The default for the ignore parameter is ":hidden". By resetting the default using the above code, you make sure that jquery validate still does not act on hidden form elements, but also does not act on elements that have a readonly="readonly" attribute.
Reply to comments
That sounds odd, you may have to post some code to get more help. One thing you could try to remove the validation errors is to manually validate the form when you toggle the readonly attribute, something like this perhaps:
$('#the_text_box').attr('readonly', 'readonly');
$.validator.setDefaults(':hidden');
$('form').valid();
$.validator.setDefaults(':hidden, [readonly=readonly]');

You could also do something similar during the initial page load to avoid the instant validation error messages.
$.validator.setDefaults(':hidden, [readonly=readonly]');
$('form').valid();


text:
Q: Google SignIn with firebase in flutter Exception PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null) I am trying googleSignIn with Firebase in flutter .My App is Already connected with Firebase firestore and Does Read/Write (Crud) Operations Perfectly.NOw I want to Integrate GoogleSignIn .But I am Getting an Un-handled exception.. I have Tried a tons of Solution of this Platform Answers and Github ,But Unfortunately non of them could solve my problem.
E/flutter ( 2995): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: ,null)

      final GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
      final GoogleSignInAuthentication googleSignInAuthentication =
     await googleSignInAccount.authentication;

final AuthCredential credential = GoogleAuthProvider.getCredential(
  accessToken: googleSignInAuthentication.accessToken,
  idToken: googleSignInAuthentication.idToken,
);

final AuthResult authResult = await _firebaseAuth.signInWithCredential(credential);
final FirebaseUser user = authResult.user;

assert(user.email != null);
assert(user.displayName != null);
assert(user.photoUrl != null);

name = user.displayName;
email = user.email;
imageUrl = user.photoUrl;

assert(!user.isAnonymous);
assert(await user.getIdToken() != null);

final FirebaseUser currentUser = await _firebaseAuth.currentUser();

assert(user.uid == currentUser.uid);

A: Try to add SHA1 to the Firebase project if you haven't done so.
This is Code 10 exception. With "sign_in_failed" error. You can get a report here with same instructions on setting up SHA1.

A: I got fixed my Problem,Actually the main problem was due to change of Package name in firebase and in my project.. Previously I used to replace the package name in json file, whenever I had to read and write the data    in firebase.Hope this may help someone in future.


text:
Q: change alignment of \lfoot and \cfoot in latex with \fancyhdr I am using \pagestyle{fancy} and am trying to align the \lfoot and \cfoot sections of a page.
Here's my code:
\documentclass{article}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{lipsum}
\renewcommand\familydefault{\sfdefault}
\makeatletter
\usepackage[letterpaper,top=1.in,left=0.4in,right=0.4in]{geometry}
\usepackage{calc}
\usepackage{varwidth} %for the varwidth minipage environment
\pagestyle{fancy}
\setlength{\footskip}{60pt}

\lhead{}
\chead{}
\rhead{}
\lfoot{\includegraphics[scale=0.22]{fakelogo}}
\cfoot{Footer \\ more footer}
\rfoot{}
\renewcommand\headrulewidth{0pt}
\renewcommand\footrulewidth{0pt}
\fancyhfoffset[LH]{\oddsidemargin + \hoffset + 0.5in}

\begin{document}

\lipsum[1-5]

\end{document}

This results in the resulting output

Based on my reading of the fancyhdr documentation and geometry, I've tried messing with \footskip and \fancyhfoffset but they all seem to move both the \cfoot and the \lfoot, and keep them non-centered. Any ideas?

A: You can raise (or lower) the contents of \lfoot and \cfoot into position, or do the following:

\documentclass{article}

\usepackage{fancyhdr,lipsum}
\usepackage[export]{adjustbox}

\pagestyle{fancy}

\fancyhf{} % Clear header/footer
\fancyfoot[L]{\includegraphics[scale=0.22,valign=c]{example-image}}
\fancyfoot[C]{\begin{tabular}{@{}c@{}}Footer \\ more footer\end{tabular}}

%\setlength{\footskip}{60pt}% Depends on image size

\begin{document}

\lipsum[1-5]

\end{document}

The image is assigned a vertical alignment that is centred, while \cfoot is placed inside a tabular. Without specifying the tabular vertical alignment, it defaults to being centred.


text:
Q: Express $1 + \frac {1}{2} \binom{n}{1} + \frac {1}{3} \binom{n}{2} + \dotsb + \frac{1}{n + 1}\binom{n}{n}$ in a simplifed form I need to express $$1 + \frac {1}{2} \binom{n}{1} + \frac {1}{3} \binom{n}{2} + \dotsb  + \frac{1}{n + 1}\binom{n}{n}$$ in a simplified form.
So I used the identity $$(1+x)^n=1 + \binom{n}{1}x + \binom{n}{2}x^2 + \dotsb   + \binom{n}{n}x^n$$
Now on integrating both sides and putting $x=1$.
I am getting $$\frac{2^{n+1}}{n+1}$$ is equal to the given expression.But the answer in my book is  $$\frac{2^{n+1}-1}{n+1}.$$
Where does that -1 term in the numerator come from?

A: $$\int^{1}_{0} (1+x)^n dx=\frac{(1+x)^{n+1}}{n+1}\bigg|^{1}_{0}=\frac{(1+1)^{n+1}-(1+0)^{n+1}}{n+1}=\frac{2^{n+1}-1}{n+1}$$
With indefinite integrals, there is always a constant of integration walking around. Hence, we use definite integrals so that the equality is kept.

A: Among $n+1$ people, a subset is randomly selected (i.e., each person will be in the subset or not with probability $1/2$). Then one person in the subset (if it is nonempty) is selected at random to win a prize. What's the probability that I (one of the $n+1$ people) win it?
There are $\binom{n}{k}$ ways to pick a subset of size $k+1$ that contains me; the probability of that subset is $\frac{1}{2^{n+1}}$, and the probability that I am the one selected is $\frac{1}{k+1}$. So the desired probability is
$$
\frac{1}{2^{n+1}} \sum_{k=0}^n \frac{1}{k+1} \binom{n}{k}. \tag{1}
$$
On the other hand, everyone out of the $n+1$ has an equal chance of winning, and there is only a $\frac{1}{2^{n+1}}$ chance of no one being selected, so the probability is
$$
\frac{2^{n+1} - 1}{2^{n+1}}  \cdot \frac{1}{n+1}. \tag{2}
$$
Thus (1) and (2) are equal, and if we multiply by $2^{n+1}$ we get
$$
\sum_{k=0}^n \frac{1}{k+1} \binom{n}{k}
= \frac{2^{n+1} - 1}{n+1}.
$$

A: Note that $$\binom{n+1}{k+1}=\frac{n+1}{k+1}\binom{n}{k}$$
Therefore,
\begin{align}
\sum_{k=0}^{n}\frac{1}{k+1}{n\choose k}&=\frac{1}{n+1}\sum_{k=0}^{n}\frac{n+1}{k+1}{n\choose k}
\\&=\frac{1}{n+1}\sum_{k=0}^{n}{{n+1}\choose {k+1}}
\\&=\frac{1}{n+1}\left [\sum_{k=0}^{n+1}{{n+1}\choose k}-1\right ]
\\&=\frac{1}{n+1}\left (2^{n+1}-1\right )
\end{align}

A: Remember when you integrate both sides, there will be the constant of integration. You need to first find this constant of integration. That's where the $-1$ comes from. In actual fact, it is $\frac{-1}{n+1}$ but looks like $-1$ because it's been absorbed into the numerator.
You may like to try $x=0$ to find this $+C$ value...


text:
Q: MSMQ compatibilty I was wondering if a VB6 app (Using MSMQ version 1) sending a message which contains an XML (Microsoft version 2.0) to a private queue can be read on the receiving end with C# application (using MSMQ version 5.0 / XML from .NET 4.0)
thx

A: The version of MSMQ doesn't matter here as all versions are compatible. There are minor gotchas, though. Also, you may find some inconsistency between the versions in your testing but I'd be surprised if you did.


text:
Q: What is the correct one to zero or one mapping in Entity Framework? I have this model:
public class Address
{
    public int Id {get; set;}
    public string Street {get; set;}
    public string HouseNo{get; set;}
}

public class Customer
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int AddressId {get; set;}
    public virtual void Address Address {get; set;}
}

The current mapping for the Customer map is:
this.Property(t => t.AddressId).HasColumnName("address_id");

this.HasOptional(t => t.Address)
    .WithMany()
    .HasForeignKey(d => d.AddressId);

There is no mapping back to the Customer in the Address map.
But this is not working because if I remove the address from the customer, the address record is not deleted from the db.
What is the correct way to add a 1..0-1 relationship where the 0-1 side is owned by the 1 side?

A: Try this one
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>()
               .HasOptional(customer => customer.Address)
               .WithRequired()
               .Map(mapping => mapping.MapKey("custom_fk_customer_id"));

   base.OnModelCreating(modelBuilder);
}


text:
Q: Integration test with infinite loop I need to run an integration test but having some issues, I know the first thing people are going to say which I have read in other answers is extract what is in the infinite loop to a method and test that, but it's not that simple as we are creating some stuff being used in the loop at runtime from a factory beforehand and I want to test the whole flow of the application via integration test.
while (true) {
    retrieveMessage();
}

I want to receive the one message I have sent and then exit (from the integration test only not from the running application when deployed).
I have thought about doing something like
if ("test".equals(getSpringActiveProfile()) {
   break;
}

But this would be bad practice would it writing into my codebase specifically for a test?
Any ideas or thoughts appreciated.
Thanks

A: In general a program should have a "natural" way to exit, infinite loops are a code smell per se... I would look for some approach like this:
boolean keepRunning = true; //even better as private field, then your class can get a "public void stop() { keepRunning = false; } method or something similar...
while(keepRunning) {
    //do whatever you need
}

This can be controlled by your test, and in the productive code, it can be used to kill the app when some kill-event arrives cleaning up everything...


text:
Q: Cannot set headers after they are sent to the client - error in my console I`m getting  the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" error in my code. Please, help me to understand what I'm doing wrong.
I try to use Passport middleware in my app
passport.strategy
passport.use(
  new LocalStrategy(
    {
      usernameField: "signinEmail",
      passwordField: "signinPassword",
    },
    //  Passport verify callback
    async (email, password, done) => {
      const user = await userService.getByEmailOrPhone(email);
      if (user) {
        if (user.password) {
          bcrypt.compare(password, user.password, (err, res) => {
            if (!err) {
              if (res) {
                return done(null, user);
              }
              return done(null, false, { message: "Incorrect password" });
            }
            console.log(err);
          });
        }
        return done(null, false, {
          message: "Please login with Google or Facebook",
        });
      }
      return done(null, false, { message: "Incorrect login" });
    }
  )
);

Route with middleware
router.post(
  "/login",
  passport.authenticate("local"),
  validationMiddleware({
    signinEmail: ["required", "email"],
    signinPassword: ["required", "min:6"],
  }),
  asyncHandler(async (err, req, res) => {
    // if (err) {
    //   console.log(res);
    // }

    const { accessToken, refreshToken } = await authService.authorizeById(
      req.req.user.user_id
    );
    console.log("user", accessToken);
    if (accessToken) {
      return res.send({
        accessToken,
        refreshToken,
        success: true,
      });
    }
    throw new UnauthorizedException("");
  })
);

I will be glad if someone helps.

A: You should add corresponding else branch of if in your strategy, You should write it as,
passport.use(
  new LocalStrategy(
    {
      usernameField: 'signinEmail',
      passwordField: 'signinPassword',
    },
    //  Passport verify callback
    async (email, password, done) => {
      const user = await userService.getByEmailOrPhone(email);
      if (user) {
        if (user.password) {
          bcrypt.compare(password, user.password, (err, res) => {
            if (!err) {
              if (res) {
                return done(null, user);
              }
              return done(null, false, { message: 'Incorrect password' });
            }
            console.log(err);
          });
        } else {
          return done(null, false, {
            message: 'Please login with Google or Facebook',
          });
        }
      } else {
        return done(null, false, { message: 'Incorrect login' });
      }
    }
  )
);


text:
Q: Why is this Monte Carlo Haskell program so slow? update:
My compilation command is ghc -O2 Montecarlo.hs. My random version is random-1.1, ghc version is 8.6.4, and my system is macOS Big Sur 11.1 (Intel chip). The command I used to test the speed is time ./Montecarlo 10000000, and the result it returns is real 0m17.463s, user 0m17.176s, sys 0m0.162s.

The following is a Haskell program that uses Monte Carlo to calculate pi. However, when the input is 10 million, the program ran for 20 seconds. The C program written in the same logic took only 0.206 seconds. Why is this, and how can I speed it up? Thank you all.
This is the Haskell version:
import System.Random
import Data.List
import System.Environment

montecarloCircle :: Int -> Double
montecarloCircle x
   = 4*fromIntegral
        (foldl' (\x y -> if y <= 1 then x+1 else x) 0
           $ zipWith (\x y -> (x**2 + y**2))
                     (take x $ randomRs (-1.0,1) (mkStdGen 1) :: [Double])
                     (take x $ randomRs (-1.0,1) (mkStdGen 2) :: [Double]) )
        / fromIntegral x

main = do
    num <- getArgs
    let n = read (num !! 0)
    print $ montecarloCircle n

This is the C version:
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>

#define N       10000000

#define int_t   long // the type of N and M

// Rand from 0.0 to 1.0
double rand01()
{
    return rand()*1.0/RAND_MAX;
}

int main()
{
        srand((unsigned)time(NULL));

        double x,y;
        int_t M = 0;

        for (int_t i = 0;i < N;i++)
        {
                x = rand01();
                y = rand01();
                if (x*x+y*y<1) M++;
        }
        double pi = (double)4*M/N;
        printf("%lf\n", pi);
}

A: It is sort of expected that on numerical applications, Haskell code tends to be say 2X to 5X slower than equivalent code written in classic imperative languages such as C/C++/Fortran. However, Haskell code being 100 times slower is very unexpected !
Sanity check: reproducing the result
Using a somewhat oldish notebook with an Intel Celeron N2840 64 bits cpu, running Linux kernel 5.3, GLIBC 2.28, GCC 8.3, GHC 8.2.2, GHC random-1.1, we get the timings:

C code,        gcc -O3:    950 msec
Haskell code,  ghc -O3:    104 sec

So indeed, with these configurations, the Haskell code runs about 100 times slower than the C code.
Why is that ?
A first remark is that the π computing arithmetics atop random number generation looks quite simple, hence the runtimes are probably dominated by the generation of 2*10 millions pseudo-random numbers. Furthermore, we have every reason to expect that Haskell and C are using completely unrelated random number generation algorithms.
So, rather than comparing Haskell with C, we could be comparing the random number generation algorithms these 2 languages happen to be using, as well as their respective implementations.
In C, the language standard does not specify which algorithm function srand() is supposed to use, but that tends to be old, simple and fast algorithms.
On the other hand, in Haskell, we have traditionally seen a lot of complaints about the poor efficiency of StdGen, like here back in 2006:
https://gitlab.haskell.org/ghc/ghc/-/issues/427
where one of the leading Haskell luminaries mentions that StdGen could possibly be made 30 times faster.
Fortunately, help is already on the way. This recent blog post explains how the new Haskell random-1.2 package is solving the problem of StdGen lack of speed, using a completely different algorithm known as splitmix.
The field of pseudo-random number generation (PRNG) is a rather active one. Algorithms routinely get obsoleted by newer and better ones. For the sake of perspective, here is a relatively recent (2018) review paper on the subject.
Moving to more recent, better Haskell components:
Using another, slightly more powerful machine with an Intel Core i5-4440 3GHz 64 bits cpu, running Linux kernel 5.10, GLIBC 2.32, GCC 10.2, and critically Haskell package random-1.2:

C code,        gcc -O3:    164 msec
Haskell code,  ghc -O3:    985 msec

So Haskell is now "just" 6 times slower instead of 100 times.
And we still have to address the injustice of Haskell having to use x**2+y**2 versus C getting x*x+y*y, a detail which did not really matter before with random-1.1. This gives us 379 msec ! So we are back into the usual 2X-5X ballpark for Haskell to C speed comparisons.
Note that if we ask the Haskell executable to run with statistics on, we get the following output:

$ time q66441802.x +RTS -s -RTS 10000000
3.1415616
     925,771,512 bytes allocated in the heap
     ...
  Alloc rate    2,488,684,937 bytes per MUT second

  Productivity  99.3% of total user, 99.3% of total elapsed

real   0m0,379s
user   0m0,373s
sys    0m0,004s

so Haskell is found to allocate close to one gigabyte of memory along the way, which helps to understand the speed difference.
A code fix:
We note that the C code uses a single random serie while the Haskell code is using two, with two calls to mkStdGen with numbers 1 and 2 as seeds. This is not only unfair but also incorrect. Applied mathematicians who design PRNG algorithms take great care to ensure any single serie has the right statistical properties, but give essentially no guarantees about possible correlations between different series. It is not unheard of to even use the seed as an offset into a single global sequence.
This is fixed in the following code, which does not alter performance significantly:
computeNorms :: [Double] -> [Double]
computeNorms []  = []
computeNorms [x] = []
computeNorms (x:y:xs2) = (x*x + y*y) : (computeNorms xs2)

monteCarloCircle :: Int -> Double
monteCarloCircle nn =
    let
         randomSeed   =  1
         gen0         =  mkStdGen randomSeed
                      -- use a single random serie:
         uxys         =  (randomRs  (-1.0, 1.0)  gen0) :: [Double]
         norms        =  take nn (computeNorms uxys)
         insiderCount =  length  $  filter (<= 1.0) norms
    in
         (4.0::Double) * ((fromIntegral insiderCount) / (fromIntegral nn))

Side note:
The new Haskell random-1.2 package has been mentioned in this recent SO question, though in the context of the new monadic interface.
A word of conclusion:
Assuming the goal of the exercise is to gauge the relative runtime speeds of the C and Haskell languages, there are essentially two possibilities:
One is to avoid using PRNG altogether, because of the different algorithms in use.
The other one is to control random number generation by manually providing one and the same algorithm into both languages. For example, one could use the publicly available MRG32k3a algorithm designed by Pierre L'Ecuyer. Candidate Haskell MRG32k3a implementation here (as of March 2021). Left as an exercise for the reader.


text:
Q: Java: Convert String containing days, hours, minutes to Date object My application gives me a string like 1 day 15 min or 15 hours 10 min etc.
I would like to convert this string to Date object.
I was trying some thing like this
Date afterAddingTenMins = new Date(t + (Integer.valueOf(duration) * ONE_MINUTE_IN_MILLIS));

But this gives me invalid Integer exception because string contains words like hours and min.
What is the best way to do it.
Thank you.

A: Here is a scala version:
object PrettyTimeParser {
  private val YEAR_REGEX = """(?<YEAR>\d+)\s*years?""".r
  private val MONTH_REGEX = """(?<MONTH>\d+)\s*months?""".r
  private val WEEK_REGEX = """(?<WEEK>\d+)\s*weeks?""".r
  private val DAY_REGEX = """(?<DAY>\d+)\s*days?""".r
  private val HOUR_REGEX = """(?<HOUR>\d+)\s*hours?""".r
  private val MINUTE_REGEX = """(?<MINUTE>\d+)\s*minutes?""".r

  private def lookup(regex: scala.util.matching.Regex, s: String): Int = {
    Try(regex.findAllIn(s).toList.headOption.map(_.split(" ")).map(_(0).toInt)).getOrElse(None).getOrElse(0)
  }

  def parse(str: String): Option[DateTime] = {
    val year = lookup(YEAR_REGEX, str)
    val month = lookup(MONTH_REGEX, str)
    val week = lookup(WEEK_REGEX, str)
    val day = lookup(DAY_REGEX, str)
    val hour = lookup(HOUR_REGEX, str)
    val minute = lookup(MINUTE_REGEX, str)

    val now = DateTime.now()

    val dt = DateTime.now().plusYears(year)
      .plusMonths(month)
      .plusWeeks(week)
      .plusDays(day)
      .plusHours(hour)
      .plusMinutes(minute)

    if (dt.isAfter(now.getMillis)) Option(dt) else None
  }

}

A: You can extract them by regex:
    String time = "1 day 15 min";
    Pattern pat = Pattern.compile("(?<DAY>\\d+)\\s*days?|(?<HOUR>\\d+)\\s*hours?|(?<MIN>\\d+)\\s*min");
    Matcher m = pat.matcher(time);
    int day = 0, hour = 0, min = 0;
    while (m.find()) {
        if (m.group("DAY") != null) day = Integer.parseInt(m.group("DAY"));
        if (m.group("HOUR") != null) hour = Integer.parseInt(m.group("HOUR"));
        if (m.group("MIN") != null) min = Integer.parseInt(m.group("MIN"));
    }
    System.out.printf("%d day %d hour %d min%n", day, hour, min);
    // -> 1 day 0 hour 15 min

A: The ideal solution would be to change your data source to provide JSON or some other reliable format:
{
    days: 15,
    hours: 9,
    minutes: 30
}

Then you can use a JSON library to parse the data.
But if you're stuck dealing with that string, you can go the regex route like saka1029 mentioned, or even simpler, just manually parse the String:
String test = "15 hour 10 min";
    String[] testArray = test.split(" ");
    long additionalDuration = 0;
    for(int i = 0; i < testArray.length; i+=2) {
        switch(testArray[i+1].toLowerCase()) {
            case "day":
            case "days":
                additionalDuration += Integer.parseInt(testArray[i]) * (1000 * 60 * 60 * 24);
                break;
            case "hour":
            case "hours":
                additionalDuration += Integer.parseInt(testArray[i]) * (1000 * 60 * 60);
                break;
            case "minute":
            case "minutes":
                additionalDuration += Integer.parseInt(testArray[i]) * (1000*60);
                break;
            default:
                System.out.println("Could not parse unit: \""+testArray[i+1]+"\"");
        }
    }
    Date futureDate = new Date(new Date().getTime() + additionalDuration);


text:
Q: jQuery Form Plugin: ajaxForm() not working with file upload Here's an issue I'm having with the .ajaxForm() method of the jQuery Form Plugin. To keep things as understandable as possible, I've included most of the salient info in comments with snippets below.
Tested in both Chrome and Firefox, and FORM_2 does actually post to server once I select a file to upload. The problem is that the deal_upload_image_file input is not being included with the post, so the server is not receiving any file.
html:
<!-- FORM_1: Big form, I need to position a file input field in here, -->
<!-- but don't want to submit the file with this form                 -->
<form id="edit_deal_form">
  <div id="upload_image_div">
    <!-- Javascript appends the "deal_upload_image_file" input here, then -->
    <!-- appends it to FORM_2 when a file is selected                     -->
  </div>
</form>

<!-- FORM_2: A second form that is not visible to user and will -->
<!-- actually do the post of the  multipart data                -->
<form id="deal_upload_image_form" name="upload_image_form" method="post" enctype="multipart/form-data" action="/upload_image" accept-charset="UTF-8">
</form>

javascript:
$(function() {
  add_upload_image_elements();
});

// Add deal_upload_image_file input to FORM_1, and add onChange handler
// to immediately POST to server once a file has been selected
function add_upload_image_elements() {
    $('<input>').attr("id", "deal_upload_image_file").attr("name", "deal_upload_image_file").attr("type", "file").appendTo($('#upload_image_div'));
    $('#deal_upload_image_file').change(function () {
        upload_image();
        return false;
    });
}

// Move the file input to FORM_2, set up the ajaxForm handler,
// and call submit() on FORM_2.
//
// For clean up, clear the file input field and add it back to FORM_1.
function upload_image() {
    // This input field is not getting posted with FORM_2
    // even though I append it here!!!
    $('#deal_upload_image_file').appendTo($('#deal_upload_image_form'));

    $('#deal_upload_image_form').ajaxForm({
        success: function(response) {
            alert("Success callback");
        },
        error: function(response) {
            alert("Error callback");
        }
    });
    $('#deal_upload_image_form').submit();

    // clean up
    $('#deal_upload_image_file').remove();
    add_upload_image_elements();
}

Thanks!

A: File inputs always have some security reasons. So copying it, reattaching it to other forms can erase values. I suggest you to change the page markup to use the file input in the same place, but in other form (visible of course). If it is difficult to position file input form without wrapping it in big form, try to use absolute positions.

A: If you don't consider old browser compatibility, just use new HTML5 APIs. See this answer: Html 5 File upload


text:
Q: Node-Forge: how can I convert the public key's modulo and exponent from decimal to hex? I'm using node forge (https://www.npmjs.com/package/node-forge) to create a public and private key pair (nodeforge.pki.rsa.generateKeyPair()) for testing purposes. The modulo (n) and exponent (e) of the public key is represented as an array of decimal values. However, the service that will provide the public key for encryption in production represents modulo and exponent in hex values. My question now is, how can I easily transform these values created by node forge from decimal to hex (I then want to use these values in NodeRSA (https://github.com/rzcoder/node-rsa)):
let pair = nodeforge.pki.rsa.generateKeyPair();

var key = new NodeRSA();
key.importKey({
    n: new Buffer(pair.publicKey.n.data, 'hex'),
    e: new Buffer(pair.publicKey.e.data, 'hex')
});

The format of the public key provided by node forge is:
"publicKey": {
    "n": {
        "data": [
            95452259,
            62292680,
            234781115,
            46168802,
            112578909,
            58538647,
            44874864,
            186853653,
            197342112,
            104676488,
            229032986,
            262511790,
            101189381,
            134141598,
            55892282,
            145717908,
            78729040,
            107967002,
            62922480,
            120440374,
            262852613,
            65361518,
            128040269,
            29796715,
            171859902,
            201093939,
            131227011,
            165441987,
            9273795,
            130804401,
            240125365,
            221986724,
            32034899,
            180589760,
            106981089,
            188935555,
            21820073,
            96309166,
            54553752,
            100808208,
            198611546,
            11382488,
            139519439,
            212193674,
            26780810,
            225883560,
            101310123,
            78467199,
            181998612,
            8435669,
            195696345,
            41284550,
            129888967,
            137003722,
            74415901,
            92893643,
            57787310,
            143216416,
            42433969,
            100838107,
            34667532,
            136300465,
            185624737,
            67347,
            93800454,
            226047286,
            76852009,
            57120535,
            266741908,
            27775411,
            39685199,
            4113773,
            214629603,
            12
        ],
        "t": 74,
        "s": 0
    },
    "e": {
        "data": [
            65537
        ],
        "t": 1,
        "s": 0
    }

The reason I want to do that is that I want to test if the encryption facility works correctly (first, encrypt a value with the public key, then decrypt the value with the private key again), because the public key is provided by an external party and else I have no possibility to check, as the private key is not provided.
Thanks a lot in advance!

A: You can use toString(16) to convert to hexadecimal
var nHex = publicKey.n.toString(16);
var eHex = publicKey.e.toString(16);


text:
Q: Fork never enters child's process I'm writing a code that mimics a shell behavior, specifically & and |.
My function receives user commands, and checks if there's an & at the end, then the child process should run in the background and the parent should not wait for it to finish and continue executing commands.
Also it's supposed to check if there's a | in the input array and run two child processes while piping their stdin and stdout.
I have implemented the behavior for &, but whenever I compile and run my code, I only get the printf sentence from the parent's process.
I would like to hear ideas how to fix this, in addition I would appreciate any suggestions regarding the implementation of | (pipes) and how to prevent zombies.
int process_arglist(int count, char** arglist) {
int pid = fork();
printf("%d", pid);
switch (pid) {
case -1:
    fprintf(stderr, "ERROR: fork failed\n");
    return 1;
    break;

case 0: // Son's proccess
    printf("I got to son");
    //check last arglist argument
    if (strcmp(arglist[count - 1], "&") == 0) {
        setpgid(0, 0);
        arglist[count - 1] = NULL;
        if (execvp(*arglist, arglist) < 0) {     //execute the command
            fprintf(stderr, "ERROR: execvp failed\n");
            exit(1);
        }
    } else { //There's no & at the end, look for pipes
        int i = 0;
        while (i < count) {
            if (strcmp(arglist[i], "|") == 0) {
                int pid2 = fork();
                if (pid2 < 0) {
                    //fork failed, handle error
                }
                if (pid2 == 0) { // Son's proccess

                } else { //Parent's code

                }
            }
        }
    }
    break;
    //in case no & and no |, call execvp

default: //Parent's code
    printf("I go to parent");
    return 1;
    break;
}
return 0;

}
The output is always "I go to parent"

A: I assume your code is for Linux or some other POSIX system. Read some good book on Linux programming (perhaps the old Advanced Linux Programming, freely downloadable, or something newer).
stdio(3) is buffered, and stdout and printf is often (but not always) line-buffered. Buffering happens for efficiency reasons (calling write(2) very often, e.g. once per output byte, is very slow; you should prefer doing write-s on chunks of several kilobytes).
BTW you'll better handle failure of system calls (see intro(2) and syscalls(2)) by using errno(3) thru perror(3) (or strerror(3) on errno). You (and the user of your shell) needs to be informed of the failure reason (and your current code don't show it).
I recommend to often end your printf format control strings with \n (this works when stdout is line-buffered) or to call fflush(3) at appropriate places.
As a rule of thumb, I suggest doing fflush(NULL);  before every call to fork(2).
The behavior you observe is consistent with the hypothesis that some printf-ed data is staying in buffers (e.g. of stdout).
You could use strace(1) on your program (or on other ones, e.g. some existing shell process) to understand what system calls are done.
You should compile with all warnings and debug info (e.g. gcc -Wall -Wextra -g with GCC), improve your code to get no warnings, and use the debugger gdb (with care, it can be used on forking processes).

I'm writing a code that mimics a shell behavior

You probably are coding some shell. Then study for inspiration the source code of existing free software shells (most -probably all- Linux shells are free software).

I would appreciate any suggestions regarding the implementation of | (pipes) and how to prevent zombies.

Explaining all that requires a lot of space (several chapters of a book, or perhaps, an entire book) and don't fit here or on any other forum. So read a good Linux or POSIX programming book. Regarding pipes, read pipe(7) (it should be created with pipe(2) before the fork). Regarding avoiding zombie processes, you need to carefully call waitpid(2) or some similar call.


text:
Q: Find an edge that is already connected with vertices to a specific vertex ID, and merge it with the result Consider facebook search results of the people list scenario. I want to get all the people from the database (hasLabel('person')). For each of these people, I want to know whether the logged in person already have connected and follows. What is the best solution to get this in gremlin (possibly avoiding duplication)?
g.addV('person').property('id',1).as('1').
  addV('person').property('id',2).as('2').
  addV('person').property('id',3).as('3').
  addV('person').property('id',4).as('4').
  addE('connected').from('1').to('2').
  addE('connected').from('2').to('3').
  addE('connected').from('3').to('1').
  addE('connected').from('4').to('2').
  addE('follows').from('1').to('2').
  addE('follows').from('1').to('3').
  addE('follows').from('1').to('4').
  addE('follows').from('2').to('1').
  addE('follows').from('2').to('3').
  addE('follows').from('3').to('1').
  addE('follows').from('3').to('4').
  addE('follows').from('4').to('2').
  addE('follows').from('4').to('3').iterate()

For instance, if the logged-in person id is 2, the formatted JSON response will be
[
    {
        "id": 1,
        "follows": true,
        "connected": true
    },
    {
        "id": 3,
        "follows": true,
        "connected": false
    },
    {
        "id": 4,
        "follows": false,
        "connected": true
    }
]

and if the logged-in person id is 4
[
    {
        "id": 1,
        "follows": false,
        "connected": false
    },
    {
        "id": 2,
        "follows": true,
        "connected": true
    },
    {
        "id": 3,
        "follows": true,
        "connected": false
    }
]

Note: The JSON response is provided to understand the outcome, but I just wanted the Gremlin query to get the outcome.

A: Below is the general pattern you are looking for however based on the script you have listed above and the direction of the edges it's unclear exactly when to return true and when not to.
g.V().
  hasLabel('person').
  not(has('id', 2)).   //find me person 2
  project('id', 'follows', 'connected').
    by('id').
    by(
      __.in('follows').
      has('id', 2).    //traverse all inbound follows edges to find if they go to person 2
      fold().          //create an array (empty if nothing)
      coalesce(unfold().constant(true), constant(false))). //return true if edge exists, else false
    by(
      __.out('connected').
      has('id', 2).
      fold().
      coalesce(unfold().constant(true), constant(false)))

Based on the script you provided there is no way to get the answers you asked for.  Let's look at just the connected edges.
For vertex 2:
using in() we would get true for 1 and 4 and false for 3
using out() we would get true for 3 and false for 1 and 4
using both() all would be true
So based on the results above it looks like you want to use in() edges.  However when we apply that to vertex 4 all the results would be false


text:
Q: Pexpect does is not synchronized with firewall prompt I am trying to get data from a firewall using Pexpect module (More specifically, pxssh). The login process is okey and the problem comes exactly in the i assignment line:
if i==2: # password or passphrase
            self.sendline(password)
            # Up to here, everything is okay#
            i = self.expect(["(?i)are you sure you want to continue connecting", original_prompt, "(?i)(?:password)|(?:passphrase for key)", "(?i)permission denied", "(?i)terminal type", TIMEOUT])

This is the firewall's dialog when a user is logged in:

Password:
Last login: Mon Sep 25 06:20:50 2017 from IPXXXX
Number of failed attempts since last successful login: 0
admin@DEVICE(active)>

I think the problem is that Pexpect don't expect these two lines of Last Login and Number of failed attempts, so the code execution is stopped in the line I said before.
Shell that the firewall uses:
admin@DEVICE(active)>

Init code of my pexpect class:
def __init__(self, host, user, password):
    str = 'ssh '+user+'@'+host
    self.user = user
    self.child = pexpect.spawn ('ssh '+user+'@'+host)
    self.child.expect ('Password:.*')
    self.child.sendline (password)
    self.child.expect (user+'.*>')
    ...

)


text:
Q: I would like to add code to all my c# services How do I add code to all the c# classes. I have a multitenants system and when the user logs in I store the user company name I use this company name as the name of my database. I need to replace the name of the default schema with the name of the company of the signed in user. I need to do this in every services. How can I repeat the code in every service without copy pasting it everywhere.
This code is the same in all services is there is smart way of getting the same code in all my services without copy pasting the same code everywhere?
public class MyService : IMyService
{
    private readonly erp_colombiaContext _context;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyService(erp_colombiaDbContext context, IHttpContextAccessor httpContextAccessor)
    {
        _context = context;
        _httpContextAccessor = httpContextAccessor;

        if (httpContextAccessor.HttpContext.User.Claims.Count() != 0)
        {
            var companyName = httpContextAccessor.HttpContext.User.Claims.ToList().Where(x => x.Type == "CompanyName").FirstOrDefault().Value;

            string connectionString = _context.Database.GetDbConnection().ConnectionString;
            connectionString = connectionString.Replace("erp_colombia", companyName);
            _context.Database.GetDbConnection().ConnectionString = connectionString;
        }
    }

}

A: What I would do is to create a base class (parent) called something like BaseService that contains all the common code that all your services have. eg:
public class BaseService {
    private readonly erp_colombiaContext _context;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public BaseService(erp_colombiaDbContext context, IHttpContextAccessor httpContextAccessor)
    {
        _context = context;
        _httpContextAccessor = httpContextAccessor;

        if (httpContextAccessor.HttpContext.User.Claims.Count() != 0)
        {
            var companyName = httpContextAccessor.HttpContext.User.Claims.ToList().Where(x => x.Type == "CompanyName").FirstOrDefault().Value;

            string connectionString = _context.Database.GetDbConnection().ConnectionString;
            connectionString = connectionString.Replace("erp_colombia", companyName);
            _context.Database.GetDbConnection().ConnectionString = connectionString;
        }
    }
}

Then, I would inherit from this class in all my interfaces. eg:
public class MyService : BaseService, IMyService
{
    public MyService(erp_colombiaDbContext context, IHttpContextAccessor httpContextAccessor) : base (context, httpContextAccessor)
    {
    }
}

Things to keep in mind is that a class can implement multiple interfaces but it can only inherit from one class. That means that C# doesn't support multiple inheritance.
EDIT: If you are using some kind of a Dependency injection framework, then the best would be that you register the service to your dependency injection container and then do constructor injection of the service to the services that need it. eg:
public class MyService : IMyService
{
    SomeService _someService;

    public MyService(SomeService someService)
    {
        _someService = someService;
    }

    public void TestMethod() {
        // use the injected service.
        // _someService.blah_blah();
    }
}


text:
Q: Deactivate mousepad while typing in KDE I am using KDE 4.13.3 on my Laptop and whenever I'm typing the cursor jumps to different places, because I accidentally touch the mousepad with my thumb. This is super annoying and other window managers have an option to disable the mousepad while typing.
How do I do this with KDE?

A: I guess you are using synaptics touchpad. If so install xf86-input-synaptics driver, which comes with syndaemon tool:

syndaemon - a program that monitors keyboard activity and disables the
  touchpad when the keyboard is being used

Once installed you can start it with -d (daemon) option. It is also possible to configure some settings like delay before re-enabling touchpad after last keyboard key was pressed.

A: sudo apt-get install kde-touchpad

and
sudo kcmshell4 kcm_touchpad

worked for me

A: Supposing you have a synaptic touchpad, as most do, install the synaptics driver if you have not already, usually called xf86-input-synaptics.
Installing the KDE touchpad config modules (usually kcm-touchpad or kde-touchpad) should provide you with the configuration GUI.
I am actually quite surprised this was not included by default by your distribution, if is ships with KDE by default.


text:
Q: programmatically validate a text field for mobile number in my application I need to validate mobile number text field in different forms. so I wish to write a
function for this purpose.my needs are:
text field accept only numbers(0-9).
error message will shown if any other characters are entered.
does't allow space but allow ctrl+c,ctrl+v,ctrl+x ans back sapce.
if ctrl+v(paste) is done it will check whether the string contains characters, if yes then display error message.
does anyone can help me to write such a function in limited number of code?
I had validated the following
Private Sub mob_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles stok.KeyPress
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then ' check whether the keypress is a number
mob.ForeColor = Color.green
Else
mob.ForeColor = Color.Red
end if
end sub

Private Sub mob_LostFocus(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles stok.KeyPress
if mob.text="" then 'for check empty space
end sub

but this is not what I need. I need all the process executed within a function

A: I think a regular expression would be best for your needs, take a look at this:
http://www.authorcode.com/how-to-use-regular-expression-for-validating-phone-numbers-in-net/
As a side note: I find the Asc(e.KeyChar) extremely ugly, I would parse the char to an int and see what happens: If int.TryParse() fails: error, if not: well it's a number.

A: Public Sub mob_validation(ByVal e As System.Windows.Forms.KeyPressEventArgs, ByVal mob As TextBox)
If e.KeyChar = Chr(22) Then
Dim output As String = New String((From c As Char In Clipboard.GetText.ToString Select c Where Char.IsLetter(c)).ToArray())
If output = "" And Len(mob.Text) = 10 Then
mob.ForeColor = Color.Green
Else
mob.ForeColor = Color.Red
Clipboard.Clear()
End If
Else
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) <> 3 Then
e.Handled = True
mob.ForeColor = Color.Red
End If
End If
Else
mob.ForeColor = Color.Green
End If
End If
End Sub


text:
Q: flatten files including foldername in filename i'd like to flatten folder-structure and in one way include each parent directory name to filename. i've tried this, but get an error:
Missing ')' in method call

I quite don't see what's the problem
(ls -r -include *.ext) | % { mv -literal $_\3 $_\3.Name.Insert(0, [String]::Format("{0} - ", $_\3.Directory.Name))}

A: Try this:
ls . -r *.ext -name | ?{!$_.PSIsContainer} | mi -dest {$_ -replace '\\','_'} -whatif

Or if on V3:
ls . -r *.ext -name -file | mi -dest {$_ -replace '\\','_'} -whatif

Remove the -whatif to actually perform the move.

A: Do you want to flatten the folder structure and move all of the renamed files to the root directory?  For example:
$rootPath = 'C:\TempPath'
(ls $rootPath -r -include *.ext) | %{
    [string]$newFilename = $_.Name.Insert(0, [String]::Format("{0} - ", $_.Directory.Name))
    #write-host $newFilename
    mv -literal $_ "$rootPath$newFilename"
}


text:
Q: How to transform to normal distribution? When using T-test to compare two group means, say group A and group B, I usually transform data to normal distribution if possible.
Before doing that, if the sample size is enough, I usually use Q-Q plot to see if the data set is normally distributed. Maybe I've been doing this wrong for many years, but what I usually do (and have been taught) is draw Q-Q plot for the whole variable (ignoring group A or group B). But what T-test assumes is that A and B are from normal distribution separately. And it is true that even when both A and B is from normal distribution with different means, the Q-Q plot of whole variable is not on the straight line.
My question is that what do you usually do to test normality? Q-Q plot together or separately? shapiro wilk test together or separately? Anderson Darling test together or separately?
If together, then two normal distribution will result a non-normal distribution. If separate, what would you do to transform them? Transform them using one method together?
Thank you!

A:
Maybe I've been doing this wrong for many years, but what I usually do (and have been taught) is draw Q-Q plot for the whole variable (ignoring group A or group B).

As you suggest in your question, if the means (or variances) differ, this combined (/marginal) variable won't be normal and it doesn't relate to what is assumed.

Q-Q plot together or separately?

You've already explained why you can't just take the raw data and do that.
You could look at residuals if you want to do them together (as long as equality of variance is a reasonable assumption).

shapiro wilk test together or separately? Anderson Darling test together or separately?

I wouldn't formally test goodness of fit at all; it answers the wrong question for what you need.

If separate, what would you do to transform them?

I probably wouldn't transform them at all*; I'd think about the question I want to answer and a reasonable way to answer that question. If my sample sizes are large non-normality may not matter and if my sample sizes are not large, I might not assume normality in the first place, unless I had some reason (outside my data) to think it might be a reasonable, if approximate, choice.
In some cases thinking about the variable being sampled might lead me to a different parametric assumption, in some cases I might consider a robustified parametric procedure, and in some cases I might lean toward not making a specific parametric assumption at all, but to simply use nonparametric procedures, depending on how these relate to the questions I want to answer.
* with some exceptions; for example there are cases where I expect (a priori) the distribution the data are drawn from to be reasonably close to lognormally distributed, and may well take logs and assume normality in that case.


text:
Q: How can I keep my program from getting this segmentation fault (core dumped)? I have a program that is getting a segmentation fault. The program is a magic square program and asks users for the size of a square (a matrix) and then for the numbers of the square by row. I am using a pointer to point to the array in the declareArray function to reference where it is declared in the main function. I want to keep the pointer in order to practice using them, even though I know I can make the program work without pointers. I think the pointer is the problem here but I cant find what I am doing wrong with it.
here is the code:
int main(void)
{
        int *arr[SIZE][SIZE] = "\0";
        declareArray(&arr);
        declareArray();

return 0;
}
        //main logic
int declareArray(int *arr[SIZE][SIZE])
{
        //variables
        int rowNumber = 0;
        int dimension = 0;
        //int arr[SIZE][SIZE] = {0};
        int row, col;
        int sum, sum1, sum2;
        int flag = 0;

        //ask for input of squares
        printf("Please enter the dimension of the square: ");
        //makes sure the size is between 1 and 15 for the dimension of the square
        if(scanf("%d", &dimension) != 1 || dimension >= 15 || dimension < 1)
        {
                printf("invalid input\n");
                return 1;
        }
        //enter the data

        //array rows
        for(row = 0; row < dimension; ++row)
        {
                printf("Please enter the data for row %d: ", ++rowNumber);
                //array columns
                        for(col = 0; col < dimension; ++col)
                        {
                                //store the user input
                                scanf("%2d", &*arr[row][col]);
                        }
        }
        printf("\n");
        printf("Here is the square");
        printf("\n");
        //print the square

        //array rows
        for(row = 0; row < dimension; ++row)
        {
                //array columns
                for(col = 0; col < dimension; ++col)
                {
                        printf("%d", *arr[row][col]);
                }
                printf("\n");
        }

 //Checks Sum of diagonal elements
   sum = 0;
   for (row = 0; row < dimension; row++) {
      for (col = 0; col < dimension; col++) {
         if (row == col)
            sum = sum + *arr[row][col];
      }
   }

   //Checks Sum of Rows
   for (row = 0; row < dimension; row++) {
      sum1 = 0;
      for (col = 0; col < dimension; col++) {
         sum1 = sum1 + *arr[row][col];
      }
      if (sum == sum1)
         flag = 1;
      else {
         flag = 0;
         break;
      }
   }

   //Checks sum of Columns
   for (row = 0; row < dimension; row++) {
      sum2 = 0;
      for (col = 0; col < dimension; col++) {
         sum2 = sum2 + *arr[col][row];
      }
      if (sum == sum2)
         flag = 1;
      else {
         flag = 0;
         break;
      }
   }
   //if the sums match, it will print a success message with the constant
   //if the sums dont match, a fail message will appear
   if (flag == 1)
      printf("\nTHE SQUARE IS A MAGIC SQUARE WITH A CONSTANT OF %d \n", sum);
   else
      printf("\nThe Square is not a magic square \n");

return 0;
}

A: I can see few issues here
         int *arr[SIZE][SIZE] = "\0"; // this wont compile
         declareArray(&arr); // needless
         declareArray();
---
         int arr[SIZE][SIZE] = {};
         declareArray(arr);
         //declareArray();

Declare function
 int declareArray(int *arr[SIZE][SIZE]) // because function call changed
---
 int declareArray(int arr[SIZE][SIZE])

finally in printf and scanf remove the * operator not needed anymore
as in
    scanf("%2d", &*arr[row][col]); // remove *
---
    scanf("%2d", &arr[row][col]);

    printf("%d", *arr[row][col]);  // remove *
---
    printf("%d", arr[row][col]);

    sum = sum + *arr[row][col];  // remove *
---
    sum = sum + arr[row][col];

A: *

*Note that when you declare an array, the name of the array is a pointer to the first element of the array:
&arr[0] == arr.

*The argument passed to the declareArray function is an array of pointers to integers, therefore the space needed for the pointers was allocated yet the space for the actual ints was not, so when you are trying to scan an integer to the address pointed to by arr[row][col], you are trying to write to the address that it holds, 0 in your case , and address 0 is most likely out of the data segment, hence the segment_fault.
What should you do then?
Allocate the space needed with malloc(), assign the address returned to arr[row][col] and then scanf() as shown below, or alternatively, and quite simpler and better use an int array and simply assign the integer to arr[row][col] as shown in the answer above
#include <stdio.h>
#include <stdlib.h>
#define SIZE 15

int declareArray(int * arr[SIZE][SIZE]);

int main(void)
{
    int * arr[SIZE][SIZE] = {0};
    declareArray(arr);

    return 0;
}
    //main logic
int declareArray(int * arr[SIZE][SIZE])
   {
    //variables
    int rowNumber = 0;
    int dimension = 0;
    int row, col;
    int sum, sum1, sum2;
    int flag = 0;
    int * myVal;
    //ask for input of squares
    printf("Please enter the dimension of the square: ");
    //makes sure the size is between 1 and 15 for the dimension of the square
    if(scanf("%d", &dimension) != 1 || dimension >= 15 || dimension < 1)
    {
            printf("invalid input\n");
            return 1;
    }
    //enter the data

    //array rows
    for(row = 0; row < dimension; ++row)
    {
            printf("Please enter the data for row %d: ", ++rowNumber);
            //array columns
                    for(col = 0; col < dimension; ++col)
                    {
                            printf("insert data to row %d col %d: ", rowNumber, col+1);
                            arr[row][col] = (int *) malloc(sizeof(int));
                            scanf("%2d", arr[row][col] );
                    }
    }

    printf("\n");
    printf("Here is the square");
    printf("\n");
    //print the square

    //array rows
    for(row = 0; row < dimension; ++row)
    {
            //array columns
            for(col = 0; col < dimension; ++col)
            {
                    printf("%d", *arr[row][col]);
            }
            printf("\n");
    }

 //Checks Sum of diagonal elements
   sum = 0;
   for (row = 0; row < dimension; row++) {
      for (col = 0; col < dimension; col++) {
        if (row == col)
            sum = sum + *arr[row][col];
      }
   }

      //Checks Sum of Rows
      for (row = 0; row < dimension; row++) {
      sum1 = 0;
      for (col = 0; col < dimension; col++) {
         sum1 = sum1 + *arr[row][col];
      }
      if (sum == sum1)
         flag = 1;
      else {
         flag = 0;
         break;
      }
   }

   //Checks sum of Columns
   for (row = 0; row < dimension; row++) {
      sum2 = 0;
      for (col = 0; col < dimension; col++) {
         sum2 = sum2 + *arr[col][row];
      }
      if (sum == sum2)
         flag = 1;
      else {
         flag = 0;
         break;
      }
    }
   //if the sums match, it will print a success message with the constant
   //if the sums dont match, a fail message will appear
   if (flag == 1)
      printf("\nTHE SQUARE IS A MAGIC SQUARE WITH A CONSTANT OF %d \n", sum);
   else
      printf("\nThe Square is not a magic square \n");

 return 0;
}


text:
Q: Mysql GROUP BY multiple clauses I have the following table.
+------------+--------------+-------------------+-------------------+
| media_id   | title        | artist            | plays             |
+------------+--------------+-------------------+-------------------+
|        100 | Song A       |              Jack |    6              |
|         35 | Song B       |           Suzzane |    33             |
|         73 | Song C       |              Anne |    2              |
|         50 | Song D       |            Jonnie |    7              |
|         50 | Song F       |            Jonnie |    123            |
|         50 | Song G       |            Jonnie |    39             |
+------------+--------------+-------------------+-------------------+

I am running this query (notice artist 'Jonnie' has same media_id)
SELECT media_id, artist, title, SUM(plays) AS total_plays
FROM table
GROUP BY media_id, artist, title
ORDER BY total_count

This query works fine, but my question is can I group by media_id those records that have unique media_id, while group by media_id, artist, title those records that have same media_id (Jonnie in this example)

A: Something like this?
SELECT z.media_id, z.artist, z.title, z.plays as "Total Plays by Title", b.total_plays as "total plays by artist"
FROM `playstable` z
inner join (select y.media_id,  SUM(y.plays) AS total_plays from `playstable` y  GROUP BY y.media_id ) b on z.media_id=b.media_id;


text:
Q: How to use a downloaded Bitbucket Reporsitory in Pycharm I have a repository that is in BitBucket here are the two things I want to do.
1. Download the repository and use it in Pycharm.
2. Directly connect to the repository in Bitbucket.
I have a testing framework that is in the repository but I can't figure how can I use that framework in Pycharm to write my test cases.


text:
Q: Pegando Output History do Terminal no Ubuntu Existe alguma forma de pegar o Output History do terminal do Ubuntu?
Como um log de tudo o que rolou em um terminal?

A: Bom, nao fica muito agradavel de ler, mas funciona:
Antes de comecar a usar o terminal (e assumindo que voce usa bash, que e o shell padrao no Ubuntu):
bash | tee bash.output

No fim, voce vai ter um arquivo bash.output no seu home com a saida, mas tudo junto, sem mostrar de onde veio cada coisa.

A: Há um outro meio e não posso deixar de comentar.
Na pasta pessoal há um arquivo chamado .bash_history(/home/usuário/.bash_history). Se você abrir pelo nautilus, dê um ctrl+h para exibir os arquivos ocultos e você o encontrará. Se quiser ver diretamente no shell, digite:
cat /home/username/.bash_history | more

Aperte enter para exibir os seguintes.

A: Output de um terminal:
H1) definir uma história de terminal comprida, e fazer cut&paste do terminal para um ficheiro
H2) usar o comando script file (guarda a sessão em file) -- script
tem várias opções que podem ser uteis.
Edição mais detalhadamente:
H1) o terminal mantem uma história acessível pela scroll-bar (por omissão 512 linha, configurável no profile do terminal).
Se, usando o rato selecionarmos a saída pretendida podemor fazer cut&paste
dentro do teu editor preferido.
H2) o commando script foi criado para questões como a levantada nesta pergunta. (ver man script); experimenta
script log
... executar alguns comandos
(CTR-D)
... e vê o conteudo do ficheiro log


text:
Q: Attach hover tooltip to specific div from loop I'm trying to get a tooltip (div) to display with information via AJAX. Here is the function that will do it:
function coworkerDetail(post, delay) {
    if(delay == 1) {
        clearInterval(TipTimer);
    } else {
        TipTimer = setInterval(function(){

            var msgType = 'person-container';
            // The position to be increased
            var height = 58;
            var left = 20;

        // Start displaying the profile card with the preloader
        $('.coworker-detail').show();
        $('.coworker-detail').html('

');

        $.ajax({
            type: "POST",
            url: "",
            cache: false,
            success: function(html) {
                $('.coworker-detail').html('Info goes here');
            }
        });
        clearInterval(TipTimer);
        }, 500);
    }
}

However, I need the tooltip to display only for the specific person-container div that I hover over in the loop:
$.each(obj.DATA, function( indexInArray, value ) {

    var topConnectedHtml = '
' +
    '
' +
        '
' + firstinitial + lastinitial +
        '
' +
    '
' +
    '
' +
        '
' + value[firstNameIndex] + ' ' + value[lastNameIndex] + '
' +
        '
' + value[titleIndex] + '
' +
    '
' +
    '
' +
    '
' +

Currently, when I hover over ANY person-container, it is bringing back EVERY tooltip for all person-containers. I need to select the specific one it's hovering over.

A: If your .hover-wrapper always accompanies the detail div, you could pass a reference like:
 onmouseover="coworkerDetail(this, 1, 0)"

Then change your coworkerDetail function to be:
function coworkerDetail(el, post, delay) {

Then instead of using:
$('.coworker-detail')

get
var detail = $(el).siblings('.coworker-detail').first();

and use that instead. This finds the one .coworker-detail div assocuated with the hover element.

A: Add an id property on the hovered object.

Then you'll be able to request this id inside hover event
$('.hoverClass').hover(function(){
    var idHovered = $(this).attr('id');
    //do your post here with specified id
    //then you can output data within the correct object id
});


text:
Q: How to improve on a long chain of elseif statements? I have have about 100 of these if statements, could I do this a better way?
function onSay (cid, words, param)
    mark = string.lower(param)
    if mark == "kojo" then
        moveTo(cid, {x=32838, y=31926, z=7})
        sendEffect({x=32838, y=31926, z=7}, 10)
    elseif mark == "habala" then
        moveTo(cid, {x=32838, y=31926, z=7})
        sendEffect({x=32838, y=31926, z=7}, 10)
    end
    -- and so on.....
end

A: Create a table using mark as the key, each element of which is a table containing the four parameters (x, y, z, and whatever that last 10 represents).  Then your onSay method can be implemented as a table lookup followed by calls to moveTo and sendEffect using the values from the identified element.  You'll still have to build the table, but you might be able to read it from a file or move it into a separate module so it doesn't dominate your onSay method.

A: LUA lacks a C-style switch, this issue is discussed here, suggesting different methods you could use.

A: If i understand what you're trying to do, you could try using
function onSay (cid, words, param)
mark = param:lower()

if mark:search("kojo", "habala", "and", "so", "goes", "on")
 then
     moveTo(cid, {x=32838, y=31926, z=7})
     sendEffect({x=32838, y=31926, z=7}, 10)
end

of course this unless moveTo and sendEffect will always have the same values


text:
Q: Jquery mobile How to remove border around ui-body class Is is possible to remove border from class ui-body in my divs ? Please ignore dashed border on top its in code I have to remove it. What I need is to remove border around each div with class ui-body. Thank you very much.
Screenshot:

HTML:

        {foreach from=$category_26 item=CAT}

                {$CAT.Title}

        {/foreach}

        {php}
            $this->assign('MaxNo',3);
        {/php}
        {assign var=number value=0}
        {section name=ArtCat_26 loop=$ArtCat_26 max=$MaxNo}
            {if $number == 0 || $number == 2}

                {foreach from=$category_26 item=CAT}

                    {$ArtCat_26[ArtCat_26].Title}

                {$ArtCat_26[ArtCat_26].ShortText}

                {/foreach}

            {else}

                {foreach from=$category_26 item=CAT}

                    {$ArtCat_26[ArtCat_26].Title}

                {$ArtCat_26[ArtCat_26].ShortText}

                {/foreach}

            {/if}
            {assign var=number value=$number+1}
        {/section}

A: First you have to find which style rule is being applied now. For that find the most specific rule in css, or just inspect the element in developer bar of your browser.
then once you find it, just remove the style from there.
If you cannot edit that file for some reason, add a more specific style somewhere
if currentstyle is
.ui-body{}

a more specific style can be
div.ui-body{}

body .ui-body{}

so these more specific styles will override the style
Only edge case is when using !important or inline styles.
if the element has some inline style applied with some javascript like

no rule in external css can override it, but !important.
if you use
.ui-body{
border:1px solid red !important;
}

this will override all styles including inline styles, which is against popular belief of javascript programmers, so its always safe not to use it as programmers usually assume inline styles can override all css rules.
Always try to use some more specific style rule, as practicing use of !important can take you to hard to debug issues as you move on.


text:
Q: Regex Everything except Item ID I'm trying to matching everything in comma delimited string that is not a Change Notice (CN) id, which is an alpha-numeric id starting with "CN".
The string is a list of items separated by a comma, where each item entry shows the item id followed by a "~-~" and some jargon.

He's an example string:

CN98765432~-~ECN for A01234 Rev A,CR00098765~-~ECR for A12345 SOME PART NAME,CN12345678~-~ECN for A12345 Rev A

In this string, I want to match everything except "CN98765432" (which appears at the beginning) and "CN12345678" (which appears at the end after the last comma)

I've tried using .*(?=CN\d), which I assumed would grab everything that ends before a "CN", but that incorrectly matched

CN98765432~-~ECN for A01234 Rev A,CR00098765~-~ECR for A12345 SOME PART NAME,

, which includes the initial CN.
I also tried .*((?=CN\d)|$), but that matched the entire string.

I've looked at similar problems but I was not able to adapt the answers into something suitable for my issue.
How to match "anything up until this sequence of characters" in a regular expression?
Regex everything but

How do I match everything except for the CN IDs?

I'm using regex ex inside a java based software, so I believe this is a JavaScript flavored regex.

A: For you example string you could try it like this to select all except "CN98765432" and "CN12345678" and as you state in your comment on karakfa's answer:
"Ideally I would want CN98765432,CN12345678 to be all that's left"
,?(?!CN\d+)\b[\w~ -]+
That would match

*

*,? Match optional comma

*(?! Negative lookahead that asserts what is on the right side is not

*

*CN\d+ Match CN followed by one or more digits

*) Close negative lookahead

*\d Word boundary

*[\w~ -]+ Character class repeated one or more times with the characters you allow to match

A: it might be easier to just delete the matched pattern
$ sed -E 's/CN[0-9]+//g' file

~-~ECN for A01234 Rev A,CR00098765~-~ECR for A12345 SOME PART NAME,~-~ECN for A12345 Rev A

if you want to capture the patterns
$ grep -oP 'CN[0-9]+' file | paste -sd,

CN98765432,CN12345678


text:
Q: Convert String to Map Ex - String str = "{Topic0 : 0, Topic1 :1, Topic2 : 0}"; String str = "{Topic0 : 0, Topic1 :1, Topic2 : 2}";

How to convert your string which conatins, key and value to a map?
map.put("Topic0", 0);
map.put("Topic1", 1);
map.put("Topic2", 2);

So I want to have a Map whose key is "Topic0, Topic1, Topic2" and corresponding values as "0, 1, 2".

A: public static void main(String[] strings) {
    String str = "{Topic0 : 0, Topic1 :1, Topic2 : 2}";
    //remove first and last char, i.e { and }
    str = str.substring(1, str.length()-1);
    Map<String,String> myMap = Pattern.compile("\\s*,\\s*")
            //split at ,
            .splitAsStream(str)
            //split at :
            .map(e -> e.split("\\s*:\\s*"))
            //map
            .map(e -> new AbstractMap.SimpleEntry<>(e[0],e[1]))
            //collect
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    System.out.println(myMap);

}


text:
Q: Elements of even order in a finite group If $G$ is a finite group with the property that every non-identity element has even order, what could be said about $G$? For example the most trivial property might be that $G$ is a group of even order. I was wondering if more could be said about the structure of $G$.
Thanks!

A: The condition holds if and only if $G$ is a $2$-group; that is, if the order of $G$ is a power of $2$.
To see this, note that Cauchy's theorem implies that $|G|$ cannot be divisible by an odd prime.


text:
Q: Array value in a set of value ranges isn't displaying I'm trying to make a simple program to display a discount depending on how many items a customer purchases.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
    class Program
    {
        const int SIZE = 4;
        static void Main(string[] args)
        {
            int itemsbought = 0;
            double discountItem = 0;
            int[] items = new int[SIZE] { 0, 10, 26, 61 };
            double[] discount = new double[SIZE] { 0.0, 0.05, 0.10, 0.15 };

            InputItems(ref itemsbought);
            getDiscount(items, discount, ref itemsbought, ref discountItem);

            Console.WriteLine("Your discount is {0}", discountItem);

        }

        private static void getDiscount(int[] items, double[] discount, ref int itemsbought, ref double discountItem)
        {
            int idx = 0;
            for (idx = 1; idx >= items.Length; idx++)
            {
                while (itemsbought >= items[idx])
                {
                    discountItem = discount[idx];
                    idx++;
                }
            }
        }
        private static void InputItems(ref int itemsbought)
        {
            Console.WriteLine("Enter the amount of items you bought");
            while (!int.TryParse(Console.ReadLine(), out itemsbought))
                Console.WriteLine("Error, whole numbers only");
        }
    }
}

Somehow I know the logic of this is really bad but I am not sure.  The topic one being of course that the discount that aligns to the input is displaying.  It's just displaying "The discount is 0" no matter what value is inputed.

A: Your for loop is all wrong. First, it isn't executing because your condition is idx >= items.Length;. It should be the opposite: idx < items.Length;. Second, I'm not sure why you are setting idx to 1 in the initializer...
The inner while loop also probably doesn't do what you want it to, but I'm not even sure what it is that you want it to do in the first place.

A: You need to fix the loop condition checking part, it is using a fault logic idx >= items.Length; which should have been idx < items.Length;.
Array in c# have zero based index, so, it must start with idx = 0.
for (idx = 0; idx < items.Length; idx++)
{
    while (itemsbought >= items[idx])
    {
        discountItem = discount[idx];
        idx++;
    }
}


text:
Q: Unwanted multiple instances of the same function I have this in my controller:
var page = 2;

$($window).scroll(function () {
    if($($window).scrollTop() == $(document).height() - $($window).height()) {
        myService.addMore(page);
        page++;
        console.log("page: " + page);
    }
});

This function runs when you scroll to the bottom of the page. The function then calls myService with the page value as a parameter.
The service function is just a http request like this:
factory.addMore = function (page) {
    $http({
        method: "GET",
        url: "url..." + page,
    }).success....
}

Every time you scroll down, the service makes a http request with the page value and some data gets printed to the view. While the page variable adds 1 every time, which it should.
However, there is a problem if you trigger the function by scrolling down, and then navigate to another page on the site, and then back again to the page with the scroll function.
The console.log outputs this:

*

*You scroll down, output: page: 3

*Scroll down more, output: page 4

*Change page, then back to scroll page and scroll down again, output: page 5
and page: 3

So now suddenly it seems like i have two of these functions running, which is a problem. How can i fix this? The page value should reset to 2 every time you go back.
I'm using ui router to change between states.
Let me know if you need any more information.

A: You are binding the listener to the window object. Which persists through states in a single page application. Either unbind the listener at state redirect or bind it to an element that gets deconstucted at state redirect (i.e. something in the template of the state).


text:
Q: Converter a saída em uma caixa de texto a uma tabela dinâmica Estou tentando fazer uma tabela dinâmica para a contagem de frequência de palavras extraídas de um arquivo externo. Me deparei com um modelo, agora eu estou tentando alterar a saída para exibir uma tabela em vez de mostrar os resultados em uma caixa de texto. Duas colunas devem aparecer desencadeada por onClick tanto botões que exibem a palavra e sua freqüência de ocorrências.
Abaixo está o que eu tenho trabalhado até agora:

Word Counter

Filename: <input id = "url" name="url" size=15 type="Text"/>

    Open document
Retrieve text

    <textarea id="ta_1" rows="20">

    </textarea>

        <button>Alphabetical Order</button>
        <button >Frequency Order</button>

    <textarea id="ta_2" rows="20">
    </textarea>

A: A function retrieve é a que está alterando a tela pelo visto.
function retrieve(node) {
            if (node.nodeType == Node.ELEMENT_NODE) {
                for (var m = node.firstChild; m != null; m = m.nextSibling)
                    retrieve(m);
            }
            else if (node.nodeType == Node.TEXT_NODE) {
                var p = document.getElementById("ta_1");
                p.appendChild(document.createTextNode(node.data));
            }
        }

Note que ele recupera o elemento "ta_1" e cria um texto dentro dele, que é esse tal node.data
Você vai precisar trabalhar essa parte aí, e inserir o seu resultado em uma tabela.
Você pode criar uma tabela no html, e então nessa function vc insere o conteudo dessa tabela.


text:
Q: Very elementary question about cosets on $\mathbb{Z}_n$ Let $\mathbb{Z}_4 = \{ 0 , 1 , 2 , 3 \} $ and $\mathbb{Z}_2 = \{0,1\}$. I computed the cosets of $\mathbb{Z}_2$:
$$ 0 + Z_2 = 1 + Z_2 = 2 + Z_2 = 3 + Z_2 = Z_2 $$
So the number of cosets of $H$ is just $1$, but we have that $| G : H | = 2 $. Why am I doing wrong ?


text:
Q: How handle a POST request with Kafka, Alpakka Kafka, Play Framework and Websocket? Let's say I have two kafka topics, request_topic for my Post requests, and response_topic for my responses.
This are the models:
case class Request(requestId: String, body: String)
case class Response(responseId: String, body: String, requestId: String)

This is my socket handler
def socket = WebSocket.accept[String, String] { req =>
  val requestId = ??? // Generate a unique requestId

  val in: Sink[String, Future[Done]] = Sink.foreach[String]{ msg =>
    val record = new ProducerRecord[String, Request]("request_topic", "key", Request(requestId, msg))
    val producer: KafkaProducer[String, Request] = ???
    Future { producer.send(record).get }
  }

  // Once produced, some stream processing apps will manage to process request and publish the reponse to response_topic
  // The Request and Response object are linked by the requestId field.

  val consumerSettings = ???
  val out: Source[ConsumerRecord[String, Response], _] = Consumer
    .plainSource(consumerSettings, Subscriptions.topics("response_topic"))
    .filter(cr => cr.value.requestId == requestId)
    .map(cr => someResponseString(cr.value))

  Flow.formSinkAndSource(in, out)
}

def someResponseString(res: Response): String = ???

Basically, for each incoming message, I publish a Request object to Kafka, then the request is processed by some stream processing app (not shown here) and hopefully a response is published back to Kafka.
I have some concerns here:
1 - Will Alpakka Kafka Connector create a new instance of the connector for each incoming message or will it use the same instance as long as Play is running ?
2 - Is it a good idea to filter response based on individual requestId, or should I send the whole stream back to each Client, and let them filter the response based on the requestId they are interested in.
3 - Am I wrong in everything ? (I am a real newbie in Websocket)
Thanks in advance.

A: 1) Depends how you configure it. For example, in the in: Sink body, you're making a new KafkaProducer for each message. Instead, you should have one producer for the entire application.
I'm not sure how Akka / Play's threading models work, but most webservers start a new thread for each incoming connection, up to a fixed number of threads in a threadpool.
2) I would like to think filtering as soon as possible would be preferred, as well as doing as much as possible on server-side. This saves on bandwidth back to the client.
Also, if you are looking to only push data from Kafka on the web-server to a client in one direction, you would likely want SSE, not Websocket


text:
Q: finite solvable groups whose commutator subgroup is nilpotent The finite solvable groups G  whose commutator subgroup G' is nilpotent,
look interesting to me  (in view of the easy structure of finite nilpotent groups and the resemblance with solvable Lie algebras in char. 0). Let me call such groups perfectly solvable. Note that the finite supersolvable groups (groups with cyclic normal series) are perfectly solvable.
Have such groups been studied in Literature ?
Thank you.


text:
Q: Delete empty value in range-loop i want to filter some data from many single table into 1 table. The problem start as i want to show only some data instead all values read from looping.eg; I have many data in column A. But I only want to select few data only, and this data has fix increment such as at column A5,A10,A15 and etc.
I have try to use if-statement to select only when there is value but not working, as it will paste all value instead.
Sub transpose1()

'***Define Variable
Dim Strings() As Variant
Dim n As Long
Dim LastRowData As Long
Dim LastRow As Long

'***Read Data
Sheets("Results").Activate
LastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
LastRowData = LastRow

'***Redefine Array
ReDim Strings(LastRowData)

'***Read Data Variable
For n = 2 To LastRowData 'loop strings data
    Strings(n) = Sheets("Results").Cells(1 + n, 1)
    n = n + 12 'data increment at fix size
Next n

'***Write data
If IsEmpty(n) = False Then 'select only n with value
    For n = 0 To LastRowData
            Sheets("Test Transpose").Cells(1 + n, 1) = Strings(n) ' paste value when only n has value only
    Next n
End If

End Sub

A: Well n is a long variable and that is not empty. You should check if strings(n) is empty:
If Isempty(strings(n)) = False Then
Also you have to place this if statement inside the for-loop, otherwise it will just check the same element everytime:
For n = 0 to LastRowData
    If Isempty(strings(n)) = False Then
          Sheets("Test Transpose").Cells(1 + n, 1) = Strings(n) ' paste value when only n has value only
    End if
Next n


text:
Q: VirtualBox Linux - Hard drive not showing correct amount of space I recently changed the amount of space of the VDI using VBoxManage modifyhd from 8 GB to 20 GB. I've checked it and it says only 6.6 GB, and now I'm running out of space. It might have been like that before, but I'm not sure. I tried adding another hard drive, but it's not showing either.

A: You need to resize the root partition.
Though I don't know the distribution you are running, I think these steps in the first answer will work: https://askubuntu.com/questions/24027/how-can-i-resize-an-ext-root-partition-at-runtime
You can also run a linux live .iso in your virtualbox, and use gparted to resize the root partition.

A: Please keep in mind that extending the VDI only shows up in fdisk -l output, as that is just a partition resize. The filesystem needs to be resized too, as mentioned above.


text:
Q: BelongsToMany relation with specific condition I've the following tables:
users (list of users) :
id |  type
5  |  client
10 |  expert
clients (assigning many users to many groups):
uid | gid
5   | 1
client_groups (groups defined by experts):
id |   title    | expert_uid
1  | diabetic   | 10
Every expert can define a group of clients and put any of his clients in one of them.
A client may belong to many experts.
Now what I want is to get the group of the current user which is defined by specific expert.
I've tried the following relation:
    class User{
        public function client_groups()
        {
            return $this->belongsToMany(\App\Models\client_group::class,"clients","uid","gid");
        }

    }

      User::with("client_groups")->
      whereIn("id",$client_ids)->
      orderby($orderBy,$order)->
      get();

But as you may guess it will return all client_groups for the current client But I want the ones that has been defined by the current expert and not all of them.
Thanks in Advance