text:
Q: spring: how to use non-default constructor when auto-wiring a prototype bean using @Autowired and context:component-scan? Suppose you have a prototype bean class as below:
@Component
@Scope("prototype")
public class Foobar {
    private String foo;
    public Foobar( String foo ) {
        this.foo = foo;
    }
}

So, is it possible to use @Autowired to wire such a bean in another class, which should use the non-default constructor Foobar(String foo) to instantiate the bean?
update
In the example above, the constructor parameter, String foo, is not available from application context but rather dynamic. So, having the constructor annotated with @Autowired and then specifying foo somewhere in the context doesn't seem an ideal solution here.

A: You need to annotate your constructor with @Autowired
and for the parameter that has to be passed to the constructor when your bean get instantiated, you have to use a non-primitive type parameter:
For example:
@Component
@Scope("prototype")
public class FooBar {

    private DataSource data;

    @Autowired
    public FooBar(DataSource data) {
        this.bdata = data;
    }
}

and then annotate your DataSource with:
@Component("dataSupplier")
public class DataSource {

    public int getData() {}
}

A: Here are 3 ways to do it, just peek the best one for your case:
Using @Autowired constructors
Better when: you have all you need to build your prototype bean in the context (even for properties such as @Value("${prop}"))
If you want an automatic way to do it, you will need to have everything that is needed to instantiate the bean in the context too (even for a prototype bean). In case you have everything needed in your context you could simply annotate the constructor as @Autowired and Spring will do the rest for your.
@Component
@Scope("prototype")
public class FooBar {

    private Baz baz;

    @Autowired
    public FooBar(Baz baz) {
        this.baz = baz;
    }

}

Using FactoryBeans
Better when: if you are using an XML based context, you will prefer this way.
Another possibility, if you need a personalized way to do it, would be using FactoryBeans. From documentation:

Interface to be implemented by objects used within a BeanFactory which are themselves factories. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.

The FactoryBean is used by Spring just to build the object you requested (being it a prototype or singleton).
For your case you could have an implementation like:
@Component
public class FooBarFactory implements FactoryBean<FooBar> {

    @Autowired
    private Baz myContextProvidedObject;

    @Override
    public FooBar getObject() throws Exception {
        return new FooBar(myContextProvidedObject, "my parameter");
    }

    @Override
    public Class<?> getObjectType() {
        return FooBar.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

}

And you could simple @Autowired FooBar on other instances of your context.
Using @Configuration
Better when: if you already have your context configured using annotations you will definitely prefer this way.
A third way to do it, and this is my favorite, would be using your @Configuration class. From documentation:

public @interface Configuration: Indicates that a class declares one or more @Bean methods and may be
  processed by the Spring container to generate bean definitions and
  service requests for those beans at runtime, for example:

Within that class your could have a method like:
@Configuration
public class MyConfig {

    @Bean
    @Scope("prototype")
    public FooBar fooBar(Baz myContextProvidedObject) {
        return new FooBar(myContextProvidedObject, "my parameter");
    }

}

A: Since component scanning has been enabled, spring will try to automatically discover and register another Foobar bean. However this will fail because spring can't create an object using the defined constructor as you have not auto-wired the constructor / parameters in the constructor. As the second step spring will try to create a Foobar with no-args constructor. Therefore you need to have auto-wired the constructor which you defined in the spring-config file in order to get rid of this error. Please refer to this article for more information on this topic.


text:
Q: How can I call a method with popped object using commons-digester? I have an XML document that looks like this:
<!-- language: xml -->
<items>
  <item type="java.lang.Boolean" name="foo" value="true" />
</items>

I'd like the <root> element to create a java.util.Map object and have each <item> element create an object of the appropriate type and then add an entry to the Map -- similar to a SetNextRule but with an argument to the call coming from the stack.
I've already created a custom Rule that will create an object of the type specified in the type attribute (java.lang.Boolean in this case) using the value in the value attribute and push it on the stack.
Now, I'd like to pop the item off the top of the stack and use it as an argument to the put method on the Map object (which is just "under" the Boolean object on the stack).
Here's the code I have written so far:
<!-- language: lang-java -->
Digester digester = new Digester();
digester.addObjectCreate("items", HashMap.class);
digester.addRule(new MyObjectCreateRule()); // This knows how to create e.g. java.lang.Boolean objects
digester.addCallMethod("items/item", "put", 2, new Class<?>[] { String.class, Object.class });
digester.addCallParam("items/item", 0, "name");
digester.addCallParam("items/item", 1, true); // take argument from stack

I'm getting the error that the method put can't be found in the java.lang.Boolean class. So, the problem is that the e.g. Boolean object is on the top of the stack, and I want to use it as an argument to the put method called on the next-to-top element on the stack:
Stack:
java.lang.Boolean value=true     <-- top of stack, desired call param
java.util.HashMap contents = {}  <-- desired call target

Is there a way to do this with existing commons-digester rules, or do I have to create another custom rule that performs this type of operation?

A: I ended up writing a custom rule that combined the two operations: constructing a new instance of the property value and inserting it into the properties bundle.
This is an adaptation of the real use-case that I had, so the code may not be 100% perfect since I copy/pasted and adapted it, here. I also understand that using property values other than java.lang.String doesn't quite make sense, but it did for my use-case (which doesn't use java.util.Properties, actually, but that class was a good analogy).
<!-- language: lang-java -->
/**
 * Implements a create-object-set-property Digester rule.
 */
public class SetPropertyRule
    extends Rule
{
    private String _classAttributeName;
    private String _nameAttributeName;
    private String _valueAttributeName;
    private HashSet<String> _acceptableClassNames;

    /**
     * Creates a new SetPreferenceRule with default attribute names and classes.
     *
     * Default class attribute name = "type".
     * Default name attribute name = "name".
     * Default value attribute name = "value".
     * Default allowed classes = String, Integer, Double, and Boolean.
     */
    public SetPropertiesRule()
    {
        this("type", "name", "value",
             new Class<?>[] { String.class, Integer.class, Double.class, Boolean.class });
    }

    /**
     * Creates a new SetPropertyRule to construct a name/value pair and
     * set it on a Properties object.
     *
     * The Properties object should be at the top of the current
     * Digester stack.
     *
     * @param classAttributeName The name of the attribute that holds the property's value type.
     * @param nameAttributeName The name of the attribute that holds the property's name.
     * @param valueAttributeName The name of the attribute that holds the property's value.
     * @param acceptableClasses The list of acceptable property value types.
     */
    public SetPreferenceRule(String classAttributeName, String nameAttributeName, String valueAttributeName, Class<?>[] acceptableClasses)
    {
        super();

        _classAttributeName = classAttributeName;
        _nameAttributeName = nameAttributeName;
        _valueAttributeName = valueAttributeName;
        _acceptableClassNames = new HashSet<String>(acceptableClasses.length);
        for(Class<?> clazz : acceptableClasses)
            _acceptableClassNames.add(clazz.getName());
    }

    @Override
    public void begin(String namespace,
                      String name,
                      Attributes attributes)
        throws Exception
    {
        // Store the values of these attributes on the digester param stack
        getDigester().pushParams(
                attributes.getValue(_classAttributeName),
                attributes.getValue(_nameAttributeName),
                attributes.getValue(_valueAttributeName)
        );
    }

    @Override
    public void end(String namespace,
                    String name)
        throws Exception
    {
        Object[] attributeValues = getDigester().popParams();

        Object props = getDigester().peek();
        if(!(props instanceof java.util.Properties))
        {
            String typeName;
            if(null == props)
                typeName = "<null>";
            else
                typeName = props.getClass().getName();

            throw new IllegalStateException("Expected instance of " + Properties.class.getName() + ", got " + typeName + " instead");
        }

        String className = (String)attributeValues[0];
        checkClassName(className);

        // Create an instance of the preference value class
        Class<?> clazz = Class.forName(className);
        Constructor<?> cons = clazz.getConstructor(String.class);
        Object value = cons.newInstance((String)attributeValues[2]);

        ((Properties)props).put((String)attributeValues[1], value);
    }

    private void checkClassName(String className)
    {
        if(!_acceptableClassNames.contains(className))
            throw new IllegalArgumentException("Class " + className + " is not allowed");
    }
}

I'd be happy to discover that there is an out-of-the-box way to do this, however.

A: For a different approach, you could move the problem out of digester itself and use an enhanced map class to provide a method more compatible with the existing digester rules:
public static class MyHashMap extends HashMap {
  public Object put(String clazz, String name, String value) {
    Object obj = ... // create object from clazz/name/value
    return super.put(name, obj);
  }
}

Then just use the existing addCallMethod / addCallParam rules:
Digester digester = new Digester();
digester.addObjectCreate("items", MyHashMap.class);
digester.addCallMethod("items/item", "put", 3, new Class<?>[] { String.class, String.class, String.class });
digester.addCallParam("items/item", 0, "type");
digester.addCallParam("items/item", 1, "name");
digester.addCallParam("items/item", 2, "value");

If you needed to get a pure HashMap as a result rather than a custom class, you could use a similar method with your custom class wrapping a native HashMap, e.g.com.google.common.collect.ForwardingMap if you are using Guava.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to resolve cross-site resource for google tag manager on react website I write react website and want to use google tagmanager to get analytics and get error about cookie.
I read some of comment about this problem and see it was set on header of server side script.But my code was on S3 that I'm not sure how to do it.
here is an error message

A cookie associated with a cross-site resource at https://www.googletagmanager.com/ was set without the SameSite attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.


text:
Q: Teste unitário de implementações de uma classe generica Suponha que temos a seguinte Interface:
public interface ICRUDService<T>
{
    T Create(T entity);
}

Implementação Abstrata:
public abstract class CrudService<T> : ICRUDService<T>
{
    IRepository repositorio;
    public EntityService(IRepository rep)
    {
        repositorio= rep;
    }

    public virtual T Create(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity ");
        }
        repositorio.Add(instance);
        return entity;
    }
}

Para cada objeto do meu domínio (Ex: Pessoa, Carro, Animal) irá implementar um serviço:
  public class PessoaService :CrudService<Model.Pessoa>{
    IRepository repositorio;
    public PessoaService (IRepository repo):base(repo)
    {
        repositorio= repo;
    }
    public void MetodoPersonalizadoServicoPessoa(){
         var oi = "oi";
    }
   }

  public class CarroService :CrudService<Model.Carro>{
    IRepository repositorio;
    public CarroService (IRepository repo):base(repo)
    {
        repositorio= repo;
    }
    public void MetodoPersonalizadoServicoCarro(){
         var oi = "oi2";
    }
   }

-Qual a melhor maneira de testar cada implementação de CrudService?
-Para cada implementação devo repetir o teste do método Create da classe abstrata?
-Existe alguma maneira de criar um teste Abstrato genérico que automaticamente testa o método Create em todas as classes que o implementarem?

A: Qual a melhor maneira de testar cada implementação de CrudService?
Criando um teste explícito para cada implementação.
Você pode testar os métodos virtuais da classe abstrata criando no código dos testes uma herança desta classe e testando esta classe herdada. É importante fazer isso para garantir que o métodos virtuais não sobrescritos por nenhuma implementação concreta também sejam testados.
Para cada implementação devo repetir o teste do método Create da classe abstrata?
Deve repetir o teste apenas para as implementações concretas que sobrescreverem o método virtual da classe pai abstrata.
Não precisa repetir o teste quando o método virtual não for sobrescrito senão você estará testando o mesmo código duas vezes.
Existe alguma maneira de criar um teste Abstrato genérico que automaticamente testa o método Create em todas as classes que o implementarem?
Se você se refere a usar alguma mágica tipo reflection para identificar todas as implementações concretas e sair testando... Não é boa idéia. Cada teste deve ser expressivo, indicando muito claramente o que está sendo testado e com que objetivo.
Se você usar reflection para identificar o que testar, pode chegar um tempo em que esta busca não encontrará nada e o teste continuará lá "sujando" sua suíte de testes e eventualmente causando confusão do tipo: os serviços CRUD parecem estar sendo testados e não estão.
Herança e testes
Evite usar herança apenas para reutilização de código.
Observe, pela quantidade de dúvidas que o uso de herança levantou, que herança adiciona bastante complexidade e quebra a abstração (veja que você precisa saber se uma classe sobrescreve ou não um método da classe pai para saber como testá-la ou para evitar testes repetidos).
O uso de herança, no seu exemplo, não está trazendo nenhum benefício.


text:
Q: .HTACCESS rewriting a url the basic i have 2 questions regarding .htaccess,
1- if i use .htaccess to rewrite the url's on my website does it affect any of the requests or do i need to change the link for all forms for example if a action post for a form is index.php?submit do i need to change that link ? when i for example hide .php extension in .htaccess or it doesn't affect it
2-how do i basically hide all .php extensions
3- if i have the below url

www.link.com/post.php?post_id=53&post_name=the-International-day-in-roma
how do i make .htaccess rewrite it to the following
www.link.com/post/the-International-day-in-roma
does it matter if there was commas or can we remove them also ?
www.link.com/post.php?post_id=53&post_name=everyday,-or-today,-or-tomorrow

A: you can hide php file name in htaccess
for example if someone click this link
www.link.com/post/the-International-day-in-roma/

htaccess file contverts the url to post.php and call the the post name by $1
 it represents this part "/([a-zA-Z0-9_-]+)/" the it is dynamic  and it can be changed !
Options +FollowSymLinks
    RewriteEngine On

RewriteRule ^post/([a-zA-Z0-9_-]+)/$ post.php?post_id=53&post_name=$1 [L]


text:
Q: jQuery Draggable + Sortable - How to drag and drop between two scrollable lists I would like to have two lists, Available Items and Selected Items, whereby Available Items are assigned to Selected Items via drag and drop. I require the Selected Items to be sortable, but not the Available Items. The challenge is that both lists can potentially contain a significant number of items, and therefore need to be scrollable.
Here is the jQuery I have thus far:

And the corresponding HTML:

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 9

Item 10

Item 7

Item 8

Item 9

Item 10

Item 11

Item 12

Item 13

Item 14

Item 15

Item 16

Item 17

Item 18

With the scrollable list requirement, however, I can't get the draggable behaviour to work elegantly (see the demo at http://pastehtml.com/view/1bsk6bt.html).
Once the item being dragged enters the Available Items list, it disappears behind the scrollable frame. I've tried the clone helper, and also tried playing around with containing divs, different overflow options, turning off the scroll option in jQuery, but cannot get it to work properly. I'm sure someone out there has accomplished something like what I'm aiming to do here and can save me some time? :)
Any help would be greatly appreciated!

A: Whew!  That was a fun one to fix.
The first problem, with the list scrolling forever horizontally, I fixed with some simple overflow changes in your CSS.  I removed both of the overflow attributes from your .drag_column, and put an overflow: hidden in .drag_container.
.drag_container {
    width: 1000px;
    margin: 0 auto;
    position: relative;
    border: 1px solid black;
    position: relative;
    z-index: 1;
    overflow: hidden;
}

.drag_column {
    padding: 5px;
    width: 490px;
    height: 200px;
    float: left;
    position: relative;
}

Unfortunately, when I did that it created a position error when you moved your draggable from one list to another (it would shoot upwards, depending on which list item you chose).  To fix this, I added the line "helper: clone" to your draggable creation function.
$( "#available > li" ).draggable({
    revert: 'invalid',
    connectToSortable: '#selected',
    containment: '#drag_container',
    helper: 'clone'
});

Once again, this created an undesirable effect.  The clone helper makes it so the original list never has items deleted.  To fix this, I had to manually create a function that would delete the old item.  What I did was I added a start: function to your draggable object, that grabbed the object id and put it in a variable.  Then I created a droppable object of your #selected list, and made a drop: function there.  That drop function simply does a slideUp(100) on the object with the matching id.  Note that I have a variable creation at the initiation of the script - this fixes a bug in IE.
var dragged = null;
$(function() {
    $( "#available > li" ).draggable({
        revert: 'invalid',
        connectToSortable: '#selected',
        containment: '#drag_container',
        helper: 'clone',
        start: function(ui, event) {
            dragged = $(this).attr('id');
        }
    });
    $( "#selected" ).droppable({
        drop: function(event, ui) {
            var ident = "#" +  dragged;
            $(ident).slideUp(100);
        }
    });

I posted a page with the full HTML at http://pastehtml.com/view/1by9nfd.html so you can play around if you want.  Hope this helps!

A: I needed this functionality and had found a way to do this
use appendTo: "body" and set position absolute on start. The element being dragged gets appended to body and is alwayz "top" of other elements because its position is absloute to the body.
$( "#available > li" ).draggable({

    revert: 'invalid',
    appendTo: 'body',
    helper: 'clone',
    connectToSortable: '#selected',
    containment: '#drag_container',

start: function( event, ui ){

    $(ui.helper).css('position', 'absolute'); //helper if you are using clone

},

stop: function(event, ui){

    $(ui.helper).css('position', 'relative'); // if you want

}

});

Hope this helps


text:
Q: Pulling Data from MySql and dropping it into SQL I was wondering if anybody had any advice or references that explain how to pull data from MySQL and drop it into SQLSever! Any input would be greatly appreciated!! Thanks!

A: You can add MySQL as a "linked server"
http://forums.mysql.com/read.php?60,123221,123221
Once you did that you can reference the MySQL  tables, views, etc with their fully qualified name in regular SQL Server queries

A: I could not tell if you wanted to access a MySQL database because you were migrating to SQL server, or if you wanted to access a MySQL database on an ongoing basis. I am answering as if you want to migrate, because you already have an excellent answer on accessing MySQL from SQL Server.
If you want to migrate, mysqldump is one way to go. Its format is easily parsed.
You can also write the results of any MySQL table -- and SQL Server for that matter -- to .csv format. .csv format is nearly a universal transfer format for data.


text:
Q: Incremental percentage calculator for Wordpress I am in charge of a real estate agency website and we've just had a big change on stamp duty tax here in the UK. The website is built on Wordpress and I would love to be able to embed a calculator like the examples below on my homepage to attract visitors. How could I go about doing this?
I was thinking there would be a percentage calculator widget but that would just do a percentage of a single number, rather than working out the slightly more complex incremental percentage of stamp duty.
The way it works is the first £125k of your property is tax free. The value between £125k and £250k is taxed at 2%, the value from £250k to £925k is taxed at 5%, the value from £925k to £1.5mil taxed at 10% and anything above £1.5mil is taxed at 12%.
Examples:

*

*http://www.telegraph.co.uk/finance/autumn-statement/11271926/Stamp-duty-calculator-how-changes-affect-you.html

*https://www.moneyadviceservice.org.uk/en/tools/house-buying/stamp-duty-calculator


text:
Q: Delete *.* Local Files in Android programmatically I am writing an app that stores files locally.
I can delete a file easily by specifying its name
 button_deleteFile.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String thisFilename=text_fileToDelete.getText().toString();
            thisFilename=thisFilename+".txt";
            deleteFile(thisFilename);
        }
    });

Is it possible to wild card delete files to empty the storage space and clean up? EDIT: If so please can you show me how.

A: try this:
 delete whole file:

  File dir = new File(Environment.getExternalStorageDirectory()+"directory_name");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
   new File(dir, children[i]).delete();
}
}

OR
  try{
   String d_path = "your file path";
   File file = new File(d_path);
   Boolean isDeleted= delete(context,file );
   }catch(Exception e){
    e.printStackTrace();
 }

public static boolean delete(final Context context, final File file) {
final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[] {
        file.getAbsolutePath()
};
final ContentResolver contentResolver = context.getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");

contentResolver.delete(filesUri, where, selectionArgs);

if (file.exists()) {

    contentResolver.delete(filesUri, where, selectionArgs);
}
return !file.exists();
}


text:
Q: Rendering a closed Marionette view Shouldn't a closed Marionette view re-delegate the defined events (events, modelEvents, CollectionEvents) when rendering again?
It seems as if I have to manually call delegateEvents after closing and re-rendering a view. Otherwise the view won't work as expected.
http://jsfiddle.net/4DCeY/
var app = new Marionette.Application();

app.addRegions({
    main: '.main'
});

var MyView = Marionette.ItemView.extend({

    template: _.template('Hi, I\'m a view! Foo is: <%= foo %>'),

    modelEvents: {
        'change': 'onChange'
    },

    onChange: function() {
        alert('change!');
    }
});

var Model = Backbone.Model.extend({});

app.addInitializer(function() {
    var m = new Model({foo: 'bar'});
    var myView = new MyView({
        model: m
    });

    app.main.show(myView);
    myView.close();
    app.main.show(myView);

    m.set({foo: 'baz'});

});

$(document).ready(function(){
    app.start();
});

A: If I understand your question right, there are multiple open github issues about this.
For example:
https://github.com/marionettejs/backbone.marionette/pull/654
https://github.com/marionettejs/backbone.marionette/issues/622
Last time I checked, Derick (the creator of Marionette) didn't feel like reusing closed views should be something regions should do.
So you could

*

*simply create a new view and show that one

*manually call delegateEvents - but there was an issue with multiple event bindings that I can't remember right now, so be careful about that one (not at work right now, so can't take a peek at the code, sorry)

*write your own region manager

*or wait and see if Derick will merge one of the pull requests

A: a couple of points:

*

*You do not need to call myView.close() Marionette Region will take care of that when you show another view

*Marionette.Region will not replace the same view with itself. It will just skip the redundant procedure if you want to test this correctly you need 2 views

*If you want a change in model to invoke render you must explicitly write it

I altered the jsfiddle with the following things:

*

*added myView1 and myView2

*removed explicit call to myView.close

*added a call for this.render() from the onChange function

Here is the corrected jsfiddle http://jsfiddle.net/4DCeY/1/ :
app.addInitializer(function() {
   var m = new Model({foo: 'bar'});
   var myView1 = new MyView({
      model: m
   });
   var myView2 = new MyView({
      model: m
   });

   app.main.show(myView1);
   app.main.show(myView2);

   m.set({foo: 'baz'});

});

And:
onChange: function() {
    alert('change!');
    this.render();
}


text:
Q: How to disable ripple/splash effect in NavigationRail destination icons? The stuff I tried:

*

*Wrapping the entire NavigationRail widget with Theme widget and passing in ThemeData where splashColor, highlightColor, hoverColor, hintColor all were set to Colors.transparent.

Although this does seem to take away the initial "splash", but the "ripple" effect is still prevalent (specially onLongPress).
       Theme(
            data : ThemeData(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent
            ),
            child: NavigationRail(
              selectedIndex: _selectedIndex,
              onDestinationSelected: (int index) {
                setState(() {
                  _selectedIndex = index;
                });
              },
              labelType: NavigationRailLabelType.selected,
              destinations: [
                NavigationRailDestination(
                  icon: Icon(Icons.favorite_border),
                  selectedIcon: Icon(Icons.favorite),
                  label: Text('First'),
                ),
                NavigationRailDestination(
                  icon: Icon(Icons.bookmark_border),
                  selectedIcon: Icon(Icons.book),
                  label: Text('Second'),
                ),
                NavigationRailDestination(
                  icon: Icon(Icons.star_border),
                  selectedIcon: Icon(Icons.star),
                  label: Text('Third'),
                ),
              ],
            ),
          )

*Wrapping NavigationRail with Semantics and setting excludeSemantics as true or just wrapping it within ExcludeSemantics widget

PS: I don't want to override the entire ThemeData from MaterialApp root although I don't see anything in NavigationRailThemeData class that references this property
PPS: There is a class derived from ColorScheme class in NavigationRail.dart file (towards the end) that takes in a Semantics widget which has all of the properties that need to be disabled, namely the InkResponse widget that defines the color, shape and radius of the splash/ripple
NavigationRail.dart
Here is the sample code that flutter.dev provides for copy/paste convenience (works very well in dartpad.dev)
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: <Widget>[
          Theme(
            data : ThemeData(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent
            ),
            child: NavigationRail(
              selectedIndex: _selectedIndex,
              onDestinationSelected: (int index) {
                setState(() {
                  _selectedIndex = index;
                });
              },
              labelType: NavigationRailLabelType.selected,
              destinations: [
                NavigationRailDestination(
                  icon: Icon(Icons.favorite_border),
                  selectedIcon: Icon(Icons.favorite),
                  label: Text('First'),
                ),
                NavigationRailDestination(
                  icon: Icon(Icons.bookmark_border),
                  selectedIcon: Icon(Icons.book),
                  label: Text('Second'),
                ),
                NavigationRailDestination(
                  icon: Icon(Icons.star_border),
                  selectedIcon: Icon(Icons.star),
                  label: Text('Third'),
                ),
              ],
            ),
          ),
          VerticalDivider(thickness: 1, width: 1),
          // This is the main content.
          Expanded(
            child: Center(
              child: Text('selectedIndex: $_selectedIndex'),
            ),
          )
        ],
      ),
    );
  }
}

A: This worked for me:
Theme(
  data: ThemeData(
     highlightColor: Colors.transparent,
     splashFactory: NoSplash.splashFactory,
  ),
  child: NavigationRail(...)

A: this works for me:
Theme(
  data: ThemeData(
    highlightColor: Colors.transparent,
    colorScheme: ColorScheme.light(primary: navigationRailColor)
  ),
  child: NavigationRail(...)

where navigationRailColor is background color of your navigation rail

A: Just add splashFactory: NoSplash.splashFactory to your theme data.


text:
Q: Where to write phpDoc? Interface or class Where should I write phpDoc? Upon interface in interface file or upon class that implements the interface?
I am a bit sad that I can't write return types and types of params before param in methods. In PHP I have to do that in phpDoc, but where should I write this?

A: I would write the docblock in the interface. If there is something specific for some class, you could write docblock for it.
You can specify argument types, see http://php.net/manual/en/language.oop5.typehinting.php


text:
Q: Два условия в JOIN запросе Есть таблицы:
product
id
1

product_property
id
1
2

product_has_property
id property_id product_id
1 1 1
2 2 1

Такой запрос срабатывает нормально:
SELECT "product".* FROM "product"
LEFT JOIN "product_has_property" "hp" ON "product"."id" = "hp"."product_id"
WHERE ("hp"."property_id"='1')

Выводится продукт со свойством 1.
Но такой запрос не срабатывает, не выводит ничего:
SELECT "product".* FROM "product"
LEFT JOIN "product_has_property" "hp" ON "product"."id" = "hp"."product_id"
WHERE ("hp"."property_id"='1') AND ("hp"."property_id"='2')

Объясните, пожалуйста, в чём проблема, по логике вроде норм? И как правильно построить запрос, чтобы выводить продукт по двум свойствам?

A: Вы в условии пишите:
WHERE ("hp"."property_id"='1') AND ("hp"."property_id"='2')

т.е. у Вас"hp"."property_id" должно быть равно и 1 и 2 одновременно. Естественно, что такого не получится.
Вам нужно OR:
WHERE ("hp"."property_id"='1') OR ("hp"."property_id"='2')

Или же IN:
WHERE "hp"."property_id" IN ('1', '2')


text:
Q: Repl showing error: object async is not a member of package scala on import I am using scala 2.11.7 Repl (ubuntu) when trying to do this import I am getting :
scala> import scala.async.Async._
<console>:18: error: object async is not a member of package scala
       import scala.async.Async._
                    ^

how can I fix that ?

A: scala-async is not part of Scala standard library. You need to import the module in your project.
If you use sbt, you can add the following to your build file.

libraryDependencies += "org.scala-lang.modules" %% "scala-async" %
  "0.9.5"

Check out this PR about the lack of information about this.
Hope this helps!

A: Use the following command to load the jar into classpath,
scala -classpath jarname.jar


text:
Q: How to only keep the columns with same names between two data frames? I have two data frames like the following:
a<-c(1,3,4,5,6,8)
b<-c(2,3,4,2,6,7)
c<-c(2,5,6,3,5,6)
df1<-data.frame(a,b,c)
d<-c(3,4,5,6,7,8)
e<-c(1,2,3,2,1,1)
c<-c(1,3,4,5,6,2)
df2<-data.frame(d,e,c)

> df1
  a b c
1 1 2 2
2 3 3 5
3 4 4 6
4 5 2 3
5 6 6 5
6 8 7 6
> df2
  d e c
1 3 1 1
2 4 2 3
3 5 3 4
4 6 2 5
5 7 1 6
6 8 1 2

I want combine the two data frames,and only keep the columns with the same names. The final data frame should like this:
> df3
  c1 c2
1  2  1
2  5  3
3  6  4
4  3  5
5  5  6
6  6  2

My real data frames have hundreds columns,so I need codes do this job. Can  anyone help me?

A: Find out which names belong to both dataframes and then bind them:
eqnames <- names(df1)[names(df1) %in% names(df2)]

df3 <- cbind(df1[eqnames], df2[eqnames])

You can then rename the columns:
names(df3) <- paste0(names(df3), 1:ncol(df3))

Resulting in:
> df3
  c1 c2
1  2  1
2  5  3
3  6  4
4  3  5
5  5  6
6  6  2


text:
Q: Booting Windows from GRUB rescue I tried installed Xubuntu via YUMI and I restarted my PC – the GUI for YUMI came up and I tried to carry on the installation by tabbing down to 'Linux Distributions' and there was nothing ahead but just to go back. From here I'm stuck.
I've tried booting Windows using GRUB, but I tried:

*

*ls (hd0)

*ls (hd0,0), etc.

and I just carry on getting 'Unknown filesystem type'.
There is only one (fd0) which I don't get that error, and I get a read error message.
I tried installing using a partition on my hard drive, and multi-booting side by side with Windows. So Windows is still installed, but I can't seem to find anywhere to boot it. On the boot menu (F11 on startup) I get my main hard drive and my external hard drive.
I'm lost on how to get back into Windows – I don't have the installation disk, and, additionally, my DVD drive isn't fully functional. The only thing I have is a laptop and external hard drive, which I can think I can use to my advantage.

A: You can borrow your friend PC with windows installed and create Windows Usb Recovery-Drive (http://windows.microsoft.com/en-us/windows-8/create-usb-recovery-drive).


text:
Q: Adding cells to existing PDF via FPDI class I am trying to add a cell to an existing PDF, but unfortunately the document is a scan, which interprets it as one layer - a photo - I think so.
When adding a cell to such a file, I only have borderless text and no cell fill color on the visible layer of the document.
Am I in any way controlling the layers of the file in such a way that the cell being added is always the top layer and is fully visible?
Method to get existing PDF:
protected function getOldPDF()
{
    $pdf = new Fpdi();
    $pdf->SetCreator('Test');
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->SetMargins(0, 0);

    $numPages = $pdf->setSourceFile($this->filePath);

    for($pageNum = 1; $pageNum <= $numPages; $pageNum++) {
        $tpl = $pdf->importPage($pageNum);
        $pdf->AddPage();
        $pdf->useTemplate($tpl);
    }

    return $pdf;
}

I add cells with TCPDF::MultiCell()


text:
Q: iOS 11 Swift 4 Adding ChildViewController to UISCrollView doesn't take full height I'm trying to make a snapchat like layout for my app.
I have a main viewcontroller with a scrollview. I add 3 viewcontrollers as children of the scrollview.
everything works fine on iOS 10 on a iPhone 5C but on iOS 11 on a iPhone 6S, the child view controller doesn't take the full height

The orange part is the child viewcontroller and the blue part is the scrollview
Here's my main VC code :
    let trendView = TrendViewController(nibName: "TrendViewController", bundle: Bundle.main)
    let homeView = HomeViewController(nibName: "HomeViewController", bundle: Bundle.main)
    let searchView = SearchViewController(nibName: "SearchViewController", bundle: Bundle.main)

    trendView.view.translatesAutoresizingMaskIntoConstraints = false
    homeView.view.translatesAutoresizingMaskIntoConstraints = false
    searchView.view.translatesAutoresizingMaskIntoConstraints = false

    self.addChildViewController(trendView)
    self.mainScrollView.addSubview(trendView.view)

    trendView.didMove(toParentViewController: self)

    self.addChildViewController(homeView)
    self.mainScrollView.addSubview(homeView.view)
    homeView.didMove(toParentViewController: self)

    self.addChildViewController(searchView)
    self.mainScrollView.addSubview(searchView.view)
    searchView.didMove(toParentViewController: self)

    var homeFrame = homeView.view.frame
    homeFrame.origin.x = self.view.frame.width
    homeView.view.frame = homeFrame

    var searchFrame = searchView.view.frame
    searchFrame.origin.x = self.view.frame.width * 2
    searchView.view.frame = searchFrame

    self.mainScrollView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height)
    self.mainScrollView.contentOffset = CGPoint(x: self.view.frame.width, y: 0)

I loaded an old project which has not the safe area in it and I don't have the problem ... don't know if there's a link with this problem
Thanks for any help

A: I know i didn't assign any height but in all the examples i found, they never assigned an height to the child vc views.
I've just added these lines :
trendView.view.leadingAnchor.constraint(equalTo: self.mainScrollView.leadingAnchor).isActive = true
        trendView.view.topAnchor.constraint(equalTo: self.mainScrollView.topAnchor).isActive = true
        trendView.view.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        trendView.view.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true

        homeView.view.leadingAnchor.constraint(equalTo: trendView.view.trailingAnchor).isActive = true
        homeView.view.topAnchor.constraint(equalTo: self.mainScrollView.topAnchor).isActive = true
        homeView.view.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        homeView.view.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true

        searchView.view.leadingAnchor.constraint(equalTo: homeView.view.trailingAnchor).isActive = true
        searchView.view.topAnchor.constraint(equalTo: self.mainScrollView.topAnchor).isActive = true
        searchView.view.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
        searchView.view.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true

And now it works :)
Thanks


text:
Q: JS queryCommandState("superscript") always return false document.queryCommandState("superscript"); //always return false
document.queryCommandState("bold"); // works fine

how to detect sub or sup in contentEditable element?

A: I know I'm rather late to this, but just for documentation purpose I thought I would reply to it:
This has most likely to do with the styling of the <sub />/<sup /> element.
In the example by @tim-down the default style is being used. I updated the fiddle (http://jsfiddle.net/alarie/vzxh3818/) to use some styles and then queryCommandState will return false. (In this case it's actually the vertical-align: baseline; property that breaks it)
The spec actually contains this note about how the state is to be determined from the effective command value:

NOTE [effective command value] is logically somewhat like CSS computed or resolved values,
  and in fact for most commands it's identical to CSS resolved values
  (see the end of the algorithm). We need a separate concept for some
  commands where we can't rely on CSS for some reason: createLink and
  unlink aren't CSS-related at all, backColor and hiliteColor need
  special treatment because background-color isn't an inherited
  property, subscript and superscript rely on <sub>/<sup> instead of CSS
  vertical-align, and strikethrough and underline don't map to unique
  CSS properties.
Source: https://w3c.github.io/editing/execCommand.html#assorted-inline-formatting-command-algorithms

And here is the actual algorithm for superscript/subscript (from that same spec):

*

*Let affected by subscript
  and affected by superscript be two boolean variables, both initially
  false.

*While node is an inline node:

NOTE Firefox 6.0a2 ignores
    vertical-align for this purpose, and only cares about  and
    tags themselves. Opera 11.11 is similar, and in fact behaves like that
    even for commands like bold. The spec originally followed Chrome 14
    dev, mainly because WebKit itself will produce spans with
    vertical-align sub or super, and we want to handle them correctly.
    However, Ryosuke informs me that WebKit's behavior here is viewed as a
    bug, so I changed it to match Gecko/Opera.

If node is a sub, set affected by subscript to true. <- this is where chrome/webkit behaves incorrectly

*Otherwise, if node is a sup, set affected by superscript to true. Set
  node to its parent. If affected by subscript and affected by
  superscript are both true, return the string "mixed". If affected by
  subscript is true, return "subscript". If affected by superscript is
  true, return "superscript". Return null.

So the solution as of now would be 1) don't fiddle with the style, or rather 2) make the check yourself.


text:
Q: Undo / Redo Bitmap is not properly working I have been stuck on this for a few days now and it's really beyond me why I can't get something so simple to work. I have a small drawing applicaiton, quite similiar to the Android FingerPaint demo, but I am saving each Bitmap after a drawing happens. This is because I plan to add a fill tool to my application later, and it's easier just to load the newly filled bitmap onto the canvas, instead of figuring out how to save the fill as a stroke to re-draw onto the canvas.
The drawing works great - the problem is, I can't undo and redo. I have tried with the code below, but nothing gets undone or redone. In theory, on undo, the mBitmapsDrawn should remove it's most recent Bitmap and push that onto the mBitmapsUndone stack, and then the method loadSurfaceBitmap() is called to draw the Bitmap that was saved before the one we just undid.
For redo, the mBitmapsUndone stack should pop the top Bitmap and push it back into mBitmapsDrawn, to then be re-loaded onto the Canvas by loadSurfaceBitmap().
When clicking redo/undo, no changes to the visual canvas happen, but the sizes of the data structures change (since I have log statemenets checking before and after, and they decrease/increase in size. So I think my problem is in the actual rendering of the latest bitmap in mBitmapsDrawn after a redo/undo happens.
private Stack<Bitmap> mBitmapsDrawn = new Stack<>();
private Stack<Bitmap> mBitmapsUndone = new Stack<>();

protected void touchStart(float x, float y) {

        mBitmapsUndone.clear();

        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
        onDraw();
    }

    protected void touchMove(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;
            onDraw();
        }
    }

    protected void touchUp() {
        mPath.lineTo(mX, mY);

        // Add path to list of paths to draw
        onDraw();
        mBitmapsDrawn.push(mBitmap);
        loadSurfaceBitmap();

        // Kill this so we don't double draw
        mPath = new Path();

        mPaint = new Paint(mPaint);

        mIsDrawing = false;
    }

    protected void onDraw() {
        if (mCanvas == null) {
            return;
        }

        mCanvas.drawPath(mPath, mPaint);
    }

    protected void loadSurfaceBitmap() {
        if (mBitmapsDrawn.size() != 0) {
              mBitmap = mBitmapsDrawn.peek();
        } else {
              mBitmap = mBgBitmap;
        }
        Canvas surfaceCanvas = mSurfaceHolder.lockCanvas();
        surfaceCanvas.drawBitmap(mBitmap, 0, 0, null);
        mSurfaceHolder.unlockCanvasAndPost(surfaceCanvas);
    }

    protected void undo() {
        int undoSize = mBitmapsUndone.size();
        int drawnSize = mBitmapsDrawn.size();
        if (drawnSize > 0) {
            Bitmap removedBitmap = mBitmapsDrawn.pop();
            mBitmapsUndone.push(removedBitmap);
            loadSurfaceBitmap();
        }
    }

protected void redo() {
        int undoSize = mBitmapsUndone.size();
        int pathsSize = mBitmapsDrawn.size();
        if (undoSize > 0) {
            Bitmap mostRecentUndo = mBitmapsUndone.pop();
            mBitmapsDrawn.push(mostRecentUndo);
            loadSurfaceBitmap();
        }
    }

TLDR: I'm having issues popping a stack / adding to an ArrayList when undo'ing / redo'ing in my application, where I should be changing the bitmap that is loaded on the surface, but it never happens.
Edit: Updated code per the answer, still no luck. Redo doesn't change the visual bitmap on the surface.

A: If your drawing works fine it doesn't seem like there's a rendering problem - it's all calling loadSurfaceBitmap() the same way, right? I don't know if handling a touch event makes a difference and if you need to call invalidate() otherwise - I've never poked at surface canvases like this.
Your undo code is a little strange though
Bitmap removedBitmap = mBitmapsUndone.remove(drawnSize - 1);
mPathsUndone.push(removedBitmap);
loadSurfaceBitmap();

You're removing a bitmap from your Undone stack when you should be removing it from your Drawn list - I'm assuming that's why you're doing remove(size - 1) instead of just pop(), because you meant to remove from the List instead of the Stack (why not just use two Stacks anyway?).
Then you place it onto something called mPathsUndone which is maybe a typo from renaming Paths to Bitmaps for the question? If so your undo code is removing a bitmap from the undo stack, then putting it back on top - otherwise it's going somewhere mysterious. (You're also using the size of the drawn list to get an index for the undo stack so that will cause big problems too)
Your redo code looks fine to me, I'm guessing the only problem is that your undo code wasn't actually adding anything to its stack, so there's nothing to redo. I'm guessing this might fix it:
protected void undo() {
    int undoSize = mBitmapsUndone.size();
    int drawnSize = mBitmapsDrawn.size();
    if (drawnSize > 0) {
        Bitmap removedBitmap = mBitmapsDrawn.remove(drawnSize - 1);
        mBitmapsUndone.push(removedBitmap);
        loadSurfaceBitmap();
    }
}

I feel like using stacks for both would be more intuitive since it's a nice pop one, push the other flow, but that's up to you!

edit here's some code updating the file you posted, something like this should work:
protected void onDraw() {
    if (mCanvas == null) {
        return;
    }
    // a new drawing event needs a new bitmap layer to draw it on,
    // starting with the contents of the current layer
    mBitmap = mBitmap.copy(mBitmap.getConfig(), true);
    // we also need a canvas for the new bitmap so we can draw on it
    mCanvas = new Canvas(mBitmap);

    mCanvas.drawPath(mPath, mFgPaint);
}

Personally I'd probably move the "add this bitmap to mBitmapsDrawn" code here too, as well as the "draw the current bitmap to the surface" code - you're doing those in touchUp but I feel like they're more directly related to the action of drawing, and touchUp is more about finalising a touch gesture and initiating the draw call. Up to you!
Here's how I'd probably organise this, if it helps. Since every draw event creates a new bitmap, you don't need to keep a reference to a bitmap's Canvas - you'll have to create a new one anyway. I'd do the rest this way:
getCurrentBitmap() {
    return the top of mBitmapsDrawn, or if empty, the background bitmap
}

drawCurrentBitmap() {
    calls getCurrentBitmap(), draws it to the Surface
}

undo() {
    pops a bitmap off Drawn and pushes onto Undo, calls drawCurrentBitmap()
}

redo() {
    pops a bitmap off Undo and pushes onto Drawn, calls drawCurrentBitmap()
}

drawPath() {
    call getCurrentBitmap to get a source image
    create a new bitmap from that
    create a canvas for it and draw to it
    push the bitmap onto Drawn
    clear Undo
    call drawCurrentBitmap
}

So everything's really about manipulating the drawn and undo stacks, and every time the drawn one changes, you call a function that displays the image on top of it. And having a getCurrentBitmap function puts that logic in one place, so everything that updates the stack doesn't also need to worry about updating mBitmap with the appropriate value.
I'll also say, storing bitmaps like this works fine, but it's pretty inefficient - your memory usage could start to pile up quickly! Since you're doing drawing operations, you might want to think about storing representations of those instead, so you can get the "current" image by replaying all the past draw operations in order.
You could get fancy and cache a bitmap of the result of all but the most recent operations, and replay the most recent ones on top of that to make redrawing faster - but you'd still have all those operations in your history, almost infinite undo. Just something to consider maybe!


text:
Q: How to to iterate through a specific time range in a logfile? For example:
[2017-04-14 03:56:22,085109]
If this is the time where event A happens, I want to go 15 minutes before this line in the logfile which will have thousands of line and I want to iterate through everyline in that period and look for specific keywords. Every line in the logfile has the time stamp with the same format.

A: You can filter the desired lines with a start and end time.
main.py
from datetime import datetime, timedelta

event_time = datetime.strptime('2017-04-14 03:56:22,085109', '%Y-%m-%d %X,%f')
event_start = event_time - timedelta(minutes=15)

def line_date(line):
    return datetime.strptime(line[1:27], '%Y-%m-%d %X,%f')

with open('example.log', 'r') as myfile:
    lines = filter(lambda x: event_start <= line_date(x) <= event_time,
                   myfile.readlines())

print(lines)

example.log
[2017-04-13 03:56:22,085109] My old log
[2017-04-14 03:55:22,085109] My log in less than 15 minutes ago
[2017-04-14 03:56:22,085109] My important event
[2017-04-14 03:57:22,085109] Log after my important event

But I recommend you to use python3 (instead of python2). filter returns an iterator, instead of the full list.


text:
Q: Sendgrid on Google Compute Engine from port 465 or 587 I'm working with a rails 4 app and am trying to send email via SendGrid. I have the app running from a GCE instance.
After reading this google post about sending email through sendgrid, I noticed that they only use port 2525. I would like to connect via port 465 (or 587) because after reading this sendgrid post I learned that SendGrid only allows SSL connections via this port. It also recommends port 587 to avoid any rate limiting that your server host may apply.
Is there a way to use a port other than 2525 on a GCE instance?
Google Compute Engine does not allow outbound connections on ports 25, 465,
and 587 but you can still set up your instances to send mail through ports 587
and 465 using servers provided through partner services, such as SendGrid.

Thanks.

A: As far as I know, GCE only supports 2525.
TLS should work on port 2525. TLS is more frequently updated and has (so far) had fewer severe security incidents like POODLE, so TLS should be preferred.
GCE won't rate limit you on port 2525 in any particular way.


text:
Q: Axis with log scale, how to include tick for 0? I need to have log scale on y-axis of my graph. Since log scale cannot include 0 value in domain, I am having the lower limit of the domain to be 1. This is causing the ticks on the axis to start at 1. How do I get the ticks to start from 0?
var yScale_for_axis = d3.scaleLog().domain([1,d3.max(vals)]).range ([height,0]);

g.append("g")
  .call(d3.axisLeft(yScale_for_axis).tickFormat( d3.format(".1e")))

I need a tick for 0 because the data I need to plot includes 0. I am yet to figure how to accomodate plotting the 0 values by bypassing the log sclae somehow. But before that I need the 0 tick represented on the axis.

A: Instead of a regular log scale (d3.scaleLog()), use a symlog scale (d3.scaleSymlog()), which allows zero in the domain.
Here is a demo with a regular, log scale and zero in the domain (it will fail, nothing will show up):

const svg = d3.select("svg")
const scale = d3.scaleLog()
  .domain([0, 1000])
  .range([20, 480])
const axis = d3.axisBottom(scale)(svg.append("g").attr("transform", "translate(0,50)"))
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="500" height="100"></svg>

Now the same code with d3.scaleSymlog():

const svg = d3.select("svg")
const scale = d3.scaleSymlog()
  .domain([0, 1000])
  .range([20, 480])
const axis = d3.axisBottom(scale)(svg.append("g").attr("transform", "translate(0,50)"))
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="500" height="100"></svg>


text:
Q: How to change the default --color preference for "ls' on Windows? I'm using ls (from Msys) on Windows. By default, ls doesn't colour-code directories and archives, but that's something I want. I'm tired of typing "ls -C" and "ls --color". Is there any way apart from setting up a bash script that will let me do this. (Remember, I'm on Windows)

A: doskey ls=ls --color $*

doskey is built-in, even!
I have a startup .bat file that acts as sort-of a .bashrc, and throw all my aliases in there, as well as having a small Python script to manage them more easily. cmd is really very bearable with a few additional tools (Cygwin goes a long way, just add its \bin to your PATH)

To apply aliases automatically with each new instance of cmd, create a .bat file, for example at %USERPROFILE%\aliases.bat with this content:
@ECHO OFF
doskey ls=ls --color $*

Then, using regedit, locate HKEY_CURRENT_USER\Software\Microsoft\Command Processor\
and add a String Value named Autorun, with Value data set to: %USERPROFILE%\aliases.bat

A: Instead of typing ls --color, you could define a bash alias:
alias ls='ls --color'

This would produce ls --color each time you write ls.


text:
Q: Any way to fix screen's mishandling of line wrap? (Maybe only Terminal.app) I'm having an issue using screen and Terminal.app.  If I get a bash prompt at the bottom of the screen and I keep typing until the line wraps to the next line, I see the next line, but I do not see the line above this one change.
Here's a visual way of illustrating my problem.  The | represents the right hand side of the terminal.
Before.  My cursor is after the third 'example' and I'm about to type 'example' a forth time:
$ asdf                        |
bash: asdf: command not found |
$ example example example     |

After.  Note how after wrapping, the screen did not scroll, but instead 'ate' the line I was on and began fresh:
$ asdf                        |
bash: asdf: command not found |
ple                           |

What I expected (and what happens without the use of screen) is that the entire screen scrolls down one after the wrap.
bash: asdf: command not found |
$ example example example exam|
ple                           |

Finally, this what happens if I move the cursor on the wrapped line to the beginning of the command line, it eats the previous line:
$ asdf                        |
$ example example example exam|
ple                           |

Any idea what is going on?

A: Success! I tried the suggestion from here:
https://serverfault.com/questions/272818/screen-not-dropping-down-a-line
which is to add:
termcapinfo xterm* ti@:te@

to your .screenrc and restart screen. This changes screen's scrollback behavior to something probably better for my average use case (eg, I can use Terminal's scrollback as long as I stay in the same window), in addition to fixing OP's problem.
Also, I can confirm the problem in 10.7's Terminal.app.

A: It could be readline's 'horizontal-scroll-mode'.  Run the following command:
bind 'set horizontal-scroll-mode off'

and see if your symptoms change.  If so, you can set that in ~/.inputrc

A: Go into terminal settings and change the "Declare terminal as:" setting from "xterm-color" to just "xterm". That fixed it for me (but also has the consequence of turning off altscreen :( )


text:
Q: How to implement json format logs in python I have a below piece of code for python logging and would want to convert the logs into json format for better accessibility of information. How can I convert them into JSON format?
import os
import logging

log_fmt = ("%(asctime)-s %(levelname)-s %(message)s")

logger = logging.getLogger()
logger.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))

logger.info(f"this is a test")

And the output looks like "2022-04-20 17:40:31,332 INFO this is a test"
How can I format this into a json object so I can access by keys?
Desired output:
{
 "time": "2022-04-20 17:40:31,332",
 "level": "INFO",
 "message": "this is a test"
}

A: You could use the Python JSON Logger
But if you don't want to, or can't do that, then your log format string should be...
log_fmt = ("{\"time\": %(asctime)-s, \"level\": %(levelname)-s, \"message\": %(message)s},")

You'll end up with an extra comma at the end of the log file that you can programatically remove later. Or, you can do this if you want the comma at the top of the file...
log_fmt = (",{\"time\": %(asctime)-s, \"level\": %(levelname)-s, \"message\": %(message)s}")

But the json will look better in an editor with the comma at the end of every line.
If you provide a mechanism for users to download, or otherwise access log files, then you can do the trailing comma cleanup there, before you send the log file to the user.


text:
Q: Continuously Subtracting value with some conditions Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time     Standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39
 1330        01866       3        H1        72           41
 1330        01867       4                  56           39
 1330        01868       5        H3        50           39
 1330        01869       6        H1        43           41
 1330        01870       7                  39           40
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

Hello everyone, this problem is stuck in my head in the past few weeks and i decide to ask now, this is not that simple for me. Im going to calculate the process standard time.
Here is the story, i did this one manually until now, the condition is :
Code start with H3 or A3, start time is 78
Other code or empty data, start time is 68
We calculate standard per Man.No, for example, at Man.No = 1330, sequence is from 1 until 7, for sequence number 7 at Man.No 1330, the code is blank, the standard will be 68 (FYI : The sequence number is varuious, it could be 7, 12, 8, or maybe 2, depends on the situation)
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time   Standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39
 1330        01866       3        H1        72           41
 1330        01867       4                  56           39
 1330        01868       5        H3        50           39
 1330        01869       6        H1        43           41
 1330        01870       7                  39           40             68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

After that, to calculate the sequence number 6 with H1 code which have to start with 68', we have to calculate it with this formula :
advance standard (68)+(45-(Average of Process2Time at current Man.No)) so it will be (68)+(45-((43+39+41+39+39+41+40)/7))) = 68+(45-40.3) = 68+4.7 = 72.7
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time     Standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39
 1330        01866       3        H1        72           41
 1330        01867       4                  56           39
 1330        01868       5        H3        50           39
 1330        01869       6        H1        43           41           72.7
 1330        01870       7                  39           40           68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39

1331        01875       5        H2A       44           38
After that, to calculate the sequence number 5 with H3 code which have to start with 78' as i said before because it need more time (10') to process product, we have to calculate it with this formula : advance standard (72.7)+(45-(Average of Process2Time at current Man.No)+10). So it will be : (72.7)+(45-((43+39+41+39+39+41+40)/7)))+10 = 72.7+(45-40.3)+10 = 72.7+4.7+10 = 87.4
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time   Standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39
 1330        01866       3        H1        72           41
 1330        01867       4                  56           39
 1330        01868       5        H3        50           39           87.4
 1330        01869       6        H1        43           41           72.7
 1330        01870       7                  39           40           68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

After that, to calculate the sequence number 4 with blank code which have to start with 68', we have to calculate it with this formula : advance standard (87.4)+(45-(Average of Process2Time at current Man.No)). So it will be : (87.4)+(45-((43+39+41+39+39+41+40)/7)))= 87.4+(45-40.3) = 87.4+4.7 = 92.1
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time   standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39
 1330        01866       3        H1        72           41
 1330        01867       4                  56           39           92.1
 1330        01868       5        H3        50           39           87.4
 1330        01869       6        H1        43           41           72.7
 1330        01870       7                  39           40           68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

continue with sequence 3 with H1 code, so we just need to plus 4,7 which is 92.1+4.7 = 96.8
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time   Standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39
 1330        01866       3        H1        72           41           96.8
 1330        01867       4                  56           39           92.1
 1330        01868       5        H3        50           39           87.4
 1330        01869       6        H1        43           41           72.7
 1330        01870       7                  39           40           68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

after that continue with sequence no 2 with H3 Code, remember, need +10. so it will be 96.8+4.7+10 = 111.5
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time   Standard
 1330        01864       1        H3       113           43
 1330        01865       2        H3        97           39           111.5
 1330        01866       3        H1        72           41          96.8
 1330        01867       4                  56           39          92.1
 1330        01868       5        H3        50           39          87.4
 1330        01869       6        H1        43           41          72.7
 1330        01870       7                  39           40           68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

So finally we go to the first sequence, it will be not add +10 because the sequence 2 is also H3/A3 which need same time to process, so we just need to calculate, 111.5+4.7 = 116.2
Man.No     ProdNumber     Sequence   Code    Process1Time   Process2Time   Standard
 1330        01864       1        H3       113           43           116.2
 1330        01865       2        H3        97           39           111.5
 1330        01866       3        H1        72           41           96.8
 1330        01867       4                  56           39           92.1
 1330        01868       5        H3        50           39           87.4
 1330        01869       6        H1        43           41           72.7
 1330        01870       7                  39           40           68
 1331        01871       1        H2A       64           42
 1331        01872       2        H2A       56           41
 1331        01873       3        H2A       53           41
 1331        01874       4        H2A       49           39
 1331        01875       5        H2A       44           38

Thats all, its so horrible for me, thats why i would like to ask here, and if you think that i explain this matter too complicated, well i dont think so, because this is the simplest way to explain this horrible thing. will be so grateful if someone can help.
Thank you so much!

A: So in order to do this in sql, first you need to come up with a formula for Standard that does not rely on the value of the standard for the next sequence. The first part is simple. If the Code is H3 or A3, you want 78, otherwise you want 68.
The next part of the formula in based on the average. You will want the average of all of the process1 times of the data with the same Man.No. As we move up the sequence, we are adding this average to the original value over and over again. Using your example, for sequence 6, we are adding the average once. For sequence 5, we are adding the average twice, for sequence 4, we add it 3 times. This becomes the average * (the max sequence # - the current sequence number). For the sequence 7, we will be adding the average on 0 times.
This is essentially the whole formula that you are using. Now, we can find these values using this formula in sql. Please note that this code is not tested and does not include your specific information since those details were not included in your question.
Select
    t.ManNum,
    t.ProdNum,
    t.Sequence,
    t.Code,
    t.Process1Time,
    t.Process2Time,
    (Select sum(Process1Time) / sum(1)
        From tabletbl t2
        Where t2.ManNum = t.ManNum
        Group by t2.ManNum)
    * ((Select max(Sequence)
         From tabletbl t2
         Where t2.ManNum = t.ManNum
         Group by t2.ManNum))-t.Sequence)
    + Case When (t.Code = H3 or t.Code = A3) Then 78 else 68 End
    as Standard
From tabletbl t


text:
Q: arraylist received in activity different from the one sent I have database 1 contains all books data (name,id,description , and so on)
and i have another database contains id of books i added to favorite
i get the data in asynctask
first i get all books data from the first database and add them in Arraylist<Book> then i get the ids of favorite books ids from the second database and add them in Arraylist<Integer> and then compare and add a parameter in books to 1 if it's in favourite
    @Override
      protected ArrayList<Book> doInBackground(Void... params) {

        ArrayList<Book> bookList = new ArrayList<>();
        ArrayList<Integer> favlist = new ArrayList<>();
        ArrayList<Integer> downlist = new ArrayList<>();
        try {
          if (mDBAdapter != null) {
          mDBAdapter.createDataBase();
          mDBAdapter.openDataBase();
          bookList = mDBAdapter.selectAllBooks();
        }
        } catch (IOException ioe) {

        throw new Error("Unable to create database");

      }
        if (mAnnotationDBAdapter!=null) {
          favlist = mAnnotationDBAdapter.selectAllFavourite();
        }
        for (int j = 0; j <bookList.size() ; j++) {

          for (int i = 0; i <favlist.size() ; i++) {
            if (bookList.get(j).getId()==favlist.get(i))
              bookList.get(j).setInFavourite(1);
          }

    }
    return bookList;
  }

  @Override
  protected void onPostExecute(ArrayList<Book> books) {
    super.onPostExecute(books);
    if (books != null && books.size() > 0) {
      Intent mainActivityintent = new Intent(mContext, Main2Activity.class);
      mainActivityintent.putExtra(AppConstance.ALL_BOOKS_KEY,books);
      mContext.startActivity(mainActivityintent);
    }
  }

here books list is ok and has infavourite parameter = 1 if the book is in favorite table
but when i receive it in main activity
i got infavourite = 0
 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    PublicMethod.mDBAdapter = new AnnotationDBAdapter(this);

      Intent intent = getIntent();

    if (intent != null) {

      if (intent.hasExtra(AppConstance.ALL_BOOKS_KEY)) {
        mBooks = intent.getParcelableArrayListExtra(AppConstance.ALL_BOOKS_KEY) ;
//here all book have infavourite = 0
      }
    }

A: I think you need to use Intent.putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)


text:
Q: MYSQL update with WHERE SELECT subquery error I have an issue with getting select sub-queries to work on an UPDATE. I'm trying something like the following:
UPDATE foo
   SET bar=bar-1
 WHERE baz=
      (
       SELECT baz
       FROM foo
       WHERE fooID='1'
      )

Where foo is the table name with primary key fooID. bar and baz are of type INT. When executing this I get the following error:
Error: A query failed. You can't specify target table 'foo' for update
in FROM clause

A: From this web article

The reason for this error is that MySQL doesn't allow updates to a table when you are also using that same table in an inner select as your update criteria.
  The article goes on to provide a solution, which is to use a temporary table.

Using this example, your update should be this:
update foo
set bar = bar - 1
where baz in
(
  select baz from
  (
    select baz
    from foo
    where fooID = '1'
  ) as arbitraryTableName
)

A: Because of error 1093 Error 1093 (ER_UPDATE_TABLE_USED) SQLSTATE = HY000.
The work around is to create a temporary table.
CREATE TEMPORARY table foo_bak (SELECT baz from foo WHERE fooID='1');

UPDATE foo
  SET foo.bar=foo.bar-1
WHERE foo.baz =
  (
    SELECT baz
    FROM foo_bak
  );

DROP TABLE foo_bak;

A: In some cases you can also take advantage of the MySQL variable. e.g.:
SET @id1 = (SELECT id FROM foo WHERE name = 'parent');
UPDATE foo SET parent_id = @id1 WHERE name = 'emails';

A: So far as I know, when updating a table, Mysql locks it in order to do a safe update. You cannot select data and update the same table as you're trying.
Those texts should help you

*

*http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

*http://verysimple.com/2011/03/30/mysql-cant-specify-target-table-for-update-in-from-clause/


text:
Q: Get SUM of value in Array I want to get sum of the values in array. With this code when I console.log(this.totalCount) I only get like this .
How to get sum of all the values?
CODE
return this.http
      .post('/media', reqBody)
      .pipe(
        map((res:IStatisticReponse) => res.data)
      ).subscribe(res => {
        this.items = res.map((r: any, i: number) => {
          r.color = this.colors[i]
          return r;
        });

        this.legendProgress = this.items.map(item => {
          return { label: item.label, color: item.color };
        });
        this.totalCount = this.items.map((item)=> item.mediaShare);
        console.log(this.totalCount)

        this.isLoading = false;
      });

A: In your current implementation you basically iterate over all items within the items array and return the objects mediaShare property.
this.totalCount = this.items.map((item)=> item.mediaShare); // => ["123", "345", ...]

What you actually want to do is to get the sum of all these values.
Considering the values inside totalCount are now a collection of strings that seem to hold a numeric value, you can do the following:
this.totalCount = this.items.map((item)=> Number.parseInt(item.mediaShare)).reduce((acc, curr) => acc + curr, 0); // Or `parseFloat`, if your values might be of type float

Read up on Array.prototype.reduce to learn how it behaves.

A: try this
let totalVal;
for(let i = 0; i < this.totalCount.length; i++) {
  totalVal = totalVal + parseInt(this.totalCount[i]);
}


text:
Q: C# wpf how to transfer data from datagrid to excel I've got little problem, with transferring data via copy and paste from datagrid to excel.
Especially from my user control, which I'm using in one datagrid column. Text columns are okay.
I got this code for copy row.
/// <summary>
/// Method which will copy entire row.
/// </summary>
private void CopyRow(object obj)
{
    var datagrid = obj as System.Windows.Controls.DataGrid;
    var currentRow = datagrid.SelectedIndex + 1;

    Dictionary<ENotifiedTruckFlags, string> transf = new Dictionary<ENotifiedTruckFlags, string>();
    string value = "";

    foreach (var e in _entityEnhancedNotifiedTruck.EFlags)
    {
        switch (e)
        {
            case ENotifiedTruckFlags.CheckRecordHasBreak:
                value = "Ridic má narízenou prestávku";
                break;
            case ENotifiedTruckFlags.CheckWeighingOn:
                value = "Režim kontrolního vážení";
                break;
            case ENotifiedTruckFlags.NoTaraWeighted:
                value = "Chybí tárové vážení";
                break;
            case ENotifiedTruckFlags.SPZProblem:
                value = "Provedte kontrolu SPZ";
                break;
            case ENotifiedTruckFlags.TimeProblem:
                value = "Provedte kontrolu ložné plochy";
                break;
        }
        transf.Add(e, value);
    }

    var myStringBuilder = new StringBuilder();
    foreach (KeyValuePair<ENotifiedTruckFlags, string> pair in transf)
    {
        myStringBuilder.AppendFormat("{0}", pair.Value);
        myStringBuilder.Append("," + " ");
    }

    datagrid.SelectAllCells();
    datagrid.ClipboardCopyMode = DataGridClipboardCopyMode.ExcludeHeader;
    ApplicationCommands.Copy.Execute(null, datagrid);
    string result = (string)Clipboard.GetData(DataFormats.Text);
    datagrid.UnselectAllCells();
    Clipboard.SetText($"{result}\t{myStringBuilder}\t ");
}

Result parameter will result my text columns side to side perfectly, but in my string builder I have my user control and the text from it it give under on new line, but I want to have this particular text adjacent to result, not in new line.
Thanks.


text:
Q: Website screenshots Is there any way of taking a screenshot of a website in PHP, then saving it to a file?

A: Since PHP 5.2.2 it is possible, to capture a website with PHP solely!

imagegrabscreen — Captures the whole screen

<?php
$img = imagegrabscreen();
imagepng($img, 'screenshot.png');
?>

imagegrabwindow - Grabs a window or its client area using a windows handle (HWND property in COM instance)

<?php
$Browser = new COM('InternetExplorer.Application');
$Browserhandle = $Browser->HWND;
$Browser->Visible = true;
$Browser->Fullscreen = true;
$Browser->Navigate('http://www.stackoverflow.com');

while($Browser->Busy){
  com_message_pump(4000);
}

$img = imagegrabwindow($Browserhandle, 0);
$Browser->Quit();
imagepng($img, 'screenshot.png');
?>

Edit: Note, these functions are available on Windows systems ONLY!

A: If you don't want to use any third party tools, I have come across to simple solution that is using Google Page Insight api.
Just need to call it's api with params screenshot=true.
https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=https://stackoverflow.com/&key={your_api_key}&screenshot=true

For mobile site view pass &strategy=mobile in params,
https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=http://stackoverflow.com/&key={your_api_key}&screenshot=true&strategy=mobile

DEMO.

A: There is a lot of options and they all have their pros and cons. Here is list of options ordered by implementation difficulty.
Option 1: Use an API (the easiest)

*

*ApiFlash (based on chrome)

*EvoPDF (has an option for html)

*Grabzit

*...

Pros

*

*Execute Javascript

*Near perfect rendering

*Fast when caching options are correctly used

*Scale is handled by the APIs

*Precise timing, viewport, ...

*Most of the time they offer a free plan

Cons

*

*Not free if you plan to use them a lot

Option 2: Use one of the many available libraries

*

*dom-to-image

*wkhtmltoimage (included in the wkhtmltopdf tool)

*phpwkhtmltopdf

*...

Pros

*

*Conversion is quite fast most of the time

Cons

*

*Bad rendering

*Does not execute javascript

*No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, HTML5 tags...)

*Sometimes not so easy to install

*Complicated to scale

Option 3: Use PhantomJs and maybe a wrapper library

*

*PhantomJs

*php-phantomjs (php wrapper library for PhantomJs)

*...

Pros

*

*Execute Javascript

*Quite fast

Cons

*

*Bad rendering

*PhantomJs has been deprecated and is not maintained anymore.

*No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, HTML5 tags...)

*Complicated to scale

*Not so easy to make it work if there is images to be loaded ...

Option 4: Use Chrome Headless and maybe a wrapper library

*

*Chrome Headless

*chrome-devtools-protocol

*puphpeteer

*...

Pros

*

*Execute Javascript

*Near perfect rendering

Cons

*

*Not so easy to have exactly the wanted result regarding:

*

*page load timing

*proxy integration

*auto scrolling

*...

*Complicated to scale

*Quite slow and even slower if the html contains external links

Disclaimer: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.

A: Well, PhantomJS is a browser that can be easily put on a server and integrate it to php. You can find the code in WDudes. They have included lot more features like specifying the image size, cache, download as a file or display in img src etc.

URL Parameters

*

*Width and Height: screenshot.php?url=google.com&w=1000&h=800

*With cropping:
screenshot.php?url=google.com&w=1000&h=800&clipw=800&cliph=600

*Disable cache and load fresh screesnhot:
screenshot.php?url=google.com&cache=0

*To download the image: screenshot.php?url=google.com&download=true
You can see the tutorial here: Capture Screenshot of a Website using PHP without API

A: cutycapt saves webpages to most image formats(jpg,png..) download it from your synaptic, it works much better than wkhtmltopdf

A: I set up finally using microweber/screen as proposed by @boksiora.
Initially when trying the mentioned link here what I got:
Please download this script from here https://github.com/microweber/screen

I'm on Linux. So if you want to run it, you may adjust my step follow to your environment.
Here are the step I did on my shell on DOCUMENT_ROOT folder:
$ sudo wget https://github.com/microweber/screen/archive/master.zip
$ sudo unzip master.zip
$ sudo mv screen-master screen
$ sudo chmod +x screen/bin/phantomjs
$ sudo yum install fontconfig
$ sudo yum install freetype*
$ cd screen
$ sudo curl -sS https://getcomposer.org/installer | php
$ sudo php composer.phar update
$ cd ..
$ sudo chown -R apache screen
$ sudo chgrp -R www screen
$ sudo service httpd restart

Point your browser to screen/demo/shot.php?url=google.com. When you see the screenshot, you are done. Discussion for more advance setting is available here and here.

A: There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc
The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.
I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.
Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.
// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots

// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');

// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';

// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'

// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!

For e.g. here's a full height screenshot of this very page:
https://api.urlbox.io/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/8f1666d1f4195b1cb84ffa5f992ee18992a2b35e/png?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F757675%2Fwebsite-screenshots-using-php%2F43652083%2343652083&full_page=true

A: LAST EDIT: after 7 years I'm still getting upvotes for this answer, but I guess this one is now much more accurate.

Sure you can, but you'll need to render the page with something.
If you really want to only use php, I suggest you HTMLTOPS, which renders the page and outputs it in a ps file (ghostscript), then, convert it in a .jpg, .png, .pdf.. can be little slower with complex pages (and don't support all the CSS).
Else, you can use wkhtmltopdf to output a html page in pdf, jpg, whatever..
Accept CSS2.0, use the webkit (safari's wrapper) to render the page.. so should be fine.
You have to install it on your server, as well..
UPDATE Now, with new HTML5 and JS feature, is also possible to render the page into a canvas object using JavaScript. Here a nice library to do that: Html2Canvas and here is an implementation by the same author to get a feedback like G+.
Once you have rendered the dom into the canvas, you can then send to the server via ajax and save it as a jpg.
EDIT: You can use the imagemagick tool for transforming pdf to png. My version of wkhtmltopdf does not support images. E.g. convert html.pdf -append html.png.
EDIT: This small shell script gives a simple / but working usage example on linux with php5-cli and the tools mentioned above.
EDIT: i noticed now that the wkhtmltopdf team is working on another project: wkhtmltoimage, that gives you the jpg directly

A: I'm on Windows so I was able to use the imagegrabwindow function after reading the tip on here from stephan.  I added in cropping (to get rid of the Browser header, scroll bars, etc.) and resizing to get a final image.  Here's my code.  Hope that helps someone.

A: You can use simple headless browser like PhantomJS to grab the page.
Also you can use PhantomJS with PHP.
Check out this little php script that do this. Take a look here https://github.com/microweber/screen
And here is the API- http://screen.microweber.com/shot.php?url=https://stackoverflow.com/questions/757675/website-screenshots-using-php

A: I used bluga.  The api allows you to take 100 snapshots a month without paying, but sometimes it uses more than 1 credit for a single page.  I just finished upgrading a drupal module, Bluga WebThumbs to drupal 7 which allows you to print a thumbnail in a template or input filter.
The main advantage to using this api is that it allows you to specify browser dimensions in case you use adaptive css, so I am using it to get renderings for the mobile and tablet layout as well as the regular one.
There are api clients for the following languages:
PHP,
Python,
Ruby,
Java,
.Net C#,
Perl
and Bash (the shell script looks like it requires perl)

A: It all depends on how you wish to take the screenshot.
You could do this via PHP, using a webservice to get the image for you
grabz.it has a webservice to do just this, here's an article showing a simple example of using the service.
http://www.phpbuilder.com/articles/news-reviews/miscellaneous/capture-screenshots-in-php-with-grabzit-120524022959.html

A: There are some ways in which you can achieve this in PHP, but realistically it's better to delegate this to a non-PHP based API which you can build yourself, or you can pay for. Many people have already listed screenshot APIs in the answers, and you can use any of those to achieve this. My own screenshot API is extremely well tested and covers many rendering cases that most APIs don't cover, but for most people, this is overkill, honestly.
My recommendation is to build your own API using Puppeteer, which is the canonical solution nowadays to build screenshot solutions. My service is built on top of Puppeteer and it really works well for most basic use cases.
You can build a serverless Puppeteer solution on AWS or GCP using something like https://www.npmjs.com/package/chrome-aws-lambda, which is an excellent serverless package for Puppeteer that comes pre-loaded with Chromium.

A: You can use https://grabz.it solution.
It's got a PHP API which is very flexible and can be called in different ways such as from a cronjob or a PHP web page.
In order to implement it you will need to first get an app key and secret and download the (free) SDK.
And an example for implementation. First of all initialization:
include("GrabzItClient.class.php");

// Create the GrabzItClient class
// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!
$grabzIt = new GrabzItClient("Sign in to view your Application Key", "Sign in to view your Application Secret");

And screenshoting example:
// To take a image screenshot
$grabzIt->URLToImage("http://www.google.com");
// Or to take a PDF screenshot
$grabzIt->URLToPDF("http://www.google.com");
// Or to convert online videos into animated GIF's
$grabzIt->URLToAnimation("http://www.example.com/video.avi");
// Or to capture table(s)
$grabzIt->URLToTable("http://www.google.com");

Next is the saving.You can use one of the two save methods, Save if publicly accessible callback handle available and SaveTo if not. Check the documentation for details.

A: After a lot for surfing on web I found this.
PPTRAAS > A free tool to capture screenshot by passing your URL as a parameter
They provide multiple options by simply hitting their URL.

*

*Get full page screenshot
https://pptraas.com/screenshot?url={YOU URL HERE}

*Get page screenshot of specific size
https://pptraas.com/screenshot?url={YOU URL HERE}&size=400,400

*One can even convert the page to pdf
https://pptraas.com/pdf?url={YOU URL HERE}

A: Not directly. Software such as Selenium have features like this and can be controlled by PHP but have other dependencys (such as running their java-based server on the computer with the browser you want to screenshot)

A: you can use cutycapt .
kwhtml is deprecated and show page like old browser.

A: I've found this to be the best and easiest tool around: ScreenShotMachine. It's a paid service, but you get 100 free screenshots and you can buy another 2,000 for (about) $20, so it's a pretty good deal. It has a very simple usage, you just use a URL, so I wrote this little script to save a file based on it:
<?php
  $url = file_get_contents("http://api.screenshotmachine.com/?key={mykey}&url=https://stackoverflow.com&size=X");

  $file = fopen("snapshots/stack.jpg", "w+");
  fwrite($file, $url);
  fclose($file);
  die("saved file!");
?>

They have a very good documentation here, so you should definitely take a look.


text:
Q: Fix a badly sized Xorg cursor that is clipped / truncated Symptom:
My cursor looks funny in Pycharm: it's too big; the bottom and right sides have been clipped off:
Cause:
My desktop resolution and orientation appears to be confusing the automatic Xorg cursor size.
System Information:

*

*Windows 7 PC

*3x 2560x1400 monitors (one in portrait orientation)

*terminal access to a OpenSUSE virtual machine using mobaxterm

*running bash

*Running Pycharm with X11 window forwarding

A: Solution:
Set the cursor size explicitly using an environment variable:
export XCURSOR_SIZE=16

Cursor now looks normal:

Note that the environment variable can be set in the ~/.bashrc file, so that it is always set on start-up.
Reference links:

*

*A similar problem is discussed in the Cygwin mailing list

*Archlinux documentation on setting cursor size and theme


text:
Q: jQuery UI dialog passing ID to popup I've been creating a Video Games Website in MCV 3 using Visual Studio and am having trouble figuring out how to pass a ID from my Page to a popup Dialog to display the correct Developer from my Database.
The Page I will put up now is my DeveloperManager Page I use to do basic CRUD and the function I'm trying to do is when I click the delete link to open a dialog asking to confirm said Developer should be deleted and then delete it.
I already have a Page call DeveloperManager/Delete that if I just click at the moment is being pass item.DeveloperID and that brings up the correct Developer and Deletes it when confirmed. But just out of convenience I'd like to Open that Page in a Dialog Box.
As You will see as well I've already managed to open a Dialog when I click the Create New button but that doesn't use a Parameter just opens the page creates a developer and closes it.
Here's the code for the DeveloperManager Page
@model IEnumerable<ReviewSite.Models.Developer>

@{
    ViewBag.Title = "Index";
}

Developers

    @Html.ActionLink("Games","Index","GameManager")
    @Html.ActionLink("Developers","Index","DeveloperManager")
    @Html.ActionLink("Publishers","Index","PublisherManager")
    @Html.ActionLink("Genres","Index","GenreManager")

<button id="createLink">Create New</button>

            Developer Name

            Developer URL

    @foreach (var item in Model)
    {

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

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

                @Html.ActionLink("Edit", "Edit", new { id = item.DeveloperID }, new { id = "editLink" }) |
                @Html.ActionLink("Details", "Details", new { id=item.DeveloperID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.DeveloperID}, new { @class = "deleteLink"})

    }

When I Click Delete it calls this Page into a Dialog
@model ReviewSite.Models.Developer

@{
ViewBag.Title = "Delete";
}

Delete

@Html.ActionLink("Games","Index","GameManager")
@Html.ActionLink("Developers","Index","DeveloperManager")
@Html.ActionLink("Publishers","Index","PublisherManager")
@Html.ActionLink("Genres","Index","GenreManager")

Are you sure you want to delete @Model.DeveloperName?

<fieldset>
<legend>Developer</legend>

Developer Name

    @Html.DisplayFor(model => model.DeveloperName)

DeveloperURL

    @Html.DisplayFor(model => model.DeveloperURL)

</fieldset>
@using (Html.BeginForm()) {

    <input type="submit" value="Delete" /> |
    @Html.ActionLink("Back to List", "Index")

}

A: http://jsfiddle.net/umwMU/6/
Assign the item.DeveloperID to an attribute on the link.
@Html.ActionLink("Delete", "Delete", new { id = item.DeveloperID}, new { @class = "deleteLink", @devid = item.DeveloperID })
Then use that id on the querystring when loading the html for the dialog.
$('.deleteLink').click(function(evt) {
    evt.preventDefault();

    var developerID = $(this).attr("devid");

    var url = '/DeveloperManager/Delete/' + developerID;
    var $deleteDialog = $('#deleteDialog').load(url, function() {
        $deleteDialog.dialog({
            autoOpen: true,
            title: 'Delete Developer',
            modal: true
        });
    });
});


text:
Q: $E = A^C \cap B^C$, is my answer good? Could anyone tell me if my answer is correct regarding this set(complement) question. As to confirm myself that I understand it or not.
$U = \{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15\}$.
$A = \{2,4,6,8,10,12,14\}$,
$B = \{1,2,3,4,5\}$.
Answer i got :
$E = A^C \cap B^C$.
$E = \{1,3,5,7,9,11,13,15\} \cap \{6,7,8,9,10,11,12,13,14,15\}$.
$E = \{9,11,13,15\}.$
Can anyone tell me if my answer is good or not?

A: The general idea is correct, but you made some small mistakes.
$E = A^c \cap B^c$
$E=\{1,3,5,7, \mathbf{9},11,13,15\} \cap \{6,7,8,9,10,11,12,13,14,15\}$
$E=\{\mathbf{7},9,11,13,15\}$


text:
Q: What are some problem books in Single variable calculus? I have finished theory for single variable calculus taught at high school level, and want a book to practice problem solving in the same.  The problem level should be difficult. Also mention some math competitions that include calculus in syllabus (at high school level).
EDIT 01 : The book should not be a tome of thousands of questions, a possible example can be "101 algebra problems by Titu Andresscu". The questions should be math contests style.
Thanks a lot.

A: I think Boris Demidovich's Problems in Mathematical Analysis is a good book if you are going for the problems.
Link and reviews: amazon

A: I think M. Spivak's Calculus could be an excellent source to help settle your theoretical understanding of Calculus, and its set of problems is challenging.
Also, in a more conceptualistic point of view, A Course of Pure Mathematics by G. H. Hardy can be a good approach to understand Calculus made-from-scratch.