text:
Q: Administrator Permissions Check (aiogram) i make a telegram bot for administrate telegram groups, but this filter just check admin status:
import aiogram
import functools
from aiogram.dispatcher.filters import BoundFilter

class CheckFilter(BoundFilter):
    key = 'is_admin'
    def __init__(self, is_admin):
        self.is_admin = is_admin
    async def check(self, message: types.Message):
       member = await bot.get_chat_member(message.chat.id, message.from_user.id)
       return member.is_chat_admin() == self.is_admin
dp.filters_factory.bind(CheckFilter)

i need to check administrator permissions. Example: for use command !ban you need to ban users permission.

A: bot.get_chat_member(chat_id, bot_id) will do the trick.
aiogram documentation says:

Returns: Returns a ChatMember object on success

And what Telegram API documentation says about ChatMember:

...
can_edit_messages Boolean    Optional. Administrators only. True, if the administrator can edit messages of other users and can pin messages; channels only
can_delete_messages Boolean    Optional. Administrators only. True, if the administrator can delete messages of other users
can_restrict_members Boolean    Optional. Administrators only. True, if the administrator can restrict, ban or unban chat members
...

Here is an example:
@dp.message_handler(commands=['rights'])
async def myrights(message: types.Message):
    member = await bot.get_chat_member(message.chat.id, TOKEN.split(":")[0])
    for x in member:
        print(x)

And its output (on my terminal) when I write /rights@BOTUSERNAME on the group:
('user', {'id': xxxxxxxxxx, 'is_bot': True, 'first_name': 'xxxxx', 'username': 'xxxxx'})
('status', 'administrator')
('can_be_edited', False)
('can_change_info', True)
('can_delete_messages', True)
('can_invite_users', True)
('can_restrict_members', True)
('can_pin_messages', True)
('can_promote_members', False)


text:
Q: Trouble installing Clickatell Php Library I'm trying to install the clickatell php library after this instruction:
https://github.com/arcturial/clickatell
But so far i was only able to install composer.
They say: this library uses composer and can be acquired using the following in your composer.json file.
{
    "require": {
        "arcturial/clickatell": "*"
    }
}

So I have to add this to the composer json file? Then require the json file in my php script? I've no idea what to do next. Any help would be great.

A: When you are in your project root, run the following:
create a composer.json file with the following contents:
{
    "name": "your/project",
    "description": "project description",
    "require": {
        "arcturial/clickatell": "*"
    }
}

php -r "readfile('https://getcomposer.org/installer');" | php
This will download a file called composer.phar
php composer.phar install
This will install the dependencies you specified in your composer.json file. Once complete, your project will now have a folder called "vendor".
Include the "vendor/autoload.php" file in your script
require_once __DIR__ . '/vendor/autoload.php';

...
Now you should be able to use the library as specified in the documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select menu item link returns undefined The action that I want is to change the video to their respective item when keyboard "enter" but it returns me an error "UNDEFINED" has something to do with the plugin I'm using to select items.
Another aspect is that the video alone it should not be loaded page (ajax).
javascript:
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Frss.cnn.com%2Fservices%2Fpodcasting%2Fac360%2Frss.xml'%20AND%20itemPath%3D%22%2F%2Fchannel%22&format=json&diagnostics=true&callback=?", function (data) {

    // Load Titles patch Json
    console.log(data.query.results.channel.item);
    var titles = data.query.results.channel.item.map(function (item) {
        return item.title;

    });
    var urls = data.query.results.channel.item.map(function (item) {
        return item.origLink;

    });
    console.log(titles);
    $(".container-list-podcast ul").append('
' + titles.join('

'));
    $(".container-list-podcast ul li").each(function (key, value) {
        var text = $(this).text();
        $(this).html('' + text + '');
    });
    $(".container-list-podcast ul li a").click(function () {
        var href = $(this).attr('href');
        alert(href);
        $("#myvideo").attr("src", href).get(0).play();
        return false;
    })
    // Load Navigation Only Key
    a = $('.nav_holder li').keynav(function () {
        return window.keyNavigationDisabled;
    });
});

jsfiddle

A: Since you are using cross domain request you should make sure that the server you connect to support requests like this.
But you also need to tell jQuery to support this request by doing the following:
 $.support.cors = true;

full answer can be seen in jQuery site


text:
Q: The reason of 0 backtest data in my pinescript code First of all, sorry for the bad English.
I'm making some strategy using S/R line and RSI.
However, after finishing the work, I realized that there is 0 backtest trade in my work.
I'm not sure about the reason, but maybe there are some errors in my script. So I'm asking your help.
Would  you check any error codes in my script? I'll post the part of mine.
//strategy//

if (not na(vrsi))
    if(co and resistancebroken)
        strategy.entry(id="buy", long=true, comment="Long")

if(strategy.position_size>0)
    if(longstoploss_level)
        strategy.close(id="buy", comment="StopLoss")
    if(supportbroken and close>strategy.position_avg_price)
        strategy.close(id="buy", comment="Long End")

if (not na(vrsi))
    if(cu and supportbroken)
        strategy.entry(id="short", long=false, comment="Short")

if(strategy.position_size<0)
    if(shortstoploss_level)
        strategy.close(id="short", comment="StopLoss")
    if(resistancebroken and close<strategy.position_avg_price)
        strategy.close(id="short", comment="Short End")

A: It's hard to say without full code. First of all, you need to change excessive multiple if blocks to single ones.
if (not na(vrsi))
    if(co and resistancebroken)
        strategy.entry(id="buy", long=true, comment="Long")

Needs to be changed to:
LongCondition = not na(vrsi) and co and resistancebroken
if LongCondition
    strategy.entry(id="buy", long=true, comment="Long")

After than you can
plot(LongCondition? 1 : 0)

to see whether your condition is is true. (probably you will be getting 0, so you have to review your enter conditions by plotting
plot(not na(vrsi) ? 1 : 0)
plot(co ? 1 : 0)
plot(resistancebroken ? 1 : 0)

and then decide which one is broken.
Same apply for your short and close conditions.


text:
Q: Rails Application Not Loading All javascript files production I am working on a personal website Hosted in AWS. Using Ruby 1.9.3 Rails 4.1.0beta1. When I run the code locally, it works like a charm. However when I push to AWS, its missing either some JS files or some CSS files. I think it is missing JS files because if I remove the following from application.js
//= require_tree .

I can reproduce the issue locally.
Here is my Gem file:
source 'https://rubygems.org'
ruby '1.9.3'
#ruby-gemset=danielhamiltondotcom_rails_4_0

gem 'rails', '4.1.0.beta1'

group :development, :test do
  gem 'rspec-rails', '2.13.1'
end

group :test do
  gem 'selenium-webdriver', '2.35.1'
  gem 'capybara', '2.1.0'
end

gem 'sass-rails', '4.0.1'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.1'
gem 'jquery-rails', '3.0.4'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'

group :doc do
  gem 'sdoc', '0.3.20', require: false
end

group :production do
  gem 'rails_12factor', '0.0.2'
end

Here is my production.rb file:
Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both thread web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable Rails's static asset server (Apache or nginx will already do this).
  config.serve_static_assets = true

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Generate digests for assets URLs.
  config.assets.digest = true

  # Version of your assets, change this if you want to expire all your assets.
  config.assets.version = '1.0'

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Set to :debug to see everything in the log.
  config.log_level = :info

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = "http://assets.example.com"

  # Precompile additional assets.
  # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
  #config.assets.precompile += %w( search.js )

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Disable automatic flushing of the log to improve performance.
  # config.autoflush_log = false

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new
  config.assets.paths << Rails.root.join('app','assets','font')
  config.assets.precompile += %w(.svg .eot .woff .ttf)
  config.assets.precompile =  ['*.js', '*.css', '*.css.erb']
end

Here is a snippet of the html.erb page.
<%= stylesheet_link_tag    "application", media: "all",
    "data-turbolinks-track" => false %>
<%= javascript_include_tag "application", "data-turbolinks-track" => false %>

I can't quite figure out which files are missing. Please let me know if you need more information. I have been looking around all over and haven't been able to resolve this issue.
I have tried this: Rails 4: assets not loading in production.

A: I was able to resolve this issue:
1) I had an extra ) in my css file. I removed that to address the compile error that AWS was giving.
2) In my Application.js file I manually required all JS files needed instead of just using the tree:
//= require jquery
//= require modernizr
//= require bootstrap
//= require jquery.fitvids
//= require jquery.easing.1.3
//= require twitter
//= require jquery.fancybox.pack
//= require jquery.fancybox-thumbs
//= require jquery.fancybox-media
//= require stellar
//= require nicescroll.min
//= require jquery.isotope.min
//= require custom
//= require custom-home
//= require portfolio
//= require jquery.flexslider
//= require retina

3) I added gem 'sprockets', '2.8' to my GemFile which i had previously omitted.

A: Try
RAILS_ENV=production bundle exec rake assets:precompile

Also check your prod server and make sure the asset files are there under public.


text:
Q: Does VS 2019 Designer have trouble with TabPage, UserControl, and TreeView? I'm encountering three issues with Visual Studio 2019 (16.6.3) Designer for .NET Core 3.1. Are these Designer problems or set-up errors on my part?

*

*TabPage - Controls I drop on a TabPage can't be selected or modified in the Designer. I can select them in the Properties panel and change things, but no mouse action in the TabPage works. (Exception: If a Panel is the only control on the TabPage, I can select it in Properties and then use the mouse to drag it out of the TabPage.)

*UserControl - Designer won't even let me begin to create a user control. When I choose Add --> User Control in the project, I get nothing.

*TreeView - I can put several root TreeNodes in the Designer and they work fine. If I add a child TreeNode to a root node, that root node vanishes (even from designer.cs file) when the project builds. (I have only tried this with checkboxes on the nodes, though I doubt that makes a difference.)

This is my first venture into a .NET Core app. Am I missing something?


text:
Q: I am not able to fetch the list value in Servlet using JsonArray I am using the JSON array to get the values from Db in Servlet. I am suing following code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    List<ProjectDto> act=new ArrayList<ProjectDto>();
    act=ActivitiesDao.getActivitiesDetails();
    JSONArray jsonarray= new JSONArray();

    for(int i=0;i<act.size();i++)
    {
        JSONObject obj = new JSONObject();
        //obj.put("issueno", quiz.get(i).getIssueno());
        obj.put("projectName",act.get(i).getProjectName());
        obj.put("projectDescription",act.get(i).getProjectDescription());
        obj.put("currentStatus", act.get(i).getCurrentStatus());
        obj.put("area", act.get(i).getArea());
        jsonarray.put(obj);
    }
    System.out.println("Json in Servelt"+ jsonarray.toString());
    response.getWriter().print(jsonarray.toString());
    }

}
I am able to get value from DB successfully. I have printed value in console.
Now, I have defined one method in some other java file to convert the data in paragraphs. Now, I am calling that method in Servlet in following way:
//method:
    public static List<String> convertParagraphs(String text){

    List <String> convertedList= new ArrayList<String>();

    if(text==null|| text==""){

    }
    else{
    String[] paragraphs= text.split("\\|");

    convertedList= Arrays.asList(paragraphs);
    }
    return convertedList;

}

calling this method in Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    List<ProjectDto> act=new ArrayList<ProjectDto>();
    act=ActivitiesDao.getActivitiesDetails();
    JSONArray jsonarray= new JSONArray();

    for(int i=0;i<act.size();i++)
    {
        JSONObject obj = new JSONObject();
        obj.put("projectName",act.get(i).getProjectName());
        String ttextt= act.get(i).getProjectDescription();
        obj.put("ProjectDescriptionList" , act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt)));
        obj.put("currentStatus", act.get(i).getCurrentStatus());
        obj.put("area", act.get(i).getArea());
        obj.put("ProjectDescriptionList" , act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt)));
        jsonarray.put(obj);

    }
    System.out.println("Json in Servelt"+ jsonarray.toString());

    response.getWriter().print(jsonarray.toString());
    }

}
Getters and Setters method:
public class ProjectDto {

private String projectName;
private String projectDescription;
private String currentStatus;
private String area;
private List<String> projectDescriptionList= new ArrayList<String>();

private List<String> currentStatusList=new ArrayList<String>();

public List<String> getCurrentStatusList() {
    return currentStatusList;
}
public void setCurrentStatusList(List<String> currentStatusList) {
    this.currentStatusList = currentStatusList;
}

public List<String> getProjectDescriptionList() {
    return projectDescriptionList;
}
public boolean setProjectDescriptionList(List<String> projectDescriptionList) {
    this.projectDescriptionList = projectDescriptionList;
    return false;
}
public String getCurrentStatus() {
    return currentStatus;
}
public void setCurrentStatus(String currentStatus) {
    this.currentStatus = currentStatus;
}
public String getArea() {
    return area;
}
public void setArea(String area) {
    this.area = area;
}

public String getProjectName() {
    return projectName;
}
public void setProjectName(String projectName) {
    this.projectName = projectName;
}
public String getProjectDescription() {
    return projectDescription;
}
public void setProjectDescription(String projectDescription) {
    this.projectDescription = projectDescription;
}
@Override
public String toString() {
    return "ProjectDto [projectName=" + projectName
            + ", projectDescription=" + projectDescription
            + ", currentStatus=" + currentStatus + ", area=" + area
            + ",  projectDescriptionList="
            + projectDescriptionList + "]";
}

}
Issue: Now, I am printing the value of ProjectDescription List, it is returning the false value. I am not sure where i am doing wrong. I tried to resolve the issues in many ways but not able to resolve the issue. could you please correct me and suggest me about my issue.
Please find my ajax code in jsp

A: Of course you will get the value as false.
in your setter you are returning a boolean, which does set the value of projectDescriptionList but finally returns the hard code false every time.
Solution,
In your getter-setter;
// optional, just stick to setter rules, set the value and don't return anything.

public setProjectDescriptionList(List<String> projectDescriptionList) {
    this.projectDescriptionList = projectDescriptionList;
}

In your doPost inside the for loop, third part of code in question
act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt));
obj.put("ProjectDescriptionList" ,act.get(i).getProjectDescriptionList() );
obj.put("currentStatus", act.get(i).getCurrentStatus());
obj.put("area", act.get(i).getArea());
// I don't know why you wrote it twice.. I'm commenting it.
//   obj.put("ProjectDescriptionList" , act.get(i).setProjectDescriptionList(NewsletterUtil.convertParagraphs(ttextt)));
jsonarray.put(obj);


text:
Q: What's the best way to actively sync two folders across two network locations? I have two Windows 2003 servers on two network locations, and the folders are supposed to have the same content at any given time. Basically, whenever a file is written to one of the folders it needs to be written to the corresponding folder on the other machine. What's the best way to achieve this?

A: You want to use DFS Replication for this.
The link provided is for 2012, but DFS-R was first introduced in 2003. It will meet your needs without all of the bells and whistles of the newer versions.

A: SyncToy
You can script it, so you could make scheduled job out of it, running once every minute or so.


text:
Q: How to create a sample django project? This doesn't work for me.
$ python django-admin.py startproject myproject

I am running a ubuntu virtual m/c on my windows system.
By default ubuntu 12.04 comes with python 2.7.3 so I am using that only
I downloaded or installed (whatever it does since I am new to django) by issuing the following command-
git clone https://github.com/django/django.git
django directory is successfully created.

I want to create a sample django application. So for this I am issuing the following command-
$ python django-admin.py startproject tango_with_django_project

Obviously, it will throw error since the default ubuntu python doesn't know that django has been installed.
My Question is how to integrate python with this Django and create a sample django application?

A: The comments above pointing you to the documentation are of course correct, but there are also other resources that can help you start your site the 'right' way. In particular, cookiecutter and its related Django template will get you set up with some really good defaults and valuable third-party apps straight away. If you have cash to spend I'd also heartily recommend the book Two Scoops of Django, by the people who wrote the two applications to which I've linked.
Jeff Knupp has also written a thoroughly useful blog post on starting a Django project the right way, which covers useful topics such as the importance of:

*

*source control;

*automated testing (see also this excellent book);

*isolating your development environment to smooth deployment; and

*managing your database with migrations (included in Django since version 1.7).


text:
Q: PHP TO LARAVEL WHAT IS THE EQUIVALENT OF fetchAll(PDO::FETCH_OBJ) to laravel I'm trying to write this code in laravel controller.
$messages = $db->query("
SELECT name, message
FROM messages
ORDER BY created ASC
LIMIT 100
");

header('Content-Type: application/json');

echo json_encode(
    $messages->fetchAll(PDO::FETCH_OBJ)
);

but I can't write the ->fetchAll(PDO::FETCH_OBJ)

A: If you are using Laravel, you might want to be using Eloquent to achieve this, however if you don't want to do that I'm going to assume you'll be using the Illuminate query builder.
Your query can be replicated as follows:
$messages = DB::table('messages')
                ->select('name', 'messages')
                ->orderBy('created', 'asc')
                ->take(100)
                ->get();

which you can then json_encode as you are.

A: if you create a Message model class, you can simply call:
$messages = Message::latest('created', 'asc')->paginate(100, ['name', 'message']);

return response()->json($messages);


text:
Q: Error activating IAuditRepository No matching bindings are available, and the type is not self-bindable WCF services.  My 1st attempt at IoC with WCF.  Calling service from Console app to test.  Funny thing is I thought these services were working so I was using them to provide data to test a POC I was working on...little did I know I'd first end up fixing the services!
(Debugging using Cassini)
Versions I'm using:

*

*FluentNHibernate 1.1.0.685

*NHibernate 2.1.2.4000

*Ninject 2.2.0.0

*Ninject.Extensions.Wcf 2.2.0.0

*.NET Framework 3.5

This is one of the examples I used as a reference: Pieter De Rycke's Blog
Almost every post I found on SO deals with MVC...I assume my issue is slightly different since this is WCF not MVC.
The Exception:
Error activating IAuditRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
    2) Injection of dependency IAuditRepository into parameter auditRepository of constructor of type ShotService
    1) Request for ShotService

Suggestions:
    1) Ensure that you have defined a binding for IAuditRepository.
    2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
    3) Ensure you have not accidentally created more than one kernel.
    4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
    5) If you are using automatic module loading, ensure the search path and filters are correct.

Console app failing code: (fails on last line)
ShotServiceClient shotSvc = new ShotServiceClient();
LookupShotAdministeredRequest request = new LookupShotAdministeredRequest();
request.ClientId = "128";
request.ClinicId = "289";
request.RequestingUserId = "1";
List<ShotsAdministeredContract> shots = shotSvc.LookupShotAdministered(request).ShotsAdministered;

The Code:
Global.asax.cs
public class Global : NinjectWcfApplication
{
    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[]
        {
            new NHibernateModule(),
            new ServiceModule(),
            new RepositoryModule()
        };
        return new StandardKernel(modules);
    }
}

NHibernateSessionFactoryProvider.cs
public class NhibernateSessionFactoryProvider : Provider<ISessionFactory>
{
    protected override ISessionFactory CreateInstance(IContext context)
    {
        var sessionFactory = new NhibernateSessionFactory();
        return sessionFactory.GetSessionFactory();
    }
}

NHibernateSessionFactory.cs
public class NhibernateSessionFactory
{
    public ISessionFactory GetSessionFactory()
    {
        ISessionFactory fluentConfiguration = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008
            .ConnectionString(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString)
            .Cache(c => c
            .UseQueryCache()
            .ProviderClass<HashtableCacheProvider>())
            .ShowSql())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<AppointmentMap>()
            .Conventions.AddFromAssemblyOf<PrimaryKeyConvention>())
            .BuildSessionFactory();
        return fluentConfiguration;
    }
}

NHibernateModule.cs
public class NHibernateModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISessionFactory>().ToProvider<NhibernateSessionFactoryProvider>().InSingletonScope();
        Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
    }
}

RepositoryModule.cs
public class RepositoryModule : NinjectModule
{
    public override void Load()
    {
        Bind<IAuditRepository>().To<AuditRepository>();
        .
        .
        .
        Bind<IShotAdministeredRepository>().To<ShotAdministeredRepository>();
    }
}

ServiceModule.cs
public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        Bind<IAuditService>().To<AuditService>();
        .
        .
        .
        Bind<IShotService>().To<ShotService>();
    }
}

NinjectInstanceProvider.cs
public class NinjectInstanceProvider : IInstanceProvider
{
    private Type serviceType;
    private IKernel kernel;

    public NinjectInstanceProvider(IKernel kernel, Type serviceType)
    {
        this.kernel = kernel;
        this.serviceType = serviceType;
    }

    public object GetInstance(InstanceContext instanceContext)
    {
        return this.GetInstance(instanceContext, null);
    }

    public object GetInstance(InstanceContext instanceContext, Message message)
    {
        //Create the instance with your IoC container of choice...here we're using Ninject
        return kernel.Get(this.serviceType);
    }

    public void ReleaseInstance(InstanceContext instanceContext, object instance)
    {
    }
}

NinjectBehaviorAttribute.cs
public class NinjectBehaviorAttribute : Attribute, IServiceBehavior
{
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        Type serviceType = serviceDescription.ServiceType;
        IInstanceProvider instanceProvider = new NinjectInstanceProvider(new StandardKernel(), serviceType);

        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            foreach (EndpointDispatcher endpointDispatcher in dispatcher.Endpoints)
            {
                DispatchRuntime dispatchRuntime = endpointDispatcher.DispatchRuntime;
                dispatchRuntime.InstanceProvider = instanceProvider;
            }
        }
    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }
}

IAuditRepository.cs
public interface IAuditRepository : IRepository<Audit>
{
}

AuditRepository.cs
public class AuditRepository : Repository<Audit>, IAuditRepository
{
    public AuditRepository(ISession session) : base(session) { }
}

ShotRepository.cs
public class ShotRepository : Repository<Shot>, IShotRepository
{
    public ShotRepository(ISession session) : base(session) { }
}

ShotService.svc.cs
[NinjectBehaviorAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class ShotService : IShotService
{
    #region Members
    private IAuditRepository _auditRepository;
    private IClientRepository _clientRepository;
    private IClinicRepository _clinicRepository;
    private IShotRepository _repository;
    private IShotAdministeredRepository _administeredRepository;
    private IShotCostRepository _costRepository;
    private IUserRepository _userRepository;
    #endregion

    #region Constructors
    public ShotService(IAuditRepository auditRepository, IClientRepository clientRepository, IClinicRepository clinicRepository, IShotRepository repository, IShotAdministeredRepository administeredRepository, IShotCostRepository costRepository, IUserRepository userRepository)
    {
        _auditRepository = auditRepository;
        _clientRepository = clientRepository;
        _clinicRepository = clinicRepository;
        _repository = repository;
        _administeredRepository = administeredRepository;
        _costRepository = costRepository;
        _userRepository = userRepository;
    }
    #endregion

    #region IShotService Members
    .
    .
    .
    public ListAdministeredShotsResponse LookupShotAdministered(LookupShotAdministeredRequest request)
    {
        ListAdministeredShotsResponse response = new ListAdministeredShotsResponse();
        try
        {
            UserService userService = new UserService(_userRepository, _auditRepository);
            User requestingUser = userService.Read(Convert.ToInt32(request.RequestingUserId));
            if (userService.HasPermission(requestingUser, Permissions.ScheduleAppointments))
            {
                ShotAdministeredService service = new ShotAdministeredService(_administeredRepository, _auditRepository);
                //Guts of method go here...irrelevant to current issue
            }
            else
            {
                throw new InvalidPermissionException("Requesting user does not have sufficient permissions to complete the request.");
            }
        }
        catch (Exception ex)
        {
            response.FailureReason = ex.Message;
        }
        return response;
    }
    .
    .
    .
    #endregion
}

I put a break point in CreateKernel(), it has not been hit.  I also put a break point in Load() in NHibernateModule.cs, that break point has also not been hit.  <-- Correction...Cassini was "not responding" so I guess I wasn't really debugging ALL of my code.  I just did an End Task on Cassini and re-ran the debugger on my services...My break point in CreateKernel() was hit as well as my break point in Load().  My main issue still exists, but at least I know this code is being executed.

A: You are using Ninject.Extensions.Wcf and you do an own integration into Wcf at the same time. There are two kernel instances involved one of which is configured and the other one not. You should decide which integration to use and configure that kernel properly.


text:
Q: Using Unicode characters with JavaFX I've been playing around with swing for some time and decided to check out FX now. So far I'm finding it a lot easier and more fun to work with as compared to swing but I've run into a small speed bump and after hours of looking around I just can't find a solution.
I am unable to use \u when I try to add it through the fxml file It works fine if I don't use the fxml but I want to use the scene builder as it is more convenient.
Here's the small piece of code:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.131" fx:controller="baitform.designDocController">
    <children>
        <Button fx:id="button" layoutX="126" layoutY="90" onAction="#handleButtonAction" text="Click Me!" />
        <Label layoutX="145.0" layoutY="129.0" text="\u0644\u0627\u062B\u0627\u0646\u0649" />
    </children>
</AnchorPane>

The error I keep getting is

Caused by: javafx.fxml.LoadException: Invalid escape sequence.

Not sure if relevant, but I'm using jdk1.8.0_131 & netbeans 8.2
If anyone could point me in the right direction here I'd really appreciate it.

A: FXML is an XML, and so you need to use XML escaping:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.131" fx:controller="baitform.designDocController">
    <children>
        <Button fx:id="button" layoutX="126" layoutY="90" onAction="#handleButtonAction" text="Click Me!" />
        <Label layoutX="145.0" layoutY="129.0" text="لاثانى" />
    </children>
</AnchorPane>

That being said, if you are able to input the characters, you can just insert them as is.
See also: https://www.w3.org/International/questions/qa-escapes


text:
Q: Python text-based random questions quiz This is a text-based quiz example, where the program is supposed to give 5 questions for the user to answer in a random order. The problem is that it works perfectly, but only gives 3 random questions, then stops.
import random

question1=["The answer is A","A","a"]
question2=["The answer is B","B","b"]
question3=["The answer is A","A","a"]
question4=["The answer is F","F","f"]
question5=["The answer is A","A","a"]

questions=[question1,question2,question3,question4,question5]

used_questions=[]

while len(used_questions)!=len(questions):

    random_question=random.choice(questions)

    while random_question in used_questions:
        random_question=random.choice(questions)

    used_questions.append(random_question)

    print([random_question[0]])

    players_answer=input("")

    if players_answer in random_question:
        print("\nCorrect!")
    else:
       print("\nWrong!")

A: Questions 1, 3, and 5 are identical, so you only have three unique questions, so only three questions are displayed. random_question in used_questions evaluates to True as long as one element of used_questions is equal to  random_question; they do not have to refer to the exact same list in memory.
As mentioned in the comments and other answers, shuffling the list is an easier approach here.
import random

questions=[
    ["The answer is A","A","a"],
    ["The answer is B","B","b"],
    ["The answer is A","A","a"],
    ["The answer is F","F","f"],
    ["The answer is A","A","a"]
]

random.shuffle(questions)
for question in questions:
    print(question[0])
    players_answer=input("")
    if players_answer in question:
        print("\nCorrect!")
    else:
       print("\nWrong!")

Result:
The answer is F
F

Correct!
The answer is A
B

Wrong!
The answer is A
Q

Wrong!
The answer is B
B

Correct!
The answer is A
A

Correct!

A: A much simpler approach is to use shuffle:
random.shuffle(questions)

This shuffles your questions in place. You can then just loop round the questions.


text:
Q: How to swap text back and forth when clicking on it? What I need is to swap back and forth the text ____ (a gap) to Word by clicking it. I don't want to have a button. The user should only need to click at the position of the gap.
I see this page describes exactly what I need, especially the CSS-Only Way, but when I try it on the TryIt Editor, either it or the jQuery-Way doesn't work.
Here is the CSS Way:
</style>
#example {
 position: relative;
}
#example-checkbox {
 display: none;
}
#example-checkbox:checked + #example:after {
 content: "Hide";
 position: absolute;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background: white;
 }
</style>

<input id="example-checkbox" type="checkbox">
Show

A: Is this what you expect?
<input id="example-checkbox" type="checkbox">
Show

Note the for attribute in label- it must have the id of the input checkbox

#example {
  position: relative;
  cursor: pointer;
}
#example-checkbox {
  display: none;
}
#example-checkbox:checked + #example:after {
  content: "Hide";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
}
<input id="example-checkbox" type="checkbox">
Show

A: The Label's for attribute must contain the id of the checkbox

#example {
  position: relative;
}
#example-checkbox {
  display: none;
}
#example-checkbox:checked + #example:after {
  content: "Hide";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
}
<input id="example-checkbox" type="checkbox">
Show

A: This is the code that will meet your requirement.

<!DOCTYPE html>

  This is a paragraph. Click on the next word -> ____ <- Have you clicked on previous word.

Having multiple hidden words
In the code below, just take a look at script in  section of the code.

Here, you just have to push the words that you want to toggle with _____ in the array words. Once the words are pushed in this array, they will automatically convert, back and forth to underscores. Just push any different word in this array from the paragraph and see the transitions yourself.

span {
  color: red
}
<!DOCTYPE html>

A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself.

Making ________ appears first when page loads
Just replace
return html.replace(replacestr, '  ' + value + ' ')

with
return html.replace(replacestr, ' ____________')

The final code will be:

span {
  color: red
}
<!DOCTYPE html>

A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself.

For both plurals and singulars
Just change the line:
var replacestr = new RegExp(value, "g");

to:
var replacestr = new RegExp('\\b'+value+'\\b', "g");

The final code would then look like:

span {
  color: red
}
<!DOCTYPE html>

A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array.

A: _____

Reference:
https://jsfiddle.net/n1rb2y57/
But see to that you choose proper background color in css matching with the website color.


text:
Q: Running Multiple Instances of Same Code/Process in SSIS We are fetching data from a web service which takes in mailbox id as input and provides policy id as output, using C# code in SSIS.
The process is as follows:
There is a SQL table containing mailbox id's. The number of mailbox ids for a given execution at a given time may vary (not a constant).
We will provide mailbox id to the web service using C# code in Script task and policy id will be returned. This policy id will be then be inserted into sql table using SQL task.
We want to run this package(which runs the above process) for multiple mailbox id's at the same time.
Any help on designing the package to execute the process in multiple instances would be appreciated.


text:
Q: git rebase -i -- why is it changing commit hashes? So I'm more or less familiar with how rebasing works, but up until recently I usually just did a git rebase -i HEAD~20, and modified whatever needed to be modified.
I was surprised to learn that this will modify the hashes of all 20 commits, even if the only action I take is to squash the last two.
I'm not sure what causes the hash change for the other 18 commits though, since neither their parents, neither their contents change... Or does it? Maybe a timestamp?
Also is there a way to prevent that?

A: You may feel that you didn't change some commits, but you actually changed them in several ways:

*

*Each commit contains the sha1 of its parents. So, changing the sha1 of a parent modifies the commit, hence its sha1. The hashes are chained, changing anything in the past changes the future. Technically, this is called a Merkle tree. This is an important property of Git, because given a sha1 it guarantees not only the integrity of the current commit but also of the whole history leading to it (assuming you can't find a collision in sha1, which is no longer really the case today, but collisions are still very hard to find).

*Each commit contains a snapshot of the current state of your project. Hence, even if a commit seems identical because it introduces the same diff, it may not correspond to the same state of the project (to the same tree object).

*As already noted, commits contain timestamps (one timestamp for the author, one for the commiter, the second one being changed when you rebase).

A:
this will modify the hashes of all 20 commits, even if the only action I take is to squash the last two.

If by "the last two" you mean the most recent two commits in the history, then no, it won't.
Please be concrete, show the actual evidence you're looking at, the todo list you got and the one you executed.  Characterizations are far too unreliablevulnerable to unshared context.
Here for instance is what happens when I squash the last two commits, as I understand it:
$ git log --oneline --reverse @{u}..
00f53a2 echo >master6
afcef3e echo >master7
1f55c48 echo >master8
c3197a0 echo >master9
d30bb35 (HEAD -> master) echo >master10
$ GIT_SEQUENCE_EDITOR='sed -i 5s/pick/squash/' git rebase -i
[detached HEAD 16dc80d] echo >master9
 Date: Mon Feb 5 09:25:55 2018 -0800
 2 files changed, 2 insertions(+)
 create mode 100644 master10
 create mode 100644 master9
Successfully rebased and updated refs/heads/master.
$ git log --oneline --reverse @{u}..
00f53a2 echo >master6
afcef3e echo >master7
1f55c48 echo >master8
16dc80d (HEAD -> master) echo >master9
$

you can see that the last two commits have been squashed together, the id's of all the commits whose history hasn't changed are left untouched.

A: From the rebase doc:

The commits that were previously saved into the temporary area are
  then reapplied to the current branch, one by one, in order.

When the commits are "reapplied" it's really creating a brand new commit...it's content may be the same, but it will have a different timestamp which is part of how it's SHA is generated...thus the new commits will have a new SHA's.
You can read more about how SHA's are calculated here.

A: Note that before Git 2.29 (Q4 2020), Git could also change the hash of the commit onto which you are rebasing in the todo message, commit which should not change (since you are replaying old commits onto this one).
See commit 5da69c0 (13 Aug 2020) by Antti Keränen (Detegr).
(Merged by Junio C Hamano -- gitster -- in commit 4499a42, 19 Aug 2020)

rebase -i: fix possibly wrong onto hash in todo
Found-by: Jussi Keränen
Signed-off-by: Antti Keränen
Acked-by: Alban Gruin

'todo_list_write_to_file' may overwrite the static buffer, originating from 'find_unique_abbrev', that was used to store the short commit hash 'c' for "# Rebase a..b onto c" message in the todo editor.
This is because the buffer that is returned from 'find_unique_abbrev' is valid until 4 more calls to find_unique_abbrev are made.
As 'todo_list_write_to_file' calls 'find_unique_abbrev' for each rebased commit, the hash for 'c' is overwritten if there are 4 or more commits in the rebase.
This behavior has been broken since its introduction.
Fix by storing the short onto commit hash in a different buffer that remains valid, before calling 'todo_list_write_to_file'.

A: this is because when you rebase the node in HEAD that's 20 commits prior to the current one interactively, you are starting at the node in HEAD 20 commits ago and reapplying the subsequent 20 commits as if they're new, with the option to make changes. Even if you only change (squash) commit -20 and -19, you are still reapplying the subsequent 18 commits as if they're new commits. You are not re-using the same node for those 18 commits, you are copying their contents but appending new ones to your rebased HEAD.
From the git book on rebasing:

Remember again that this is a rebasing command – every commit included
  in the range HEAD~3..HEAD will be rewritten, whether you change the
  message or not.


text:
Q: Setting and Getting Methods with wait() and notifyAll() I don't know why my get method doesn't work. It returns " ".
I have Producer and Consumer classes that use this class and Buffer interface that just have set and get methods. Producer reads from file and Consumer writes into another file. Both Producer and Consumer uses thread.
Please help me. Thanks in advance.
import java.util.Stack;

public class synchronizedFile implements Buffer {

public Stack<String> StackBuffer = new Stack<String>();

public void set(String value) {

    synchronized (StackBuffer) {
        if (StackBuffer.size() <= 15) {
            StackBuffer.push(value);
            System.out.println(StackBuffer.toString());
            StackBuffer.notifyAll();
            System.out.println("Consumer notify");
        } else {
            try {

                System.out.println("Produser is waitting--------------------------------");
                StackBuffer.wait();
                System.out.println("Consumer tries to write");
                set(value);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

public String get() throws InterruptedException {

    String Flag = " ";
    synchronized (StackBuffer) {
        if (!StackBuffer.isEmpty()) {

            Flag = StackBuffer.firstElement();
            StackBuffer.remove(StackBuffer.firstElement());
            StackBuffer.notifyAll();
            System.out.println("Producer notify");
            return Flag;
        } else {
            StackBuffer.wait();
            System.out.println("Consumer is waitting --------------------");
            get();

        }

    }

    return Flag;

}

}

A: You are at least missing a Flag = get() in your else branch of the get() method.
Apart from that consider using a BlockingQueue, there are implementations in java.util.concurrent that do the heavy lifting in concurrent programming for you. Using the low level constructs wait and notify is error prone. Without checking it thoroughly, I would be surprised if your implementation would be correct.

A: You wait and notify for two different status: full and empty. Therefore, you must use two separate lock objects. This has been covered a short while ago here.
Basically, if you are not implementing this for the sake of using the Stack class or some kind of assignment, use a BlockingQueue from java.util.concurrent.

A: Here you call get() recursively but throw away its result:
StackBuffer.wait();
System.out.println("Consumer is waitting --------------------");
get();

Something like Flag = get(); or return get();would be more appropriate.
(Also I'm not sure if entering synchronized section twice with doing wait is valid. Maybe it is, I'm just unsure).


text:
Q: My strdup in ASM Hello every body for my school i have to do my own strdup function in ASM [intel] [NASM].
I have e strange problem ...
In my code if I call _malloc
My code segfault with this error :
Program received signal SIGSEGV, Segmentation fault.
0x00007fff849612da in stack_not_16_byte_aligned_error () from /usr/lib/system/libdyld.dylib

I don't understand why because In the section .text I said extern _malloc
Some one have an idee why I got this mistake ? :)
This is my code :
section .text
     global _ft_strdup
     extern _strlen
     extern _malloc
     ;  extern _ft_memcpy

_ft_strdup:
     call _strlen           ;rax = len of str
     mov r8, rdi            ;r8 = str = src
     inc rax                ;rax++
     ;  mov r9, rax         ;len of dest with '\0'
     mov rdi, rax           ;to send the len for malloc
     call _malloc           ;rax = ptr of dest
     ;  cmp rax, 0          ;malloc failled
     ;  jle _error_malloc
     ;  mov rdi, rax        ;malloc param 1 of ft_memcpy
     ;  mov rsi, r8         ;str in param 2 of ft_memcpy
     ;  mov rdx, r9         ;len of str with '\0' param 3 of ft_memcpy
     ;  call _ft_memcpy     ;call ft_memcpy
     ret
_error_malloc:
     xor rax, rax           ;return NULL
     ret

All functions start with ft_are the same than the libc Thx all

A: This error message indicates that you called malloc with an insufficiently aligned stack. The SysV-ABI for amd64 mandates that the stack is aligned to 16 bytes on function call.
In your own code, you can ensure this by making sure that you always push an even number of quadwords onto the stack and remember that on entry, the stack is misaligned by 8 bytes due to the return address being on the stack already.
Without seeing your source code it is hard to give more specific help.


text:
Q: Laravel MQTT subscription - Undefined index: qos I try to subscribe to a topic, I get below mentioned error:
Undefined array key "qos"
My code:
`try {
$mqtt = new Mqtt();
$mqtt->ConnectAndSubscribe('myTopic', function ($topic, $msg) {
       Log::info("Mqtt Msg Received");
});

} catch (\Exception $e) {
 dd($e->getMessage());

}`
(As in the example, I inserted it into a controller).
$buffer .= chr($callback["qos"]);
in vendor/salmanzafar/laravel-mqtt/src/MqttClass/MqttService.php:173
If I solve the problem adding a simple "?? 0", when I try to subscribe, it doesn't seems to work.
I'm using Laravel 8.16 with PHP 8.0 and "salmanzafar/laravel-mqtt": "^2.0".

A: Docs: https://packagist.org/packages/salmanzafar/laravel-mqtt
Please check whether QoS is configured in your Config/mqtt.php:
    'host'      => env('mqtt_host','127.0.0.1'),
    'password'  => env('mqtt_password',''),
    'username'  => env('mqtt_username',''),
    'certfile'  => env('mqtt_cert_file',''),
    'localcert' => env('mqtt_local_cert', ''),
    'localpk'   => env('mqtt_local_pk', ''),
    'port'      => env('mqtt_port','1883'),
    'debug'     => env('mqtt_debug',false) //Optional Parameter to enable debugging set it to True
    'qos'       => env('mqtt_qos', 0), // set quality of service here
    'retain'    => env('mqtt_retain', 0) // it should be 0 or 1 Whether the message should be retained.- Retain Flag


text:
Q: Prove that if a graph has six vertices, then at least one of G or $\bar{G}$ has a subgraph isomorphic to $K_3$ I think this proof is related to proving to Theorem on friends and strangers which can be proved with the pigeonhole principle. But I am at a loss as to what are the holes and pigeons in this case.
I have tried many different graphs and they all work out to have a subgraph that is isomorphic to the $K_3$.

A: See the youtube video on the subject posted by Numberphile here.

Theorem: A graph, $G$, with six or more vertices will always contain $K_3$ as an induced subgraph or its complement, $\overline{G}$, will contain $K_3$ as an induced subgraph.

The argument is as follows:
Suppose you have a graph, $G$, on six vertices.  (The vertices may represent people, and edges between vertices represents that the two people are friends.  We assume friendship is a symmetric binary relation)
Pick one of those vertices and call it $v$.  Among the five other vertices one of the following two things will be true:

*

*$v$ has at least 3 neighbors

*$v$ has at least 3 non-neighbors
(seen easily from pigeon-hole principle)
Without loss of generality, assume it is the first case.  Label three of $v$'s neighbors as $x, y, z$.  (There could be more than three neighbors, that is fine.  We only need three for our purposes).
If it so happens that some two of $v$'s neighbors are adjacent to eachother, for example $x$ and $y$, then those two along with $v$ form a $K_3$ in $G$ and we have the result we were looking for.  If that were not the case, then $x,y,z$ form an independent set with no two of them being adjacent, in which case it follows that $x,y,z$ form a $K_3$ in the complement graph, $\overline{G}$.
(the proof for the case where $v$ has at least 3 non-neighbors is identical)

This is a special case of a much larger result called Ramsey's Theorem in a branch of mathematics what is known as Ramsey Theory.  We define $R(r,s)$ to be the fewest number of vertices such that a graph on at least that many vertices will always contain either a $K_r$ or the graph's complement will always contain a $K_s$.  Our earlier work shows that the number $R(3,3)\leq 6$.  The pentagon acts as a counter example for 5 vertices showing that $R(3,3)>5$ and completes the proof that $R(3,3)=6$.
It has been proven that $R(r,s)$ always exists and is finite for any finite $r$ and $s$, though calculating the specific numbers is incredibly difficult.  $R(3,3)$ is one of the few simple cases we can prove exactly.

"Erdős asks us to imagine an alien force, vastly more powerful than us, landing on Earth and demanding the value of R(5, 5) or they will destroy our planet. In that case, he claims, we should marshal all our computers and all our mathematicians and attempt to find the value. But suppose, instead, that they ask for R(6, 6). In that case, he believes, we should attempt to destroy the aliens."

Several generalizations of this problem exist, where instead of working with the graph and its complement, we work with a coloration of the edges of the graph with an arbitrary number of colors (in the version of the problem discussed here, you could treat edges as "blue edges" and non-edges as "red edges"), or working with arbitrary subgraphs apart from just complete subgraphs.  In each of these generalizations, it has been proven again that the number exists and is finite and we have upper bounds on the numbers, but is again frequently difficult to strictly determine.  It is in contexts like these that numbers such as Graham's Number find its purpose.


text:
Q: Historical report for configurable number of days I have a table of test runs, which have 3 runs daily. I need to show historical data for average of on load time
testID   testName   runID    date         LoadTime

1        Test1      r1      08-01-2016    2.04
1        Test1      r2      08-01-2016    2.02
1        Test1      r3      08-01-2016    2.01
2        Test2      r1      08-01-2016    2.04
2        Test2      r2      08-01-2016    2.02
2        Test2      r3      08-01-2016    2.01
1        Test1      r1      08-02-2016    2.00
1        Test1      r2      08-02-2016    2.04
1        Test1      r3      08-02-2016    2.05
2        Test2      r1      08-02-2016    2.03
2        Test2      r2      08-02-2016    2.02
2        Test2      r3      08-02-2016    2.04
.
.
.
.

Here we have historical data for 2 test. Each test has 3 runs per day and we have data for several months. I need historical data in below format
testID   testName   08-01-2016  08-02-2016 ........... 08-31-2016

1        Test1      2.04        2.05       ...........  2.01
2        Test2      2.02        2.05       ...........  2.01

Which means I will have number of rows equals unique testID and dates as columns. Data is average of 3 runs per day per test.
I know that we have to use Pivot here but main challenge is to get dynamic column names. e.g. above result is for August, however based on a date variable, I should get data for different month.

A: This is Average, but your desired results looks like max
Declare @Date1 date = '2016-08-01'
Declare @Date2 date = '2016-08-31'

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Date]) From Yourtable Where Date between @Date1 and @Date2  Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select [testID],[testName],' + @SQL + '
From (
        Select testID,testName,date,LoadTime
        From YourTable
        Where Date Between '''+cast(@Date1 as varchar(10))+''' and '''+cast(@Date2 as varchar(10))+'''
     ) A
 Pivot (avg(LoadTime) For [Date] in (' + @SQL + ') ) p'
Exec(@SQL);

Returns
testID  testName    2016-08-01  2016-08-02
1       Test1       2.023333    2.030000
2       Test2       2.023333    2.030000


text:
Q: How to draw boxplot by creating age buckets from integer age entries I have a data frame in R, an example of which is given below:
age     number_of_visits
19            10
50            24
25            50
24            35
31            19
42            26
55            40
64            15
20            35
67            20
69            18
33            15
28            50
62            18

I need to create age bins like 18 to 24, 25 to 39, 40 to 54, 55 to 65, and above 65, and then for each of these age bins I need to create boxplots for number of visits.
It would be helpful, if any one can provide code to be used in Rstudio
Thank you!

A: You could do this with cut2 from the Hmisc package:
library(Hmisc)

# Toy Data
age <- rnorm(100, mean=45, sd=15)
number_of_visits <- rnorm(100, mean=20, sd=10)

# cut2 lets you set custom cutpoints
interval <- cut2(age, c(18,25,40,55,65))

boxplot(number_of_visits ~ interval)


text:
Q: Save Extension in Data base with .(Dot) I am getting extension name from user to save in db in Asp Form . How i can validate that user enter extension name with .(Dot) and without .(Dot) name generate Error.

A: Do you want to validate the data as the user is entering it on the form, before submitting?  If so, you may be looking for a RegularExpressionValidator.  See:  https://msdn.microsoft.com/en-us/library/eahwtc9e(v=vs.71).aspx and http://asp.net-tutorials.com/validation/regular-expression-validator/ then use one of the Regular expressions that Webruster and Ahsan provided you.
Sample:
<asp:TextBox runat="server" id="txtExt" />
<asp:RegularExpressionValidator runat="server"
          id="rexDot" controltovalidate="txtExt"
          validationexpression="^[.]([a-zA-Z0-9]+)?$"
          errormessage="Please enter a Dot!" />

A: By using RegEx I can do it.
Regex.Match("String to Compare" , @"^[.]([a-zA-Z0-9]+)?$")

I get user input in  a string and compare it with this Validation using RegEx.

A: Regular expression to validate file formats for .mp3 or .MP3 or .mpeg or .MPEG or .m3u or .M3U
Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$/;

Regular expression to validate file formats for .doc or .docx
Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.DOC|.DOCX)$/;

Regular expression to validate file formats for .txt or .TXT
Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.txt|.TXT)$/;

Regular expression to validate file formats for .jpeg or .JPEG or .gif or .GIF or .png or .PNG
Re= /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpeg|.JPEG|.gif|.GIF| .png|.PNG)$/;


text:
Q: Xamarin.Auth unable to login with Google [Xamarin.Forms] I am using Xamarin.Auth for the Facebook and Google Login but every time I am getting an error displayed in the Screenshot.
Google Login:
Code:
var googleauth = new OAuth2Authenticator(
    "ClientId",
    "ClientSecret",
    "https://www.googleapis.com/auth/userinfo.email",
    new Uri("https://accounts.google.com/o/oauth2/auth"),
    new Uri("http://www.someurl.com"),
    new Uri("https://accounts.google.com/o/oauth2/token")
);

Error:

What should I do to resolve this issues?

A: Go to the console for your project and look under API Access.
https://console.developers.google.com
You should see your client ID & secret there, along with a list of redirect URIs. If the URI you want isn't listed, click edit settings and add the URI to the list.

A: No. This is not problem with Xamarin.Auth, but PEBKAC.
The redirect_uri_mismatch means that uri reigstered on google console differes from one sent by the client, could be ! Xamarin.Auth.


text:
Q: Windows Phone: find the VerticalOffset of a button In Windows phone, how do I find the VerticalOffset of a button? I have a ScrollView with a bunch of content. I want to use ScrollViewer.ScrollToVerticalOffset to get to a specific point (a button), but don't know how to get the position of that point.

A: if you have both items, you should be able to use TransformToVisual to get the location of one control relative to another, then use that to scroll
see http://msdn.microsoft.com/en-us/library/system.windows.media.visual.transformtovisual.aspx

A: This is how I get the x and y coordinates of two buttons in my app and move them. Maybe you can do something similar:
Canvas.SetLeft(imUp, Canvas.GetLeft(imUp) + offsetX);
Canvas.SetLeft(imDown, Canvas.GetLeft(imDown) + offsetX);


text:
Q: How to interpret single photon interference when the two possible paths are different in length? Here is my question.
I struggle with the definition of single photon interference. Let's assume we have a Michelson interferometer and the interference pattern we observe is a single photon result, then if we have and we almost always have different lengths of the two possible photon paths after the beam splitter then how it could be possible to have the same time arrival of the two photon paths when they are traveling different distances? Maybe my assumption that the beam splitter generates the two paths in the moment the photon is interacting with the beam splitter is false, but I can't explain the obtained interference unless I accept that there is a time delay in the two possible paths. This is not a paradox only for this type of experiment but for all the experiments that involve some kind of interference. It seems for me that we cannot use the usual assumption of simultaneousness of events.

A: Have a look at my answer to Slit screen and wave-particle duality because this covers a lot of topics relevant to your question.
You're correct that if we imagine the photon as a little ball then if the arms of the interferometer are different lengths the two "halves" of the little ball cannot arrive at the detector at the same time. But this is not how the interference works. It does not work by the photon splitting and its two halves then interfering with each other.
To imagine the light as a little ball (the photon) ricocheting around your interferometer is highly misleading. The behaviour of the light is best explained by quantum field theory, but sticking to regular quantum mechanics we'd have to say that until we interact with the light (e.g. by it hitting a CCD or photographic plate) the light is delocalised over your whole interferometer.
This doesn't mean the photon has a position but we don't know it, it means the light simply has no position in the classical sense. The wavefunction that describes it covers your whole experimental equipment. The probability of detecting the photon at some point in your kit is given by the magnitude squared of its wavefunction at that point. If you change the geometry of your interferometer then you will change the wavefunction and therefore change the probability of detecting the photon at any particular point.

A: When one  says "photon"  one is in the quantum mechanical frame. Quantum mechanics does not follow the rules of classical mechanics if one  tries to consider the photon one classical entity, like a bag of energy flowing. The photon is a point like elementary particle in the standard model, it has no extent and when it hits the detector it registers at a point of space (x,y,z) at time t. One point. There is no interference pattern from one photon in the energy given up. It is all at one point.
Single photon interferences appear cumulatively, from the random accumulation of individual photons:see page7 here..

Maybe my assumption that the beam splitter generate the two path in the moment the photon is interacting with the beam splitter is false,

Yes , it is wrong. At the individual photon frame the beam splitter affects the probability of which path the single photon will take, it does not split the photon. In quantum mechanics it is the probabilities that control the behavior of elementary particles, and the accumulation of individual hits of different photons will give the interference patterns, which are probability histograms as far as an individual photon's behavior can be gauged.
The probabilities in quantum mechanics are given by the square of the wavefunction's solution for the specific problem with its boundary conditions.
As far as the electromagnetic waves go, it is simpler mathematically to treat the behavior classically. The quantum mechanical wavefunction for the photon is derived by a special form of Maxwell's equation and the classical field emerges naturally form the accumulation of zillions of photons, but that is another story.


text:
Q: a bytes-like object is required, not 'str': typeerror in compressed file I am finding substring in compressed file  using following python script. I am getting "TypeError: a bytes-like object is required, not 'str'". Please any one help me in fixing this.
from re import *
import re
import gzip
import sys
import io
import os

seq={}
with open(sys.argv[1],'r') as  fh:
    for line1 in fh:
            a=line1.split("\t")
            seq[a[0]]=a[1]
            abcd="AGATCGGAAGAGCTCGTATGCCGTCTTCTGCTTG"
            print(a[0],"\t",seq[a[0]])

count={}
with gzip.open(sys.argv[2]) as gz_file:
    with io.BufferedReader(gz_file) as f:
            for line in f:
                    for b in seq:
                            if abcd in line:
                                    count[b] +=1

for c in count:
    print(c,"\t",count[c])

fh.close()
gz_file.close()
f.close()

and input files are
TruSeq2_SE      AGATCGGAAGAGCTCGTATGCCGTCTTCTGCTTG
the second file is compressed text file.  The line "if abcd in line:" shows the error.

A: The "BufferedReader"  class gives you bytestrings, not text strings - you can directly compare both objects in Python3 -
Since these strings just use a few ASCII characters and are not actually text, you can work all the way along with byte strings for your code.
So, whenever you "open"  a file (not gzip.open), open it in binary mode (i.e.
open(sys.argv[1],'rb') instead of 'r' to open the file)
And also prefix your hardcoded string with a b so that Python uses a binary string inernally:  abcd=b"AGATCGGAAGAGCTCGTATGCCGTCTTCTGCTTG"  - this will avoid a similar error on your if abcd in line  - though the error message should be different than the one you presented.
Alternativally, use everything as text - this can give you more methods to work with the strings (Python3's byte strigns are somewhat crippled) presentation of data when printing, and should not be much slower - in that case, instead of the changes suggested above, include an extra line to decode the line fetched from your data-file:
with io.BufferedReader(gz_file) as f:
    for line in f:
        line = line.decode("latin1")
        for b in seq:

(Besides the error, your progam logic seens to be a bit faulty, as you don't actually use a variable string in your innermost comparison - just the fixed  bcd  value - but I suppose you can fix taht once you get rid of the errors)


text:
Q: No preposition in "Why can't you get a girlfriend your own age" before "your own age"? While I was re-watching a Friends episode (S6E21), I stumbled the line as below.

Why can't you get a girlfriend your own age?

I can understand what he meant (a girlfriend from your own age group), but I thought I wouldn't be able to use this kind of expression because I'm not sure it's even a correct expression.
To be specific, if I were to express in this way, I would probably try to come up with a proper preposition to place before "your own age", like "from" preceding "your own age group". Why is this usage okay and is there any underlying grammar?

A: It was fairly simple. It's just that "who is" before "your own age" was omitted. I keep ignoring this kind of omitting is quite common.

A: See https://ell.stackexchange.com/a/312729/139225:

This is a very particular construction consisting of two noun phrases, where the second part is a noun phrase serving as modifier within the larger noun phrase. The second part describes some property, like size, shape, or color.


text:
Q: Prove $\sqrt s$ exists by the Intermediate Value Thorem? I'm pretty sure the process is right, but I'm not sure if I've validly presented the proof. Here is what I wrote:
Suppose that $s > 0$ and consider the function $f(x) = x^2$ on the interval $[a,b]$ where $a=0$ and $b=s+(1/2)$. Thus, $f(a) = f(0) = 0$ and $f(b) = f(s+(1/2)) = s^2 + s + (1/4)$. Because $s>0$,
$0<s<s^2+s+(1/4)$,
meaning $f(a) < s < f(b)$. Therefore, by the Intermediate Value Theorem, there exists a $c$ in $(0, s + (1/2))$ such that $f(c) = s$. Because $f(c) = c^2$, plugging in a value of $\sqrt s$ for $c$ yields $f$($\sqrt s$) = $s$. Therefore, $c = \sqrt s $ exists.
Is this thorough enough?


text:
Q: Different notations of probability I have seen probability density functions defined as $p(x)$ or $p_X(x)$ or $f(x)$  or $F'(x)$. What does each of these notations mean in context and when should I use one over another?
Do they all mean the same and exist as functions to begin with?

A: $f_X(x)$ is the conventional notation for probability density function of the continuous random variable $X$.   Though it can also be so used, $p_X(x)$ is more often used for a probability mass function of a discrete random variable, $X$.
$F_X(x)$ is usual notation for a cumulative distribution function.   If the random variable is continuous and real valued, then $F'_X(x)$ is the density function.
When the identity of the random variable is implicitly understood, then it is permissible to omit the identifying subscript.   Many engineering or physics texts feel that lowercase token, $x$, is sufficient to do this.   This may save typesetting but really should not be done when discussing multiple random variables.


text:
Q: Merging non-zeros, non-overlapping elements from two lists in Perl I'm looking for a clean method in Perl to merge a collection of
lists. The all have the same length, and each consists mainly of
zeros, but also has short contiguous segments of non-zero
entries.  For example, here are two representative lists of
length 25:
@flags1 = qw( 0  0  0  0 21 22 23  0  0  0  0  0  0  0  0 41 42 43  0  0  0  0  0  0  0);
@flags2 = qw(11 12 13  0  0  0  0  0  0  0  0  0  0 31 32 33  0  0  0  0  0 51 52  53 0);

The objective is to merge the elements of @flags2 into @flags1 for all the places
where a contiguous clump of non-zero elements in @flags2 replaces
only zero entries in @flags1.  If there is an overlap with any of
the non-zero elements of @flags1, the associated contiguous clump
of non-zero values in @flags2 is discarded instead of being
merged.
Thus, for the example above, the contiguous clump of values 31,
32, and 33 in @flags2[13..15] are discarded because one of the
entries, $flags2[15] is non-zero and collides with the non-zeros value at $flags1[15].  The resulting desired merged list
would be:
@merged = qw(11 12 13  0 21 22 23  0  0  0  0  0  0  0  0 41 42 43  0  0  0 51 52  53  0);

I have experimented with collecting up contiguous elements of
non-zero elements into a list of lists, and then comparing them
using for and if statements, but it's a mess, and I think it will
be difficult for any other developer to understand the logic.  If
anyone could propose an more elegant solution that would be much
appreciated.

A: use List::Util qw( none );

my $s = 0;
while (1) {
   # Find start of next clump.
   ++$s while $s < @flags2 && !$flags2[$s];

   # Exit if at end of array.
   last if $s == @flags2;

   # Find end of clump.
   my $e = $s+1;
   ++$e while $e < @flags2 && $flags2[$e];

   # Merge in clump.
   my @clump = $s .. $e-1;
   if ( none { $_ } @flags1[ @clump ] ) {      # Or `!grep { $_ }`
      @flags1[ @clump ] = @flags2[ @clump ];
   }

   $s = $e;

   # Exit if at end of array.
   last if $s == @flags2;
}

This is another approach that is akin to the merge portion of a merge sort.
sub get_next_clump {
   my ( $f, $s ) = @_;
   ++$s while $s < @$f && !$f[$s];
   return if $s == @$f;
   my $e = $s+1;
   ++$e while $e < @$f && $f[$e];
   return $s, $e;
}

my $ok1 = my ( $f1_s, $f1_e ) = get_next_clump( \@flags1, 0 );
my $ok2 = my ( $f2_s, $f2_e ) = get_next_clump( \@flags2, 0 );

while ( $ok1 && $ok2 ) {
   if ( $f2_s < $f1_e && $f2_e > $f1_s ) {
      $ok2 = ( $f2_s, $f2_e ) = get_next_clump( \@flags2, $f2_e );
      next;
   }

   if ( $f1_s < $f2_s ) {
      $ok1 = ( $f1_s, $f1_e ) = get_next_clump( \@flags1, $f1_e );
   } else {
      @flags1[ $f2_s .. $f2_e-1 ] = @flags2[ $f2_s .. $f2_e-1 ];
      $ok2 = ( $f2_s, $f2_e ) = get_next_clump( \@flags2, $f2_e );
   }
}

while ( $ok2 ) {
   @flags1[ $f2_s .. $f2_e-1 ] = @flags2[ $f2_s .. $f2_e-1 ];
   $ok2 = ( $f2_s, $f2_e ) = get_next_clump( \@flags2, $f2_e );
}

A: Your approach is workable, it just needs some organization. Let's take it a step at a time:
sub to_ranges {
  my $in = shift;
  my (@ret, $in_range);
  for my $i (0 .. $#$in) {
    if ($in->[$i]) {
      if ($in_range) { # Extend an existing range
        $ret[-1]{end} = $i;
        push @{$ret[-1]{values}}, $in->[$i];
      } else { # Start a new one
        push @ret, { start => $i, end => $i, values => [ $in->[$i] ] };
        $in_range = 1;
      }
    } else {
      $in_range = 0;
    }
  }
  # Dummy entry to make sure the output will be padded to the right length
  push @ret, { start => scalar @$in, end => scalar @$in, values => [] };
  return \@ret;
}

This turns a list into a list of "chunks", each of which knows its start, end, and the values it contains. (end is not strictly necessary but it makes things tidier).
sub from_ranges {
  my $in = shift;
  my @ret;
  for my $r (@$in) {
    push @ret, 0 while $#ret < $r->{end};
    splice @ret, $r->{start}, $r->{end} - $r->{start} + 1, @{ $r->{values} };
  }
  return \@ret;
}

This does the reverse transformation: from_ranges(to_ranges(\@x)) should contain the same elements as @x.
sub overlaps_any {
  my ($r, $ll) = @_;
  for my $l (@$ll) {
    return 1 if $r->{start} >= $l->{start} && $r->{start} <= $l->{end};
    return 1 if $r->{end} >= $l->{start} && $r->{end} <= $l->{end};
  }
  return 0;
}

This is a helper that returns true if the range $r overlaps any of the ranges in @$ll.
sub merge_ranges {
  my ($ll, $rr) = @_;
  my @rr_new = grep { !overlaps_any($_, $ll) } @$rr;
  return [
    sort {
      $a->{start} <=> $b->{start}
    } @$ll, @rr_new
  ];
}

And this takes two sets of ranges, @$ll and @$rr and returns all of the ranges in @$ll plus the ranges in @$rr that don't overlap. The sort is actually only for ease of debugging; you can just return [ @$ll, @rr_new ] if you prefer.
sub merge {
  my ($ll, $rr) = @_;
  return from_ranges(
    merge_ranges(
      to_ranges($ll),
      to_ranges($rr),
    )
  );
}

put the pieces together, and it works.
ikegami has provided an overall simpler soluion, but I'll still offer up this one because maybe you have other things you need to do that would benefit from this representation.


text:
Q: Obtaining URL of notebook which has been published using "Save or Publish" button If I use "Save or Publish" button in top right, it uploads notebook and gives me URL of location. What if I forget the location, is there a way to retrieve the ULR later for that notebook?
My current pattern is to copy-paste the following cell into beginning of every notebook. When I run it, it publishes the notebook and inserts URL of the location into the notebook. It's a bit cumbersome.
(* deploys with canonical name *)
deploy := Module[{notebookFn, parentDir, cloudFn, result},
   Print[DateString[]];
   notebookFn = FileNameSplit[NotebookFileName[]][[-1]];
   parentDir = FileNameSplit[NotebookFileName[]][[-2]];
   cloudFn = parentDir~StringJoin~"/"~StringJoin~notebookFn;
   result =
    CloudDeploy[SelectedNotebook[], CloudObject[cloudFn],
     Permissions -> "Public", SourceLink -> None];
   Print["Uploading to ", cloudFn];
   result
   ];
deploy

A: You can get a list of all cloud objects with CloudObjects. Also, CloudObjects["dir"] returns all cloud objects in given directory "dir".
Then, you can use First to extract the URL.
First /@ CloudObjects[]

(* {"https://www.wolframcloud.com/obj/domen/Base",
    "https://www.wolframcloud.com/obj/domen/Desktop",
    "https://www.wolframcloud.com/obj/domen/Document1.nb",
    "https://www.wolframcloud.com/obj/domen/Document2.nb",
    "https://www.wolframcloud.com/obj/domen/Published",
    "https://www.wolframcloud.com/obj/domen/trash",
    "https://www.wolframcloud.com/obj/domen/userEIWLs"} *)

First /@ CloudObjects["Desktop"]
(* {"https://www.wolframcloud.com/obj/domen/Desktop/Document3.nb"} *)


text:
Q: How to play different frequeny sound in android? HI,
I want to create a animal repeller application.I'm new bie to android.I want to play different  frequency sound to repel the animal,but I'm not clear how to play .please help me out .
Thanx in advance.
Praween.

A: Your best bet is to use a ToneGenerator:
http://developer.android.com/reference/android/media/ToneGenerator.html
Allows you to create tones to you specific needs, includes controlls for frequency, length of tone, so on.
Read up on the class and find the best way to do what you want it to do.
Hope this helps


text:
Q: save() does not change using mongoose I have this code that is supposed to edit an object grabbed from a MongoDB. One of the fields is a map that has an array in it. I push to that array in the map. I log the object itself and it definitely got put into the array of the Map. It just doesn't update in the Database
Guild Model:
let {
    Schema,
    model
} = require('mongoose');
let Guild = new Schema({
    guildID: {
        type: String,
        required: true
    },
    guildname: {
        type: String,
        required: true
    },
    prefix: {
        type: String,
        required: false,
        default: "y!"
    },
    welcome_channel: {
        id: {
            type: String,
            required: false,
            default: null
        },
        message: {
            type: String,
            required: false,
            default: "has joined the server!",
        }
    },
    mod_log: {
        type: String,
        required: false,
        default: null
    },
    spaces: {
        type: Map,
        required: false,
        default: []
    }
})

module.exports = model('Guild', Guild);

I grab the guild object in my code later on, it isn't null or undefined.
let fetch_guild = await Guild.findOne({"guildid": id});
// successfully grabs the object from the db
let temp_space = fetch_guild.spaces.get(args[0]) ? fetch_guild.spaces.get(args[0]) : null;
if(temp_space.admins.includes(message.mentions.users.first().id)) return message.reply("That person is already an admin!");
temp_space.admins.push(message.mentions.users.first().id);
console.log(fetch_guild.spaces)

Result of that console.log:
Map {
  'test' => { name: 'test', admins: [] },
  'test2' => { name: 'test2', admins: [] },
  'test3' => { name: 'test3', admins: [ '500765481788112916' ] }
}

And I save it using:
await fetch_guild.save();

In the database, it is still an empty array

A: try using updateOne() of mongoose.
await fetch_guild.updateOne(fetch_guild);


text:
Q: Handle multipart/form-data request with a file in Spring Web 4 I am creating a rest controller that looks like this:
@RequestMapping(value = "/clients", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RestResponse> createClientRecord(
                                                       @RequestPart(value = "imageFile") MultipartFile imageFile,
                                                       @RequestPart(value = "field1") String field1,
                                                       @RequestPart(value = "field2") String field2) {... }

I am trying to send a request from Postman by setting body type to be "form-data" in the Postman UI:

But I am having this error:
Status 500 accessing url: '/api/v1/clients' -> UT000072: Failed to decode url ... ... (some unreadable characters) to charset UTF-8

My question is: what should I do to handle the http post request with multipart form data with a file in Spring web 4?

A: Use org.springframework.web.bind.annotation.@RequestParam instead.


text:
Q: Linux Shell Script: Encrypting password in Linux Shell Script (.sh)? is it possible i wonder if it is possible to "hide" the password in Linux Shell Script?
for example, i have a code here
echo "Enter Password:"
read p

if [ $p = "Passwords" ]
then
    echo "Password Granted"
else
    echo "Password Denied"
fi

as you can see  when im going to bash it at Linux Terminal, i will be asked to type/enter the password in line 2. in Linux Terminal, whatever you type, the characters are visible. if i type "passwords" or "passhwords" or any character, i can see visibly each character/letter of what i type there.
i wonder if it is possible to "hide" it? similar to Facebook or Google account login where when i type any character it will appear as "*****" instead of the actual characters.
is there a code i should enter before "read p"(2nd line) so whatever i will type will be hidden?
OS: Ubuntu


text:
Q: At what argument $x$ is the tangent to the graph $y=\frac{1}{2}x^2-\ln x$ horizontal?
At what argument $x$ is the tangent to the graph $y=\frac{1}{2}x^2-\ln x$ horizontal?

Well this is a question which I found in a website.
I found the Derivative to be $(x^2+1)/x$.
As far as I know that should be zero but I can't go any further from there.

A: The derivative is actually $\frac{x^2-1}{x}$, so setting that equal to $0$ gets you the roots $x = \pm1$.

A: $$y'=x-\frac{1}{x}=\frac{x^2-1}{x}$$
Then $y'=0$ for $x=1$ since $y$ is defined for $x >0$, the curve has horizontal tangent at $x=1$, $y=\frac{1}{2}$.


text:
Q: why can a char pointer be a char array in C In C, you can declare an char array either by
char []array;

or
char *array;

The later one is a pointer, why can it be an array?

A: Pointers and arrays are two completely different animals; a pointer cannot be an array and an array cannot be a pointer.
The confusion comes from two concepts that aren't explained very well in most introductory C texts.
The first is that the array subscript operator [] can be applied to both pointer and array expressions.  The expression a[i] is defined as *(a + i); you offset i elements from the address stored in a and dereference the result.
So if you declare a pointer
T *p;

and assign it to point to some memory, like so
p = malloc( N * sizeof *p );

you'll get something like the following:
        +---+
     p: |   | ---+
        +---+    |
         ...     |
        +---+    |
  p[0]: |   |<---+
        +---+
  p[1]: |   |
        +---+
         ...
        +---+
p[N-1]: |   |
        +---+

p stores the base address of the array, so *(p + i) gives you the value stored in the i'th element (not byte) following that address.
However, when you declare an array, such as
T a[N];

what you get in memory is the following:
        +---+
  a[0]: |   |
        +---+
  a[1]: |   |
        +---+
         ...
        +---+
a[N-1]: |   |
        +---+

Storage has only been set aside for the array elements themselves; there's no separate storage set aside for a variable named a to store the base address of the array.  So how can the *(a+i) mechanism possibly work?
This brings us to the second concept: except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array ijn a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.
In other words, when the compiler sees the expression a in the code, it will replace that expression with a pointer to the first element of a, unless a is the operand of sizeof or unary &.  So a evaluates to the address of the first element of the array, meaning *(a + i) will work as expected.
Thus, the subscript operator works exactly the same way for both pointer and array expressions.  However, this does not mean that pointer objects are the same thing as array objects; they are not, and anyone who claims otherwise is confused.


text:
Q: TableView showing repeated data after some index I am using custom table view cell and my table view showing repeated data after index 5 I don't know why it is done When in ipad it shows after index 8 repeated data it may be indexing problem but couldn't find it below is the code
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"item";
ItemCell *cell = (ItemCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[ItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(@"indexpath.row is %d",indexPath.row);

NSString *stre = [grouporphoto objectAtIndex:indexPath.row];
if([stre isEqualToString:@"Group"]){
    folderimage = YES;
    NSLog(@"here is folder");

    cell.item = [items objectAtIndex:indexPath.row];

}
else if([stre isEqualToString:@"Photo"]){
    folderimage = NO;
    NSLog(@"here is Photo");

    cell.item = [items objectAtIndex:indexPath.row];

}

return cell;
}

Please help
Thanks in advance

A: You should reset all your variables in another else-statement so that when your cell is reused the variables in them aren't.
else
{
    cell.item = nil;
}

This should fix it for you.

A: It is because of the way iOS handles TableViews. As soon as a new cell comes into view (from being out of view i.e. below the bottom of the screen), it will ask for a new one, in which case it will try to reuse a cell that has moved out of the view.
Because of the reuse, not all instance variables are reset on the cell. You need to explicitly change everything you want to change. In other words, all pictures, text, labels etc etc that you want potentially different on each cell, set them explicitly each time.


text:
Q: Rendering the result of a controller method to a partial in the view I have this Rails code in a method in a controller. It takes four parameters, does a bit of math and I'd like it to return a the value stored in the 'attendance' variable to a partial in a view.
def find_attendance(lesson_id, student_id, start_date, end_date)
    marks = Array.new

    all_registers = Register.where(:lesson_id => lesson_id)

    start_date.upto(end_date) do |date|
        all_registers.each do |register|
            if date == register.date
                this_mark = RegisterMark.where(:student_id => student_id, :register_id => register.id)
                this_mark.each do |mark|
                    marks << mark.mark
                end
            end
        end
    end

    attendance = ((Float(marks.count("O")) + Float(marks.count("N"))) / Float(marks.count)) * Float(100)
end

I have created a _find_attendance.html.erb file in the relevant view directory, and tried calling the partial by using <%= render :partial => "find_attendance" %> but I'm having trouble passing parameters and using the correct variable name within the partial.
I've tried playing around with using instance variables on 'attendance'.
Any pointers?

A: The first thing you need to do is put the values that you want to pass to your views (regular views and partial views) into a controller variable, like this:
@attendance = ((Float(marks.count("O")) + Float(marks.count("N"))) / Float(marks.count)) * Float(100)

Next, you'll need to rename your partial something other than find_attendance.  That's the name of the view for the find_attendance action, and if I understand your question, you want that view (find_attendance.html.erb) to call a partial with the attendance. So, try something like this:
find_attendance.html.erb:
<%= render :partial => "attendance", :object => @attendance %>

Now, inside the partial _attendance.html.erb, you can refer to an instance variable attendance. (Partials assume the existence of an instance variable with the same name as the partial; that's the :object we passed through render.
_attendance.html.erb:

Attenance: <%= attendance %>

A: You almost certainly want to add this method as a method to the model. Maybe in your case the lesson model?
class Lesson < ActiveRecord::Base

  has_many :registers

  def calculate_attendance_for_student(student, start_date, end_date)
    valid_dates = start_date.upto(end_date)
    registers.each do |register|
    ...
  end
end

Then in your view you can get at the @lesson model to get attendance.
There's some area for improvement in your loops, I included a simple way to loop through all Register for a Lesson above. You can do this for both your Register.where and your RegisterMark.where for speed improvements


text:
Q: how to find the length of the longest contiguous subarray whose sum is divisible by a given number I want to find the longest continuous sub array whose sum is divisible by a number 'k'.I have already done it using brute force with complexity o(n^2).But wants to do it for o(n).can anyone suggest me the efficient way to solve this problem in o(n) time.
for eg:
    {1 3 1 3 6}
the max length of subarray which is divisible by 3 is
 2. i.e {3,6}
Also to note that the value of k here is very large around 10^6 so I can not use the prefix sum method where in modulo of each element is recorded as it is valid for small numbers only.
so kindly suggest me the efficient way to solve this problem in C.

A: Here is a way that can be used:
Create an array of summation-modulo k, eg.
Let the array be: {3,4,10,15,1,4,7}
and k = 5. Then, summation modulo array would look like:
{3,2,2,2,3,2,4} which is created as: {3%5, (3+4)%5, (3+4+10)%5... } and so on.
Now find max index difference b/w similar numbers. Since k<=10^6, you can easily do this using array of size k.
In this case, it can be: {(4-0 = 4) ->index of 3} or {(5-1 = 4) ->index of 2}, so 4.
#include<stdio.h>
int main(){
    int n,k,i,j;
    scanf("%d%d",&n,&k);                    //size of the input array 'n' and modular 'k'
    int a[n];
    for(i = 0;i < n;i++)
            scanf("%d",&a[i]);

    //actual processing starts
    //creating summation modulo array in 'a' itself
    a[0] %= k;
    for(i = 1;i < n;i++){
            a[i] = (a[i-1] + a[i]) % k;
    }

    int r[2][k];
    for(i = 0;i < k;i++)
            r[0][i] = r[1][i] = -1;                 //initializing 'r' to -1
    //now evaluating min and max position of any spec no.
    for(i = 0;i < n;i++){
            if(r[0][a[i]] == -1)
                    r[0][a[i]] = i;
            else
                    r[1][a[i]] = i;
    }
    //evaluation of min-max indices complete

    int g = 0;
    //now find max diff if both values are set
    for(i = 0;i < k;i++){
            if(r[0][i] != -1 && r[1][i] != -1 && r[1][i] - r[0][i] > g)
                    g = r[1][i] - r[0][i];
    }
    printf("%d\n",g);               //this is the required answer
}


text:
Q: Play2 Controller Test sending JSON I want to test my controller by sending some JSON:
 val fakeRequest = FakeRequest(Helpers.POST, controllers.routes.AuthController.login().url,
      FakeHeaders(Seq(HeaderNames.CONTENT_TYPE ->Seq(MimeTypes.JSON))),json)

 val result = controllers.AuthController.login()(fakeRequest)

 status(result) must equalTo(OK) <== Cannot check requires Future[SimpleResult]

Returned type is:
Iteratee[Array[Byte],SimpleResult]

How can I get Future[SimpleResult] ?
When I'm using simple FakeRequest without parameters everything works fine:
 val fakeRequest = FakeRequest()

 val result = controllers.AuthController.list()(fakeRequest)

 status(result) must equalTo(OK)

A: I found the solution, just use another constructor and method withJsonBody:
FakeRequest(Helpers.POST, controllers.routes.AuthController.login().url).withJsonBody(json).withHeaders(
      (HeaderNames.CONTENT_TYPE, MimeTypes.JSON))


text:
Q: how to keep in the same cell after refeshing the datagridview c# i use timer for refreshing datagridview. pls help me
every 10 secs the datagridview refresh . i can't find code where after refreshing or sorti g the datagridview the selected cell will remain pls help me..
private void timer1_Tick(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {
            SqlCommand cmd = new SqlCommand("SELECT (Cust_No) as [Customer ID],(Cust_surname) as [Surname], (Cust_fname) as [First Name], (Cust_mi) as [Middle Initial],  (Cust_address) as [Address], (Cust_ContactNO) as [Contact Number], (Cust_Faxno) as [Fax Number], (Cust_Tin)as [TIN]  FROM Customer WHERE cust_status like ('Active')");
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            da = new SqlDataAdapter(cmd);
            ds = new DataSet("ds");
            da.Fill(ds);
            ds.Tables[0].TableName = "table_mirror";
            dataGridView2.DataSource = ds.Tables["table_mirror"];

        }
        else
        {
            SqlCommand cmd1 = new SqlCommand("SELECT (comp_no) as [Company ID],(comp_name) as [Company Name], (comp_contactperson) as [Contact Person], (comp_address) as [Address],  (comp_contactno) as [Contact No], (comp_fax) as [Fax], (comp_Tin) as [Tin] FROM Company WHERE comp_status like ('Active')");
            cmd1.CommandType = CommandType.Text;
            cmd1.Connection = conn;
            da = new SqlDataAdapter(cmd1);
            ds = new DataSet("ds");
            da.Fill(ds);
            ds.Tables[0].TableName = "table_mirror";
            dataGridView2.DataSource = ds.Tables["table_mirror"];
        }
    }

A: i think this help u.
        Point[] oldSelectedCells = new Point[dataGridView1.SelectedCells.Count];
        for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
        {
            oldSelectedCells[i].X = dataGridView1.SelectedCells[i].ColumnIndex;
            oldSelectedCells[i].Y = dataGridView1.SelectedCells[i].RowIndex;
        }

        // refresh datagridview

        dataGridView1.CurrentCell = null;
        foreach (Point p in oldSelectedCells)
            dataGridView1[p.X, p.Y].Selected = true;