text:
Q: Image is not showing on ion-option I need to add images after the brand names inside ion-option.
I have the codes below but they do not work. Can anyone help me?
Note: No error is displayed, only the images are not displayed!
HTML:
    <ion-item>
            <ion-label>Nome da marca</ion-label>

            <ion-select [(ngModel)]="marcasModel" #C (ionChange)="onChangeMarcas(C.value)" multiple="false" cancelText="Cancelar" okText="Concluído">
                <ion-option *ngFor="let marca of marcas" value="{{ marca.id }}">
                    {{ marca.name }} <img src="{{marca.image}}" alt="" width="30px" height="30px">
                </ion-option>
            </ion-select>
        </ion-item>

Model:
this.marcas = [
        { 'id': 1, 'name': 'Fiat', 'image':'http://www.pngmart.com/files/4/Fiat-Logo-PNG-Transparent-Image.png' },
        { 'id': 2, 'name': 'Ford' },
        { 'id': 3, 'name': 'GM Chevrolet' },
        { 'id': 4, 'name': 'Volkswagen' }
    ]


text:
Q: PineScript proper way of comparing previous indicator data? I'm trying to do an indicator on pinescript and I'm pretty much new to the language. This is the code:
study("Tester", overlay = true)

ma = ema(close, 50)

signal = (high[1] > ma[1] and close[1] < ma[1])? true : false

plotshape(signal, location = location.abovebar, style = shape.xcross)

And my expected result is an x every time the upper wick of a candle goes above the 50 period ema but closes below it. I'm getting Xs where I can't seem to find any reason on why the condition triggers.

EDIT
Code adjusted to non-shifted bar:
study("Tester", overlay = true)

ma = ema(close, 50)

signal = (high > ma and close < ma)? true : false

plotshape(signal, location = location.abovebar, style = shape.xcross)

Image of the issue:

A: Thats because you shift your signal by 1 bar, so the signal X is printed on the candle when the condition was met on the previous bar.
if you want to plot X exactly on the candle where the condition was met - don't use history reference operator ([1]).
study("Tester", overlay = true)
ma = ema(close, 50)
plot(ma)
signal = (high > ma and close < ma)? true : false
plotshape(signal, location = location.abovebar, style = shape.xcross)

redpajama_set_name: RedPajamaStackExchange


text:
Q: querySelectorAll for any div within an element I'd expect this to pop up an alert for any div I click inside the section id playGrid, but it does nothing.

JavaScript
document.getElementById("playGrid").querySelectorAll('section div').forEach(function(el){
  el.addEventListener('click', function() {
    alert(this.id);
  });
});

A: I think the problem is that your code runs before the document is fully loaded. To run your code after page is loaded add event listener for 'DOMContentLoaded' event:
document.addEventListener('DOMContentLoaded', function(){
  document.getElementById("playGrid").querySelectorAll('section div').forEach(function(el) {
    el.addEventListener('click', function() {
      alert(this.id);
    });
  });
});

https://codepen.io/mikhailsidorov/pen/BaoPKoX

A: two options add content like so

content

content

content

content

content

or use css by adding a class .content to all your divs :
.content{
height: 10px;
width:10px;
}

A: Something like this should work. Also, make sure your script is being executed after the page loads, not before. Use the defer tag on your


text:
Q: Spring @Transactional Isolation propagation Can the Isolation level be changed between the Same Transaction
I have a usecase where I want either the uncommited data that was persisted using saveAndFlush of SpringDataJpa to be available across different Transactions OR make the Inner Transaction commit the data but should be able to rollback in case of any exception in the outer transaction
This is needed as I want to update a resource and would have an entry in lock table to avoid concurrent updates. The lock table in DB is not getting updated untill the Update transaction is getting completed , hence I want to commit the data to lock table and at the same time should rollback in case of any exceptions during update operation.

*

*Service1  method having @Transactional would call a method of Service2. Service2 have @Transactional(isolation=Isolation.READ_UNCOMMITTED) which in turn will call the repository.

Does the Service2 Isolation of READ_UNCOMMITED will take precedence or the Default one?
Does this Change in Isolation reflect in same Transaction that was propagated from Service1?
Scenario 1:
@Service
class Service1{
@Autowired
Service2 service2;
@Transactional
public void method1(){
Foo foo=new Foo();
foo.setId("f123");
service2.saveValue(foo);
}
}

@Service
@Transactional(isolation=Isolation.READ_UNCOMMITTED)
class Service2{
@Autowired
FooRepository fooRepository;

public void saveValue(Foo value){
fooRepository.saveAndFlush(value);
}
}

public interface FooRepository extends JpaRepository<Foo, String>{
}

Scenario 2:
@Service
class Service1{
@Autowired
Service2 service2;

@Transactional
public void method1(){

Foo foo=new Foo();
foo.setId("f123");
service2.saveValue(foo);

try{
updateOperation()
}catch(Throwable e){   // does Spring @Transactional revert on ERRORS, by default it rollback on RuntimeException and Exception(in case we explicitly mention)?
  service2.deleteByFooId(foo.getId());
  throw e;
}

}

private void updateOperation(){
 /* update logic for resource */- Not a DB update

}

@Service
@Transactional(propagation=Propagation.REQUIRES_NEW)
class Service2{
@Autowired
FooRepository fooRepository;

public void saveValue(Foo value){
fooRepository.saveAndFlush(value);
}

public void delete(String id){
     deleteByFooId(id);
}
}

public interface FooRepository extends JpaRepository<Foo, String>{
}

*Let Thread1 started TX1 and Thread2 started TX2.

Can TX2 access the uncommited data in case TX1 has executed the saveAndFlush but not yet commited to DB(as TX1 is not yet completed)?

*If Isolation cannot be changed once Transaction is initiated

Is there a way using Propagation or Isolation (or any other means) using which the inner transaction can be commited individually but can also rollback in case of any exception in the outer Transaction?
PROPAGATION_REQUIRES_NEW on Service2 method - will commit the data but in case of any exception in Service1 it wont rollback
PROPAGATION_NESTED on Service2 method - will commit data only when Service1 tx will commit
Is there any way to achieve the usecase highlighted in BOLD at the top?

*The solution I am trying now is to have to handle any exception in case of updation and then revert the DB lock operation manually. This is tedious in case we need to track many DB commits and revert the same. For the pseudocode refer Scenario2

A: The scenario 2 where in ..Propagation Require_New ..Is what I have used.  And in case of any runtime exception during the parent  method, I have handled that exception in try catch and reverted the lock which is updated in the DB as part of the new transaction and threw the same exception in catch block so that parent transaction gets reverted too.
This approach will be difficult in case you have many dB states to be reverted by you individually, but for now it suffice


text:
Q: Difference between ul#someid and #someid ul Simple question. What is the difference between ul#someid and #someid ul?

A: The first one selects a
 element that has an id attribute of someid. The second one selects all
 elements that are inside of any element that has an id of someid. The space makes a huge difference.

A: The first is targetting a ul node with the id of someid and the second is targetting a ul which is anywhere in the children nodes of a node with id someid
The first pattern matches:

   ...

and the second pattern matches:

    ...

A: The former selector selects a
 that has the id #someid while the latter looks for an element with id #someid that has a
 as a descendant. The space is called a descendant combinator


text:
Q: python getopt not processing flags as expected I'm trying to parse command line arguments using getopt. It will successfully parse a single argument. When I try to pass multiple arguments, it takes the first flag and leaves everything else in args. Additionally, when I fail to pass arguments with a colon after them in the argument list, the exception doesn't fire.
I have :
def main(argv):
    try:
        opts, args = getopt.getopt(argv,"ns:i:",["num_ratios", "sample=", "iteration="])
    except getopt.GetoptError:
        print ('test.py -s <sampleName -i <iteration>')
        sys.exit(2)
    print (opts)
    print (args)
    for opt, arg in opts:
        if opt == '-n':
            n = arg
        elif opt == '-s':
            sampleName=arg
        elif opt == '-i':
            iteration = arg

if __name__ == "__main__":
    main(sys.argv[1:])

If I then execute:
python calculateRatios.py -n 1 -s wibble

I get
[('-n', '')]
['1', '-s', 'wibble']

which says to me that it's picking up -n as an option but not associating the value 1 with it, then it's stopping. It's not finding further flags as so not assigning values.
When I then execute:
python calculateRatios.py -n 1

my understanding is that the exception should kick off as I've got a colon after the s in the getopt.getopt call. It doesn't, instead I get
[('-n', '')]
['1']

In both of these examples, there's an empty string in opt, that I don't know where it's coming from. Is that the problem? Where's it from? I'm guessing it's something small that I've missed.
I

A: That's expected. You have to put a colon or parameter won't be associated to n option, and n option is just a switch. Arg parsing is desynchronized after that, and since getopt doesn't encounter another option it assumes some other non-option arguments are passed.
Fix it like that.
"n:s:i:",["num_ratios=", "sample=", "iteration="]

Note that the only way you're getting an exception is by passing argument-required argument without argument at the end of the command line, otherwise, other switches/arguments are consumed.
What I did to prevent users from omitting the arguments and desynchronize argument parsing - which is applicable most of the time - is to test that arg doesn't start with - (most arguments don't start by -) like this:
for opt, arg in opts:
    if arg.startswith("-"):
        raise Exception("Argument omitted for {}".format(opt))
    if opt == '-n':
        n = arg
    elif opt == '-s':
        sampleName=arg
    elif opt == '-i':
        iteration = arg

that doesn't work so well if option argument can start with -, but in most case it cannot.


text:
Q: how to check longitude latitude database sql server i have longitude and latitude in geofence table how to check longitude and latitude in database level. if car longitude latitude are in Zone, update geofance column zones = 'car in zone area'
CREATE TRIGGER Tr_CheckGeoFance
ON CheckGeoFance
AFTER INSERT AS
BEGIN
Update tblgeofencing
Set CarZone ='Car In Zone Area'
END
GO
ShapesString ={"shapes":[{"type":"rectangle","color":"#1E90FF","bounds":{"northEast":{"lat":"32.379961464357315","lon":"70.99365234375"},"southWest":{"lat":"31.840232667909362","lon":"70.2685546875"}}}]}

A: First You have to decode the ShapesString which is currently in json format and then find out the latitude and longitude out of the decoded json.
Then check the lat-long lie in your defined range to update the column.
Refer this to decode the json:-
Parse JSON in TSQL


text:
Q: Could not create SSL/TLS secure channel error when both client and server support TLS 1.2 We have upgraded our server to only accept TLS 1.2 and disabled SHA/MD5. Now from this server, we are calling a third party API that supports TLS 1.2, TLS 1.1 and TLS 1.0. Now, whenever I call this third part api using C# HttpClient library I am getting Could not create SSL/TLS secure channel error. From code I set,
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I am getting the same error. The only way to get rid of this error is to enable TLS 1.2, TLS 1.1 and TLS 1.0 in my server. How can I enable only TLS 1.2 while making my third party api work or how can I get more information what is the main cause of TLS error?


text:
Q: How to import a class in typescript I am new to typescript programming. I tried to create a very simple project running in the browser using typescript.
When I run the application I get following error;
Uncaught ReferenceError: exports is not defined

I understand the problem is loading the class. But I am not really sure how to get this fixed.
Can anyone provide some assistance please?
I saw several sites that I need to use a module loader to do this. But couldn't find any examples showing how to do this.
I have following files in the app
person.ts
    export class Person{
    greet()
    {
        console.log("hello");
    }
}

main.ts
import {Person} from './person'
let p = new Person();
p.greet();

index.html
<!DOCTYPE html>
<html>
    <head>
        <script src="./main.js"></script>
    </head>
    <body>
    </body>
</html>

tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  }
}

package.json
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "lite-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "lite-server": "^2.4.0"
  }
}


text:
Q: Creating a custom Hibernate UserType - What does isMutable() mean? I am creating a custom UserType in Hibernate for a project. It has been relatively straightforward until I came to the isMutable method. I am trying to figure out what this method means, contract-wise.
Does it mean the class I am creating the UserType for is immutable or does it mean the object that holds a reference to an instance of this class will never point to a different instance?
I found some examples in the Hibernate Community Wiki where they returned true, because the object itself was mutable - http://www.hibernate.org/73.html.
Other examples in the community wiki returned false without addressing why, even though they were also mutable.
I have checked the JavaDoc, but it's not very clear either.
From the JavaDoc for UserType:
public boolean isMutable()
    Are objects of this type mutable?
    Returns:
        boolean

From JavaDoc for Type:
public boolean isMutable()
    Are objects of this type mutable. (With respect to the referencing
    object ... entities and collections are considered immutable because
    they manage their own internal state.)
    Returns:
        boolean

A: The typical example here is the String class - it is Immutable, i.e. once the string is created you cannot change its contents or state, and if you want to then you're going to have to process it into a new copy.
isMutable returning true means you are saying this object can have its state changed by outside objects, returning false means you will have to copy this object to a new instance makign the changes to state along the way. Or as you said: "does it mean the object that holds a reference to an instance of this class will never point to a different instance".

A: Hibernate will treat types marked as "mutable" as though they could change (i.e. require an UPDATE) without pointing to a new reference. If you assign a new reference to a Hibernate-loaded property Hibernate will recognize this even if the type is immutable - this happens all the time with, for instance, String fields.
But if, say, you have a StringBuilder field and you mark it as immutable Hibernate will not notice if you modify the StringBuilder.
See this blog post for more details and a sample project.


text:
Q: How to access current_user from a Rails Notification? I'm building an audit trail that needs to know which user is currently making the request. My audit trail is built using ActiveSupport::Notifications to receive an even that needs to be audited.
What I would like to do is use an ActiveSupport::Concern to encapsulate the logic for my audit needs, so that I can easily add auditing to any model in my system.
In general this is easy to do. I even blogged about it a while back. However, I'm having a hard time figuring out how to get the current user that making the request to the web server, so that I can log who is making what changes in my audit trail.
I know there are a ton of questions about "how do I get current_user in my model" but I'm not asking about doing it in a model, so I'm hoping there is a better set of answers. Since my audit code is infrastructure related, I am hoping that there is some way I can tap into the current request that is being processed, or something else that would definitively tell me who is currently logged in / making the request.
I've read a lot of "answers" that say to use thread storage and put the current_user in there. I don't like this answer for many of the reasons that others don't - there is no guarantee that thread storage is safe. it could bleed across multiple requests if the server uses the same thread to process multiple requests, etc.
so... given that I am not trying to access current_user from my model, but rather from either an ActiveSupport::Concern or ActiveSupport::Notifications event subscription, are there any good options for me to know who the current user is?
Update
I'm using devise for authentication, which uses Warden on the back end. devise retrieves the current_user by calling request.env['warden'].authenticate(:scope => :user) (assuming i use a "User" model for authentication).
Is there a way for me to access the current request object from within my concern or notification subscription? Back in my .NET days, I would have been able to call HttpContext.Current.Request and all would be good. What's the equivalent in Rails?

A: Rails' ActionController::Instrumentation has explicit support for this, using append_info_to_payload.
Add a method to your ApplicationController:
def append_info_to_payload(payload)
  super
  payload[:current_user_id] = current_user.try(&:id)
end

now, when your observer is called back, the information will be in the event.payload:
ActiveSupport::Notifications.subscribe /process_action.action_controller/ do |*args|
  event = ActiveSupport::Notifications::Event.new(*args)
  current_user_id = event.payload[:current_user_id]
  # do something interesting with current_user_id here
end

A: You already have the answer, what you're doing is the same as when people are accessing the request in models.  The current_user is just a method defined on your ApplicationController.  When you're not in a controller or other class that inherits from it, you can't access that method.
HttpContext.Current.Request  << I would bet a lot that this uses thread storage.  Any other solution we find will also be thread storage at some level or another.
Either pull out what you need from the request in the controller and pass it down as parameters, or use thread storage -- but this is inherently dangerous anyway.  What if you start using delayed job to do the notifications or something?


text:
Q: Jenkins & Artifactory On a server running ubuntu 12.04 I have installed jenkins 1.532.1 and artifactory 2.6.4.
Both of then are running fine separately.  I also have maven 2.
With jenkins, I can build maven java project with sources on subversion.
With maven I can use Artifactory.
The problem is with the artifactory plugin for jenkins.
I added an artifactory server with credentials.  Using connection check tell me : "Found Artifactory 2.6.4".  It seems to be ok.
But when I create a maven job, in post build actions, I choose Deploy artifacts to artifactory.  My server is already selected in the artifactory server but nothing is available in the repositories.
What can I do.  Do I have to configure something special in Artifactory ?

A: I had also this issue, the problem comes from a refresh of Jenkins Plugin.
To deal with that issue, you should:

*

*open your job

*add a task for artifactory

*save your job

*Open again your job

Now you should be able to see your repositories.
Conclusion: You should add/save and reload your job to see your list of repo of artifactory.

A: I also have this problem, when switching from one artifactory server to another and it looks like a bug for me.
But if I save the settings once without a "non-selectable" repository and access the configuration of the job again, the repositories will be shown.

A: Ok, so after a very long time I tried again and ... I don't know why but now (I'm quite sure it was not working few months ago) the solution given by aorfevre and user3424040 are working.
I have also upgraded jenkins to 1.565.1 and the artifactory plugin to 2.2.3 and now there is a Refresh Repositories button in the Deploy artifacts to Artifactory task.

A: For the "Generic-Artifactory Integration" I had to configure Artifactory a bit. I added a group 'deployers' and a user 'deploy' in that group. Also I added a Permission Target for the LOCAL repositories where the group was granted deploy permissions.


text: Q: add net a new card on ubuntu I have a net card named eth0,and then I add a new net card ,sometimes it will named eth1,sometimes it will named eth0,and my old eth0 will changed to eth1,this will influence my network,because /etc/network/interfaces eth name will not compare with Mac,so the network will wrong.I just want to knew how ubuntu control this.I use a ubuntu based linux,and there is not 75-presistent rules file,and i copy this file from ubuntu,it doesn't work,i also copy write_net_rules,set grub biosdevname and net.ifname,it still doesn't work,thank you!


text:
Q: problem to play sound i have develop one application(in 1.5) in which 2 activity stay there. in first activity i have put background sound.and in second activity i have put animal sound.now when i am play it in emulator it work fine but when i have test it in android device version 2.1,i got force close error.
Take action:

*

*while i have remove background sound and continue with animal sound
it work fine in device.

*while i have remove animal sound and continue with background sound
it work fine in device.

*set rebuild automatically.

*clean it again and again.

I cant able to get exactly what error are raise, because it is happen only in device.
i have use to play sound ::
mPlayer = MediaPlayer.create(this, R.raw.touch_and_show);
mPlayer.start();

A: may be
mPlayer = MediaPlayer.create(this, R.raw.touch_and_show);
mPlayer.prepare();
mPlayer.start();


text:
Q: Move object to the position of another object in 2 different display groups I have 2 display groups. Each group has few display objects inside it. Each display object has unique (x,y) positions. Each group itself has unique (x,y) positions. Both groups have anchoreChildren = true
What I would like to do is when I click on an object from the first group is to move to a corresponding object's position (while remaining a child of its original group) from the second group. I use a "transition" and the object:localToContent method to get the (x,y) of the target object.
What happens is the object moves "close" to the target but not at its exact position, there is always an offset.
Here is how I move it:
local x,y = target:localToContent( 0, 0 )
transition.to( object, {x=x, y=y, time=200} )

Basically what I need to do is:
I need to get the position of object2 inside group 2 relative to object 1 that is inside group 1 and move object 1 there.
simple  object2:localToConten`t doesn't work properly as I mentioned above.

A: I understood what you want to do. You should calculate the distance of objects.
See this code:
local x1, y1 = object1:localToContent(0, 0)
local x2, y2 = object2:localToContent(0, 0)
transition.to(object2, {x = x1 - x2, y = y1 - y2, time = 200})

The code is working for me.


text:
Q: what exactly cuda does for opengl applications? I guess some portion of an opengl application used to run on CPU, and now through cuda people can run it on GPU, and accelerate those portions (portion of an opengl application or pipeline) .
Can someone explain me what exactly cuda does for opengl ? I mean exactly what operations are offloaded to GPU for processing by cuda?

A: CUDA is a totally separate API than OpenGL; you can use them at the same time but CUDA isn't necessary to get GPU acceleration of rendering. In OpenGL you use shaders, which are conceptually somewhat similar to CUDA kernels, to achieve hardware acceleration of many tasks in OpenGL.
CUDA does allow interoperability with OpenGL (and Direct3D) but it is by no means necessary; you'd usually only want to do that if you both want to do scientific computing AND rendering in the same application. That's becoming even less necessary though, now with compute shaders available in both GL and D3D


text:
Q: Routing all web 'traffic' via tun device on Mac OSX Having checked through Stack Overflow I cannot find a suitable answer, so hope the community are able to help me.
I am using a DNS tunneling program called iodine, on the Mac as a client device and am currently able to connect to the server correctly, create the tun0 device and ping the server as defined, via the tunnel.
I am now trying to route my normal browsing traffic via this 'virtual' tun0 device but am failing to do so. I have seen some reference to amending the preferences.plist but cannot seem to get it to connect properly (presume due to my inability to find or define the UUID)
Anyway, if anyone has any ideas they will all be greatly received.
ifconfig tun0: flags=8851<UP,POINTOPOINT,RUNNING,SIMPLEX,MULTICAST> mtu 1130
inet 10.0.0.2 --> 10.0.0.2 netmask 0xffffffe0
open (pid 447)

A: Normally, rerouting traffic through a tunnel is done by changing the default route in the routing table on your system using a command such as route add default 10.0.0.2.  It may also be necessary to remove the existing default route to avoid confusing the routing subsystem.


text:
Q: Get number of records as a grouped time series from a database I have a table projects where users can enter new projects and the user and date_added are recorded (among other fields):
|----|------------|--------------|
| id | user_added | date_added   |
|----|------------|--------------|
| 1  | 'person 1' | '2017-01-05' |
| 2  | 'person 2' | '2017-02-10' |
| 3  | 'person 3' | '2017-02-23' |
| 4  | 'person 1' | '2017-03-04' |
| 5  | 'person 3' | '2017-03-31' |
|----|------------|--------------|

I wonder if and how i can get the number of projects per month grouped by the user who added the projects. Expected output for the above table:
|------------|---------|---------|---------|-----|
| user_added | 2017-01 | 2017-02 | 2017-03 | etc.|
|------------|---------|---------|---------|-----|
| 'person 1' |    1    |    0    |    1    | ... |
| 'person 2' |    0    |    1    |    0    | ... |
| 'person 3' |    0    |    1    |    1    | ... |
|------------|---------|---------|---------|-----|

A: Don't put the values into columns.  The SQL way is one row per person and per month:
select user_added, strftime(date_added, '%Y-%m') as yyyymm, count(*)
from t
group by user_added, strftime(date_added, '%Y-%m')
order by 1, 2;

This is the SQLish way to return the result.  You can pivot the values in your application.
The problem with pivoting them in SQL is that you cannot handle an arbitrary number of months.  A SQL query returns a fixed number of columns, whose names have to be specified in the query.

A: You can use aggregation to do pivoting like this provided you have year-month known beforehand:
select user_added,
    count(case
            when ym = '2017-01'
                then 1
            end) "2017-01",
    count(case
            when ym = '2017-02'
                then 1
            end) "2017-02",
    count(case
            when ym = '2017-03'
                then 1
            end) "2017-03",
    . . .
from (
    select user_added,
        strftime(date_added, '%Y-%m') ym
    from your_table
    ) t
group by user_added;

If not, then keep the year-month in single column along with it's count for each user:
select user_added,
    ym,
    count(*)
from (
    select user_added,
        strftime(date_added, '%Y-%m') ym
    from your_table
    ) t
group by user_added,
    ym;

A: As Gordon Linoff said - you can only pivot within the database when you have a fix number of possible values to pivot into - in your case year-month combinations.
If you stick to your 3 year-month values, it will work like this (and, yes, you will need to hard-wire the year-month values into the column names):
WITH
-- input
projects(id,user_added,date_added) AS (
          SELECT 1  , 'person 1' , DATE '2017-01-05'
UNION ALL SELECT 2  , 'person 2' , DATE '2017-02-10'
UNION ALL SELECT 3  , 'person 3' , DATE '2017-02-23'
UNION ALL SELECT 4  , 'person 1' , DATE '2017-03-04'
UNION ALL SELECT 5  , 'person 3' , DATE '2017-03-31'
)
,
-- vertical display
vertical_grouped AS (
SELECT
  user_added
, strftime(date_added,'%Y-%M') AS yearmonth
, COUNT(*)                     AS projcount
FROM projects
GROUP BY
  user_added
, strftime(date_added,'%Y-%M')
)
SELECT
  user_added
, IFNULL(SUM(CASE yearmonth WHEN '2017-01' THEN projcount END),0) AS "2017-01"
, IFNULL(SUM(CASE yearmonth WHEN '2017-02' THEN projcount END),0) AS "2017-02"
, IFNULL(SUM(CASE yearmonth WHEN '2017-03' THEN projcount END),0) AS "2017-03"
FROM vertical_grouped
GROUP BY
  user_added
;

user_added|2017-01|2017-02|2017-03
person 1  |      1|      0|      1
person 2  |      0|      1|      0
person 3  |      0|      1|      1


text:
Q: Resumable uploads (Google Drive SDK for Android or Java) I had referred to Check progress for Upload & Download,  Resumable upload using Drive API for Android and Direct and Resumable Media Uploads.
However, I cannot get solution from them, and the resumable media upload is always failed.
My test step is try to disconnect WiFi/connect to another WiFi during upload, and then upload the same file again, but it always upload the file from beginning.
Any suggestion is appreciated.
Logcat:
08-13 21:56:02.541 13190 13968 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 19%
08-13 21:56:02.931 13190 13968 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 19%
08-13 21:56:03.262 13190 13968 W System.err: javax.net.ssl.SSLException: Read error: ssl=0x7ac0ba00: I/O error during system call, Connection timed out
08-13 21:56:03.262 13190 13968 W System.err:    at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method)
08-13 21:56:03.262 13190 13968 W System.err:    at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:692)
08-13 21:56:03.262 13190 13968 W System.err:    at java.io.BufferedInputStream.fillbuf(BufferedInputStream.java:168)
08-13 21:56:03.262 13190 13968 W System.err:    at java.io.BufferedInputStream.read(BufferedInputStream.java:227)
08-13 21:56:03.262 13190 13968 W System.err:    at com.android.okhttp.internal.Util.readAsciiLine(Util.java:316)
08-13 21:56:03.262 13190 13968 W System.err:    at com.android.okhttp.internal.http.RawHeaders.fromBytes(RawHeaders.java:308)
08-13 21:56:03.272 13190 13968 W System.err:    at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:135)
08-13 21:56:03.272 13190 13968 W System.err:    at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:644)
08-13 21:56:03.272 13190 13968 W System.err:    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)
08-13 21:56:03.272 13190 13968 W System.err:    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
08-13 21:56:03.272 13190 13968 W System.err:    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
08-13 21:56:03.272 13190 13968 W System.err:    at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:136)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:36)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:965)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.googleapis.media.MediaHttpUploader.executeCurrentRequestWithoutGZip(MediaHttpUploader.java:545)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.googleapis.media.MediaHttpUploader.resumableUpload(MediaHttpUploader.java:417)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:336)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:418)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
08-13 21:56:03.272 13190 13968 W System.err:    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
08-13 21:56:03.272 13190 13968 W System.err:    at com.example.drivequickstart.UploadFileActivity$UploadFileTask.doInBackground(UploadFileActivity.java:94)
08-13 21:56:03.272 13190 13968 W System.err:    at com.example.drivequickstart.ServiceBaseActivity$GeneralDriveTask.doInBackground(ServiceBaseActivity.java:1)
08-13 21:56:03.272 13190 13968 W System.err:    at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-13 21:56:03.272 13190 13968 W System.err:    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-13 21:56:03.272 13190 13968 W System.err:    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-13 21:56:03.272 13190 13968 W System.err:    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-13 21:56:03.272 13190 13968 W System.err:    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-13 21:56:03.272 13190 13968 W System.err:    at java.lang.Thread.run(Thread.java:864)
08-13 21:56:12.792 13190 13190 D UploadFileActivity:  onConnected()
08-13 21:56:12.812 13190 14305 D UploadFileActivity: [INITIATION_STARTED]
08-13 21:56:13.432 13190 14305 D UploadFileActivity: [INITIATION_COMPLETE]
08-13 21:56:13.953 13190 14305 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 0%
08-13 21:56:14.203 13190 14305 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 0%
08-13 21:56:14.514 13190 14305 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 0%
08-13 21:56:14.754 13190 14305 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 0%
08-13 21:56:15.044 13190 14305 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 1%
08-13 21:56:15.294 13190 14305 D UploadFileActivity: [MEDIA_IN_PROGRESS] progress: 1%

Code snip:
private class UploadFileTask extends GeneralDriveTask {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            java.io.File fileContent = new java.io.File(fileUri.getPath());

            // File's metadata.
            File fileMetadata = new File();
            fileMetadata.setTitle(fileContent.getName());
            //body.setMimeType("image/jpeg");
            fileMetadata.setMimeType("video/mp4");
            fileMetadata.setFileSize(fileContent.length());

            // File's binary content

            InputStreamContent mediaContent = new InputStreamContent("video/mp4", new BufferedInputStream(new FileInputStream(fileContent)));
            mediaContent.setLength(fileContent.length());

            Drive.Files.Insert insert = getDriveService().files().insert(fileMetadata, mediaContent).set("uploadType", "resumable");
            insert.set("uploadType", "resumable");
            insert.getMediaHttpUploader().setDirectUploadEnabled(false);
            insert.getMediaHttpUploader().setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE);
            insert.getMediaHttpUploader().setProgressListener(mUploadFileProgressListener);

            File file = insert.execute();
            if (file != null)
                showToast("Video uploaded: " + file.getTitle());
        } catch (UserRecoverableAuthIOException e) {
            GetGoogleDriveToken();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }
}

private static class UploadFileProgressListener implements MediaHttpUploaderProgressListener {
    @Override
    public void progressChanged(MediaHttpUploader uploader) throws IOException {
        switch (uploader.getUploadState()) {
            case INITIATION_STARTED:
            Log.d(LOG_TAG, "[INITIATION_STARTED]");
              break;
            case INITIATION_COMPLETE:
                Log.d(LOG_TAG, "[INITIATION_COMPLETE]");
              break;

            case MEDIA_IN_PROGRESS:
                int percent = (int)(uploader.getProgress() * 100);
                Log.d(LOG_TAG, "[MEDIA_IN_PROGRESS] progress: " + percent + "%");
                break;
            case MEDIA_COMPLETE:
                Log.d(LOG_TAG, "[MEDIA_COMPLETE] progress: 100%");
                break;
            default:
                break;
        }
    }
};

A: It seems that MediaHttpUploader did not handle resume upload well.
The reason is that "Request the upload status." mentioned in
Google Drive SDK Upload Files  always fail to get Content-Range.
So, The way to solve it is polling Content-Range all the time during upload.
Thus it's able to resuming an interrupted upload by "Resume the upload from the point where it left off."
private String getUploadID(Uri fileUri, String token) {
    Log.d(LOG_TAG, "[sendResumableHttpRequest] +++");

    String upload_id = "";

    java.io.File fileContent = new java.io.File(fileUri.getPath());
    String fileName = fileContent.getName();
    String contentLength = String.valueOf(fileContent.length());
    String mimeType = getMimeFromURI(fileUri);

    Log.d(LOG_TAG, "[sendResumableHttpRequest] fileName : " + fileName);
    Log.d(LOG_TAG, "[sendResumableHttpRequest] contentLength : " + contentLength);
    Log.d(LOG_TAG, "[sendResumableHttpRequest] mimeType : " + mimeType);

    try {
        String url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", "Bearer " + token);
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("X-Upload-Content-Type", mimeType);
        con.setRequestProperty("X-Upload-Content-Length", contentLength);

        JSONObject jobj = new JSONObject();
        jobj.put("title", fileName);
        byte[] postData = jobj.toString().getBytes();

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        String location = con.getHeaderField("Location");
        if (location.contains("upload_id")) {
            String[] uploadParameters = location.split("upload_id");
            upload_id = uploadParameters[1].replace("=", "");
        }

        Log.d(LOG_TAG, "[sendResumableHttpRequest] Response Code : " + responseCode);
        Log.d(LOG_TAG, "[sendResumableHttpRequest] Response Location : " + location);
        Log.d(LOG_TAG, "[sendResumableHttpRequest] Response uploadID : " + upload_id);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.d(LOG_TAG, "[sendResumableHttpRequest] ---");

    return upload_id;
}

private void putFileWithUploadID(Uri fileUri, String token, long range) {
    Log.d(LOG_TAG, "[putFileWithUploadID] +++");

    java.io.File fileContent = new java.io.File(fileUri.getPath());
    String fileName = fileContent.getName();
    String contentLength = String.valueOf(fileContent.length());
    String mimeType = getMimeFromURI(fileUri);

    Log.d(LOG_TAG, "[putFileWithUploadID] fileName : " + fileName);
    Log.d(LOG_TAG, "[putFileWithUploadID] contentLength : " + contentLength);
    Log.d(LOG_TAG, "[putFileWithUploadID] mimeType : " + mimeType);

    long totalBytesFromDataInputStream = 0;

    try {
        String url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=" + mUploadID;
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("PUT");
        con.setRequestProperty("Authorization", "Bearer " + token);
        con.setRequestProperty("Content-Type", mimeType);
        //con.setFixedLengthStreamingMode(MediaHttpUploader.MINIMUM_CHUNK_SIZE);

        long nextByte = 0;
        if (range == 0) {
            con.setRequestProperty("Content-Length", contentLength);
        }
        else {
            nextByte = range + 1;
            long remainContentLength = Long.parseLong(contentLength) - nextByte;
            con.setRequestProperty("Content-Length", String.valueOf(remainContentLength));
            String contentRange = "bytes " + (range + 1) + "-" + ( Long.parseLong(contentLength) - 1) + "/" + contentLength;
            con.setRequestProperty("Content-Range", contentRange);

            Log.d(LOG_TAG, "[putFileWithUploadID] Content-Length : " + String.valueOf(remainContentLength));
            Log.d(LOG_TAG, "[putFileWithUploadID] Content-Range : " + contentRange);
        }
        con.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        @SuppressWarnings("resource")
        DataInputStream inputStream = new DataInputStream(new FileInputStream(fileContent));

        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = inputStream.read(bufferOut)) != -1) {
            if (nextByte > 0) {
                nextByte = nextByte - bytes;
                if (nextByte >= 0) continue;
            }
            wr.write(bufferOut, 0, bytes);
            totalBytesFromDataInputStream += bytes;
        }
        Log.d(LOG_TAG, "[putFileWithUploadID] totalBytesFromDataInputStream:" + totalBytesFromDataInputStream);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        Log.d(LOG_TAG, "[putFileWithUploadID] Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        isUploadCompleted = true;
        isInterrupted = false;
        mLastUploadBytes = 0;
        Log.d(LOG_TAG, "[putFileWithUploadID] isUploadCompleted:" + isUploadCompleted);
        Log.d(LOG_TAG, "[putFileWithUploadID] isInterrupted:" + isInterrupted);
    } catch (Exception e) {
        e.printStackTrace();
        isInterrupted = true;
        Log.d(LOG_TAG, "[putFileWithUploadID] isInterrupted:" + isInterrupted);
        Log.d(LOG_TAG, "[putFileWithUploadID] totalBytesFromDataInputStream:" + totalBytesFromDataInputStream);
    } finally {
    }

    Log.d(LOG_TAG, "[putFileWithUploadID] ---");
}

private void putFileWithUploadID(Uri fileUri, String token) {
    putFileWithUploadID(fileUri, token, 0);
}

private long requestUploadStatus(Uri fileUri, String token) {
    Log.d(LOG_TAG, "[requestUploadStatus] +++");

    String range_so_far = "0";

    java.io.File fileContent = new java.io.File(fileUri.getPath());
    String contentLength = String.valueOf(fileContent.length());

    Log.d(LOG_TAG, "[requestUploadStatus] contentLength : " + contentLength);

    try {
        String url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&upload_id=" + mUploadID;
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("PUT");
        con.setRequestProperty("Authorization", "Bearer " + token);
        con.setRequestProperty("Content-Length", "0");
        con.setRequestProperty("Content-Range", "bytes */*");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        String rangeHeader = con.getHeaderField("Range");
        if (rangeHeader != null && rangeHeader.length() > 0) {
            String[] range = rangeHeader.split("-");
            range_so_far = range[1];
        }

        Log.d(LOG_TAG, "[requestUploadStatus] Response Code : " + responseCode);
        Log.d(LOG_TAG, "[requestUploadStatus] Response rangeHeader : " + rangeHeader);
        Log.d(LOG_TAG, "[requestUploadStatus] Response range_so_far : " + range_so_far);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

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

    Log.d(LOG_TAG, "[requestUploadStatus] ---");

    return Long.parseLong(range_so_far);
}


text:
Q: How to obtain images in the head? How can I obtain and head like this, with images in it till the limit of the paper, and with a gradient similar to the image?

I have used fancyhdr package any times, but... in a very simple way with only text (Right Center or Left).

A: A solution with mdframed.
MWE:
\documentclass{article}
\usepackage{graphicx}
\usepackage[framemethod=tikz]{mdframed}

\usepackage{fancyhdr}
\let\oldheadrule\headrule
\renewcommand{\headrule}{\vskip-3\baselineskip\oldheadrule}
\renewcommand\headrulewidth{0pt}
\fancyhf{}
\fancyhead[C]{%
\begin{mdframed}[%
    innertopmargin=0pt,
    innerbottommargin=0pt,
    innerleftmargin=0pt,
    tikzsetting={shade,left color=blue!50,right color=blue!10}
    ]
\includegraphics[scale=0.05]{example-image-a}\hfill\raisebox{.3\baselineskip}{\leftmark}
\end{mdframed}%
\fancyfoot[C]{\thepage}
}
\pagestyle{fancy}

\usepackage{lipsum}

\begin{document}

\section{test}
\lipsum[1-10]

\end{document}

A: I would use TikZ and an environment which doesn't affect other typeset material in the header. It can be achived by the pgfinterruptboundingbox environment, then an object has width of 0 pt and height of 0 pt to the surrounding typeset material. I enclose an example as a starting point.
Edit: Next, I wrapped it all in the scope environment to move it all to the left margin of the paper. I changed twice \textwidth to \paperwidth. I usually use absolute positioning offered by TikZ, well, I wished to give scope a chance.
\documentclass[a4paper]{article}
\usepackage{lipsum}
\usepackage{xcolor,tikz}
\usepackage{fancyhdr}\pagestyle{fancy}\fancyhf{}
\renewcommand{\headrulewidth}{0.0pt}
\def\mysquare{1cm}
\colorlet{myblue}{blue}
\fancyhead[L]{%
\begin{tikzpicture}[inner sep=0pt, outer sep=0pt]
\begin{scope}[xshift=-1in-\hoffset-\oddsidemargin]
\begin{pgfinterruptboundingbox}
\shade[fill=yellow, anchor=west, left color=myblue, right color=myblue!10, xshift=\mysquare] (0,0) rectangle (\paperwidth-\mysquare,\mysquare);
\node[minimum width=\mysquare, minimum height=\mysquare, draw, align=center, font=\bfseries\color{white}, fill=myblue, anchor=south west] at (0,0) (leftside) {MM\\O};
\node[font=\bfseries, anchor=east] at (\paperwidth,0.5\mysquare) {\leftmark\hspace{3mm}\thesection\hspace*{6mm}};
\end{pgfinterruptboundingbox}%
\end{scope}
\end{tikzpicture}%
}% End of \fancyhead...
\begin{document}
\renewcommand{\sectionmark}[1]{%
\markboth{#1}{}}
\section{Enfriamiento simulado}
\lipsum[2]
\end{document}


text: Q: How to handle K8S CRD CRUD requests by only one instance of an operator I have a K8S CRD and a custom operator for that, which is scaled to several replicas. On a new CRUD request for that CRD all of the operator instances are triggered. Is there a way to somehow round robin CRUD requests or to mark them as being processed by a particular instance of the operator? I guess if I add an external DB to mark particular request as being processed by a particular instance it will work, but I don't wont to introduce more complexity than needed.


text:
Q: How to connect to MySQL running on Docker from the host machine I have already googled on this subject and found few threads. Based on these threads I have followed the following steps. But I am facing a problem.
Basically, I want to create a docker image for mysql and then connect to it from my host machine (Mac OS X).
Based on this post , I have to share the mysql unix socket with the host. towards this I have done the following steps
1. Start docker quick terminal
2. docker run --name mysql -e MYSQL_ROOT_PASSWORD=password -d mysql/mysql-server:latest
3. docker exec -it mysql bash
4. mysql -uroot -p
5. create database MyDB;
6. GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';
7. exit;
8. mkdir /Users/abhi/host
9. docker run -it -v /host:/shared mysql/mysql-server:latest

Now I get the error
MacBook-Pro:~$ docker run -it -v /Users/abhi/host:/shared mysql/mysql-server
error: database is uninitialized and password option is not specified
  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD

But you see that I have provided the password and initialized my database.
All I want is that from my host machine, I can connect to the mysql database running inside docker.
EDIT:: ----- solution which worked ------
Thanks RICO. Finally the steps which worked for me are
1. Start docker quick terminal
2. docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -d mysql/mysql-server:latest
3. docker exec -it mysql bash
4. mysql -uroot -p
5. create database MyDB;

  or:
  CREATE USER 'root'@'%' IDENTIFIED BY 'root';
  GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

6. GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';
7. exit;
8. docker-machine env default

Use the IP address obtained in step 8. port is 3306, user is root, password is password, database is MyDB.
Connection is successful!

A: docker run -e MYSQL_ROOT_PASSWORD=pass --name sql-db -p 3306:3306 mysql
docker exec -it sql-db bash
mysql -u root -p

A: So you basically you need to expose the mysql port to your host:
docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=password -d mysql/mysql-server:latest

Then you can access from your host using the mysql command line:
mysql -h127.0.0.1 -ppassword -uroot

Not sure why you are trying to run another container to connect (perhaps you meant linking two containers)
If you are using Mac (or Windows) with docker-machine you want to connect to the IP address of your docker-machine VM. For example:
$ docker-machine ssh default
                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/
 _                 _   ____     _            _
| |__   ___   ___ | |_|___ \ __| | ___   ___| | _____ _ __
| '_ \ / _ \ / _ \| __| __) / _` |/ _ \ / __| |/ / _ \ '__|
| |_) | (_) | (_) | |_ / __/ (_| | (_) | (__|   <  __/ |
|_.__/ \___/ \___/ \__|_____\__,_|\___/ \___|_|\_\___|_|
Boot2Docker version 1.9.0, build master : 16e4a2a - Tue Nov  3 19:49:22 UTC 2015
Docker version 1.9.0, build 76d6bc9
docker@default:~$ ifconfig eth1
eth1      Link encap:Ethernet  HWaddr 08:00:27:E6:C7:20
          inet addr:192.168.99.100  Bcast:192.168.99.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fee6:c720/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:18827 errors:0 dropped:0 overruns:0 frame:0
          TX packets:10280 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1791527 (1.7 MiB)  TX bytes:2242596 (2.1 MiB)

Then connect to:
mysql -h192.168.99.100 -ppassword -uroot


text:
Q: How to get desktop path from windows service? I have windows service which is written on Qt. How to get desktop path for current user?

A: QStandardPaths will give you standart paths for system and current user.
But don't forget what your service are running under system user by default and not under your local user profile if you didn't set it so. Just check it in services.msc  On the second tab in your service preferences you can also change the user under which your service will be executed.

EDIT: Also you can use standard MSDN API to get system and user paths. This code for example will give you Documents folder for current user under which the service is running. With fromWCharArray you can convert it then to QString
#include "Shlobj.h"
    QString path;
    wchar_t* localAppData = nullptr;
        if (SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &localAppData) == S_OK)
        {
            path = QString::fromWCharArray(localAppData);
            CoTaskMemFree(reinterpret_cast<void*>(localAppData));
        }

A: Services do have limited access. usually they can't access anything desktop-related. Qt is supposed to be used for desktop apps.
Linux daemon and windows service are completely different in principle of function. Windows maintains life cycle of  a service and there are service-specific subsystems in API. Linux daemon is just another process running in background, nothing  special in comparison to other processes otherwise.
Services run under system account, network account or some superuser account, with no access to desktop function. Services not meant to interact with current logged-in user, it's background  processes for interaction with OS and hardware (drivers are kind of service too).
It is possible to enable access to current user but such is a security risk and involves Windows API, as well as action to be taken to configure service. Running service as local user that got a profile is a security risk too.
Usual setup is to create service and GUI app that interacts with that service and runs under current user.
Services use different entry points from standard application, just like windows .dll got its own entry points.
https://msdn.microsoft.com/en-us/library/9k985bc9(v=vs.100).aspx
Complete example of service:
https://msdn.microsoft.com/en-us/library/windows/desktop/bb540476(v=vs.85).aspx
There was component called QtService, but it is no longer maintained, probably because of security changes. Unless  service support for Qt as project type would be added, at best it would be not a fully functional service.


text:
Q: in expressions, `_` can only be used on the left-hand side of an assignment I've the following code I implemented to return an error when a string doesn't contain a match to something like "Mark, 55" to return an error. The compiler complains about my code Err(error) =>  Err(ParsePersonError::ParseInt(_))
use std::num::ParseIntError;
use std::str::FromStr;

#[derive(Debug, PartialEq)]
struct Person {
    name: String,
    age: usize,
}

// We will use this error type for the `FromStr` implementation.
#[derive(Debug, PartialEq)]
enum ParsePersonError {
    // Empty input string
    Empty,
    // Incorrect number of fields
    BadLen,
    // Empty name field
    NoName,
    // Wrapped error from parse::<usize>()
    ParseInt(ParseIntError),
}
// My implementation
    impl FromStr for Person {
        type Err = ParsePersonError;
        fn from_str(s: &str) -> Result<Person, Self::Err> {

    if s.len() == 0 {
        Err(ParsePersonError::Empty)
    }
    else {
        let v: Vec<&str> = s.split(",").collect();
        println!("{:?}",v);
        if &v[0]== &""{
            Err(ParsePersonError::NoName)
        }
        else if v.len()!=2 {
            Err(ParsePersonError::BadLen)
        }
        else {
            let num = match v[1].parse::<usize>() {
                Ok(n) => {

                    let name = v[0].to_string();
                    let age = n;
                    return Ok(Person {name,age})
                },

                Err(error) =>  Err(ParsePersonError::ParseInt(_))
            };

            Err(ParsePersonError::ParseInt(_))

        }

    }
}

}
However, the compiler doesn't complain about the same code in my test case.
ParsePersonError::ParseInt(_))

     #[test]
        fn missing_name_and_age() {
            assert!(matches!(
                ",".parse::<Person>(),
                Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_))
            ));
        }

What am I missing?

A: If you de-sugar the match macro in test, it is something like
let result = ",".parse::<Person>();
let r = match result {
    Err(ParsePersonError::NoName) => true,
    Err(ParsePersonError::ParseInt(_)) => true,
    _ => false,
};
assert!(r);

Essentially the '_' is to hold the value attached to ParseInt. Hence an assignment. This is what the compiler error message means.


text:
Q: How to calculate size of array from pointer variable? i have pointer of array(array which is in memory).
Can i calculate the size of array from its pointer ?
i dont know actually where is the array in memory.
i only getting pointer adress(suppose 9001)
using that adress i have to calculate array size.
Thanks.

A: You cannot do this in C. The size of a pointer is the size of a pointer, not the size of any array it may be pointing at.
If you end up with a pointer pointing to an array (either explicitly with something like char *pch = "hello"; or implicitly with array decay such as passing an array to a function), you'll need to hold the size information separately, with something like:
int twisty[] = [3,1,3,1,5,9];
doSomethingWith (twisty, sizeof(twisty)/sizeof(*twisty));
:
void doSomethingWith (int *passages, size_t sz) { ... }

The following code illustrates this:
#include <stdio.h>

static void fn (char plugh[], size_t sz) {
    printf ("sizeof(plugh) = %d, sz = %d\n", sizeof(plugh), sz);
}

int main (void) {
    char xyzzy[] = "Pax is a serious bloke!";
    printf ("sizeof(xyzzy) = %d\n", sizeof(xyzzy));
    fn (xyzzy, sizeof(xyzzy)/sizeof(*xyzzy));
    return 0;
}

The output on my system is:
sizeof(xyzzy) = 24
sizeof(plugh) = 4, sz = 24

because the 24-byte array is decayed to a 4-byte pointer in the function call.

A: No, you cannot calculate the size of the array.  Objects in C do not carry type information, so you must arrange to know the size of the array ahead of time.  Something like this:
void my_function(int array[], int size);

A: No. arrays in C doesn't have this info. you should hold a variable "next" to the array with this data.
if you have the array it self you can use the sizeof to get his size in compilation stage.
char array1[XXX];
char* pointer1 = array1;
sizeof(array1); // this is XXX
sizeof(pointer1); // this is the size of a pointer in your system

you should do the following and use the variable in you program (or pass it to function when you passing the array to a function)
int array1size = sizeof(array1);


text:
Q: A code in Python that I need explanation to it I've tried to learn python for the last 3 weeks, and I saw a code that I need to understand what it does.
In general, the code should somehow connect to two images, and then give me a password that I need to submit.
The code is:
#env 3.7
from PIL import Image, ImageFont
import textwrap
from pathlib import Path
def find_text_in_image(imgPath):
    image = Image.open(imgPath)
    red_band = image.split()[0]
    xSize = image.size[0]
    ySize = image.size[1]
    newImage = Image.new("RGB", image.size)
    imagePixels = newImage.load()
    for f in range(xSize):
        for j in range(zSize):
            if bin(red_band.getpixel((i, j)))[-1] == '0':
                imagePixels[i, j] = (255, 255, 255)
            else: imagePixels[i, j] = (0,0,0)
    newImgPath=str(Path(imgPath).parent.absolute())
    newImage.save(newImgPath+'/text.png')

It would be lovely if someone could explain it to me.
thanks!

A: I'll break the above snippet into parts and explain each indivdiually.
The first block are imports. PIL is usually imported by installing the Pillow library. textwrap and pathlib are two packages included in the Python Standard Library.
#env 3.7
from PIL import Image, ImageFont
import textwrap
from pathlib import Path

The next block tells you you're about to define a function that does some image processing. I'll write more in inline comments.
def find_text_in_image(imgPath):
    # open the image file given and load it as an `Image` from PIL
    image = Image.open(imgPath)

    # this splits the image into its Red, Green, and Blue channels
    # then selects the Red
    red_band = image.split()[0]

    # these two lines get the size of the image, width and height
    xSize = image.size[0]
    ySize = image.size[1]

    # this constructs a new `Image` object of the same size, but blank
    newImage = Image.new("RGB", image.size)

    # this makes an 3-d array of the new image's pixels
    imagePixels = newImage.load()

    # this loops over the width, so the iterator `f` will be the column
    for f in range(xSize):

        # loops over the height, so `j` will be the row
        for j in range(zSize):  # <-- This should probably be `ySize`. `zSize` is not defined.

            # this is getting a pixel at a particular (column, row) in the red channel
            # and checking if it can be binarized as 0
            if bin(red_band.getpixel((i, j)))[-1] == '0':

                # if so, set the same spot in the new image as white
                imagePixels[i, j] = (255, 255, 255)

            # if not, make it black
            else: imagePixels[i, j] = (0,0,0)

    # now make a new path and save the image
    newImgPath=str(Path(imgPath).parent.absolute())
    newImage.save(newImgPath+'/text.png')

There are major problems with this code as well. In some places you refer to zSize and i despite not defining them. Also, as a matter of practice, you can create paths with pathlib objects in the idiomatic way
    newPath = Path(oldPath).with_name('new_filename.ext')


text:
Q: Empty rows in file generated from macros in excel I am trying to split a file with 120 records into files of at-most 50 records each. So expectation is it should genarate 2 files with 50 records and 1 file wit 20 but what I am getting is 3 files of 51 records with 1 empty file in the end for first 2 and 31 empty lines in 3rd file.
Sub SplitAndSaveFile()
Dim myRow As Long, myBook As Workbook, splitCount As Integer, thisWBName As String, splitCountStr As String, spaceRange As Range
lastRow = ThisWorkbook.Sheets("Data").Cells(rows.Count, 1).End(xlUp).Row
splitCount = 1
splitCountStr = CStr(splitCount)
thisWBName = Replace(ThisWorkbook.Name, ".xlsm", "") + "_Part"
For myRow = 4 To lastRow Step 50
    Set myBook = Workbooks.Add
    ThisWorkbook.Sheets("Data").rows(myRow & ":" & myRow + 49).EntireRow.Copy myBook.Sheets("Sheet1").Range("A1")
    myBook.SaveAs (ThisWorkbook.Path + "\" + thisWBName + splitCountStr + ".txt"), FileFormat:=xlText
    myBook.Close
    splitCount = splitCount + 1
    splitCountStr = CStr(splitCount)
Next myRow
MsgBox ("File(s) generated.")
End Sub

A: Export Data by Number of Rows
A Partial Quick Fix

*

*Your code seemed to work fine on my testing data, so the only thing I could think of, considering your description of the issue, was that in column A there are formulas evaluating to an empty string at the bottom, which you don't want to include. To fix this, you could use the Find method:

Dim LastRow As Long: LastRow = ThisWorkbook.Worksheets("Data") _
    .Columns("A").Find("*", , xlValues, , , xlPrevious)

*

*Unfortunately, you also didn't consider the case when there will be fewer than 50 records to be copied to the last workbook. See how it is handled in the 'In-Depth' solution.

In Depth

*

*This will export the records in a worksheet to new workbooks, saved as text, containing maximally 50 rows.

Option Explicit

Sub SplitAndSaveFile()
    Const ProcName As String = "SplitAndSaveFile"
    Dim dwbCount As Long ' Generated Workbooks Count
    On Error GoTo ClearError

    ' Source
    Const swsName As String = "Data"
    Const sCol As String = "A"
    Const sfRow As Long = 4

    ' Destination
    Const dfCellAddress As String = "A1" ' needs to be 'A' since entire rows.
    Const dMaxRows As Long = 50
    Const dNameSuffix As String = "_Part"
    ' In the loop, this will be replaced by a number ('dwbCount').
    Const dIdPlaceHolder As String = "?" ' the '?' is illegal for file names
    ' The following two lines are dependent on each other.
    Const dFileExtension As String = ".txt"
    Dim dFileFormat As XlFileFormat: dFileFormat = xlText

    ' Create a reference to the source first cell ('sfCell').
    Dim swb As Workbook: Set swb = ThisWorkbook
    Dim sws As Worksheet: Set sws = swb.Worksheets(swsName)
    Dim sfCell As Range: Set sfCell = sws.Cells(sfRow, sCol)

    ' Calculate the number of records (rows) ('drCount').

    ' This will find the last non-blank cell i.e. cells containing
    ' formulas evaluating to an empty string are ignored.
    ' Make sure that the worksheet is not filtered and there are no hidden
    ' cells.
    Dim slCell As Range
    Set slCell = sfCell.Resize(sws.Rows.Count - sfRow + 1) _
        .Find("*", , xlValues, , , xlPrevious)
    If slCell Is Nothing Then Exit Sub ' no data
    Dim slRow As Long: slRow = slCell.Row

    ' This is the preferred way, but besides a few pros, it behaves like 'End'
    ' i.e. it will find the last non-empty cell. A cell is not empty
    ' if it contains a formula evaluating to an empty string ('""'):
    ' it is blank.
    'Dim slCell As Range
    'Set slCell = sfCell.Resize(sws.Rows.Count - sfRow + 1) _
        .Find("*", , xlFormulas, , , xlPrevious)
    'If slCell Is Nothing Then Exit Sub ' no data
    'Dim slRow As Long: slRow = slCell.Row

    ' The classic last row using 'End' will find the last non-empty cell.
    'Dim slRow As Long: slRow = sws.Cells(sws.Rows.Count, sCol).End(xlUp).Row

    Dim drCount As Long: drCount = slRow - sfRow + 1
    If drCount < 1 Then Exit Sub ' no data (highly unlikely but...)

    ' Determine the generic file path (dwbGenericFilePath)
    Dim swbBaseName As String: swbBaseName = swb.Name
    Dim DotPosition As String: DotPosition = InStrRev(swb.Name, ".")
    If DotPosition > 0 Then swbBaseName = Left(swbBaseName, DotPosition - 1)
    Dim dwbExtension As String: dwbExtension = dFileExtension
    If Left(dwbExtension, 1) <> "." Then dwbExtension = "." & dwbExtension
    Dim dwbGenericFilePath As String
    dwbGenericFilePath = swb.Path & Application.PathSeparator & swbBaseName _
        & dNameSuffix & dIdPlaceHolder & dwbExtension

    Application.ScreenUpdating = False

    ' Additional variables used in the loop.
    Dim srg As Range
    Dim dwb As Workbook
    Dim dws As Worksheet
    Dim dfCell As Range
    Dim dFilePath As String

    Do Until drCount = 0
        ' Create a reference to the current source range.
        If drCount > dMaxRows Then ' all workbooks but the last
            Set srg = sfCell.Resize(dMaxRows).EntireRow
            Set sfCell = sfCell.Offset(dMaxRows)
            drCount = drCount - dMaxRows
        Else ' the last workbook
            Set srg = sfCell.Resize(drCount).EntireRow
            drCount = 0
        End If
        ' Copy the current source range to the current destination range.
        dwbCount = dwbCount + 1 ' count the number of generated workbooks
        Set dwb = Workbooks.Add(xlWBATWorksheet) ' one worksheet only
        Set dws = dwb.Worksheets(1)
        Set dfCell = dws.Range(dfCellAddress)
        srg.Copy dfCell
        ' Save and close the current destination workbook.
        dFilePath = Replace(dwbGenericFilePath, dIdPlaceHolder, CStr(dwbCount))
        Application.DisplayAlerts = False ' overwrite without confirmation
        dwb.SaveAs dFilePath, dFileFormat
        Application.DisplayAlerts = True
        dwb.Close SaveChanges:=False
    Loop

ProcExit:

    Application.ScreenUpdating = True

    Select Case dwbCount
    Case 0
        MsgBox "No files generated.", vbCritical, ProcName
    Case 1
        MsgBox "One file generated.", vbInformation, ProcName
    Case Else
        MsgBox dwbCount & " files generated.", vbInformation, ProcName
    End Select

    Exit Sub
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Sub


text:
Q: Connect broken headphone+mic wires Does someone know how to connect this wires without using additional hardware?

Thank you in advance for replies!
P.S. Right item is a Logitech's and left one is SVEN's

A: You will generally need to use a continuity tester (most convenient is to use an off-the-shelf multimeter in diode beep mode; but you could also use a battery and a buzzer) to find out where the leads go on your headset and on the jacks. There is no standard by which I could say "connect this colour to this colour and you'll be fine".
Except the blank copper strands, they should definitely all go to the ground or the sleeve part of the jack.
If we were to go without a multimeter, you need to determine whether (a) the thin wire on the left is insulated, and (b) whether the thick one on the left has a copper shield, then an insulator (can be clear lacquer) and another wire inside it. In the (a) case, that wire will be for the microphone. In the (b) case, the inner of THAT wire will be for the microphone. You can find whether a wire is insulated by lacquer by using a cigarette lighter, the lacquer will burn. By elimination, you might find which wires should go to the speakers.
Speaker part has 3 wires: left signal, right signal and common return (ground).
Microphone part has 2 wires: bias+signal and return (ground).
Return (ground) is sometimes combined into one from both parts, so some cables have 4 wires, some 5 wires, some cables have simple cables for speaker with a ground hanging loose outside but a separately shielded microphone wire.
Signal wires are always insulated; ground wires sometimes are but usually are not.
Microphone wire can have a thinner conductor than other wires without ill effect but for it to work optimally, it needs to be better shielded than other wires - sometimes you can see that in cable design, but sometimes all of this wisdom gets thrown out of the window.
Sorry if it seems like information overload, but given the amount of guesswork that will go into correctly identifying the wires without continuity tester, you will probably need it.
On the right, you need to determine which wires go to the speakers. You connect a 1.5V or weaker battery to the ground wire and the wire of which you think it might be a speaker wire, and listen for a pop in the corresponding speaker when you make the connection.
Using a multimeter is a very good idea; you can measure resistance between wires. You can get nominal impedance of the speakers from the headphone data sheet, but usually it's between 16 and 45 Ohm, and the DC resistance will be close to that, maybe up to 30% lower. If you measure two speakers together, you will see double that resistance. If you measure a microphone against its ground, you will see about 1-2.5 kOhm.


text:
Q: How to use "Composite Design Pattern" with Ninject Validation Rule Contract:
public interface IValidationRule
{
    bool IsValid();
}

Concrete Validation Rule:
public class MyClass : IValidationRule
{
    public bool IsValid()
    {
        return true;
    }
}

Composite:
public class ValidationRuleComposite : IValidationRule
{
    private readonly IEnumerable<IValidationRule> _validationRules;

    public ValidationRuleComposite(IEnumerable<IValidationRule> validationRules)
    {
        _validationRules = validationRules;
    }

    public bool IsValid()
    {
        return _validationRules.All(x => x.IsValid());
    }
}

When I ask the containter for IValidationRule I want to get ValidationRuleComposite. If I ask the container for a list of IValidationRule I want to get all implementations of IValidationRule except of the ValidationRuleComposite.
How can I achieve this with Ninject?

A: First you want to set up the bindings for the IEnumerable<IValidationRule> that will be injected into the composite. You can just bind them individually:
// Bind all the individual rules for injection into the composite
kernel.Bind<IValidationRule>().To<MyClass>().WhenInjectedInto<ValidationRuleComposite>();
kernel.Bind<IValidationRule>().To<RuleTwo>().WhenInjectedInto<ValidationRuleComposite>();

Or you can also setup the IEnumerable fairly easy with the convention binding extensions, so that you don't have to add a separate binding for each individual concrete rule. Just be sure to add the Exlcuding clause for the composite class like so:
using Ninject.Extensions.Conventions;

// Bind all the non-composite IValidationRules for injection into ValidationRuleComposite
kernel.Bind(x => x.FromAssemblyContaining(typeof(ValidationRuleComposite))
    .SelectAllClasses()
    .InheritedFrom<IValidationRule>()
    .Excluding<ValidationRuleComposite>()
    .BindAllInterfaces()
    .Configure(c => c.WhenInjectedInto<ValidationRuleComposite>()));

In my example the composite and the rest of the concretes are in the same assembly, but obviously you can vary your convention binding if they're somewhere else.
Finally, we need to set up the binding so that everywhere else an IValidationRule is request, Ninject provides the composite. There doesn't seem to be an elegant method existing for this, so I wrote my own When clause to avoid the cyclical injection:
// Now bind the composite to the interface for everywhere except itself
kernel.Bind<IValidationRule>().To<ValidationRuleComposite>()
    .When(x => x.Target == null
          || x.Target.Member.ReflectedType != typeof(ValidationRuleComposite));

A: Here I'm assuming that you want all the validation rules and not a partial list of them, as per the more generic pattern.
I would slightly change the Composition class so that you can do a
kernel.Get<IValidationRuleComposite>()

and a
kernel.GetAll<IValidationRule>()

A simple example follows.
The interfaces
public interface IValidationRule
{
    bool IsValid();
}
public interface IValidationRuleComposite : IValidationRule
{
    void ValidationRuleCompose(List<IValidationRule> validationRules);
}

and the rules
public class MyClass1 : IValidationRule
{
    public bool IsValid()
    {
        Debug.WriteLine("Valid 1");
        return true;
    }
}
public class MyClass2 : IValidationRule
{
    public bool IsValid()
    {
        Debug.WriteLine("Valid 2");
        return false;
    }
}

The composite rule
public class ValidationRuleComposite : IValidationRuleComposite
{

private List<IValidationRule> _validationRules;
public void ValidationRuleCompose(List<IValidationRule> validationRules)
{
    _validationRules = _validationRules.Union(validationRules).ToList();
}
public ValidationRuleComposite()
{
    _validationRules = new List<IValidationRule>();
}
public bool IsValid()
{
    Debug.WriteLine("Composite Valid");
    return _validationRules.All(x => x.IsValid());

}

}

and a main
        StandardKernel kernel = new StandardKernel();
        kernel.Bind<IValidationRule>().To<MyClass1>();
        kernel.Bind<IValidationRule>().To<MyClass2>();
        kernel.Bind<IValidationRuleComposite>().To<ValidationRuleComposite>();

        IValidationRuleComposite try1 = kernel.Get<IValidationRuleComposite>();

        IEnumerable<IValidationRule> rules = kernel.GetAll<IValidationRule>();
        foreach(IValidationRule trycomp in rules)
            { Debug.WriteLine("trycomp: " + trycomp.GetType().ToString()); trycomp.IsValid(); };

        try1.ValidationRuleCompose(rules.ToList());
        Console.WriteLine("{0}",try1.IsValid());
        Debug.WriteLine("try1: " + try1.GetType().ToString());

EDIT
Equivalent alternative, preserving your composite constructor
public interface IValidationRuleCompositeConstr : IValidationRule
{

}
public class ValidationRuleCompositeOriginal : IValidationRuleCompositeConstr
{
    private readonly IEnumerable<IValidationRule> _validationRules;

    public ValidationRuleCompositeOriginal(IEnumerable<IValidationRule> validationRules)
    {
        _validationRules = validationRules;
    }

    public bool IsValid()
    {
        return _validationRules.All(x => x.IsValid());
    }
}

with corresponding usage:
    StandardKernel kernel = new StandardKernel();
    kernel.Bind<IValidationRule>().To<MyClass1>();
    kernel.Bind<IValidationRule>().To<MyClass2>();
    kernel.Bind<IValidationRuleCompositeConstr>().To<ValidationRuleCompositeOriginal>();

    IEnumerable<IValidationRule> rules = kernel.GetAll<IValidationRule>();
    Ninject.Parameters.ConstructorArgument therules = new Ninject.Parameters.ConstructorArgument("therules", rules);
        IValidationRuleCompositeConstr try2 = kernel.Get<IValidationRuleCompositeConstr>(therules);
        Debug.WriteLine("Second Class");
        Debug.WriteLine (string.Format("{0}",try2.IsValid()));

A: With the help of Soldarnal I came to the following solution:
public static class KernelExtensions
{
    public static void BindComposite<TComposite, TCompositeElement>(this StandardKernel container) where TComposite : TCompositeElement
    {
        container.Bind(x => x.FromAssemblyContaining(typeof(TComposite))
            .SelectAllClasses()
            .InheritedFrom<TCompositeElement>()
            .Excluding<TComposite>()
            .BindAllInterfaces()
            .Configure(c => c.WhenInjectedInto<TComposite>()));

        container.Bind<TCompositeElement>().To<TComposite>()
          .When(IsNotCompositeTarget<TComposite>);
    }

    private static bool IsNotCompositeTarget<TComposite>(IRequest x)
    {
        if (x.Target == null)
            return true;
        return x.Target.Member.ReflectedType != typeof(TComposite);
    }
}

Usage:
var container = new StandardKernel();
container.BindComposite<ValidationRuleComposite, IValidationRule>();

A: I don't know how you could do that directly with Ninject, but you could use Ninject to create a class which then creates your validation rules.
public class ValidationRuleFactory : IValidationRuleFactory
{
    public IValidationRule CreateComposite()
    {
        var rules = CreateRules();
        return new ValidationRuleComposite(rules);
    }

    private IEnumerable<IValidationRule> CreateRules()
    {
        //return all other rules here.
        //I would hard code them and add new ones here as they are created.
        //If you don't want to do that you could use reflection.
    }
}

as this class doesn't hold any state you can then create it with singleton scope.
kernel.Bind<IValidationRuleFactory>().To<ValidationRuleFactory>().InSingletonScope();

Then you inject this class and use it to create your composite
public class MyClass()
{
    private readonly IValidationRuleFactory _validationRuleFactory;

    public MyClass(IValidationRuleFactory validationRuleFactory)
    {
        _validationRuleFactory = validationRuleFactory;
    }

    public bool CheckValid()
    {
        var composite = _validationRuleFactory.CreateComposite();
        return composite.IsValid();
    }
}

A: You wire up your concrete instances of ValidationRule in Ninject, like this.
this.Kernel.Bind<ValidationRule1>().ToSelf();
this.Kernel.Bind<ValidationRule2>().ToSelf();
this.Kernel.Bind<IValidationRule>().To<ValidationRuleComposite>()
    .WithConstructorArgument("validationRules",
        new IValidationRule[] {
            this.Kernel.Get<ValidationRule1>(),
            this.Kernel.Get<ValidationRule2>()
        });

Now, whenever you have a service that takes an IValidationRule in its constructor, you will get the ValidationRuleComposite concrete type with both ValidationRule1 and ValidationRule2 injected.
As far as I know, Ninject doesn't play nice when it comes to injecting multiple instances of the same type. In this case, we avoid doing that so resolving IValidationRule always results in the composite type.
However, you could build your own scanning convention using Reflection that automatically finds all of the types, excludes any that have the suffix "Composite" in the name, then loops through the types to first bind them to self and then create an array of instances to inject. Have a look at this example of a custom scanning implementation, and its usage.


text:
Q: Loading multiple files in HTML  in Grunt using globbing Is there any kind of Grunt task or plugin for loading many files in the <head> of an HTML page using globbing?
We're using Ember.js and starting to see a lot of duplication:
<script type="text/javascript" src="js/controllers/(controller).js">
<script type="text/javascript" src="js/controllers/(controller).js">
<script type="text/javascript" src="js/controllers/(controller).js">

<script type="text/javascript" src="js/models/(model).js">
<script type="text/javascript" src="js/models/(model).js">
<script type="text/javascript" src="js/models/(model).js">

In our Gruntfile we use the globbing pattern that's pretty common in Grunt tasks, something like scripts/{,*/}*.coffee.
Is there any kind of plugin we can use to drop in a glob pattern into our HTML page to load all of these at once?
This would be pretty useful if we could use it to load CSS, as well. My guess is we'd need some kind of non-specific file loader where we can just specify a pattern and directory.
Thanks!

A: grunt-html-build (https://github.com/spatools/grunt-html-build) should do the job. You can define a HTML template with placeholders for scripts, styles and other HTML templates, which is then compiled by the plugin.
Grunt HTMLBuild config
htmlbuild: {
    dev: {
        src: 'index.html',
        dest: 'build/',
        options: {
            styles: {
                app: 'styles/*.css'
            },
            scripts: {
                app: 'scripts/*.js'
            }
        }
    }
}

HTML template
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />

        <!-- build:style app -->
        <!-- /build -->
    </head>

    <body>
        <!-- build:script app -->
        <!-- /build -->
    </body>
</html>

This compiles the HTML template from index.html into build/index.html, including all styles and scripts under styles/ and scripts/.


text:
Q: Updated output is concatenating with old output Can anyone figure out why after removing a found value, the output includes all the information from before the remove?
  // Prints current items in both arrays
  String titles = "";
  String lengths = "";
  for (int i = 0; i < numOfSongs; i++) {
     titles += songTitles[i] + " ";
     lengths += songLengths[i] + " ";
  }
  JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);
  // Determines if the user wants to remove a song from the current list
        boolean found = false;
        // If search matches a song in array, set title to null and length to 0
        for (int i = 0; i < songTitles.length; i++) {
           if (search.equalsIgnoreCase(songTitles[i])) {
              found = true;
              songTitles[i] = null;
              songLengths[i] = 0;
           }
        }
        // Update arrays, song count, and duration across all songs
        if (found) {
           titles += songTitles[numOfSongs] + " ";
           lengths += songLengths[numOfSongs] + " ";
           totalDuration -= songLengths[numOfSongs];
           numOfSongs--;
        }
        // Print updated playlist
        JOptionPane.showMessageDialog(null, "**Current Playlist**" + "\nSong titles: " + titles + "\nSong lengths: " + lengths);

A: titles and totalDuration strings are initialized with all the elements in songTitles and songLengths.
If you find search in songTitles you remove it from songTitles but you don't update songTitles. Instead you append on more song title from songTitles.
You probably want to clear songTitles and songLengths and recreate them skipping null values in songTitles. E.g.
titles = "";
lengths = "";
for (int i = 0; i < numOfSongs; i++) {
    if (songTitles[i] != null) {
        titles += songTitles[i] + " ";
        lengths += songLengths[i] + " ";
    }
}

Also consider creating your strings like this (Java 8)
String titles = String.join(" ", songTitles);
String lengths = String.join(" ", songLengths);

A: Below statements are causing to concatenate with old values.
titles += songTitles[numOfSongs] + " ";
lengths += songLengths[numOfSongs] + " ";

You should first clear the existing values by setting strings empty before adding a new value.
titles = "";
lengths = "";


text:
Q: System directly booting to Windows without showing GRUB menu I have a hp pavillion 15 n203tx with preinstalled Windows 8.1.
I installed Ubuntu 14.04 in it, and then it used to show a GRUB menu every time I turned on the machine. The menu said something like:
1. Ubuntu
2. Advanced options for Ubuntu
3. Windows Boot Manager(on /dev/sda2)
4. System Setup

Everything was working well. If I wanted to run Ubuntu I chose the Ubuntu option and if I wanted to boot Windows then I chose the third option of Windows Boot Manager.
Out of curiosity once I tried that last option-system setup, and a new menu loaded up, a startup menu showing the following options-
1. f1 system information
2. f2 system diagnostics
3. f9 boot device options
4. f10 bios setup
5. f11 system recovery

enter- continue setup

then I pressed enter and Windows started booting. Since then, my system is booting directly to Windows without showing the GRUB menu.
If I want to see that grub menu, I have to press the esc key on starting my system. Then the startup menu appears (which I have mentioned above) and I have to press f9. Then I am presented with a boot menu options screen with the following options:
1. OS boot manager
2. Ubuntu
3. Boot from EFI file

I have to select the second option to get to the GRUB menu.
I want my system to work as it did earlier.

A: If I understand you correctly, but it sounds like F9 would be the right choice. I'm not sure though because every PC I've ever owned uses F12 to select a boot device. If F9 doesn't work try F12. Basically you want to get to the menu where you'd select a boot device (like when you're booting from a live usb) and choose the correct partition.
All you have to do is arrow down to the partition ((device) with Ubuntu installed and press enter. Then open a terminal and type sudo update-grub. It should find Ubuntu and re-add it to the grub menu.

A: In my case, I had to press and hold the Shift button during the boot of the system.
This should allow the grub menu to show up. Then you only need access Ubuntu and set the grub options via "boot repair" or similar programs.
I hope this helps!


text:
Q: Why won't Skyrim start? So, I've got Skyrim downloaded and everything, my computer more than meets the requirements and when I go to press the play button on the startup window nothing happens.
I've updated my video card drivers, updated my firewall setting, and searched google for any related problems people are having with the game. The only thing that I can find is that people are having the game crash due to some sound problem.
Well, I would try some of the solutions to that problem but my game won't even start at all.
Any ideas?

A: Basic steps to take:

*

*Reboot your computer, and try to run it

*If it fails and you can hear sound, update video card drivers.

*If it fails and you can see video but no sound, update sound drivers.

*If it fails and you see nothing, uninstall the game, reboot, reinstall the game. Reboot after install and try again.

*If it still fails, and you are on Vista or Win7, dig through your program files and find the executable, and right click->properties->advanced->run as administrator. Then try to run it again from the desktop/steam shortcut.

*If none of the above work, I recommend you contact their support.

A: Have you overclocked your GPU(s)?
If so, remove it (the overclock) and try again. I had a similar problem and it was my OC which was killing it.

A: I worked on this for like two days and this is how I got it to work:

*

*When you download Steam, create a folder in something other that Programs (86)...so create a folder in your C drive

*After installation, if it still doesn't load when you click on Play do the following...

*Go to your Steam Folder

*Click on Steam Apps

*Click Common Folder than Skyrim

*Right click on Skyrim Launcher go into properties and run as Administrator

Once you have done that, click on Skyrim Launcher again and you should be good!

A: Go to: control panel > sound > default speakers > Properties > Advanced tab
change your sound from 48000 Hz to 44100 Hz and try again.
I had the same problem and this solved it for me, I would make sure you are patched up to version 1.6 as this was suppose to solve this issue as far as I am aware.

A: TLDR: Set steam to offline mode.
I had Skyrim freeze on the "Loading Skyrim..." page in steam - very scary 120+ hours into it.
Here's how I fixed it: In steam, click the "Steam" menu, the "Go offline" (or something like that). Steam will restart in offline mode and for some reason Skyrim will start. After a few hours I went back online and it all worked fine.

A: I had to do two things to resolve the same problem:

*

*Set Skyrim Launcher to run as Administrator (as in Michelle's answer on this page - thanks Michelle!)

*Install DirectX 9 from http://www.microsoft.com/en-us/download/details.aspx?id=35 - I'm running Windows 7 with DirectX 11, but my guess is that Skyrim is older than DirectX 11 and doesn't know how to talk to it? Or something? In any case, installing DirectX from the installer at that link fixed the issue and doesn't seem to have caused any other problems.


text:
Q: Exchange 2007 SCR Setup Error finding Domain Controller? just setting up my SCR enviroment however when running the Enable-StorageGroupCopy command its returning with an error stating that my exchange server object could not be found on my domain controller.
any ideas as to why it would state this ? Both the live server and DR server are in the domain and all client PC's are able to send and receive email through the live server. You can view this server and even manage it from AD so i'm unsure why i'm receiving this error message. any help would be great
Thanks
Nathan
here is the error i'm receiving - EXSRV01 is the live server and EXSRV02 is the Standby and FSG is the storage group i want to copy over
     Welcome to the Exchange Management Shell!

Full list of cmdlets:          get-command
 Only Exchange cmdlets:         get-excommand
 Cmdlets for a specific role:   get-help -role UM or Mailbox
 Get general help:              help
 Get help for a cmdlet:         help  or  -?
 Show quick reference guide:    quickref
 Exchange team blog:            get-exblog
 Show full output for a cmd:     | format-list
Tip of the day #31:
Do you love the Exchange Management Shell's Tip of the Day? Try this out:
Get-Tip
[PS] C:\Windows\system32>enable-storagegroupcopy -identity fsg -standbymachine e
xsrv02
Enable-StorageGroupCopy : The operation could not be performed because object '
fsg' could not be found on domain controller 'dc003.network.com'.
At line:1 char:24
+ enable-storagegroupcopy <<<<  -identity fsg -standbymachine exsrv02
    + CategoryInfo          : NotSpecified: (0:Int32) [Enable-StorageGroupCopy
   ], ManagementObjectNotFoundException
    + FullyQualifiedErrorId : FEF7F95C,Microsoft.Exchange.Management.SystemCon
   figurationTasks.EnableStorageGroupCopy
[PS] C:\Windows\system32>


text:
Q: MCMC/EM limitations? MCMC over EM? I am currently learning hierarchical Bayesian models using JAGS from R, and also pymc using Python ("Bayesian Methods for Hackers").
I can get some intuition from this post: "you will end up with a pile of numbers that looks "as if" you had somehow managed to take independent samples from the complicated distribution you wanted to know about." It is something like I can give the conditional probability, then I can generate a memoryless process based on the conditional probability. When I generate the process long enough, then the joint probability can converge.and then I can take a pile of numbers at the end of the generated sequence. It is just like I take independent samples from the complicated joint distribution. For example, I can make histogram and it can approximate the distribution function.
Then my problem is, do I need to prove whether a MCMC converges for a certain model? I am motivated to know this because I previously learned the EM algorithm for GMM and LDA (graphical models). If I can just use MCMC algorithm without proving whether it converges, then it can save much more time than EM. Since I will have to calculate the expected log likelihood function (will have to calculate posterior probability), and then maximize the expected log likelihood. It is apparently more cumbersome than the MCMC (I just need to formulate the conditional probability).
I am also wondering if the likelihood function and prior distribution are conjugate. Does it mean that the MCMC must converge? I am wondering about the limitations of MCMC and EM.

A: EM is an optimisation technique: given a likelihood with useful latent variables, it returns a local maximum, which may be a global maximum depending on the starting value.
MCMC is a simulation method: given a likelihood with or without latent variables, and a prior, it produces a sample that is approximately distributed from the posterior distribution. The first values of that sample usually depend on the starting value, which means they are often discarded as burn-in (or warm-up) stage.
When this sample is used to evaluate integrals associated with the posterior distribution [the overwhelming majority of the cases], the convergence properties are essentially the same as those of an iid Monte Carlo approximation, by virtue of the ergodic theorem.
If more is needed, i.e., a guarantee that $(x_t,\ldots,x_{t+T})$ is a sample from the posterior $\pi(x|\mathfrak{D})$, some convergence assessments techniques are available, for instance in the R package CODA. Theoretically, tools that ensure convergence are presumably beyond your reach. For instance, perfect sampling or rewewal methods.