text:
Q: Find a css file node js Hi I'm new to nodejs and I've just succeed to deploy a nodejs app online. Now I would like to know how to link CSS, JS or image files be cause when I try to do it like I used to, I get the error GET (not found).
The folder architecture is:
--public
    --assets
    --css
       index.css
    --js
--views
    --index.ejs
--node modules
app.js
package.json

Assuming that I want to code the link index.css in index.ejs, what I need to write in my app.js file please.
app.js code:
var express = require('express');
var app = express.createServer();

app.set('view engine', 'ejs');

app.use(express.static(__dirname + '/public'));

app.get('/', function(req,res){
    res.render('index');
});

app.listen(8080,'IP_ADRESS');

index.ejs code:
<link rel="stylesheet" type="text/css" href="/css/index.css">

A: The basic set up of serving static files in express :
var express = require("express");
var app = express();
...
app.use(express.static(__dirname + '/public'));
...
app.listen(3000);

Now in your .ejs in order to load the css styles or js scripts :
<link rel="stylesheet" href="/css/index.css"/>

A: First, there's a thing called a static file. Basically, that's a file that's sent over the internet without any kind of modification. Image and CSS files are typically static files.
It looks like you've put your static files in a folder called public.
Express has a built-in feature for sending static files, called express.static. You can use it like this:
// Require the modules we need.
var express = require('express');
var path = require('path');

// Create an Express app.
var app = express();

// Get the path to the `public` folder.
// __dirname is the folder that `app.js` is in.
var publicPath = path.resolve(__dirname, 'public');

// Serve this path with the Express static file middleware.
app.use(express.static(publicPath));

// ...

You should now be able to see static files. If your site is normally accessible at http://localhost:3000, you'll be able to see index.css at http://localhost:3000/css/index.css.
If you want to know way too much about express.static, you can check out a blog post I wrote that goes into Express's static files in depth.


text:
Q: Is there a way to make Libre Office more responsive in order to be able to center text while the window is in half-screen display So first of all I am using Libre Office with the following settings:
Version: 6.0.7.3
Build ID: 1:6.0.7-0ubuntu0.18.04.2
CPU threads:8; OS: Linux 4.18; UI render: default; VCL: gtk3;
Locale: en-US (en_US.UTF-8); Calc: group

And so whan I am using it in half-screen mode (so using 2 applications side-by-side) I would like to center some text BUT I can't because the centering button is not available!
My current screen: as you can see the "center text" button is hidden and not available

but in "full screen" mode I can see it on the right:

Do you please know any ways to fix it ? It seems libre office is kind of non-responsive so that's kinda annoying to use.
edit: screenshot

A: The toolbar requires a minimum screen width. If you want all buttons to remain in view, make sure you make your windows wide enough, or work with a maximized window.
Alternatively, you can customize the toolbars or change their location. You can edit toolbars and remove items, or move them to new toolbars. You can customize toolbars and other interface elements under Tools - Customize. You can also right-click the toolbar handle to access settings for changing it.
The answers to this question indicates how it can be done for prior versions of Libreoffice. For recent versions, that dialog has changed. Select the toolbar you want to customize from the dropdown menu under Target. Click the cog symbol under Target to add new toolbars.
Alternatively, grab the handle of the toolbar and drag it. You can place a toolbar vertically along the left or right side of the window by dragging it.
Thus, Libreoffice allows the flexibility to rearrange the interface in a way that works best for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to create routemap with angularjs ngRoute I am creating web application similar to gdrive or dropbox, when I navigate through my folders through links, i need to get path in url. I need to change the path from client side itself using angularJS.
e.g
 $stateProvider
        .state('/root',
                    {
                     url: "/root",
                     templateUrl: "cloud.html"
                    })
        .state('root.___',
                    {
                        url: "/root/:path",
                        templateUrl: "cloud.html"
                    })
        .otherwise({ redirectTo: "/root" });
       });

The controller and template need not be changed, only the url need to be changed, look like this
http://mycloud.com/newfolder/newfolder or http://mycloud.com/newfolder/.../.../../folder

How to achieve this in angular js ui-router what need to be filled in the blank space?

A: ___ can be replaced by 'path' or any other state of your choice.
$stateProvider
        .state('/root',
                    {
                     url: "/root",
                     templateUrl: "cloud.html"
                    })
        .state('root.path',
                    {
                        url: "/root/:path",
                        templateUrl: "cloud.html"
                    })
        .otherwise({ redirectTo: "/root" });
       });
Since you already have param :path in your url, it will take care of your URLs.
While using ui-sref, just pass the param path along with it.
Like Path
You need to remember that states follow hierarchy. Refer angular-ui's state page .


text:
Q: mat-checkbox does not update checked state when I change its model in jasmine unit tests I wrote a unit test for material check box. I used [(ngModule)] to bind check-box to the model. the first test case is ok, clicking on the checkbox will update the model however when I change the model in the next unit test, It does not happen. In other words, when I set enabled to true, the checked state does not change to true!
How can I pass the last unit test?
The code is uploaded to github

@Component({
  selector: 'app-checkbox',
  templateUrl: './checkbox.component.html'
})
export class CheckboxComponent implements OnInit {
  enabled = false;

  constructor() { }

  ngOnInit(): void {
  }

}

describe('CheckboxComponent', () => {
  let component: CheckboxComponent;
  let fixture: ComponentFixture<CheckboxComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CheckboxComponent ],
      imports: [
        MatCheckboxModule,
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CheckboxComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('click checkbox changes enabled', () => {
    const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
    expect(component.enabled).toBeFalse();
    checkBox.click();
    expect(component.enabled).toBeTruthy();
  });

  it('changing enabled will alter checkbox state', (done) => {
    const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
    component.enabled = true;
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(checkBox.checked).toBeTrue();
      done();
    });
  });
});
<mat-checkbox [(ngModel)]="enabled">Check me!</mat-checkbox>

A: You most likely need a new reference to the DOM/HTML. checkbox refers to the old DOM before the fixture.detectChanges().
Try this:
it('changing enabled will alter checkbox state', (done) => {
    const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
    component.enabled = true;
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const newCheckbox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; // grab new reference
      expect(newCheckbox.checked).toBeTrue();
      done();
    });
  });

A: I solved it by adding another detectChanges() in whenStable()
it('changing enabled will alter checkbox state', (done) => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
component.enabled = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
  fixture.detectChanges(); // <--- this line
  expect(checkBox.checked).toBeTrue();
  done();
});
});


text:
Q: Claim Based Authentication: Using Windows Authentication, but gathering user roles from SQL Database I am currently tasked with planning authentication for a new SharePoint 2013 site.
My goal is to allow users to sign on using Windows Authentication, however once they login I would like to query a SQL database to gather a list of permissions and details about what files they can see.
At first I was thinking of using ADFS, and having it send a token that includes all the necessary information.
However, is it possible to simply use Windows Auth and then query the database at the time the user hits the site. Once the user hits the site, can I hide and show files depending on the information retrieved from the database?

A: Firstly let me say that this is very feasible, but will not be without a significant amount of effort both in thinking through the right design and in implementing it.  There is no quick fix here, having said that here are your options.
What you basically need to look at is Augmented Claims, that is to say you need a way to augment the set of claims that SharePoint is aware of for your authenticated users. SharePoint allows you to secure items against claims.
You can do claims augmentation in several ways but the two most common are:
ADFS - You have already hinted at this but if ADFS is used as a custom identity provider for your application then you can use ADFS claim rules and Attribute Stores to query the SQL database and assign new claims to your user.  You then just need to secure SharePoint using these new claims.  If you are following this route then basically read everything that Steve Peschka has ever published on the subject, starting with this:
http://blogs.technet.com/b/speschka/archive/2010/07/30/configuring-sharepoint-2010-and-adfs-v2-end-to-end.aspx
To find more information on using a SQL Attribute Store in ADFS to augments claims take a look at this:
http://blogs.technet.com/b/vinitt/archive/2013/04/15/how-to-use-to-custom-sql-attribute-store-to-generate-claims-and-authorize-user.aspx
Custom Claim Provider - You can write a Custom Claim Provider for SharePoint and register it against your web application, you will need to write all the code to query the database and process the returned values, but I am assuming that is not a problem.  This option actually gives you more control over the user experience in securing SharePoint as ADFS on its own will not allow you to integrate any validation or search aspects into the Claim Picker (People Picker).  In fact worse than that it will appear that any value searched for in the People Picker is valid whether it exists as a valid attribute value or not, this is very open to human error when securing items in SharePoint so you may wish to consider a hybrid approach which uses ADFS for the augmentation of claims, but has a Custom Claim Provider as well to allow you to search and resolve names from your SQL database.
More information and a starting point for Custom Claim Providers can be found here:
http://msdn.microsoft.com/en-us/library/gg615945%28v=office.14%29.aspx
Though again Steve Peschka has written lots of blog posts on this subject and I recommend taking a look through all of them as you build out a design.
This is just a kick start in the right direction and no doubt you will have more questions before you get all the answers you need.
Hope that helps.


text:
Q: How to install nodejs in cpanel shared hosting(linux based) I created chatting application in nodejs and want to  run nodejs server on cpanel linux based hosting. Someone please guide me, or give me step wise instructions to run it.

A: I don't think it's possible with shared hosting. Unless they explicitly mention they support it.


text:
Q: Output of the 2 lists mixed Recently i got task on my work which is quite "too big" for me.
I am looking to create generator for mixing two elements.

*

*The list of locations

*The code or text

*Output will enter location to code/text for each new line

This is the current work on HTML

Because i am pretty noob at PHP can somebody explain what functions should i use to make this generator work?
This is my code:

Generate Locations

Input locations in new line each

    <textarea rows="20" style="width:100%">
    </textarea>

Input code. Use "??Location" to replace.

    <textarea rows="20" style="width:100%">
    </textarea>

<button type="button" class="btn btn-primary" style="margin-top:20px;" >Generate</button>

Output

    <textarea rows="20" style="width:100%">
    </textarea>

A: First, give your textareas IDs so you can reference them easily:
<textarea rows="20" style="width:100%" id="locations">
</textarea>

<textarea rows="20" style="width:100%" id="inputcode">
</textarea>

<textarea rows="20" style="width:100%" id="output">
</textarea>

The rest is Javascript:

You can call this function with your button:
<button onclick="generateLocations()" type="button" class="btn btn-primary" style="margin-top:20px;">Generate</button>

A: add id locations, code and output to location's, code's and output's textarea respectively.
add this in script tag
function generate(){
   var lta = document.getElementById("locations");
   var cta = document.getElementById("code");

   var locations = lta.split("\n");
   var codes = cta.split("\n");
  var final = "";
   codes.forEach(function(code){
      locations.forEach(function(loc){
          var codeCopy = code;
          final += codeCopy.replace("??Location", loc) + "\n";
      })
   })
  var out = document.getElementById("output");
  out.innerText = final;
}

call it on onclick of generate button


text:
Q: Ionic application not connecting to internet after signing Ionic application not able to connect to internet after signing the application.
<access origin="*"/>   is there in config.xml
Unsigned apk is working in mobile.
Also tried changing http <-> https nothing worked.

A: <!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">-->

try it ?


text:
Q: How to add to a class a string with two integers and show the sum Greeting fellow programmers!
I am currently studying software development (I started not a month ago) and I have a problem that needs a solution. Underneath you can find the code and as you can see, the method WriteNumber needs help. I need to write the code in a way that when I run the program, on the console screen the following two lines will be shown:
Hello World!
81
The Main method code cannot be changed and also I cannot add more methods to the class Calculator so the code needs to be done only within the WriteNumbers method. I have tried a lot of things but I am still grasping how everything works so any help is welcome! Thank you in advance for your time.
Namespace CalculatorTest
{

class Calculator
{
    public static string WriteText (string input)
    {
        return "" + input;
    }
    public static string WriteNumber()
    {

    }
}

class Program
{
    static void Main(string[] args)
    {
        string s = Calculator.WriteText("Hello World!");
        Console.WriteLine(s);

        string n = Calculator.WriteNumber(53 + 28);
        Console.WriteLine(n);

        Console.Read();
    }
}

A: Not to do your homework for you to just be copied/pasted, hopefully I can give you some hints...
Notice how the method is being invoked:
Calculator.WriteNumber(53 + 28)

The 53 + 28 part happens first, then the result of that operation is passed to the method.  That result, naturally, is 81.  What's important about that is its type, which is an integer.
So, reasonably, the method signature needs to accept an int as a parameter.  This would be done very similarly to how the other method accepts a string as a parameter:
public static string WriteText(string input)

What, then, does that method need to do with that input?  Well, it's only a single value, so there aren't any calculations to be performed on it.  It would appear that the method simply needs to return the value as a string.  (It's your homework so you tell me, is that correct?)
This can be done with exactly two things:

*

*Calling .ToString() on the value

*Using the return keyword to return the result of that operation

(Note: The .ToString() operation does something very intuitive on value types, such as int or double or bool.  As you progress into using reference types, you're going to find that it does something very different.  Any time you have a custom class on which you want to call .ToString(), you'll need to override the .ToString() method on that class first.)

A: Please read David's answer, it's important that you make the effort to understand why this works the way it does.  That being said:
public static string WriteNumber(int number)
{
   return number.ToString();
}

A: Thank you all for your valuable input but special thanks to David because he showed where I made my error. I forgot that the two numbers in the main function will be summed up FIRST and THEN forwarded to the method in the class Calculator. After that got cleared up, it was easy to understand what to do (basically adjust the type of the input parameter to int).
namespace CalculatorTest
{

class Calculator
{
    public static string WriteText (string input)
    {
        return "" + input;
    }
    public static string WriteNumber(int sumOfNumbers)
    {
        return "" + sumOfNumbers;
    }
}

class Program
{
    static void Main(string[] args)
    {
        string s = Calculator.WriteText("Hello World!");
        Console.WriteLine(s);

        string n = Calculator.WriteNumber(53 + 28);
        Console.WriteLine(n);

        Console.Read();
    }
}

}


text:
Q: Android Studio multiple onCreate methods I've been trying to make two buttong on my main layout. The buttons are supposed to open a second layout, called barcode_scanner.xml and vragen.xml
However, only the first button opens the scanner. The second button does not do anything.
This is my current code from MainActivity.java
package com.kvprasad.zbarbarcodescanner;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button scannerButton;

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

    // scannerButton = (Button) findViewById(R.id.scannerButton);

    //scannerButton.setOnClickListener(new View.OnClickListener() {
    //  @Override
    // public void onClick(View v) {

//                Intent intent = new Intent(v.getContext(), BarcodeScanner.class);
    //              startActivity(intent);
    //        }
    //  });
    //}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    //Barcodescanner knop
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button next = (Button) findViewById(R.id.scannerButton);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }

//bovenbouw knop
    public class AutoBodyActivity extends MainActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button next = (Button) findViewById(R.id.bovenbouw);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Vragen.class);
                startActivityForResult(myIntent, 0);

                    }
                });
            }};
        }

This is the specific part with the onCreate methods:
@Override
    //Barcodescanner knop
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button next = (Button) findViewById(R.id.scannerButton);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }

//bovenbouw knop
    public class AutoBodyActivity extends MainActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button next = (Button) findViewById(R.id.bovenbouw);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), Vragen.class);
                startActivityForResult(myIntent, 0);

                    }
                });
            }};
        }

The button with id: 'scannerButton' works fine, but the button with id: 'bovenbouw'
I don't see any mistakes in the code. What is possibly wrong?

A: You should declare both buttons in the MainActivity.onCreate(..) method
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);

and then register your onClick listeners to open a new Activity.
For your second activity you'd have an own class SecondActivity with its own onCreate method to take care of stuff.
To open the second Activity you just open a new Intent like so
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent)

hope this helps :)


text:
Q: GLM Poisson Regression with Overdispersion I use R for a poisson regression (GLM) to test for a difference in the number of years of schooling based on race (6 categories) and religion (3 categories), see structure of dataset and output below. Since the original poisson model suffers from rather significant overdispersion I conducted the same analysis but with a quasipoisson distribution.
Structure of dataset:

GLM Quasipoisson regression:

ANOVA - Test predictors relative to the full model:

*

*The output of the quasipoisson regressions shows one statistically significant interaction. I read the following "use F tests with an empirical scale parameter instead of chi-squared (The R Book, Crawley M. J. 2013.  p. 570)" as yet another suggested technique to deal with overdispersion. Hence, I conduct an ANOVA with an F-test for the model which then shows that the interaction term is not statistically significant. What is the correct way to interpret this result? Should I, based on the ANOVA state that the interaction is not statistically significant and then instead go on trying a model without the interaction term?

A: Tests of significance are not used to determine whether or not variables are meant to be included in the model or not. If the goal is prediction or variable selection, you probably shouldn't be using quasilikelihood at all. That said, it looks like you've tested for the interaction of religion with race using the method that Crawley has advocated. The reason is that you need an estimate of the covariates and the dispersion parameter under the "reduced" model.


text:
Q: How to transfer [String] information through a socket I'm trying to make a client chat application using Java
I want to transfer messages but Its seems like its not working.
Typing is a JTextField
Button is a button (No way :O)
and ChatView is the JTextAreafor sending messages between the clients
Leave the length() its there so the button doesn't accept spam.
Heres code
 public  void actionPerformed(ActionEvent e){
     int x = Typing.getText().length();
      if (x > 0)  {
     System.out.println(Typing.getText().length());
     ChatView.insert("\n"+Typing.getText(),0);
     Typing.setText("");}
       try {
    ServerSocket MainServer = new ServerSocket(344);
Socket Connect = MainServer.accept();
OutputStream outstream =  Connect.getOutputStream();
 PrintWriter out = new PrintWriter(Connect.getOutputStream());
 out.print("Works");
} catch (Exception ee) {
    System.err.print("/n"+"error");
}

A: The problem is , stream should be flushed if some body is trying to read that stream
After out.print("Works"); either flush the the stream or close the srtream
out.flush(); or out.close();


text:
Q: Multiple webpack bundles, one vuex store I have vue project which has multiple webpack bundles. However one page could have multiple bundles present with multiple components hence in order for them to share the same store - we need a single state.
webpack.mix.js
mix.js(['src/searchFilters.js'], 'dist/search-filter-components.js').vue({
    version: 2,
    options: {
        shadowMode: true,
        dontLeakScopedModules: false
    }
});

mix.js('src/provider.js', 'dist/provider-components.js').vue({
    version: 2,
    options: {
        shadowMode: true,
        dontLeakScopedModules: false
    }
});

I have seen many questions were asked reguarding that, But still couldn't find a solution.
However those solutions seems to work only for the first component that imports the store. For the next component from a different bundle that imports the store - the computed properties do not recompute! Just wondering if anyone has come across this or has  solution to sharing a vuex store between different webpack bundles.
Thanks in advance.

A: Ok. I found a solution. I may not be a perfect But it solved my problem.
I used laravel-mix webpack mix.extract to extract vue and vuex.
mix.extract([
    'vue', 'vuex',
]);

mix.js('src/main.js', 'dist/web-components.js').vue({
    version: 2,
    options: {
        shadowMode: true,
        dontLeakScopedModules: false
    }
});

and it generates two scripts and added those scripts to my non vue website.
<script defer="" src="http://ox_byondmarket/search-filter-components.js"></script>
<script type="text/javascript" src="http://ox_byondmarket/manifest.js"></script>
<script type="text/javascript" src="http://ox_byondmarket/vendor.js"></script>
<search-filters page="search"></search-filters>


text:
Q: Testing helpers in Rails 3 with Rspec 2 and Devise My helper code looks like this (and works fine btw):
module ProvidersHelper
  def call_to_review(provider)
    if user_signed_in? && review = Review.find_by_provider_id_and_user_id(provider.id, current_user.id)
      link_to "Edit Your Review", edit_provider_review_path(provider, review), :class => "call_to_review"
    else
      link_to "Review This Provider", new_provider_review_path(provider), :class => "call_to_review"
    end
  end
end

Unfortunately, this produces the following error when I run my tests:
 undefined method `user_signed_in?' for #<ActionView::Base:0x00000106314640>
 # ./app/helpers/providers_helper.rb:3:in `call_to_review'

Clearly the Devise::Controllers::Helpers are not being included in my helpers when rspec is running the test.  Any suggestions that might help this work?
Edit: to provide a bit more information, my spec_helper does have this:
config.include Devise::TestHelpers, :type => :controller
config.include Devise::TestHelpers, :type => :view
config.include Devise::TestHelpers, :type => :helper

(Sadly, I couldn't get it to work with :type => [:controller, :view, :helper])
Anyway I believe that these lines add the sign_in(scope, object) (and other) test helpers to your tests.  They don't add the helpers that you would actually leverage in your controller / view code.

A: I think the philosophy of rspec is to test the view/helpers/models in total isolation as much as possible. So in this case, i would stub out the user_signed_in? and returns false or true and my results should change appropriately.
This gives you a clean isolated test.

A: Are you currently including the test Helpers as suggested in the wiki?
# spec_helper.rb:
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

type would be probably helper in your case.

A: Maybe try putting this is in a before block?
  @request.env["devise.mapping"] = :user

A: This has not been solved to my satisfaction and probably never will be.  I think the best work-around for now is to manually stub helper.current_user and any other Devise methods you use in the helper method you're testing.
Yes, Devise provides these stubbing facilities for controller and view specs.  I suspect that it's something about the combination of Devise/Rails/Test::Unit/Rspec that proves this to be difficult for helper specs.

A: my helper test uses Devise and cancan and works without stubbing anything (but I'm not sure if it is better to actually stub everything).
Here's the gist: https://gist.github.com/shotty01/5317463
i also tried to add user_signed_in? in the helper method and it still was fine.
The following is required:
add to spec_helper.rb:
config.include Devise::TestHelpers, :type => :helper

My spec gems:
rspec (2.10.0)
rspec-core (2.10.1)
rspec-expectations (2.10.0)
rspec-mocks (2.10.1)
rspec-rails (2.10.1)

of course you can sign in without factory girl, you just have to rewrite the ValidUserHelper methods to create a user directly or from fixtures.


text:
Q: How to dynamically name dataframes? Suppose I have a dataframe as follows:
s = df.head().to_dict()
print(s)

{'BoP transfers': {1998: 12.346282212735618,
  1999: 19.06438060024298,
  2000: 18.24888031473687,
  2001: 24.860019912667006,
  2002: 32.38242225822908},
 'Current balance': {1998: -6.7953,
  1999: -2.9895,
  2000: -3.9694,
  2001: 1.1716,
  2002: 5.7433},
 'Domestic demand': {1998: 106.8610389799729,
  1999: 104.70302507466538,
  2000: 104.59254229534136,
  2001: 103.83532232336977,
  2002: 102.81709401489702},
 'Effective exchange rate': {1998: 88.134,
  1999: 95.6425,
  2000: 99.927725,
  2001: 101.92745,
  2002: 107.85565},
 'RoR (foreign liabilities)': {1998: 0.0433,
  1999: 0.0437,
  2000: 0.0542,
  2001: 0.0539,
  2002: 0.0474},
 'Gross foreign assets': {1998: 19.720897432405103,
  1999: 22.66200738564236,
  2000: 25.18270679890144,
  2001: 30.394226651732836,
  2002: 37.26477320359688},
 'Gross domestic income': {1998: 104.9037939043707,
  1999: 103.15361867816479,
  2000: 103.06777792080423,
  2001: 102.85886528974339,
  2002: 102.28518242008846},
 'Gross foreign liabilities': {1998: 60.59784839338306,
  1999: 61.03308220978983,
  2000: 64.01438055825233,
  2001: 67.07798172469921,
  2002: 70.16108592109364},
 'Inflation rate': {1998: 52.6613,
  1999: 19.3349,
  2000: 16.0798,
  2001: 15.076,
  2002: 17.236},
 'Credit': {1998: 0.20269913592846378,
  1999: 0.2154280880177353,
  2000: 0.282948948505006,
  2001: 0.3954812893893278,
  2002: 0.3578263032373988}}

which can be converted back to its original form using:
df = pd.DataFrame.from_dict(s)

I am interested in dynamically naming dataframes such that, for instance:
dim = df.shape[1]

counter1 = 0
counter2 = 1

while(counter1 <= dim):
   df_str(counter2) = df.iloc[:, counter1: (counter1 + 3)]
   counter1 = counter1 + 3
   counter2 = counter2 + 1

Obviously this code is wrong and won't work. But essentially I need to end up with df_1, df_2, df_3 and so on, depending on the number of columns of the dataframe. I have read in many posts that this is bad practice and that this can be accomplished using dictionaries; but this is not clear to me. Some guidance is very much appreciated.

A: i = 0
res = []
while i < df.shape[1]:
    res.append(df.iloc[:, i: (i + 3)])
    i = i + 3
print(res[0])
print(res[1])
print(res[2])


text:
Q: how to add ViewPager with SherlockFragment tabs in android This is my code:
public class FragmentLifenews extends SherlockFragment {
    private ActionBar actionBar;
    private ViewPager viewPager;

    public FragmentLifenews() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_life, container, false);
        viewPager = (ViewPager) view.findViewById(R.id.pager);
        viewPager.setOnPageChangeListener(onPageChangeListener);
        viewPager.setAdapter(new ViewPager1(getFragmentManager()));
        addActionBarTabs();

        return view;
    }

    private ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            actionBar.setSelectedNavigationItem(position);
        }
    };

    private void addActionBarTabs() {
        getSherlockActivity().getSupportActionBar();
        getSherlockActivity().setSupportProgressBarVisibility(true);
        getSherlockActivity().setSupportProgressBarIndeterminate(true);
        String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
        for (String tabTitle : tabs) {
            ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
                    .setTabListener(tabListener);
            actionBar.addTab(tab);
        }
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }

    private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }
    };

public class ViewPager1 extends FragmentStatePagerAdapter {

    private final int PAGES = 3;

    public ViewPager1(FragmentManager actionBar) {
        super(actionBar);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new Tab1Fragment();
            case 1:
                return new Tab2Fragment();
            case 2:
                return new Tab3Fragment();
            default:
                throw new IllegalArgumentException("The item position should be less or equal to:" + PAGES);
        }
    }

    @Override
    public int getCount() {
        return PAGES;
    }

FragmentLifenews is class which extends from SherlockFragment. I want to add ViewPager  with SherlockFragment  tabs but i am unable to get i am getting error at:
   com.locii.fragment.FragmentLifenews.onCreateView(FragmentLifenews.java:28)
   viewPager.setOnPageChangeListener(onPageChangeListener);
   viewPager.setAdapter(new ViewPager1(getFragmentManager()));

please tell me what i am doing wrong i have changed getFragmentManager() in place of getSupportActionBar() please suggest me .

A: @SuppressLint("ResourceAsColor")
public class MainActivity extends FragmentActivity implements
        OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;

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

    mViewPager = (ViewPager) findViewById(R.id.viewpager);

    // Tab Initialization
    initialiseTabHost();

    // Fragments and ViewPager Initialization
    List<Fragment> fragments = getFragments();
    pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
    mViewPager.setAdapter(pageAdapter);
    mViewPager.setOnPageChangeListener(MainActivity.this);
}

// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost,
        TabHost.TabSpec tabSpec) {
    tabSpec.setContent(new MyTabFactory(activity));
    tabHost.addTab(tabSpec);
}

// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
    int pos = this.mTabHost.getCurrentTab();
    this.mViewPager.setCurrentItem(pos);
    // mTabHost.getTabWidget().setDividerDrawable(null);
    setSelectedTabColor();
}

@Override
public void onPageScrollStateChanged(int arg0) {
}

// Manages the Page changes, synchronizing it with Tabs
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
    int pos = this.mViewPager.getCurrentItem();
    this.mTabHost.setCurrentTab(pos);
    // mTabHost.getTabWidget().setDividerDrawable(null);
}

@Override
public void onPageSelected(int arg0) {
}

@SuppressLint("ResourceAsColor")
private void setSelectedTabColor() {
    for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
        mTabHost.getTabWidget().setDividerDrawable(
                android.R.color.transparent);
        TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i)
                .findViewById(android.R.id.title);
        tv.setTextColor(getResources().getColor(R.color.white));
        mTabHost.getTabWidget()
                .setShowDividers(TabWidget.SHOW_DIVIDER_NONE);
        mTabHost.getTabWidget().getChildAt(i)
                .setBackgroundColor(R.drawable.bottom_home_back);
        // mTabHost.getTabWidget().getChildAt(0).getLayoutParams().width =
        // 50;
    }
    mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab())
            .setBackgroundResource(R.drawable.btn_selected);
    // mTabHost.getTabWidget().getChildAt(0).getLayoutParams().width = 50;
}

private List<Fragment> getFragments() {
    List<Fragment> fList = new ArrayList<Fragment>();

    // TODO Put here your Fragments
    // DealTab f1 = DealTab.newInstance();
    DealTab_New f1 = DealTab_New.newInstance();
    EventTab f2 = EventTab.newInstance();

    MyAccountFragment f3 = MyAccountFragment.newInstance();
    MessageFragment f4 = MessageFragment.newInstance();
    MoreFragment f5 = MoreFragment.newInstance();
    QrCodeFragment f6 = QrCodeFragment.newInstance();

    // fList.add(f1);
    fList.add(f1);
    fList.add(f2);
    fList.add(f3);
    fList.add(f4);
    fList.add(f5);
    fList.add(f6);

    return fList;
}

// Tabs Creation
@SuppressLint("ResourceAsColor")
private void initialiseTabHost() {
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();

    // TODO Put here your Tabs
    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Tab1").setIndicator(
                    "",
                    getApplicationContext().getResources().getDrawable(
                            R.drawable.btn_deals)));

    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Tab2").setIndicator(
                    "",
                    getApplicationContext().getResources().getDrawable(
                            R.drawable.btn_event)));
    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Tab3").setIndicator(
                    "",
                    getApplicationContext().getResources().getDrawable(
                            R.drawable.btn_my_account)));
    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Tab4").setIndicator(
                    "",
                    getApplicationContext().getResources().getDrawable(
                            R.drawable.btn_message)));
    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Tab5").setIndicator(
                    "",
                    getApplicationContext().getResources().getDrawable(
                            R.drawable.btn_more)));

    mTabHost.setOnTabChangedListener(this);

    setSelectedTabColor();
}

}
i use in this my Application to use tab host and also view pager...


text:
Q: How to encode an authorization request_uri I need to construct a custom request_uri for an implementation of Spring OAuth2.  What specific code should be used to properly encode each of the parameters in the request_uri?
The full, unencoded, request_uri is as follows, but is resulting in an error that indicates that a token is not granted:
http://localhost:9999/uaa/oauth/authorize?client_id=acme
&redirect_uri=http://localhost:8080/login&response_type=code
&state=13ab71ae-c8ed-4370-a60f-dd7fe47ed763

As you can see, the individual parameters are:
client_id=acme
redirect_uri=http://localhost:8080/login
response_type=code
state=13ab71ae-c8ed-4370-a60f-dd7fe47ed763

And the code that was used to construct the above request_uri is:
CsrfToken csrf = (CsrfToken) attr.getRequest().getAttribute(CsrfToken.class.getName());
String attrToken = csrf.getToken();
authorizationRequest.setState(attrToken);
String newRequestUri = "http://localhost:9999/uaa/oauth/authorize?";
String clientId = authorizationRequest.getClientId();
newRequestUri = newRequestUri + "client_id=" + clientId;
String redirectUri = authorizationRequest.getRedirectUri();
newRequestUri = newRequestUri + "&redirect_uri="+redirectUri;
Set<String> respTypes = authorizationRequest.getResponseTypes();
String respType = respTypes.iterator().next();//this plucks the first one, but is not safe for when there is a list.
newRequestUri = newRequestUri +"&response_type="+respType;
String state = authorizationRequest.getState();
newRequestUri = newRequestUri + "&state="+state;
attr.setAttribute("javax.servlet.forward.request_uri", newRequestUri, RequestAttributes.SCOPE_REQUEST);
//now re-set the request attributes to reflect the changes we just made
RequestContextHolder.setRequestAttributes(attr);

More specifically, this OP asks what syntax should be used to encode the following string values in the code above: newRequestUri, clientId, redirectUri, respType, and state.
The Official OAuth2 Spec says you can use the application/x-www-form-urlencoded Content-Type and UTF-8 encoding, but then also gives this example:
/authorize?response_type=code&client_id=s6BhdRkqt3
&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

Similarly, the Spring OAuth2 Developer Guide only contains one use of the word encode.

A: Seems you are looking for what is commonly called percent-encoding or URL-encoding. There are functions for this in almost every language's HTTP library, either for a single value or for a set of key-value pairs.
In practice application/x-www-form-urlencoded is almost the same as URL-encoded.


text:
Q: How do you create and load modules dynamically at runtime in Elixir, or Erlang? The basic scenario is this:  I need to load text from a database, and then turn that text into an Elixir module (or an Erlang module) and then make calls into it.  The text is effectively the same as a module file. So this is a form of hot code loading.  I want to compile the "file" and then load the resulting module, then make calls into it.  Later I'll unload it. The only difference is the code exists in a database rather than a file on the disk. (and it doesn't exist at the time that I'm writing the code that will be loading it.)
I know Erlang supports hot code loading, but seems focused on compiling files on disk and then loading the beams.  I wish to do this as a more dynamic process, and I won't be replacing running code, but loading the code, then running it, then unloading it.
There are several facilities in Elixir for evaluating code at runtime. I'm trying to figure out how to do this with them, and the documentation is a bit sparse.
Code.compile_string(string, "nofile")

"returns a list of tuples where the first element is the module name and the second one is its binary".   So, now I have the modules names and their binaries, but I do not know of a way to then load the binaries into the runtime and call into them.  How would I do that?  (There's no function for that in the Code library that I can see.)
Possibly I could then use the Erlang function:
:code.load_binary(Module, Filename, Binary)  ->
           {module, Module} | {error, What}

Ok, so this returns a tuple with the atom "module" and then the Module.  If the string loaded from the database defined a module called "Paris", how in my code would I then execute
paris.handler([parameters])

since I don't know in advance that there will be a module called paris?  I could know, by having the string "paris" also stored in the database that this is the name, but is there any way of calling into a module, using a string as the name of the module you're calling?
There is also:
eval(string, binding // [], opts // [])

Which evaluates the contents of the string.  Can this string be the entire definition of a module?  It appears not.  I'd like to be able to write this code that's being evaluated in such a way that it has multiple functions that call each other--e.g. a complete little program, with a pre-defined entry point (Which could be a main, such as "DynamicModule.handle([parameter, list])"
Then there's the EEx module, which has:
compile_string(source, options // [])

Which is great for doing templates.  But ultimately it only seems to work for the use case where there's a string and you've got Elixir code embedded in it.  It evaluates the string in the context of the options and produces a string.  I'm seeking to compile the string into one or more functions that I can then call.  (If I can only make one function that's fine, that function can pattern match or switch into doing the other things that are needed....)
I know this is unconventional, but I have my reasons for doing it this way and they are good ones.  I'm looking for advice about how to do this, but don't need to be told "don't do that".  It seems like it should be possible, Erlang supports hot code loading and Elixir is pretty dynamic, but I just don't know the syntax, or the right functions.   I'll be monitoring this question closely. Thanks in advance!

EDITS based on the first answers:
Thanks for the answers, this is good progress. As Yuri showed, eval can define a module, and as José points out, I can just use code eval for small parts of code with bindings.
The code being evaluated (whether turned into a module, or not) is going to be fairly complex.  And its development would be best involving breaking it down into functions and calling those functions.
To help, let me provide some context.  Assume I'm building a web framework.  The code loaded in from the database is handlers for specific URIs.  So, when an HTTP call comes in, I might load the code for example.com/blog/  This page might involve several different things, such as comments, a list of recent posts, etc.
Since many people are hitting the page at the same time, I'm spawning a process to handle each page view.  Thus there are many times when this code may be evaluated simultaneously, for different requests.
The the module solution allows one to break the code up into functions for different parts of the page (eg: the list of posts, comments, etc. )  And I would load the module once, at startup, and let many processes spawn that call into it.  The module is global, correct?
What happens if there's a module already defined?  EG: When the module changes, and there are processes already calling that module.
In iex, I am able to redefine a module that's already been defined:
iex(20)> Code.eval "defmodule A do\ndef a do\n5\nend\nend"
nofile:1: redefining module A

What happens if I redefine the module at runtime, to all the processes currently calling into that module?   Also, will this redefinition work outside of iex, in normal operation?
Assuming that redefining the module would be problematic, and that modules being global might run into problems with namespace collisions, I looked into using eval to define a function.
If I can merely have the code from the database define functions, then those functions are within the scope of whatever process, and we don't have the possibility of global collisions.
However, this doesn't seem to work:
iex(31)> q = "f = function do
...(31)> x, y when x > 0 -> x+y
...(31)> x, y -> x* y
...(31)> end"
"f = function do\nx, y when x > 0 -> x+y\nx, y -> x* y\nend"
iex(32)> Code.eval q
{#Fun<erl_eval.12.82930912>,[f: #Fun<erl_eval.12.82930912>]}
iex(33)> f
** (UndefinedFunctionError) undefined function: IEx.Helpers.f/0
    IEx.Helpers.f()
    erl_eval.erl:572: :erl_eval.do_apply/6
    src/elixir.erl:110: :elixir.eval_forms/3
    /Users/jose/Work/github/elixir/lib/iex/lib/iex/loop.ex:18: IEx.Loop.do_loop/1

iex(33)> f.(1,3)
** (UndefinedFunctionError) undefined function: IEx.Helpers.f/0
    IEx.Helpers.f()
    erl_eval.erl:572: :erl_eval.do_apply/6
    erl_eval.erl:355: :erl_eval.expr/5
    src/elixir.erl:110: :elixir.eval_forms/3
    /Users/jose/Work/github/elixir/lib/iex/lib/iex/loop.ex:18: IEx.Loop.do_loop/1

I also tried:
    iex(17)> y = Code.eval "fn(a,b) -> a + b end"
{#Fun<erl_eval.12.82930912>,[]}
iex(18)> y.(1,2)
** (BadFunctionError) bad function: {#Fun<erl_eval.12.82930912>,[]}
    erl_eval.erl:559: :erl_eval.do_apply/5
    src/elixir.erl:110: :elixir.eval_forms/3
    /Users/jose/Work/github/elixir/lib/iex/lib/iex/loop.ex:18: IEx.Loop.do_loop/1

So, in summary:

*

*Can modules be redefined using Code.eval when there are processes calling into them?

*Is it possible to use Code.eval to make functions whose scope is bound to the process in which Code.eval was called?

*If you understand what it is I'm trying to do, can you suggest a better way to go about it?
Also, if there is a better forum where I should be asking this, feel free to let me know.  And if there are docs or relevant examples I should read, please feel free to point me to them.  I'm not trying to get you to do all the work, I just am unable to figure it out myself.
I'm learning Elixir specifically for the ability to dynamically evlauate code, but my Elixir knowledge is minimal now- I just started- and my erlang is rusty too.
Much thanks!

A: Have you checked: Dynamic Compile Library by Jacob Vorreuter. See example below
1> String = "-module(add).\n -export([add/2]). \n add(A,B) -> A + B. \n".
"-module(add).\n -export([add/2]). \n add(A,B) -> A + B. \n"
2> dynamic_compile:load_from_string(String).
{module,add}
3> add:add(2,5).
7
4>

Also, check out this question and its answer

A: As you described, there are many different approaches you could take by ultimately they boil down to two different categories: 1) code compilation and 2) code evaluation. The example you described above requires compilation, which will define a module and then you would have to invoke it. However, as you found out, it requires defining a module name and potentially purging and discarding those modules when the database changes. Also, note that, defining modules may exhaust the atom table, as an atom is created for every module. I would only use this approach if you need to compile at maximum a dozen modules.
(A small note, Code.compile_string already defines the module, so you don't need to call load_binary).
Maybe a simpler approach is to call Code.eval passing the code from the database, thus code evaluation. It works fine if all you want to is to evaluate some custom rules. The Code.eval accepts a binding, which would allow you to pass parameters to the code. Let's suppose you have "a + b" stored in the database, where a and b are the parameters, you could evaluate it as:
Code.eval "a + b", [a: 1, b: 1]

EDIT BASED ON QUESTION'S EDITS
If you are evaluating code, keep in mind that Code.eval returns the result of evaluating the code and the new binding, so your example above would be better written as:
q = "f = function do
x, y when x > 0 -> x+y
x, y -> x* y
end"

{ _, binding } = Code.eval q
binding[:f].(1, 2)

However, given your use case, I wouldn't consider using eval but I would indeed compile a module. Since the information is coming from the database, you can use this fact to generate unique modules per record for you. For example, you can assume developers will be adding the contents of a module to the database, something like:
def foo, do: 1
def bar, do: 1

After you get this information from the database, you can compile it using:
record   = get_record_from_database
id       = record.id
contents = Code.string_to_quoted!(record.body)
module   = Module.concat(FromDB, "Data#{record.id}")
Module.create module, contents, Macro.Env.location(__ENV__)
module

Where record is anything that you get back from the database. Assuming the record id is 1, it would define a module FromDB.Data1 which then you would be able to invoke foo and bar.
Regarding code reloading, both defmodule and Module.create use :code.load_binary to load the module. Which means that if you update the module, the old version is still kept around until another new version is loaded.
One of the things you should add as well is cache expiration, so you don't need to compile a module on every request. This can be done if you have a lock_version in the database that you increment every time you change the record contents. The final code would be something like:
record  = get_record_from_database
module  = Module.concat(FromDB, "Data#{record.id}")
compile = :code.is_loaded(module) == false or
            record.lock_version > module.lock_version

if compile do
  id       = record.id
  contents = Code.string_to_quoted!(record.body)
  contents = quote do
    def lock_version, do: unquote(record.lock_version)
    unquote(contents)
  end
  Module.create module, contents, Macro.Env.location(__ENV__)
end

module

A: Code.eval can be used to define a module:
iex(1)> Code.eval "defmodule A do\ndef a do\n1\nend\nend"
{{:module,A,<<70,79,82,49,0,0,2,168,66,69,65,77,65,116,111,109,0,0,0,98,0,0,0,11,8,69,108,105,120,105,114,45,65,8,95,95,105,110,102,111,95,95,4,100,111,99,115,9,102,117,...>>,{:a,0}},[]}
iex(2)> A.a
1

Does this help?


text:
Q: Using powershell to return folder permissions I am new to powershell and trying to use this script that I found to return folder permissions:
Function Get-SecGroups($path)
{
  $a = @{};
  get-acl -Path $path | %{Write-Host `n $path; $_.Access} | %{
    #ONLY SHOW PERMISSIONS ON FOLDER, NOT FILES
    #CHECK TO SEE IF THE USER/GROUP ONLY HAS "List" PERMISSION
    if ($_.InheritanceFlags -eq "ContainerInherit")
    {
      Write-Host `t $_.IdentityReference "List";
    }
    else
    {
      Write-Host `t $_.IdentityReference, $_.FileSystemRights;
    }
  }
}
#END Get-SecGroups

get-childitem -Path "d:\*\*\" | where {$_.PsIsContainer} | %{Get-SecGroups($_.FullName)} | out-file c:\output.txt

The problem I have is that it creates the output.txt but with no data. The data is displayed on screen. Where am I going wrong?

A: Juste replace write-host by write-output in your function.


text:
Q: How to compare and get matched fields in Javascript? I have json data below
var dataA = {
   "state":"TX",
   "city":"Dallas",
   "code":"75201",
   "totalareas":"75201",
   "website":"asdf.ccom"

}

and I have an array of objects
var dataB =[
    {
     "key":"state",
     "value":"TX"

    },
    {
    "key":"city",
    "value":"Dallas"
    },
    {
     "key":"yu",
     "value":"2"
    },
   {
     "key":"website",
     "value":"asdf.ccom"
    }
    ]

I want to compare this dataA and dataB and get only matched fields with object how can I do this
My expectation result
{
   "city":"Dallas",
   "state":"TX",

}

A: You can use reduce to loop thru dataB. Convert each object into an array using Object.entries and use forEach to loop thru. If the key exist and the same value, assign the key and value to the accumulator.

var dataA = {
  "state": "TX",
  "city": "Dallas",
  "code": "75201",
  "totalareas": "75201"
}

var dataB = [{
  "city": "Dallas",
  "citycode": "",
  "population": "234k"
}, {
  "state": "TX",
  "statecode": "asdf5678"
}, {
  "zip": "75201",
  "areacount": "567"
}]

var result = dataB.reduce((c, v) => {
  Object.entries(v).forEach(([i, o]) => {
    if (dataA[i] && dataA[i] === o) c[i] = o;
  })
  return c;
}, {});

console.log(result);

UPDATE: You dont need to convert each object into an array. You can use just use the key and value on the condition.

var dataA = {"state":"TX","city":"Dallas","code":"75201","totalareas":"75201","website":"asdf.ccom"}
var dataB = [{"key":"state","value":"TX"},{"key":"city","value":"Dallas"},{"key":"yu","value":"2"},{"key":"website","value":"asdf.ccom"}]

var result = dataB.reduce((c, v) => {
  if (dataA[v.key] && dataA[v.key] === v.value) c[v.key] = v.value;
  return c;
}, {});

console.log(result);


text:
Q: Converting these Networking Command Lines to /etc/network/interfaces file? I am currently working with a LIDAR that requires one to run several commands:
https://data.ouster.io/downloads/software-user-guide-v1.13.0.pdf
The commands are listed here:
ip addr flush enp2s0f2
ip addr show dev enp2s0f2
sudo ip addr add 10.5.5.1/24 dev enp2s0f2
sudo ip link set enp2s0f2 up
ip addr show dev enp2s0f2
sudo dnsmasq -C /dev/null -kd -F 10.5.5.50,10.5.5.100 -i enp2s0f2 --bind-dynamic

The documentation says:

See the documentation for your operating system on how to make these changes persistent, e.g., by using a network configuration daemon like NetworkManager

Unfortunately I have no idea how to do this. I know we need to add some lines to the /etc/network/interfaces file. Can someone tell me how to do this? I'm effectively assigning a static IP-address at bootup, and then running a local DHCP server for that port

A: Adding the following to /etc/network/interfaces should work:
allow-hotplug enp2s0f2
iface enp2s0f2 inet static
address 10.5.5.1/24
post-up dnsmasq -C /dev/null -F 10.5.5.50,10.5.5.100 -i enp2s0f2 --bind-dynamic
pre-down killall dnsmasq

*

*dnsmasq should be spawned in background (don't use -kd options) as otherwise ifup would hang.

*dnsmasq is killed before the interface goes down.


text:
Q: Difference between ngModules and index.ts I have been looking at angular seed and I am wondering why do they use both index.ts and modules.
from my understanding, they can both be used to export typescript types.

A: These two are entirely unrelated.
index.ts is for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.
NgModule is to register directives, components, pipes, and providers in other NgModules.


text:
Q: Where do you set the button size of a UISegmentedControl? I have my own custom UISegmentedControl subclass. It's buttons are bigger than the standard size. Each button is 100.0 points wide.
@implementation SegmentedControlExplore

- (id) init
{
    return [super
        initWithItems:[NSArray arrayWithObjects:
            @"Uno",
            @"Dos",
            nil
        ]
    ];
}

- (void) layoutSubviews
{
    for (NSUInteger i = 0; i < self.numberOfSegments; i++) {
        [self setWidth:100.0 forSegmentAtIndex:i];
    }
    [super layoutSubviews];
}

@end

When I attempt to use this in my controller, I could not center it in my UINavigationBar.
SegmentedControl* sc = [[[SegmentedControl alloc] init] autorelease];
[self.navigationController.navigationBar addSubview:sc];
sc.center = self.navigationController.navigationBar.center;

It's off-center to the right. The reason is because the button size setting actually gets called after its center property gets changed. So where should I move my button size setting so it gets done first? I tried moving it to init, but the size did not get changed.

A: Replace your layoutSubviews function with this code.
- (void) layoutSubviews {

    self.frame = CGRectMake(0, 0, self.numberOfSegments*100, 44);
    self.center = self.superview.center;

    CGRect frame = self.frame;

    if (![[UIApplication sharedApplication] isStatusBarHidden]) {
        self.frame = CGRectMake(frame.origin.x, frame.origin.y-20, frame.size.width, frame.size.height);
    }

    for (NSUInteger i = 0; i < self.numberOfSegments; i++) {
        [self setWidth:100 forSegmentAtIndex:i];
    }

    [super layoutSubviews];
}


text:
Q: Add links on right of footer I have these 3 links on the left side of footer, on the left side of the logo. I would like to add another 3 that are on the right side of the logo. But kinda float right and will always be 100px or so from the right side of web browser.
Here is my fiddle:
For the css I tried basically copying and pasting the list and getting it to float right but couldn't get it working right.

footer {
  background-color: #30659B;
  height: 135px;
  width: 100%
}

.logo2 {
  width: 150px;
  fill: white;
  display: block;
  position: relative;
  margin: 0 auto;
  padding-top: 27px;
}

.nav2 {
  list-style-type: none;
  overflow: hidden;
  position: absolute;
  display: table;
  text-align: center;
  margin-top: -22px;
  padding: 0;
}

.li2 {
  display: inline-block;
  padding: 0;
  font-family: proxima nova;
  font-size: 10px;
  text-decoration: none;
}

.li2 a {
  display: block;
  text-decoration: none;
  text-align: center;
  color: white;
  /*   margin: 32px 20px 0px 20px; */
  margin-left: 100px;
}

    <svg class="logo2" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 268 50"><title>Artboard 1</title><path         d="M46.26,10.5h6.46V35.17H65.55v5.69H46.26Z"/><path  d="M82.8,38.59a9.1,9.1,0,0,1-7,2.82c-3.5,0-7.65-2.37-7.65-7.28,0-5.14,4.14-7,7.65-7,2.91,0,5.51.91,7,2.69v-3c0-2.23-1.91-3.69-4.82-3.69a9.25,9.25,0,0,0-6.42,2.59l-2.18-3.87A14.42,14.42,0,0,1,79,18.33c5,0,9.6,2,9.6,8.33v14.2H82.8Zm0-5.74a5.78,5.78,0,0,0-4.64-1.91c-2.28,0-4.14,1.23-4.14,3.32s1.87,3.23,4.14,3.23a5.78,5.78,0,0,0,4.64-1.91Z"/><path d="M109.15,38.08a10.29,10.29,0,0,1-7.74,3.32c-4.82,0-7.1-2.64-7.1-6.92V18.88h5.78V32.21c0,3,1.59,4.05,4.05,4.05a6.47,6.47,0,0,0,5-2.5V18.88h5.78v22h-5.78Z"/><path d="M135.5,27.57c0-3-1.59-4.1-4.05-4.1a6.26,6.26,0,0,0-5,2.59V40.86h-5.78v-22h5.78v2.87a10.07,10.07,0,0,1,7.69-3.41c4.82,0,7.15,2.73,7.15,7V40.86H135.5Z"/><path d="M157.26,18.33c4.51,0,7.24,2,8.69,4l-3.78,3.5a5.44,5.44,0,0,0-4.64-2.37c-3.5,0-6,2.55-6,6.37s2.46,6.42,6,6.42a5.55,5.55,0,0,0,4.64-2.37L166,37.4c-1.46,2-4.19,4-8.69,4-6.78,0-11.65-4.78-11.65-11.56S150.48,18.33,157.26,18.33Z"/><path d="M184.61,27.48c0-3-1.59-4-4.1-4a6.4,6.4,0,0,0-5,2.59V40.86h-5.78V10.5h5.78V21.74a10.17,10.17,0,0,1,7.74-3.41c4.82,0,7.15,2.64,7.15,6.92V40.86h-5.78Z"/><path d="M196.12,49.24V18.88h5.78v2.78a8.49,8.49,0,0,1,6.78-3.32c5.64,0,9.74,4.19,9.74,11.52s-4.1,11.56-9.74,11.56A8.4,8.4,0,0,1,201.9,38v11.2Zm10.74-25.76a6.47,6.47,0,0,0-5,2.5v7.78a6.62,6.62,0,0,0,5,2.5c3.32,0,5.55-2.59,5.55-6.42S210.19,23.47,206.86,23.47Z"/><path d="M235.94,38.59a9.1,9.1,0,0,1-7,2.82c-3.51,0-7.65-2.37-7.65-7.28,0-5.14,4.14-7,7.65-7,2.91,0,5.51.91,7,2.69v-3c0-2.23-1.91-3.69-4.82-3.69a9.25,9.25,0,0,0-6.42,2.59l-2.18-3.87a14.42,14.42,0,0,1,9.6-3.46c5,0,9.6,2,9.6,8.33v14.2h-5.78Zm0-5.74a5.78,5.78,0,0,0-4.64-1.91c-2.28,0-4.14,1.23-4.14,3.32s1.87,3.23,4.14,3.23a5.78,5.78,0,0,0,4.64-1.91Z"/><path d="M262.57,38.08a8.62,8.62,0,0,1-6.78,3.32c-5.55,0-9.74-4.19-9.74-11.51s4.14-11.56,9.74-11.56a8.47,8.47,0,0,1,6.78,3.37V10.5h5.83V40.86h-5.83Zm0-12.11a6.36,6.36,0,0,0-5-2.5c-3.28,0-5.55,2.59-5.55,6.42s2.28,6.37,5.55,6.37a6.36,6.36,0,0,0,5-2.5Z"/><path d="M7.56,38.52l8.13,10.73a1.41,1.41,0,0,0,2.16,0L26,38.52a1.34,1.34,0,0,0-.56-2L18.53,33A4,4,0,0,0,15,33l-6.89,3.5A1.34,1.34,0,0,0,7.56,38.52Z"/><path d="M30.31,14.15,18.12.82a1.91,1.91,0,0,0-2.7,0L3.23,14.15a4,4,0,0,0-1,2.16L-.38,34.52c-.13.9,1,1.53,1.93,1.07L4.29,34.2l12.48-6.37L29.25,34.2,32,35.59c.92.47,2.06-.17,1.93-1.07l-2.57-18.2A4,4,0,0,0,30.31,14.15Z"/></svg>

ABOUT US

OUR WORK

SERVICES

Here is what the footer should look like in the end

A: Try with this

ABOUT US

OUR WORK

SERVICES

<svg class="logo2" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg">Tu logo</svg>

TWITTER

INSTAGRAM

FACEBOOK

A: You can simply achieve that footer with the use of flexbox as demonstrated below. Hope, this helps.

footer {
  background-color: #30659B;
  width: 100vw;
}

.logo2 {
  width: 150px;
  fill: white;
  display: block;
}

.nav {
  padding:0;
  list-style-type: none;
  color: white;
  display: flex;  /*Generates a flexbox layout with default flex direction as row */
  width: 100%; /* Not really required */
  height:100px;
  align-items: center; /*Aligns contents vertically */
  justify-content: space-around;
}

li {
  padding:0;
  font-family: proxima nova;
  font-size: 10px;
  text-decoration: none;
  text-align:center;
  margin:5px;
}
li:first-child{
margin-left:100px;
}
li:last-child{
margin-right:100px;
}

li a {
  text-decoration: none;
  color: white;
}

ABOUT US

OUR WORK

SERVICES

    <svg class="logo2" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 268 50"><title>Artboard 1</title><path         d="M46.26,10.5h6.46V35.17H65.55v5.69H46.26Z"/><path  d="M82.8,38.59a9.1,9.1,0,0,1-7,2.82c-3.5,0-7.65-2.37-7.65-7.28,0-5.14,4.14-7,7.65-7,2.91,0,5.51.91,7,2.69v-3c0-2.23-1.91-3.69-4.82-3.69a9.25,9.25,0,0,0-6.42,2.59l-2.18-3.87A14.42,14.42,0,0,1,79,18.33c5,0,9.6,2,9.6,8.33v14.2H82.8Zm0-5.74a5.78,5.78,0,0,0-4.64-1.91c-2.28,0-4.14,1.23-4.14,3.32s1.87,3.23,4.14,3.23a5.78,5.78,0,0,0,4.64-1.91Z"/><path d="M109.15,38.08a10.29,10.29,0,0,1-7.74,3.32c-4.82,0-7.1-2.64-7.1-6.92V18.88h5.78V32.21c0,3,1.59,4.05,4.05,4.05a6.47,6.47,0,0,0,5-2.5V18.88h5.78v22h-5.78Z"/><path d="M135.5,27.57c0-3-1.59-4.1-4.05-4.1a6.26,6.26,0,0,0-5,2.59V40.86h-5.78v-22h5.78v2.87a10.07,10.07,0,0,1,7.69-3.41c4.82,0,7.15,2.73,7.15,7V40.86H135.5Z"/><path d="M157.26,18.33c4.51,0,7.24,2,8.69,4l-3.78,3.5a5.44,5.44,0,0,0-4.64-2.37c-3.5,0-6,2.55-6,6.37s2.46,6.42,6,6.42a5.55,5.55,0,0,0,4.64-2.37L166,37.4c-1.46,2-4.19,4-8.69,4-6.78,0-11.65-4.78-11.65-11.56S150.48,18.33,157.26,18.33Z"/><path d="M184.61,27.48c0-3-1.59-4-4.1-4a6.4,6.4,0,0,0-5,2.59V40.86h-5.78V10.5h5.78V21.74a10.17,10.17,0,0,1,7.74-3.41c4.82,0,7.15,2.64,7.15,6.92V40.86h-5.78Z"/><path d="M196.12,49.24V18.88h5.78v2.78a8.49,8.49,0,0,1,6.78-3.32c5.64,0,9.74,4.19,9.74,11.52s-4.1,11.56-9.74,11.56A8.4,8.4,0,0,1,201.9,38v11.2Zm10.74-25.76a6.47,6.47,0,0,0-5,2.5v7.78a6.62,6.62,0,0,0,5,2.5c3.32,0,5.55-2.59,5.55-6.42S210.19,23.47,206.86,23.47Z"/><path d="M235.94,38.59a9.1,9.1,0,0,1-7,2.82c-3.51,0-7.65-2.37-7.65-7.28,0-5.14,4.14-7,7.65-7,2.91,0,5.51.91,7,2.69v-3c0-2.23-1.91-3.69-4.82-3.69a9.25,9.25,0,0,0-6.42,2.59l-2.18-3.87a14.42,14.42,0,0,1,9.6-3.46c5,0,9.6,2,9.6,8.33v14.2h-5.78Zm0-5.74a5.78,5.78,0,0,0-4.64-1.91c-2.28,0-4.14,1.23-4.14,3.32s1.87,3.23,4.14,3.23a5.78,5.78,0,0,0,4.64-1.91Z"/><path d="M262.57,38.08a8.62,8.62,0,0,1-6.78,3.32c-5.55,0-9.74-4.19-9.74-11.51s4.14-11.56,9.74-11.56a8.47,8.47,0,0,1,6.78,3.37V10.5h5.83V40.86h-5.83Zm0-12.11a6.36,6.36,0,0,0-5-2.5c-3.28,0-5.55,2.59-5.55,6.42s2.28,6.37,5.55,6.37a6.36,6.36,0,0,0,5-2.5Z"/><path d="M7.56,38.52l8.13,10.73a1.41,1.41,0,0,0,2.16,0L26,38.52a1.34,1.34,0,0,0-.56-2L18.53,33A4,4,0,0,0,15,33l-6.89,3.5A1.34,1.34,0,0,0,7.56,38.52Z"/><path d="M30.31,14.15,18.12.82a1.91,1.91,0,0,0-2.7,0L3.23,14.15a4,4,0,0,0-1,2.16L-.38,34.52c-.13.9,1,1.53,1.93,1.07L4.29,34.2l12.48-6.37L29.25,34.2,32,35.59c.92.47,2.06-.17,1.93-1.07l-2.57-18.2A4,4,0,0,0,30.31,14.15Z"/></svg>

TWITTER

FACEBOOK

INSTAGRAM

A: Sure, try with this css class:
.nav2 {
  list-style-type: none;
  overflow: hidden;
  text-align: center;
  margin: auto;
  padding: 0;
  width:100%;
  z-index:1000;
}


text:
Q: How to automate archiving a copy of mails received/sent through sendmail MTA on CentOS? We have an application which sends out emails and also receives emails from the users which trigger functionality in the application. There are a lot of emails going back and forth. We would like to have an ability to automate archival of all emails sent / received and if possible have a searchable archival. We are talking about almost 1 GB of emails a day.

A: Take a look at Archiving milters.


text:
Q: Config reverse DNS PTR on cpanel with AWS EC2 Anybody here has experience with configuration SMTP on Cpanel host by AWS EC2.
After I have done configurations, DKIM is valid, SPF is valid, but PTR is not valid (reverse DNS). Then when I sent a test email to mail-tester.com, it was 3/10. Here is the error message
We didn't find a server (A Record) behind your hostname ip-172-31-1-135.ap-southeast-1.compute.internal.

You may want to publish a DNS record (A type) for the hostname
ip-172-31-1-135.ap-southeast-1.compute.internal or use a different hostname in your mail software.

I'm a newbie for DNS stuff, if you need more information, please give me a comment.

A: *

*You should configure your mail server software to use your custom hostname (for example mail.example.com), not the AWS assigned default (such as ip-172-31-1-135.ap-southeast-1.compute.internal)

*You need to contact AWS support to have PTR record configured https://aws.amazon.com/blogs/aws/reverse-dns-for-ec2s-elastic-ip-addresses/

*Keep in mind that Amazon EC2 throttles traffic on port 25 of all EC2 instances by default, but you can request for this throttle to be removed: https://aws.amazon.com/premiumsupport/knowledge-center/ec2-port-25-throttle/

A: If you want to receive emails on this server you can't change port number from 25 to something else as other servers will try to connect on this port to deliver emails. You also have to ask AWS to remove throttle on port 25 as stated before.
If you haven't already, create A DNS record for cpanel.mydomain.com pointing to your elastic IP (it is important that you have elastic IP not automatically assigned public IP)

A: Finally, I got 9.8/10 after tweaking some configuration and waiting for AWS Support to map Elastic IP to my domain name, then I can get 10/10

Most importantly, have to make sure hostname has to your my domain
1. set hostname
sudo hostname cpanel.mydomain.com

*Set it automatically

cd /etc/dhcp/dhclient-exit-hooks.d/
sudo nano set-hostname.sh

file set-hostname.sh
#!/bin/sh
hostname cpanel.mydomain.com
/scripts/fixetchosts

For more detail, please free to reference here


text:
Q: $ in the Solr field name I have an index with $ sign in field names in Solr. Reindexing is not an option.
There are functional queries in Solr with $ being variable identifier (See here). When i call a query to retrieve specific fields (fl=$created_dt,name), solr will return an error

Error parsing fieldname: Missing param created_dt while parsing function '$created_dt,$name'

I understand that is because Solr interpret it as a variable. Is there any way to fix it?

A: In general, as you have discovered, it's a good idea to avoid most symbols in field names in Solr. In particular $ is used to allow for separate arguments in the query string for replacement while parsing (such as foo=$qq&qq=bar).
There is however a small hack for the fl-parameter that you can use: if the first field doesn't have a symbol, it should parse OK. If you use fl=name,$created_dt, it will work (although you might have meant to have $name as well, from the error message you included. If that's the case, use another field name without $). &fl=name,$foo_i works under 4.9.0 at least.
You might want to plan a migration to more normalized field names in the future.


text:
Q: Bootstrap div element and nested navbar not taking up 100% page width There seems to be a bit of space between my navbar and the edge of the viewport. The navbar is nested in a div that is container-fluid, and I don't see where any padding or margin would be coming into play.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    Generic
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

            </button>

          Link

          Link

          Link

A: You need to set the padding to 0 for your container-fluid


text:
Q: The class inherits two different generic derivations of the same class What is the proper way of precising the type of an iterable through inheritence.
as inherit FOO[like babar] is not alowed
FOO
class FOO

inherit
    ITERABLE[detachable ANY] -- I know garbage but for DB_RESULT its the case

feature -- Access

    new_cursor: ITERATION_CURSOR[like items.item]
        do
            Result := items.new_cursor
        end

    items: ARRAY[detachable ANY]

end -- class FOO

BAR
class BAR

inherit
    FOO -- I know garbage but for DB_RESULT its the case

    ITERABLE[STRING] -- I know garbage but for DB_RESULT its the case

feature -- Access

    new_cursor: ITERATION_CURSOR[like items.item]
        do
            Result := items.new_cursor
        end

    items: ARRAY[STRING]

end -- class FOO

A: I would suggest using a formal generic parameter in class FOO:
class FOO [G]
inherit
    ITERABLE [G]

Then, class BAR would provide a suitable actual generic parameter:
class BAR
inherit
    FOO [STRING]


text:
Q: CodeIgniter with PHP Access Forbidden (Windows 10) I am working on a PHP project on the localhost using CodeIgniter/XAMPP and have encountered this as soon as I try get into one of my controllers.

I have worked on other computers and have had no problems like this.

A: The issue appears to be with your permissions. You need to change the permssions of the '/var/www' on Apache2 or if you're using Apache change the permission of 'Htdocs'.


text:
Q: select distinct(username) running too slow I have a postgres table like this
id, username
The question is why request like this is running too slow
select count(distinct(username)) as cnt from client

I've tried to create an index like this
CREATE INDEX idx_client_username ON client(username);
Update.
Here are two queries that I tried.
EXPLAIN (ANALYZE) select count(distinct(username)) as cnt from client
"Aggregate  (cost=14430.43..14430.43 rows=1 width=8) (actual time=1813.138..1813.139 rows=1 loops=1)"
"  ->  Seq Scan on client  (cost=0.00..14064.80 rows=731265 width=10) (actual time=0.018..120.601 rows=731282 loops=1)"
"Planning Time: 0.450 ms"

"Execution Time: 1813.169 ms"

EXPLAIN ANALYZE select count(*) as cnt from (select from client group by username) t;
"Aggregate  (cost=14814.21..14814.22 rows=1 width=8) (actual time=461.042..461.043 rows=1 loops=1)"
"  ->  HashAggregate  (cost=14430.43..14607.56 rows=59044 width=10) (actual time=408.084..449.494 rows=195382 loops=1)"
"        Group Key: client.username"
"        ->  Seq Scan on client  (cost=0.00..14064.80 rows=731265 width=10) (actual time=0.023..136.145 rows=731282 loops=1)"
"Planning Time: 0.490 ms"
"Execution Time: 463.872 ms"


text:
Q: How can I increment a field value by 1 using SQL Query in MS Access I'm working on a project using Automation Anywhere Client.
I'm extracting data from MS Excel to MS Access using SELECT and UPDATE statements, but it is possible that the data could repeat itself, and in this case, I would like to UPDATE only 3 fields, those are the statements that I'm using
    INSERT INTO $vDiagnosis$
    VALUES ('$vID$','$vFirstName$','$vLastName$','$vGender$','$vPhone$','$vAge$',
    '$vDateOfVisit$','$vCondition$','$vInsuranceCo$','$vInsuranceNr$','$vVisitingNumber$')

    Update $vDiagnosis$
    SET DateOfVisit = '$vDateOfVisit$', Condition = '$vCondition$'
    WHERE ID = '$vID$'

which are the DateOfVisit and the Condition and the VisitingNumber (which is the number of times someone visited that hospital). The thing is, I'm trying to increment the VisitingNumber every time the UPDATE statement is executed, for example, someone visits today, I want it to be 1, the UPDATE statement is executed again, I want that 1 to increment.
I tried making a variable, and to increment it every time the UPDATE is being executed but whenever it loops and goes to the next INSERT statement, it continues incrementing, even if it inserts a new value.
A preview of the work I'm trying to do on Automation Anywhere
Any help would be appreciated.
Thanks in advance!

A: Not sure about the variable aspect mentioned, but bumping the VisitingNumber count should be able to be done as:
UPDATE $vDiagnosis$
   SET DateOfVisit = '$vDateOfVisit$',
       Condition = '$vCondition$',
       VisitingNumber = VisitingNumber + 1
 WHERE ID = '$vID$'

To the insert, the value for the visitingNumber could simply be 1 without a variable, like so:
INSERT INTO $vDiagnosis$
VALUES ('$vID$','$vFirstName$','$vLastName$','$vGender$','$vPhone$','$vAge$',
'$vDateOfVisit$','$vCondition$','$vInsuranceCo$','$vInsuranceNr$', 1)

Or better, perhaps a default value of 1 could be specified at the table level, and then it would not need to be included with the insert query at all. (it would be set to 1 at insert)
Hope that makes sense.


text:
Q: Python equivalents of the common Perl modules? I need to rewrite some Perl code in python. So I'm looking for the closest modules to what I'm using now in Perl (i.e. with similar functionality and stability):

*

*DBI + DBD::mysql

*LWP::UserAgent

*WWW::Mechanize

*XML::LibXML

*HTML::TreeBuilder

*CGI::FormBuilder

*Template::Toolkit
What are the Python equivalents to these?

A: DBI + DBD::mysql

*

*MySQLdb
LWP::UserAgent

*

*urllib (Python STL)

*urllib2 (Python STL)

WWW::Mechanize

*

*Mechanize
XML::LibXML

*

*libxml2

*lxml
HTML::TreeBuilder

*

*xml.etree.ElementTree (Python STL)

CGI::FormBuilder

*

*cgi and cgitb (Python STL)

Template::Toolkit

*

*Template-Python
Note: Items marked above as Python STL are included as part of the Python Standard Library as listed in the Python v2.6.4 documentation.

A: *

*All Python database modules use the same API, so either MySQLdb or oursql will work.

*urllib2

*mechanize

*etree or lxml

*No direct equivalent, but BeautifulSoup and lxml can parse, and etree and lxml can generate.

*FormEncode

*Genshi, Jinja2, mako, cheetah, and too many others

urllib2 and etree are in the standard library; the rest are easy enough to get.


text:
Q: zipWith for trees in Haskell I am learning Haskell using The Haskell School of Expression: Learning Functional Programming through Multimedia and I am unsure how to go about solving this exercise.

Using the definition of trees given by
data Tree a = Node (Tree a) (Tree a) | Leaf a

Define tree versions of the list functions zip and zipWith. There
  will be cases at the leaves or where trees are of different shapes
  where you'll have to make design decisions. Try to make your decisions
  as elegant as possible.

For zip I have this but I am unsure if it is "elegant"
zipTree :: Tree a -> Tree b -> Tree (a,b)
zipTree (Leaf a)     (Leaf b)     = Leaf (a,b)
zipTree (Node l1 r1) (Node l2 r2) =
  let l = zipTree l1 l2
      r = zipTree r1 r2
  in Node l r

-- Problems...
zipTree (Node _ _)  (Leaf _)   = Node undefined undefined
zipTree (Leaf _)    (Node _ _) = Node undefined undefined

And I am unsure how to adapt it to have zipWith functionality although I do know a elegant definition of zipWith.
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (x:xs) (y:ys) = f x y : zipWith f xs ys
zipWith _ _ _ = []

A: First of all I believe your solution is not elegant because you are using undefined.
You want to avoid partial functions, and structures, as much as possible and simply inserting some Node undefined undefined in a tree structure doesn't sound like a good idea.
Think about this: once you have a Node undefined undefined how would it act with the other operations on the tree? You'd probably get tons of exceptions.
So you have to find an alternative.
zipTree (Node l r) (Leaf a) = Node x y
    where
        x = ... ?
        y = ... ?

Now how should x and y be defined? x should depend on l and Leaf a while y should depend on r and Leaf a.
The easiest way to define this case is to simply perform the recursive calls:
zipTree (Node l r) a@(Leaf _) = Node (zipTree l a) (zipTree r a)

So we are zipping all leafs in the l and r subtrees with the leaf a.
As for the zipWithTree: that's easy. You have to add an f parameter and use f x y instead of (x, y) when you perform the zipping, which is done only in the Leaf v Leaf case:
zipWithTree f (Leaf a) (Leaf b) = Leaf $ f a b

Obviously you have to add the f parameter to all the rules and pass f to recursive calls.

Note that there is also an other way to define zipWith, which is:
zipTree (Node _ _) (Leaf a) = Leaf (undefined, a)

This still isn't a good solution because it introduces an undefined however it has some advantages against the Node undefined undefined solution:

*

*It acts for similarly to zip from lists. zip [1,2] [1,2,3,4] == [(1,1), (2,2)] so you stop when the shorter list ends.

*The undefined is inside the value. This allows for example to have:
mapTree snd (zipTree x y) == y

whenever x has longer branches. Using Node undefined undefined you have mapTree f (zipTree x y) is always an exception whenever the trees aren't isomorphic (because mapTree will try to evaluate undefined).


text:
Q: Specify proper line in listBox using C# Windows Forms Application I'm using C# Windows Forms Application to create a simple application. I've used a listBox to read and display a text file (10 lines). How to specify the First, Last, Previous and Next line in the listBox by pressing a proper button? Any help will be appreciated. Thank you.
[enter image description here][1]

A: I ~think~ you're asking how to change the selected item in the listbox by pressing the buttons?
If so, something like:
OpenFileDialog openFile = new OpenFileDialog();

private void btnLoadFile_Click(object sender, EventArgs e)
{
    if (openFile.ShowDialog() == DialogResult.OK )
    {
        try
        {
            List<String> lines = new List<String>(System.IO.File.ReadAllLines(openFile.FileName));
            lines.RemoveAll(l => l.Trim().Length == 0);
            if (lines.Count > 0)
            {
                listBox1.Items.Clear();
                listBox1.Items.AddRange(lines.ToArray());
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Error Loading File");
        }
    }
}

private void btnFirst_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count > 0)
    {
        listBox1.SelectedIndex = 0;
    }
}

private void btnLast_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count > 0)
    {
        listBox1.SelectedIndex = (listBox1.Items.Count - 1);
    }
}

private void btnPrevious_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count > 0)
    {
        listBox1.SelectedIndex = (listBox1.SelectedIndex > 0) ? (listBox1.SelectedIndex - 1) : 0;
    }
}

private void btnNext_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count > 0)
    {
        listBox1.SelectedIndex = (listBox1.SelectedIndex < (listBox1.Items.Count - 1)) ? (listBox1.SelectedIndex + 1) : (listBox1.Items.Count - 1);
    }
}

Note that if no item is currently selected, then pressing previous or next will select the first item in the listbox.

A:
How to specify the First, Last, Previous and Next line in the listBox by pressing a proper button?

Note: This answer assumes you want only show one line at a time, either it be the first line, next, previous and or last line in the text file.
Let's first go over your current approach. The routine button6_Click is only trying to load a file, read the line and if the line/string is not null then add this string to listBox1; this is doing this for every string in that file. The usage of OpenFileDialog and StreamReader implement IDisposable, you should wrap these in a using block to ensure objects are properly disposed of as well.
Your current approach is more than likely not what you need as you don't want to load everything up at once, only when needed. With this in mind, you would need to keep some sort of collection of these lines from the file; there's more than a few ways, but I will focus on just one way.
First, create a new class as per below:
public class NavigateFile
{
    // Stores the file lines collection
    public IEnumerable<string> CurrentFileLines { get; private set; }

    // Tracks the current line index
    public int CurrentFileLineIndex { get; private set; } = 0;

    // Tracks the next line index
    public int NextFileLineIndex { get; private set; } = 1;

    // Tracks the previous line index
    public int PreviousFileLineIndex { get; private set; } = -1;

    // Tracks the last line index
    public int LastFileLineIndex { get; private set; } = 0;

    // Routine to load the file
    public void LoadFile()
    {
        using (OpenFileDialog ofd = new OpenFileDialog())
            if (ofd.ShowDialog() == DialogResult.OK)
                CurrentFileLines = File.ReadLines(ofd.FileName).Where(line => !string.IsNullOrEmpty(line));

        CurrentFileLineIndex = 0;
        NextFileLineIndex = 1;
        PreviousFileLineIndex = -1;
        LastFileLineIndex = CurrentFileLines.Count();
    }

    // Routine return the first line in the file
    public string GoToFirstLine()
    {
        CurrentFileLineIndex = 0;
        return CurrentFileLines.ToList()[CurrentFileLineIndex];
    }

    // Routine return the next line in the file if we can
    public string GoToNextLine()
    {
        if((CurrentFileLineIndex + 1) <= CurrentFileLines.Count() - 1)
        {
            CurrentFileLineIndex++;
            return CurrentFileLines.ToList()[CurrentFileLineIndex];
        }

        return CurrentFileLines.ToList()[CurrentFileLineIndex];
    }

    // Routine return the previous line in the file if we can
    public string GoToPreviousLine()
    {
        if ((CurrentFileLineIndex - 1) >= 0 && (CurrentFileLineIndex - 1) <= CurrentFileLines.Count())
        {
            CurrentFileLineIndex--;
            return CurrentFileLines.ToList()[CurrentFileLineIndex];
        }

        return CurrentFileLines.ToList()[CurrentFileLineIndex];
    }

    // Routine return the last line in the file
    public string GoToLastLine()
    {
        CurrentFileLineIndex = CurrentFileLines.Count() - 1;
        return CurrentFileLines.Last();
    }

}

Next you could use this simply by calling a few functions to return what you would need. Put below logic in your specific buttons to handle what you would need to.
 // put this in your class where you will be using the new class
 private NavigateFile NavigateFile { get; set; } = new NavigateFile();

 // Load a file
 listBox1.Items.Clear();
 NavigateFile.LoadFile();
 listBox1.Items.Add(NavigateFile.GoToFirstLine());

 // Go to first line
 listBox1.Items.Clear();
 listBox1.Items.Add(NavigateFile.GoToFirstLine());

 // Go to next line
 listBox1.Items.Clear();
 listBox1.Items.Add(NavigateFile.GoToNextLine());

 // Go to previous line
 listBox1.Items.Clear();
 listBox1.Items.Add(NavigateFile.GoToPreviousLine());

 // Go to last line in the file
 listBox1.Items.Clear();
 listBox1.Items.Add(NavigateFile.GoToLastLine());

If you should need to lookup an item, you can build a Linq query against CurrentFileLines in the NavigateFile class and pull what you would need, it may be helpful if needed somewhere.
Note:
I was clearing out the listBox1.Items every time I did something, you don't have to, but I did. Also keep in mind, make sure you have a file loaded before calling any of these functions and or edit them to make sure you have data. If there is something you don't understand, please let me know and I can help.


text:
Q: How to select lines within Tukey's test result? This mays be a dumb question, but I'm kinda of stuck.
I've got a .csv data files organized in Year, Month, Day and Likes helping me analyze my Instragram account (yeah I'm a bit bored but basically I've got like 2020,March,Monday,38).
I wanted to compare the mean of each month with each other in order to see if there was an actual difference or not (independent data) from one month to the other.
According to the ANOVA result, there is a difference (1.93e-07) but when I go with the TukeyHSD test, I end up with a huge list of each combination and I can't seem to select which line I want.
I would like to select lines with a p-value < 0.05 or lines comparing only a specific month.
I couldn't find any help, apparently I can't work on the Tukey's result like a list or a dataframe. I don't really know how to do it =/
If any of you have a solution thanks in advance !


text:
Q: How to create a Rails gem with conditional dependency installation I'm trying to write my first gem, and want to create one that provides functionality to dry-up serialization. I'm using one gem at the moment and don't foresee any issues with it, but I'd like to be able to add support for multiple serialization gems. The only downside I see is that it would require adding them to the dependancy list and installing them into the project that uses the gem I am writing.
Is there a way, using an initializer, to set the preferred gem that a user might want to use and only install that one and not any of the others?
I'm going to write it without this functionality for now, but in the future, I'd like to make it more robust with the support for multiple gems.

I updated with an install generator that creates an initializer with a default gem listed, along with what I thought would work for dynamically adding the dependency. My test passes, and I am able to bundle install locally without any issue and my gem seems to be working as intended, but when I try to push to gemfury I am now getting an error:
remote: Initializing build: done.
remote: ----→ Building package...
remote:        RubyGem build detected
remote:        Invalid gemspec in [/build/app/my_gem.gemspec]: cannot load such file -- blueprinter
remote:        ERROR:  Error loading gemspec. Aborting.

And in my gemspec
spec.add_dependency MyGem.configuration.serializer || 'blueprinter'

Here is the code relevant to the current configuration attempt:
# lib/my_gem

require "my_gem/version"
require 'my_gem/configuration'
require "my_gem/blueprinter"

module MyGem

  class << self
    attr_accessor :configuration
  end

  def self.configuration(&block)
    @configuration ||= Configuration.new
  end

  def self.configure
    yield(configuration)
  end
end

# lib/my_gem/configuration

module MyGem
  class Configuration
    attr_accessor :serializer

    def initialize
      @serializer = nil
    end
  end
end

A: I wasn't able to really figure out the dependency injection for now. So I tried to take what @engineersmky suggested and created an install for the gems. So for right now I have this as my install generator
require 'generators/base_generator'

module MyGem
  module Blueprinter
    class InstallGenerator < BaseGenerator
      source_root File.expand_path("../../../templates", __FILE__)

      # Add blueprinter gem to gemfile after my_gem declaration and bundles the newly declared gem
      def install_blueprinter
        remove_other_supported_gems('ActiveModelSerializers', 'FastJsonapi')
        puts 'Installing Blueprinter...'
        insert_into_file('Gemfile',
                         "\ngem 'blueprinter'",
                         after: "gem 'dry_serialization', source: 'https://gem.fury.io/my_private_gems/'")
        run 'bundle install'
      end

      def helper_include
        copy_api_controller
        gsub_file(API_CONTROLLER_PATH, /^\t*(include MyGem::.*)\n/, '')
        puts 'Adding include statement to ApiController'
        insert_into_file(API_CONTROLLER_PATH,
                         "\n\tinclude MyGem::Blueprinter",
                         after: 'class ApiController < ActionController::API'
        )
      end

    end
  end
end

Gets called with rails g my_gem::blueprinter::install
This creates an ApiController that inherits from ActionController::Base unless one already exists, inserts gem 'blueprinter' into the gemfile after my_gem's declaration, removes references to other serializer gems, then bundles to install the gem.
I like to separate my controllers into api and application to separate the concerns if I decide on a monolith app :D
Then you can use the dryed up methods that I'm creating in each file for each respective gem :D


text:
Q: Get JWT Token Created During User profile creation : Ember js I am using ember-simple-auth and jwt to authenticate a user profile, this is a code for signup and after signing up I wan't to print the token value created(which is in the response) in the console
import Controller from '@ember/controller';

export default Controller.extend({
    actions: {
        signup: function(){
            var credentials = this.getProperties('name','identification','password');
            let list = this.store.createRecord('user', {
                name: credentials.name,
                email: credentials.identification,
                password: credentials.password
            });
            list.save();

        // I want to print the token value in console here

            this.setProperties({
                'name': '',
                'identification': '',
                'password': ''
            });

        }
    }
});

A: @Sreenath, since you said the jwt is stored in a service,
This is how you'd console.log it.

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';

export default Controller.extend({
    nameOfService: service(),

    actions: {
        signup: function(){
            // ...

            // I want to print the token value in console here
            console.log(this.nameOfService.nameofPropertyThatJWTIsOn);

            // ...

        }
    }
});


text:
Q: Canard gem - how should I programatically make an admin user? I'm using the Canard gem (CanCan + RoleModel) for authentication on Ruby on Rails, but I'm having some issues with making an initial user admin. An Account has Users. When an Account is created, there's an Owner User who has billing details. I'd like that Owner to have the :admin role.
class SomewhereElseInSystem
  ...
  account = Account.register(hash) # Company Admin submits form with
                                   # details of account, owning user,
                                   # and a load more objects we don't
                                   # show here.
end

class Account < ActiveRecord::Base
  has_many :users, dependent: :destroy, include: [:profile]
  has_one :owner, class_name: 'User', conditions: { owner: true }
  accepts_nested_attributes_for :owner

  def self.register(details)
    ...
    hash = { name:   details[:client_name],
             domain: details[:subdomain],
             plan:   details[:plan],
             owner_attributes: {
               name:                  details[:owner_name],
               password:              details[:owner_password],
               password_confirmation: details[:owner_password],
               email:                 details[:owner_email] } }
    account = Account.create hash
    ...
  end
end

class User < ActiveRecord::Base
  belongs_to :account
  acts_as_user roles: [:saas_admin, :admin, :manager]

  # owner is a boolean DB field

  before_validation :owners_are_admins

  protected

  def owners_are_admins
    return unless owner
    self.roles << :admin
  end
end

However, I'm finding that when I make an account the associated owner is not an admin, and has no roles set. I've tried several variations on the above and am convinced that I'm missing something basic. Help?
Update:
If I go into the console, I can have great fun seeing 4 non-admins instead of 1 admin and 3 non-admins via the scopes, but a different answer via admin? and the actual fields.
[46] subscriptions »  account.users.count
   (0.5ms)  SELECT COUNT(*) FROM "users" WHERE "users"."account_id" = 1
=> 4
[47] subscriptions »  account.users.admins.count
   (0.4ms)  SELECT COUNT(*) FROM "users" WHERE "users"."account_id" = 1 AND ("users"."roles_mask" & 2 > 0)
[48] subscriptions »  account.users.non_admins.count
[48] subscriptions »  account.users.non_admins.count
   (0.6ms)  SELECT COUNT(*) FROM "users" WHERE "users"."account_id" = 1 AND ("users"."roles_mask" & 2 = 0 or "users"."roles_mask" is null)
=> 4
[49] subscriptions »  account.users.map(&:admin?)
=> [
  [0] false,
  [1] false,
  [2] false,
  [3] true
]
[51] subscriptions »  account.users.select{ |user| user.roles_mask & 2 > 0 }.count 0;34# Same as query above
=> 1

But better yet, if I do
account.users.admins # 0
owner = account.owner
owner.roles << :admin # Should be a no-op
owner.save!
account.user.admins # 1!

Clearly my callback isn't doing the equivalent of the << in the console after all. Which I don't understand.


text:
Q: How do I directly increment a cell value by 1 as part of a, LibraCalc, macro function I am making a spreadsheet to tally votes for a car show.  I used basic years ago but it is not the same as writing a macro so I have been Using the macro record function in LibraCalc (this is included with LibraOffice, an open source program similar to MS Office and Excel.) I am able to select the cell I want to change from a table.  I copy the cell value to another cell, add 1 to the value, then save it back to the table as a value.
I would like a faster more direct method to directly increment the cell value while keeping the result as a value; without all the copy, move, and past steps.
My macro record function works but it is slower than what I want and not very elegant.  There can be several hundred votes to count so saving time is important.  My concern is an inefficient program will be too slow.


text:
Q: Center 3 images in a div Bootrstrap how can I make this 3 images to be in center of the page with Bootstrap?
my code:

A: if you just want the image to be aligned in the center of the page, you just have to add text-center class to the containing div.

check this jsfiddle