Q: How do you reference a C# class library from a Win8 Javascript metro application? When I try the standard way it complains of an unsupported reference and I can't seem to use any of my classes.

A: You need to create a Windows Runtime component by creating a class library from the "Visual C#" -> "Windows Metro Style" -> "Class Library" template. Then in the properties for that class library project you need to mark the output type as "WinMD File"
Better instructions can be found here:
http://msdn.microsoft.com/en-us/library/windows/apps/hh779077(v=vs.110).aspx
This isn't stated in the documentation and is probably just a bug with the Windows 8 Consumer Preview and the Visual Studio 11 Beta but be sure not to include a period in the name of the project you're referencing. For instance, I was working on a Car application so I made an assembly named "Car.Business". The application would always crash with a blank startup screen whenever I tried to reference this. If on the other hand I just used "Business" as the name of the assembly then the application would work fine.


Q: How do I reference the Toggle Button Circle and override vertical alignment of the Aero theme Expander? Currently, I am referencing the Aero theme in my App.xml file.
In the main.xml file, I am using expanders to display the content in a resizable width app.
(For this example, I limited the width to 500)
The expander header content generally will be short, but it allows for up to 500 chars.
Depending on the window size (600 pixels by default), the content can wrap (thereby stretching the expander header downwards).
This is fine, but the toggle button (a circle /w arrow) is set for VerticalAlignment=center from what I can tell.
I need a way to override that VerticalAlignment in a style without re-creating the Aero template for the Expander.
I just cant seem to reference the circle and arrow objects.
I have tried overriding Toggle Button as well, with no luck.
As you can see below, I can override some aspects of the Aero Expander.
I just need that little nudge to get the Toggle Button Circle and Arrow objects to change the VerticalAlignment.
Thanks
Code example follows:
<Window.Resources>
    <Style TargetType="{x:Type Expander}" BasedOn="{StaticResource {x:Type Expander}}">
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Background" Value="#464646" />
        <Setter Property="Width" Value="Auto" />
        <Setter Property="Margin" Value="1,0,1,0" />
        <Setter Property="IsExpanded" Value="False" />
    </Style>
</Window.Resources>

<Expander ContextMenu="{StaticResource cMnu}" Width="auto">
    <Expander.Header>
        <StackPanel Orientation="Horizontal" Width="auto" Margin="0">
            <TextBlock Width="65">Normal</TextBlock>
            <TextBlock Width="80">Open</TextBlock>
            <TextBlock Width="80">10/31/2009</TextBlock>
            <TextBlock TextWrapping="Wrap" Width="500">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Aliquam ultrices auctor magna, sit amet commodo ipsum accumsan eu.
            Sed a mollis felis. Nam ullamcorper augue vel mauris consequat imperdiet.
            Nunc in augue mauris.
            Quisque metus tortor, porttitor nec auctor id, mollis nec ipsum.
            Suspendisse eget ipsum vitae lectus fermentum porta.
            Aliquam erat volutpat.
            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
            Phasellus congue dui ac arcu eleifend a amet.
            </TextBlock>
        </StackPanel>
    </Expander.Header>
</Expander>

A: If you look at the default template for the Expander, you can see why none of your property setters are working:
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="20" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <ToggleButton IsChecked="{Binding Path=IsExpanded,Mode=TwoWay,
                RelativeSource={RelativeSource TemplatedParent}}"
                OverridesDefaultStyle="True"
                Template="{StaticResource ExpanderToggleButton}"
                Background="{StaticResource NormalBrush}" />
  <ContentPresenter Grid.Column="1"
                    Margin="4"
                    ContentSource="Header"
                    RecognizesAccessKey="True" />
</Grid>

The ToggleButton's VerticalAlignment is what you are after, and there are no setters for it.
It seems to me that there is no way to change this alignment property through the Style. You must provide a new template.


Q: How to ensure the exception "The calling thread cannot access this object because a different thread owns it"? In C# WPF application, if in the following button click event habdler:
private void start_Click(object sender, RoutedEventArgs e)
{
  for (int i = 2; i < 20; i++)
  {
    var t = Task.Factory.StartNew
    (() =>
         {
            var result=Thread.CurrentThread.ManagedThreadId.ToString();
       //this.Dispatcher.BeginInvoke(new Action(() =>
            textBlock1.Text += "root " + i.ToString() + " " +
            result + Environment.NewLine
       ;//to comment this line if to uncomment th others
       //), null);
          }
     );
  }
}

to uncomment the commented lines, i.e. to output to textblock through Dispatcher.BeginInvoke() then it is filled with varying thread IDs.
Though with commented lines, as shown above, the textblock stays blank and there is no exception thrown.
In similar situation using Parallel.For
private void start_Click(object sender, RoutedEventArgs e)
{
  Parallel.For(2, 6, (i)
     => {
           var result = Thread.CurrentThread.ManagedThreadId.ToString();
           textBlock1.Text += "root " + i.ToString() + " " +
                               result + Environment.NewLine;

         }   );
}

the application breaks with exception:

"The calling thread cannot access this object because a different
  thread owns it"

Why isn't it thrown in first case, while using Task.Factory.StartNew() ?
Any way to ensure this exception?

A: Exceptions thrown in tasks are always handled by the Task object itself. The exception is later rethrown when you, e.g., access the Task.Result property. This way the handling of the exception is left to the thread creating the Task. If you run the first code snippet and look at the Output pane, you'll see that there are multiple first-chance InvalidOperationException logged there. The exceptions are thrown - the tasks just stash them away for later rethrowing.
Parallel.For actually does the same - it stashes away all exceptions occurring within the delegate and then, when the loop is finished, it rethrows all exceptions that occurred in a single AggregateException. You'll notice that the debugger breaks in the thread calling Parallel.For, not within the delegate passed to it.
To cause the exception in the task to propagate to the calling thread, like Parallel.For does, call Wait/WaitAll on the tasks.


Q: Morphia aggregation query to get size of list I am trying to count the number of elements in a list of each document in a collection, similar to below example. (https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size)
db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            numberOfColors: { $size: "$colors" }
         }
      }
   ]
)

This query would return size of list "colors" in each document.
An equivalent morphia query would be something like this :
pipeline =  ds.createAggregation(Abc.class)
                .match(query)
                .project(Projection.projection("count",
                 Projection.expression("$size","colors")));

Error on executing above : java.lang.String cannot be cast to com.mongodb.DBObject
I am unable to arrive at an equivalent morphia query to achieve the same.
Any help in this regard would be greatly appreciated.

A: Change the following lines of code
project(Projection.projection("count",
                 Projection.expression("$size","colors"))

to
Projection.expression("count",new BasicDBObject("$size","$colors")))

A: Did you try
Projection.expression("$size","$colors")));

With dollar before colors?


Q: distinct value of one column based on another column mysql Table structure
Column1 | Column2 | Column 3 | Column 4 . . .. .  Column N

Col1Val1    | Col2Val2    |  . . . . .
Col1Val1    | Col2Val2    | . . . ..
Col1Val1    | Col2Val3    | . . . .
Col1Val2    | Col2Val4    | .  . .
Col1Val3    | Col2Val5    | . .
Col1Val3    | Col2Val6    | . ..

I want to query for all the distinct values of column2 for a every distinct value of column1 and its count & values
Example output should be:
Col1Val1 | Col2Val2,Col2Val3 | 2
Col1Val2 | Col2Val4          | 1
Col1Val3 | Col2Val5,Col2Val6 | 2
.
.

This is pretty much doable from the querying + application handling.
Can this/similar output be achieved via only the sql query.

A: You can use GROUP_CONCAT() to aggregate and count he distinct Column2 values:
SELECT
    Column1,
    GROUP_CONCAT(DISTINCT Column2),
    COUNT(DISTINCT Column2)
FROM yourTable
GROUP BY Column1

Output:

Demo here:
Rextester

A: Try this.
select Column1 , group_concat(distinct column2) ,count(distinct column2)
from your_table
group by column1


Q: Prolog: How to find and remove minimum list element? I am new to Prolog.
I need help writing a predicate which finds and deletes the minimum element in a list.
Thank you very much!

A: If all list items are integers, we can use clpfd!
:- use_module(library(clpfd)).

We define zmin_deleted/2 using maplist/2, (#=<)/2,
same_length/2, and select/3:
zmin_deleted(Zs1,Zs0) :-
   same_length(Zs1,[_|Zs0]),
   maplist(#=<(Min),Zs1),
   select(Min,Zs1,Zs0).

Sample queries:
?- zmin_deleted([3,2,7,8],Zs).
  Zs = [3,7,8]
; false.

?- zmin_deleted([3,2,7,8,2],Zs).
  Zs = [3,  7,8,2]
; Zs = [3,2,7,8  ]
; false.

Note that zmin_deleted/2 also works in the "other direction":
?- zmin_deleted(Zs,[3,2,7,8]).
  _A in inf..2, Zs = [_A, 3, 2, 7, 8]
; _A in inf..2, Zs = [ 3,_A, 2, 7, 8]
; _A in inf..2, Zs = [ 3, 2,_A, 7, 8]
; _A in inf..2, Zs = [ 3, 2, 7,_A, 8]
; _A in inf..2, Zs = [ 3, 2, 7, 8,_A]
; false.

A: Let me google it for you.
How could you find a minimum of a list..
Anyway, there is a nice min_list predicate.
?- min_list([1,2,2,3],X).
X = 1.

Here is a little example how could you remove some element from a list (notice, that all 2s is gone):
?- delete([1,2,2,3],2,X).
X = [1, 3].

If you wanna remove only first occasion of a element, use select:
?- select(2, [2,1,2,2,3], X), !.
X = [1, 2, 2, 3].

So your final answer could be something like that:
delete_min(A, C) :-
  min_list(A, B),
  select(B, A, C), !.

And
?- delete_min([1,1,2,3],X).
X = [1, 2, 3].

A: Again, just use the structural recursion on lists. Lists are built of nodes, [H|T], i.e. compound data structures with two fields - head, H, and tail, T. Head is the data (list element) held in the node, and T is the rest of the list.
We find minimum element by rolling along the list, while keeping an additional data - the minimum element from all seen so far:
minimum_elt([H|T],X):- minimum_elt(T,H,X).

There is no definition for the empty list case - empty lists do not have minimum elements.
minimum_elt([],X,X).

If there are no more elements in the list, the one we have so far is the answer.
minimum_elt([A|B],M,X):-

two cases here: A < M, or otherwise:
    A < M, minimum_elt(B,A,X).

minimum_elt([A|B],M,X):-

    A >= M, minimum_elt(B,M,X).

Nothing more to say about it, so this completes the program.

edit: except, you wanted to also delete that element. This changes things. Hmm. One obvious approach is first find the minimum elt, then delete it. We'll have to compare all elements once again, this time against the minimal element found previously. Can we do this in one scan?
In Lisp we could have. To remove any element from a list, surgically, we just reset the tail pointer of a previous node to point to the next node after the one being removed. Then using this approach, we'd scan the input list once, keeping the reference to the previous node to the minimum element found so far, swapping it as we find the smaller and smaller elements. Then when we've reached the end of the list, we'd just surgically remove the minimal node.
But in Prolog, we can't reset things. Prolog is a set once language. So looks like we're stuck with the need to pass over the list twice ... or we can try to be very smart about it, and construct all possible lists as we go, sorting them out each time we find the new candidate for the smallest element.
rem_min([A|B],L):-
    % two possibilities: A is or isn't the minimum elt
    rem_min(B,A,([A|Z],Z,Z),L).

rem_min([],A,(With,Without,Tail),L):- Tail = [],
    % A is indeed the minimal element
    L = Without.

rem_min([H|T],A,(With,Without,Tail),L):- H >= A, Tail=[H|Z],
    rem_min(T,A,(With,Without,Z),L).

rem_min([H|T],A,(With,Without,Tail),L):- H < A,  % use this H
    copy_the_list(With,Tail,W2,T2),              % no good - quadratic behaviour
    Tail=[H|Z], T2=Z,
    rem_min(T,A,(With,W2,Z),L).

copy_the_list([A|B],T,[A|C],C):- var(B), !, T=B.            % fresh tail
copy_the_list([A|B],T,[A|C],T2):- copy_the_list(B,T,C,T2).

So looks like we can't avoid the second pass, but at least we can save all the superfluous comparisons:
rem_min([A|B],L):- N=[A|_], rem_min(B,A,N,[N|Z],Z,L).

rem_min([],_A,N,L2,Z,L):- Z=[], N=[_,1], % finalize the minimal entry
    scan(L2,L).
rem_min([H|T],A,N,L2,Z,L):- H >= A, Z=[H|Z2], rem_min(T,A,N,L2,Z2,L).
rem_min([H|T],A,N,L2,Z,L):- H < A,       % use this H
    N2=[H|_], N=[_],                     % finalize the non-minimal entry
    Z=[N2|Z2], rem_min(T,H,N2,L2,Z2,L).

scan( [], []).
scan( [[_,1]|B],C):- !, scan(B,C).       % step over the minimal element
scan( [[A]|B],[A|C]):- !, scan(B,C).     % previous candidate
scan( [A|B], [A|C]):- !, scan(B,C).


Q: Compare two NSDate by .Day in swift is giving wrong results Im trying to compare two NSDate by .Day doing this (both on gmt timezone):
 var order = NSCalendar.currentCalendar().compareDate(event.startDate!, toDate: cell.date!,
                    toUnitGranularity: .Day)
                    if (order == .OrderedSame) {
                            print(String(event.startDate!) + " == " + String(cell.date!))
                        cell.events.append(event)
                        break
                    }

When using 2016-03-08 21:43:53 +0000 and 2016-03-09 00:00:00 +0000 it says they are orderedSame, but they arent, the days are different. This function outputs:
 2016-03-08 21:43:53 +0000 == 2016-03-09 00:00:00 +0000

Can someone help me please?

A: Those two logged dates are being logged in the UTC timezone. But if your current timezone is west of that, then both dates are on March 8, 2016 in your timezone and the comparison is done in your timezone. Or, if you live east of that by at least 2.5 hours, then both dates are March 9, 2016.
Example. If you live in the eastern USA (GMT-4 currently but GMT-5 on March 8), then those two dates are actually 2016-03-08 16:43:53 -0500 and 2016-03-08 19:00:00 -0500.
Example. If you live in eastern Europe or Asia (say GMT+5), then those two dates would be 2016-03-09 02:43:53 +0500 and 2016-03-09 05:00:00 +0500.
As you can see, those are on the same day so the comparison is correct.


Q: iFrame disappears on Internet Explorer A friend of mine created a simple web site using iWeb and added an iFrame to one of the pages. iWeb seems to be loading iFrames through a series of Javascript libraries and CSS files (quite strange). But whenever I look at this page on IE, the iFrame disappears after a few seconds: http://bit.ly/fD7QGD
Does anyone know what could be causing this buggy behavior on IE?
Thanks,
Ralph

A: Well, I tried it on Firefox, Chrome and IE and waited more than 1 minutes. It didn't disappear.
Maybe there's a problem with your browser or it was a temporary bug.


Q: LibGDX 3d mesh transformation my intention is to make the "liquid" 3d structure, which is dynamically changing. The idea is to make it as the array of meshes and then change the elevation of the points of meshes.
So, my question is how to transform the mesh by setting the vertices Y variable? And is it even possible in LibGDX?


Q: Catch throw error from node module I am using a module which throws an error in case something is wrong. The error is not being returned as part of the callback and the run is being stopped when is thrown.
I am calling it like this:
co(function*(){
  try{
    for (let item of items){
       item.newValue = yield myFunction(param)
    }
  }catch(err){
  }
}

myFunction: function(param){
return new Promise(function(resolve, reject){
   module.callMethod(param), function(result){
     if (result)
         resolve(result)
  }else{
      reject('err')}
}
}

During callMethod I get a throw error but it is not caught on the co try and I'd like in case of a error to catch it but allow the for loop to continue.
How can I properly catch the thrown error?

A:
I'd like in case of a error to catch it but allow the for loop to
  continue

Promise constructor should treat errors thrown inside executor as promise rejection.

MDN If an error is thrown in the executor function, the promise is
  rejected.

So moving try-catch inside for loop should work.
.

'use strict'
co(function*() {
  for (let item of [1, 2, 3, 4]) {
    try {
      const newValue = yield myFunction(item)
      console.log(newValue)
    } catch (e) {
      console.error(e.message)
    }
  }
})

function callMethod(param, cb) {
  if (param % 2) cb('Success')

  throw new Error(`Invalid param ${param}`)
}

function myFunction(param) {
  return new Promise(function(resolve, reject) {
    callMethod(param, function(result) {
      if (result) {
        resolve(result)
      } else {
        reject('err')
      }
    })
  })
}
<script>
  const module = {}
</script>
<script src="https://unpkg.com/co@4.6.0/index.js"></script>


Q: Can't run jar file of JavaFx application on Linux I created JavaFx application on Windows.Then created jar file which works normal on windows.But when i try run this jar on Linux Mint i get this log:
нояб. 07, 2022 3:15:00 PM com.sun.javafx.application.PlatformImpl startup
WARNING: Unsupported JavaFX configuration: classes were loaded from 'unnamed module @6a7840b4'
java.lang.ClassNotFoundException: com.sun.glass.ui.gtk.GtkPlatformFactory
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
 at java.base/java.lang.Class.forName0(Native Method)
 at java.base/java.lang.Class.forName(Class.java:375)
 at com.sun.glass.ui.PlatformFactory.getPlatformFactory(PlatformFactory.java:42)
 at com.sun.glass.ui.Application.run(Application.java:146)
 at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:291)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:293)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:163)
 at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:659)
 at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:679)
 at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
 at java.base/java.lang.Thread.run(Thread.java:833)
Failed to load Glass factory class
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.sun.glass.ui.PlatformFactory.createApplication()" because the return value of "com.sun.glass.ui.PlatformFactory.getPlatformFactory()" is null
 at com.sun.glass.ui.Application.run(Application.java:146)
 at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:291)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:293)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:163)
 at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:659)
 at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:679)
 at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
 at java.base/java.lang.Thread.run(Thread.java:833)

I installed on Linux openjfx and i have openjdk 17.0.4.
Please, i'm waiting any help.


Q: Flask SQLAlchemy pagination error I have this code and the all() method and every other method works on this and I have looked all over and I could that the method paginate() works on BaseQuery which is also Query
@app.route('/')
@app.route('/index')
@app.route('/blog')
@app.route('/index/<int:page>')
def index(page = 1):
    posts = db.session.query(models.Post).paginate(page, RESULTS_PER_PAGE, False)
return render_template('index.html', title="Home", posts=posts)

but this gives me the error AttributeError: 'Query' object has no attribute 'paginate'
I've looked everywhere and I can't find any solution to this.

A: From your question...
that the method paginate() works on BaseQuery which is also Query

I think this is where you're being confused. "Query" refers to the SQLAlchemy Query object. "BaseQuery" refers to the Flask-SQLALchemy BaseQuery object, which is a  subclass of Query. This subclass includes helpers such as first_or_404() and paginate(). However, this means that a Query object does NOT have the paginate() function. How you actually build the object you are calling your "Query" object depends on whether you are dealing with a Query or BaseQuery object.
In this code, you are getting the SQLAlchemy Query object, which results in an error:
db.session.query(models.Post).paginate(...)

If you use the following code, you get the pagination you're looking for, because you are dealing with a BaseQuery object (from Flask-SQLAlchemy) rather than a Query object (from SQLAlchemy).
models.Post.query.paginate(...)


Q: Field Dao in DaoImpl required a bean named 'entityManagerFactory' that could not be found I have error message as follows:
***************************
APPLICATION FAILED TO START
***************************

Description:

Field visitorDao in com.ahmed.service.VisitorDaoImpl required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

Please have the classes as below. I am unable to understand what compiler wants to say.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>landon-hotel-event-mgmt-app</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <!--<scope>test</scope>-->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!--         jsr303 validation
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
        </dependency>-->
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <hibernate.version>5.2.17.Final</hibernate.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <name>Ahmed Visitor application</name>
</project>

Here are the classess.
package com.ahmed.service;

import com.ahmed.dao.VisitorDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VisitorDaoImpl {

    @Autowired
    VisitorDao visitorDao;

}

Here is another....
package com.ahmed.dao;

import com.ahmed.domain.Visitor;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 *
 * @author abhiramagopaladasa
 */
@Repository
public interface VisitorDao extends CrudRepository<Visitor, Integer>{
    List<Visitor> findByOutTime(LocalDateTime outTime);
    List<Visitor> findByInTime(LocalDateTime outTime);

}

I also have the HibernateConfiguration class as such:
[![/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ahmed.configuration;

import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 *
 * @author abhiramagopaladasa
 */

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ahmed.domain" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String\[\] { "com.ahmed.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }

}][1]][1]

Any help will be greatly appreciated. According to me I have already done everything required. I dont know what I am missing. Do I need to have another class configuring the entityManager or something?


Q: Why did jupyter server fail in VS code? I had this problem for a while now. I am trying to work on Jupyter Notebooks on VS code, but the jupyter server doesn't connect when I open VS code directly, but it works when I open VS code from Anaconda. Here is the error message:
Activating Python 3.7.4 64-bit ('base': conda) to run Jupyter failed with Error: StdErr from ShellExec, tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
 for . /Users/jingzhaogao/opt/anaconda3/bin/activate && conda activate base && echo 'e8b39361-0157-4923-80e1-22d70d46dee6' && python /Users/jingzhaogao/.vscode/extensions/ms-python.python-2020.6.88468/pythonFiles/pyvsc-run-isolated.py /Users/jingzhaogao/.vscode/extensions/ms-python.python-2020.6.88468/pythonFiles/printEnvVariables.py.

Please assist.

A: Unfortunately there's nothing to specifically do here other than continue to open VS Code from the activated conda environment. Conda simply wants to own the environment you work from and those settings need to propagate into the one VS Code works from to make conda work.


Q: Identifying Windows Active Directory Connection - Windows 8 Is there a way from within a Windows 8 store app (C#) to either identify that the OS is Windows 8 Pro or Enterprise edition?  Can you also check to see if the OS has the capability to connect to an AD domain?
I have found other posts saying that it isn't possible to find the version of Windows, and the posts suggest checking for capabilities.  I have not been able to find any information on how to check if the user is connected to a domain or not.

A: You can call UserInformation.GetDomainNameAsync to determine if the user is part of a domain.  The app must declare the Enterprise Authentication app capability.
To determine if you are on Pro, you might be able to call GetNativeSystemInfo and figure it out from the processor architecture.


Q: Python assert -- Best way to report non-existing files in a list with one line Background
I use assert statement to check if certain files in a list exist in my computer, then I would like to do further work if these files are all there.
I've referenced to this thread, so I do something like this:
from pathlib import Path

# The list containing several filepaths
files = ['folder/file1', 'folder/file2', 'folder/file3']

# check if all of these files are exist
assert all(Path(n).exists() for n in files)

# Do something else ...
# ...

This piece of code is runnable. If one file does not exist, the program will raise AssertionError.
Question
Now I would like to all the file(s) that not exist, instead of a simple AssertionError.
Is there any one-liner solution for this?
What I have tried
I've tried the following:
assert all(Path(n).exists() for n in files), f"file {n} not exist!"

Runing this code will report NameError: name 'n' is not defined.

A: You'll need to use a loop:
for file in files:
    assert Path(file).exists(), f"{file} does not exist!"

In Python 3.8+, you can do it in one line by using the walrus operator:
assert not (missing_files := [n for n in files if not Path(n).exists()]), f"files missing: {missing_files}"

A: n from comprehension isn't in scope where you do f'{n}'
You can show all not exists files
not_exists = [f for f in files if not Path(f).exists()]
assert not not_exists, f'Files {not_exists} not exist'

Or, only the first one
for f in files:
  assert Path(f).exists(), f'{f} not exists'

A: As already pointed out in comments, assert is strictly a development tool. You should use an exception which cannot be turned off for any proper run-time checks; maybe create your own exception for this. (Assertions will be turned off in production code under some circumstances.)
Secondly, the requirement to do this in a single line of code is dubious. Code legibility should trump the number of lines everywhere, except possibly in time-critical code, where execution time trumps both.
class MissingFilesException(Exception):
   pass

missing = {x for x in files if not Path(x).exists()}
if missing:
    raise MissingFilesException(
        'Missing files: {}'.format(", ".join(missing))


Q: Determining what action an NPC will take, when it is partially random but influenced by preferences? I want to make characters in a game perform actions that are partially random but also influenced by preferences.  For instance, if a character feels angry they have a higher chance of yelling than telling a joke.  So I'm thinking about how to determine which action the character will take.  Here are the ideas that have come to me.
Solution #1: Iterate over every possible action.  For each action do a random roll, then add the preference value to that random number.  The action with the highest value is the one the character takes.
Solution #2: Assign a range of numbers to an action, with more likely actions having a wider range.  So, if the random roll returns anywhere from 1-5, the character will tell a joke.  If it returns 6-75, they will yell.  And so on.
Solution #3: Group all the actions and make a branching tree.  Will they take a friendly action or a hostile action?  The random roll (with preference values added) says hostile.  Will they make a physical attack or verbal? The random roll says verbal.  Keep going down the line until you reach the action.
Solution #1 is the simplest, but hardly efficient.  I think Solution #3 is a little more complicated, but isn't it more efficient?
Does anyone have any more insight into this particular problem?  Is #3 the best solution? Is there a better solution?

A: #1 and #2 are simple but probably won't scale well to more complicated behaviors. Behavior trees (#3) seem to be the preferred system in many games nowadays. You can find some presentations and notes on AiGameDev.com, e.g. http://aigamedev.com/open/coverage/paris09-report/#session3 and http://aigamedev.com/open/coverage/gdc10-slides-highlights/#session2 (the first one from Crytek is quite good)
You probably don't need to worry about "efficiency" here in the sense of CPU usage, since this is very unlikely be a major bottleneck in your game. Reducing the amount of programmer/designer time needed to tweak the behavior is much more important.

A: If you're going to go with options 1 or 2, look into buckets of random results - see Randomness without Replacement.  If you go with a tree action, you can still use some of the same concepts to determine which branch of the tree to go down; however, you'd have a bit more determinism built in, as your options will restrict as you traverse down the tree.
If I recall correctly, Neverwinter Nights, which had a fairly nice scripting engine for its NPCs, would use a random probability to determine some of the actions their NPCs would take in certain states, but the states themselves were more driven by the script for that NPC (more of a state machine than a tree, but the concepts are similar).  For example, if the NPC was walking, there was a chance they would stop, maybe laugh, etc. - but if they were attacked, they would switch to combat and stay there.
In other words, it all depends on what your actions are, and how you want the character to behave.

A: Markov chain, influenced by real user actions.
From wikipedia:

A Markov chain is a discrete random
  process with the property that the
  next state depends only on the current
  state.


Q: javascript function internal scope property What is the Difference in internal scope property assigned on function declaration and on entering the function execution context?
Definition:
[[Scope]] property is already written and stored in function object. [[Scope]] in contrast with Scope (Scope chain) is the property of a function instead of a context.
Link:(http://dmitrysoshnikov.com/ecmascript/chapter-4-scope-chain/#function-creation)
What i mean is :as soon as function gets declared will it be assigned scope property or during execution time will scope property gets assigned.

A: This is the closure concept.  It is worded differently here than normal.  Basically there are two things going on -- first you have the closure, that is the variables that are declared locally to the context of the function definition are made available to the function.  This is the "scope chain" he refers to.  In addition, locally defined variables (var statements within the function) don't exist until the function starts at "execution context".  (Typically these are stored on the stack or a heap).


Q: Bluebird promises and async.forEach iteration This is my first time asking a question, so please bear with me. I'm trying to write a content scraper in node.js. My program will go to the landing page of the site, get the link to the next page and get the link for the next batch of pages. My problem is when I have to cycle through an array of links, go to that page, and get scrape information there. I'm trying a async.forEach iteration, but it finishes after the last then() in my chained promises.  Many of the concepts here are new to me, so I'm sure this code is screwy. Any help would be appreciated.

var sX = require('scraper-x');
var request = require('request');
var async = require('async');
var Promise = require('bluebird');
var request = (require('request'));
var colors = require('colors');

var baseURL = 'http://shirts4mike.com';
var arrShirts = [
    {
        link: 'shirt.php?id=101',
        img: 'some img'
    },
    {
        link: 'shirt.php?id=102',
        img: 'some img'
    },
    {
        link: 'shirt.php?id=103',
        img: 'some img'
    }
];

var page = '';

var configMain = {
    repeatItemGroup: '.nav > li',
    dataFormat: {
        link: {
            selector: 'li > a',
            type: 'attr:href'
        }
    }
};

var configShirts = {
    repeatItemGroup: '.products > li',
    dataFormat: {
        link: {
            selector: 'li > a',
            type: 'attr:href'
        },
        img: {
            selector: 'li > a > img',
            type: 'attr:src'
        }
    }
};

var configDetails = {
    repeatItemGroup: '.shirt-details',
    dataFormat: {
        price: {
            selector: '.price',
            type: 'text'
        },
        title: {
            selector: '.shirt-details > h1',
            type: 'text'
        }
    }
};

function getPage(url, config) {
    return new Promise(function(resolve, reject) {
        request(url, function(error, response, body, shirt) {
                if (error) {
                    console.log('error');
                    reject();
                }
                if (!error && response.statusCode == 200) {
                    detail = sX.scrape(body, config);
                    resolve(detail);
                }
            });

    });
}

function getDetailPage(arr, config) {
    return new Promise(function(resolve, reject) {
        async.forEach( arr, function( item, callback) {
            request('http://www.shirts4mike.com' + '/' + item.link, function(error, response, body, item) {
                if (!error && response.statusCode == 200) {
                    detail = sX.scrape(body, configDetails);
                    console.log('Item: ', detail);
                }
            });
           callback();
        });
        resolve(detail);
    });
}

    getPage(baseURL, configMain).then( function(data) {
        for (var i = 0; i < data.length; i++) {
            //console.log('getMainPage: ', scrapedResult[i].link);
            if (data[i].link.search('shirt') !== -1) {
                page = '/' + data[i].link;
                console.log(page.yellow);
                baseURL += page;
                return baseURL;
            }
        }
    }).then( function(baseURL) {
        return getPage(baseURL, configShirts);
    }).then( function(data) {
        for (var i = 0; i < data.length; i++) {
            //console.log(data[i].link);
            if (data[i].link.search('shirt') !== -1) {
                arrShirts.push(data[i]);
                console.log("arrShirts[" + i + "]: " + arrShirts[i].link);
            }
        }
        return arrShirts;
    }).then( function(arr) {
        return getDetailPage(arrShirts, configDetails);
    }).then(function (data) {
        console.log("end: ", data);
    }).catch( function(err) {
        console.log(err);
    });

A: I would suggest a bunch of changes.

*

*Stop using globals or higher scoped variables or undeclared variables.  Declare local variables where they are used/needed and don't share variables with other functions.

*Don't mix the async library with promises.  Since you're already promisifying your async functions, then use promise functions to manage multiple async operations.  You can just remove the async library from this project entirely.

*Promisify at the lowest level that is practical so all higher level uses can just use promises directly.  So, rather than promisifying getPage(), you should promisify request() and then use that in getPage().

*Since you have the Bluebird promise library, you can use it's higher level iteration functions such as Promise.map() to iterate your collection, collect all the results and return a single promise that tells you when everything is done.
Using these concepts, you can then use code like this:
// promisified request()
function getRequest(url) {
    return new Promise(function(resolve, reject) {
        request(url, function(err, response, body) {
            if (err) {
                reject(err);
            } else {
                resolve(body);
            }
        });

    });
}

// resolves to scraped contents for one page
function getPage(url, config) {
    return getRequest(url).then(function(body) {
        return sX.scrape(body, config);
    });
}

// resolves to an array of scraped contents for an array of objects
// that each have a link in them
function getDetailPage(arr, config) {
    return Promise.map(arr, function(item) {
        return getPage('http://www.shirts4mike.com' + '/' + item.link);
    });
}


Q: Using "this" in a jquery multiple selector Im trying to figure this one out, but no joy yet. For reasons that I cant go into here, I need to use both "this" and another selector to bind a click event.. Example
    $('mySelector').each(function(){
    $(this, this.siblings('img')).bind('click', function(e){
        e.preventDefault();
        doStuffTo($(this));
    });
});

But I cant figure out how to do it. Anyone have any idea how I would achieve it?

A: Most of the jQuery methods (that don't return a value) are automatically applied to each element in the collection, so each() is not necessary.
Combining siblings() and andSelf(), the code can be simplified to:
$('.mySelector').siblings('img').andSelf().click(function (e) {
    e.preventDefault();
    doStuffTo($(this));
});

A: Instead, you could do this:
$('mySelector').each(function(){
    $(this).siblings('img').andSelf()).bind('click', function(e){
        e.preventDefault();
        doStuffTo($(this));
    });
});

A: It's not entirely clear what you're trying to do, but perhaps it's this:
var f = function(e){
    e.preventDefault();
    doStuffTo($(this));
};

$('mySelector').each(function() {
   $(this).bind('click', f);
   $(this).siblings('img').bind('click', f);
});


Q: Google Domain Shared Contacts API Using OAuth 2.0 for Server to Server Applications - Credential params I'm trying to get the "Google Domain Shared Contacts API" described here:
https://developers.google.com/admin-sdk/domain-shared-contacts/
Working using "OAuth 2.0 for Server to Server Applications" described here:
https://developers.google.com/accounts/docs/OAuth2ServiceAccount
The recommendation from the OAuth page is to use the provided Google client library... I'm using the Java library. But the Shared-Contacts API doesn't have an example that uses this library, and I'm having trouble figuring out how to use the library with the Shared-Contacts API.
I am able to make the example for the OAuth to work for me... It uses Google Cloud Storage. Here's a snippet of the code:
String STORAGE_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write";
try {
          try {
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      String p12Content = Files.readFirstLine(new File(keyFile), Charset.defaultCharset());
      // Build service account credential.
      GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
          .setJsonFactory(JSON_FACTORY)
          .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
          .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
          .setServiceAccountPrivateKeyFromP12File(new File(keyFile))
          .build();

      // Set up and execute Google Cloud Storage request.
      String URI;

      URI = "https://storage.googleapis.com/" + BUCKET_NAME;
      HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
      GenericUrl url = new GenericUrl(URI);
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse response = request.execute();
      content = response.parseAsString();
          } catch (IOException e) {
              System.err.println(e.getMessage());
            }
          } catch (Throwable t) {
            t.printStackTrace();
          }
      return content;

It's a request to get a listing of what's in a certain bucket on GCS. It calls a specific URL using the Credentials object, where the Credentials object does the work of the OAuth, using a key file I downloaded. There's other steps involved for getting it to work (setting the service account email, etc), which I did. It returns an xml string containing what is inside the bucket, and it works fine for me.
I then tried changing the URI to this string:
URI = "https://www.google.com/m8/feeds/contacts/myGoogleAppsDomain.com/full";
and I changed the STORAGE_SCOPE variable to be this string:
STORAGE_SCOPE = "http://www.google.com/m8/feeds/";
Hoping it would then return an xml-string of the shared-contacts. But instead, it returns this error:
403 Cannot request contacts belonging to another domain
I believe I'm getting this error because I'm not specifying the "hd" parameter when I do the authentication request... However, I'm unsure how I can specify the "hd" parameter using the GoogleCredential object (or the other parameters, except for "scope")... Can someone help me with that?

A: I think the issue here is that you are not specifying which user you want to impersonate in the domain (and you haven't configured the security settings in your domain to authorize the service account to impersonate users in the domain).
The doubleclick API auth documentation has good examples on how to do this. You can use their sample and replace the scopes and API endpoint:
https://developers.google.com/doubleclick-publishers/docs/service_accounts#benefits


Q: Data Studio SYSTEM_ERROR Code 13 with SQL query SELECT user_leads.id,
       first_name                              AS 'Nombres',
       last_name                               AS 'Apellidos',
       ip                                      AS 'IP o número de telefono',
       city                                    AS 'Ciudad',
       state                                   AS 'Estado',
       From_unixtime(user_leads.timestamp)     AS 'Fecha',
       Count(wadmin.id)                        AS 'Total Grupos de Whatsapp (Admin)',
       Coalesce(Group_concat(wadmin.name), '') AS 'Grupos de Whatsapp (Admin)',
       lead_sources.name                       AS 'Fuente',
       lead_statuses.name                      AS 'Status',
       dw.session_id
FROM   user_leads
       LEFT JOIN dialogflow_sessions AS dw
              ON dw.lead_id = user_leads.id
       LEFT JOIN user_lead_global_fields AS gf_ans
              ON gf_ans.leadid = user_leads.id
       LEFT JOIN lead_sources
              ON lead_sources.id = sourceid
       LEFT JOIN lead_statuses
              ON lead_statuses.id = user_leads.statusid
       LEFT JOIN whatsapp_groups AS wadmin
              ON wadmin.admin_lead_id = user_leads.id
GROUP  BY user_leads.id
ORDER  BY user_leads.id DESC

Im currently using that query, here is what I tried

*

*Removing special characters

*Removing "as *" statements

*clearing cache

*changing sql data source and double checked my connection yet nothing

Has anyone faced this issue?

A: Found it. Data Studio doesn't like spaces in column aliases, yet it won't show any error for them. The working is the same with all spaces in aliases replaced by underscore


Q: Multiple Actions (Forms) on one Page - How not to lose master data, after editing detail data? I've got a form where users can edit members of a group.
So they have the possibilty to add members or remove existing members. So the Url goes like
".../Group/Edit/4"  Where 4 is the id of the group.
the view looks like this
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("AddUser", "Group")) %>
    <%{%>
        User
        <%=Html.TextBox("username")%>
        <input type="submit" value="Add"/>

    <%}%>

    <% using (Html.BeginForm("RemoveUser", "Group")) %>
    <%{%>

        Bestehende Mitglieder
        <%= Html.ListBox("groupMember", from g in Model.GetMembers() select new SelectListItem(){Text = g}) %>
        <input type="submit" value="Remove" />

    <%}%>
</asp:Content>

The problem is that after adding or removing one user i lose the id of the group. What is the best solution for solving this kind of problem?
Should I use hidden fields to save the group id?
Thanks in advance.

A: Hidden fields are a good way of persisting the id during posts.

A: You could use a hidden field or you could just parse the value into your route.  I'm not sure how you're parsing the group id to the view but it would look something like:
<% using (Html.BeginForm("AddUser", "Group", new { groupId = Model.GroupID })) { %>

Then your controller will look something like this using the PRG pattern
[HttpGet]
public ViewResult Edit(int groupId) {
  //your logic here

  var model = new MyModel() {
    GroupID = groupId
  };
  return View("Edit", model);
}

[HttpPost]
public ActionResult AddUser(int groupId, string username) {
  //your logic here
  return RedirectToAction("Edit", new { GroupID = groupId });
}

[HttpPost]
public ActionResult RemoveUser(int groupId, string username) {
  //your logic here
  return RedirectToAction("Edit", new { GroupID = groupId });
}

The advantage to this method is that it's more RESTful


Q: How to properly continue tasks when a given parameter is different I'm facing tasks right now and I have doubts. After an email/pass registration, I had to update the user's profile. So I first tried this:
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
    .continueWithTask(new Continuation<AuthResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setDisplayName(fullname)
                .build();
            return t.getResult().getUser().updateProfile(profileUpdates);
        }
    })
    .addOnFailureListener(this, mOnSignInFailureListener)
    .addOnSuccessListener(this, mOnSignInSuccessListener); // <- problem!

The problem is in the last line my listener waits for an AuthResult parameter but updateProfile task sends a Void. I handled that situation like bellow but it seems too messy. Tell me if there is another better way to do this:
final Task<AuthResult> mainTask;
mainTask = FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password);
mainTask
    .continueWithTask(new Continuation<AuthResult, Task<Void>>() {
        @Override
        public Task<Void> then(@NonNull Task<AuthResult> t) throws Exception {
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                .setDisplayName(fullname)
                .build();
            return t.getResult().getUser().updateProfile(profileUpdates);
        }
    })
    .continueWithTask(new Continuation<Void, Task<AuthResult>>() {
        @Override
        public Task<AuthResult> then(@NonNull Task<Void> t) throws Exception {
            return mainTask;
        }
    })
    .addOnFailureListener(this, mOnSignInFailureListener)
    .addOnSuccessListener(this, mOnSignInSuccessListener);

A: It looks like you're expecting an AuthResult to get passed directly to mOnSignInSuccessListener.  In this particular case, in my opinion, it's not worthwhile to try to coerce an extra Continuation to return the value you're looking for.
Instead of trying to arrange for the AuthResult to be passed to that listener as a parameter, the listener can simply reach directly into mainTask.getResult(), or you can save the AuthResult in a member variable and access it that way.  Either way, it's safe because the mOnSignInSuccessListener will only be invoked after mainTask completes, which ensures the AuthResult is ready.


Q: How to check if it's null? I retrieve data from database like below. How do I check whether the value retrieved from database is null?
Private Function GetBatch() As DataSet
        Dim dataset As New DataSet
        Dim adapter As Data.SqlClient.SqlDataAdapter
        Dim cn As New System.Data.SqlClient.SqlConnection(connectionstring())
        GetBatchCommand.Connection = cn
        adapter = New Data.SqlClient.SqlDataAdapter(GetBatchCommand)
        adapter.Fill(dataset)
        Return dataset
End Function

Dim dataset As New DataSet
            dataset = GetBatch()

With dataset.Tables(0)

Dim PersonID As String = .Rows(int).Item("personId")

I'd like to check whether personID is null. How do do that?

A: Try DataRow's IsNull method to check null values :
Dim isPersonIDNull As Boolean = .Rows(0).IsNull("personId")

Or use IsDBNull method :
Dim isPersonIDNull As Boolean = IsDBNull(.Rows(int).Item("personId"))

Or manually Check if the value equals DBNull :
Dim isPersonIDNull As Boolean = .Rows(int).Item("personId").Equals(DBNull.Value)

A: If DBNull.Value.Equal(.Rows(int).Item("personId")) Then
...

DBNull

A: You can also use the Convert.DbNull constant.

A: You have to check if the value is null before you assign it to PersonID
like:
if .Rows(int).Item("personId") = DBNull.Value Then
  ' Assign some Dummy Value
  PersonID = ""
else
  PersonID = .Rows(int).Item("personId")
end if

I would recommend to extract that piece of code into a helper method which gets either the value or a default for a given column.

A: This situation can occur if table with no rows, that time ds.Table(0).Rows(int).Item("personId") will return null reference exception
so you have to use two conditions
Dim PersonID As String =""
if(ds.tables.count>0) Then
 if(ds.tables(0).Rows.Count>0) Then
   if(NOT DBNull.Value.Equal((ds.tables(0).Rows(int).Item("PersonID"))) Then
              PersonID = ds.tables(0).Rows(int).Item("PersonID")

I think It will solve your issue..just minor syntax variation may be present


Q: Concatenating char variables I tried making a small program using the libraries "iostream" and "String" to display a given string backwardly as the output on the command prompt. I used a recursive returning-value (string) function to perform the whole process of getting the given string in backward and returning it to the main function to be displayed on screen, as you can see below:
#include <iostream>
#include <string>
using namespace std;
string rev(string, int);

int main() {
    string let;
    cout << "Enter your string: ";
    cin >> let;
    cout << "The string in reverse is: " << rev(let, let.length());
    cout << endl;
    return 0;
}

string rev(string x, int y) {
    if (y != 0 )
        return x[y - 1] + rev(x, y - 1);
    else
        return "\0";
}

What I don't get about the process, is that while the concatenation performed on the rev function, recursively, and with the char variables works correctly and returns the string in backward to the main function, trying to concatenate the char variables normally like this gives rubbish as the output:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string hd;
    string ah = "foo";
    hd = ah[2] + ah[1] + ah[0];
    cout << hd << endl;
    return 0;
}

And even if I add to the "hd" chain "\0", it still gives rubbish.

A: Your first example implicitly converts characters to strings and uses appropriate operator +
While your second example is adding up characters
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
returns reference to character at position

A: Writing instead
hd = ""s + ah[2] + ah[1] + ah[0];

will, informally speaking, put + into a "concatenation mode", achieving what you want. ""s is a C++14 user-defined literal of type std::string, and that tells the compiler to use the overloaded + operator on the std::string class on subsequent terms in the expression. (An overloaded + operator is also called in the first example you present.)
Otherwise, ah[2] + ah[1] + ah[0] is an arithmetic sum over char values (each one converted to an int due to implicit conversion rules), with the potential hazard of signed overflow on assignment to hd.

A: How about making use of everything that's already available?
string rev(const string &x) { return string{x.rbegin(), x.rend()}; }

Reverse iterators allow you to reverse the string, and the constructor of string with 2 iterators, constructs an element by iterati from begin to end.


Q: SQL - Average Quarter-Hour Persons (AQH) In radio broadcasting there is a term called, "Average Quarter-Hour Persons" aka (AQH), which can be defined as...as the average number of persons listening to a particular station for at least five minutes during a 15-minute period.
I am not quite sure how to start this in SQL as the listening sessions span between the different 15-minute buckets.
The 15-minute buckets are 0-15, 15-30, 30-45, and 45-60.
Here is an example from the creator of the metric, "For example, 1:00-1:05, 1:00-1:10 or 1:00-1:15 each equal one quarter-hour of listening. But, 1:11-1:19 is
not a quarter-hour of listening (there is not five minutes in either clock quarter-hour, 1:00-1:15 or 1:15-1:30)."
Let's assume I have the following table where each row contains the radio station, the time a user started listening and the time the user stopped listening.  For sake of simplicity I am not including any sort of User ID, etc.
radio_station varchar
session_start time
session_stop time
How would I write the SQL to calculate said metric per hour?

A: This query work in sql server. Only question is how to handle those sessions that span or end at midnight, how they are represented.
Set up sample data:
declare @t table(session_start time, session_stop time)
insert @t values ('1:00','1:05'),('1:00','1:10'),('1:00','1:15'),('1:11','1:19')

Query based on a CTE. Create the time buckets. If CTEs are not available, create a table containing these entries instead., and rest of the query is unchanged.
;with valid_times as (
select convert(time,'00:00') as valid_start, convert(time,'00:15') as valid_end
union all
select dateadd(minute,15,valid_start), dateadd(minute,15,valid_end)
from valid_times
where valid_start<='23:30'
)
select valid_start, valid_end,
    sum(case when datediff(minute,
        case when session_start<valid_start then valid_start else session_start end,
        case when session_stop>valid_end then valid_end else session_stop end
        )>=5 then 1 else 0 end) as AQH
from valid_times
left join @t t on valid_end>=session_start and valid_start<=session_stop
group by valid_start, valid_end


Q: Create a new column in excel with a condition I want to create a new column called Book in which I take data from a column called Exposure. If the value from the exposure column is 0, I want it to return 100, else I want to retain the same value.
This is what I've already tried:
df['Book'] = np.where(df['Exposure']==0,100,)

how do I get it to return the same value if it's not zero?

A: Try this :
df['Book'] = df['Exposure'].replace(0, 100)


Q: Does it matter which algorithm you use for Multiple Imputation by Chained Equations (MICE) I have seen MICE implemented with different types of algorithms e.g. RandomForest or Stochastic Regression etc.
My question is that does it matter which type of algorithm i.e. does one perform the best? Is there any empirical evidence?
I am struggling to find any info on the web
Thank you

A: Yes, (depending on your task) it can matter quite a lot, which algorithm you choose.
You also can be sure, the mice developers wouldn't out effort into providing different algorithms, if there was one algorithm that anyway always performs best. Because, of course like in machine learning the "No free lunch theorem" is also relevant for imputation.
In general you can say, that the default settings of mice are often a good choice.
Look at this example from the miceRanger Vignette to see, how far imputations can differ for different algorithms. (the real distribution is marked in red, the respective multiple imputations in black)

The Predictive Mean Matching (pmm) algorithm e.g. makes sure that only imputed values appear, that were really in the dataset. This is for example useful, where only integer values like 0,1,2,3 appear in the data (and no values in between). Other algorithms won't do this, so while doing their regression they will also provide interpolated values like on the picture to the right ( so they will provide imputations that are e.g. 1.1, 1.3, ...) Both solutions can come with certain drawbacks.
That is why it is important to actually assess imputation performance afterwards. There are several diagnostic plots in mice to do this.


Q: Set value of jtable column using setValueAt() I am trying to set the value of a jtable column using setValueAt() in netbeans and it is not working.
following is what i have set using 'customize code' option.
The columns showing null are of type boolean ie they can be checked and unchecked.
I want to read values from the database and set the column values accordingly.
pref_table = new javax.swing.JTable();

pref_table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
    {"MONDAY", null, null, null, null},
    {"TUESDAY", null, null, null, null},
    {"WEDNESDAY", null, null, null, null},
    {"THURSDAY", null, null, null, null},
    {"FRIDAY", null, null, null, null},
    {"SATURDAY", null, null, null, null}
},
new String [] {
    "DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
}
) {
    Class[] types = new Class [] {
    java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
};

public Class getColumnClass(int columnIndex) {
    return types [columnIndex];
}
});

As the frame containing the jtable(pref_table) is initialised,the column values are either set to true or false by calling the following function but it does not seem to work.
public void set_tab_val(boolean x,int r,int c)
{
  pref_table.setValueAt(true,r,c);
}

A: I have added a button to the frame and called the method which you wrote and it worked fine for me.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class TableSetEx
{

    static JTable pref_table;

    public static void main(String[] args) {
        pref_table = new javax.swing.JTable();

        pref_table.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"MONDAY", null, null, null, null},
            {"TUESDAY", null, null, null, null},
            {"WEDNESDAY", null, null, null, null},
            {"THURSDAY", null, null, null, null},
            {"FRIDAY", null, null, null, null},
            {"SATURDAY", null, null, null, null}
        },
        new String [] {
            "DAY", "9 A.M-11 A.M", "11 A.M-1 P.M", "1 P.M-3 P.M", "3 P.M-5 P.M"
        }
        ) {
            Class[] types = new Class [] {
            java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
        });

        JButton button = new JButton("Click");
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                // Some hardceded cell.
                set_tab_val(true,2,3);
            }
        });

        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        frame.add(new JScrollPane(pref_table), BorderLayout.NORTH);
        frame.add(button, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void set_tab_val(boolean x,int r,int c)
    {
      pref_table.setValueAt(true,r,c);
    }
}


Q: Two classes inheriting from the same base to see each other I have a program with a lot of classes. I want classes in the program to be visible to each other. For that, I am following a trick such that all classes are inherited from a base class, which holds pointers to every class. But I hit an error in doing so. Below is a piece of code produces the error I am after:
#include <iostream>
using namespace std;

class AClass;
class BClass;

class RoofClass {
 public:
  RoofClass();
  AClass* a_class;
  BClass* b_class;
};

class BaseClass {
 public:
  BaseClass(RoofClass* roof_class) {
   a_class = roof_class->a_class;
   b_class = roof_class->b_class;
  }
  AClass* a_class;
  BClass* b_class;
};

class AClass : public BaseClass {
 public:
  AClass(RoofClass* roof_class) : BaseClass(roof_class) {}
  void Afunction();
  int Aint = 1;
};

class BClass : public BaseClass {
 public:
  BClass(RoofClass* roof_class) : BaseClass(roof_class) {}
  void Bfunction();
  int Bint = 2;
};

void AClass::Afunction() {
  cout << b_class->Bint << endl;
}

void BClass::Bfunction() {
  cout << a_class->Aint << endl;
}

RoofClass::RoofClass() {
  a_class = new AClass(this);
  b_class = new BClass(this);
}

int main(int argc, char **argv) {
  RoofClass roof_class;
  cout << "b calls a" << endl;
  roof_class.b_class->Bfunction();
  cout << "a calls b" << endl;
  roof_class.a_class->Afunction();
}

Roof is the top level class which consists of classes A and B. I want A and B visible to each other. To achieve that, as I said, they both inherit from the Base class. My problem, in particular, is that while B sees A, A does not see B. The reason for this is probably due to the fact that A is initialized before B in constructor of Roof. So, why can I solve this issue?

A: When RoofClass constructor creates an instance of AClass, it passes a pointer to itself, with uninitialized members a_class and b_class. AClass constructor then copies those values and returns. When RoofClass constructor sets a_class to point to the newly constructed object, the pointers inside AClass are still pointing to nothing.
You probably want BaseClass to store a pointer to RoofClass instead:
class BaseClass {
 public:
  BaseClass(RoofClass* roof_class) {
   r_class = roof_class;
  }
  RoofClass* r_class;
};
class AClass : public BaseClass {
 public:
  AClass(RoofClass* roof_class) : BaseClass(roof_class) {}
  void Afunction();
  int Aint = 1;
  // access class B as r_class->b_class
};

A: I actually solved the question. It is like this:
In its constructor, the RoofClass creates a and b objects, in order. It first initializes a object by going into its constructor (which actually is the constructor of BaseClass due to inheritance) and setting a's a and b objects to roof's a and b. But the problem is that, roof's b is not constructed yet. That is why, a's b is initialized to a value of 00000000. When the RoofClass goes to b object's constructor for initialization, this time both roof's a and b are in place so that b's a and b's b are properly initialized. That is why, b can have a proper a but not vice versa.
The solution is introducing an InitPointer function to the base class, which acts after the roof objects constructs all a and b objects. This way, InitPointer sets pointers of a and b objects to already constructed a and b objects. Here is the working code:
#include <iostream>

using namespace std;

class AClass;
class BClass;

class RoofClass {
 public:
  RoofClass();
  AClass* a_class;
  BClass* b_class;
};

class BaseClass {
 public:
  BaseClass() {}
  void InitPointer(RoofClass* roof_class) {
    a_class = roof_class->a_class;
    b_class = roof_class->b_class;
  }
  AClass* a_class;
  BClass* b_class;
};

class AClass : public BaseClass {
 public:
  AClass() : BaseClass() {}
  void Afunction();
  int Aint = 1;
};

class BClass : public BaseClass {
 public:
  BClass() : BaseClass() {}
  void Bfunction();
  int Bint = 2;
};

void AClass::Afunction() {
  cout << b_class->Bint << endl;
}

void BClass::Bfunction() {
  cout << a_class->Aint << endl;
}

RoofClass::RoofClass() {
  a_class = new AClass();
  b_class = new BClass();
  a_class->InitPointer(this);
  b_class->InitPointer(this);
}

int main(int argc, char **argv) {
  RoofClass roof_class;
  cout << "b calls a" << endl;
  roof_class.b_class->Bfunction();
  cout << "a calls b" << endl;
  roof_class.a_class->Afunction();
}

Thanks for the all discussion!


Q: wcf configuration maxStringContentLength does not seem to be working We're trying to send a large xml string to a service method in WCF and we're getting the error

The maximum string content length
  quota (8192) has been exceeded while
  reading XML data.

The error suggests increasing the maxstringcontentlength although we weren't sure if we were supposed to do this on the client side or the server side or both. We've tried putting in on both but we still seem to get the error. I'm going to post the client and service configs below. I'm assuming there is a problem with one or both of them preventing this from working.
Any suggestions?
Client:
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_ITESTService"
                closeTimeout="00:01:00" openTimeout="00:01:00"
                receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false"
                hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288"
                maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8"
                transferMode="Buffered" useDefaultWebProxy="true">
               <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
                    maxArrayLength="2147483647" maxBytesPerRead="4096"
                    maxNameTableCharCount="2147483647" />
               <security mode="None" />
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint name="BasicHttpBinding_ITESTService"
            address="http://localhost/TESTService.svc"
            binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_ITESTService"
            contract="TESTService.ITESTService" />
    </client>
</system.serviceModel>

Server:
<system.serviceModel>
   <bindings>
      <basicHttpBinding>
          <binding
              name="BasicHttpBinding_Service1"
              maxBufferSize="2147483647"
              maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="32"
              maxStringContentLength="2147483647" maxArrayLength="2147483647"
              maxBytesPerRead="4096" maxNameTableCharCount="2147483647" />
          <security mode="None" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
       <service name="TESTService">
          <endpoint name="BasicHttpBinding_Service1"
              address="http://localhost/TESTService.svc"
              binding="basicHttpBinding"
              bindingConfiguration="BasicHttpBinding_Service1"
              contract="ITESTService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

A: Try adding a 'default' binding (without any name specified).
Add the readerQuota settings to this binding.
You can then even remove the readerQuota settings from the named binding you are actually using.
This worked for me (although I'm not sure why the readerQuotas on the correct named binding are ignored by WCF)

A: 'default' binding option worked for me. I was trying customize maxStringContentLength value in named WebHttpBinding but for some reason it did not picked up by WCF. finally I followed the D.Tiemstra work around then it started working.
    <webHttpBinding>
    <binding  maxReceivedMessageSize="2147483647" >
      <readerQuotas maxDepth="2147483647"
       maxStringContentLength="2147483647"
       maxArrayLength="2147483647"
       maxBytesPerRead="2147483647"
       maxNameTableCharCount="2147483647" />
    </binding>
  </webHttpBinding>

A: This thread explains in detail how to specify the binding settings on server and client correctly in order to change the MaxStringContentLength.
This other thread also provides a clear and efficient answer on using the readerQuotas.

A: I would use this values for the WCF configuration (programmatically):
Security = { Mode = SecurityMode.None},
CloseTimeout = TimeSpan.MaxValue,
OpenTimeout = TimeSpan.MaxValue,
SendTimeout = TimeSpan.FromMinutes(5),
ReceiveTimeout = TimeSpan.FromMinutes(5),
MaxBufferSize = 2147483647,
MaxBufferPoolSize = 524288,
MaxReceivedMessageSize = 2147483647,
ReaderQuotas = new XmlDictionaryReaderQuotas
{
   MaxDepth = 32,
   MaxStringContentLength = 8192,
   MaxArrayLength = 16384,
   MaxBytesPerRead = 4096,
   MaxNameTableCharCount =1638
}


Q: find element that doesn't equal a string in xpath Need help in finding element that doesn't equal to a string, Here is my XML:
<collection >
<device>
    <name>Test</name>
    <dcs>
        <dc>
            <nodes>
                <node>
                    <name>Host1</name>
                </node>
                <node>
                    <name>test</name>
                </node>
                <node>
                    <name>testing</name>
                </node>
            </nodes>
        </dc>
        <dc>
            <nodes>
                <node>
                    <name>test</name>
                </node>
                <node>
                    <name>testing</name>
                </node>
            </nodes>
        </dc>
    </dcs>
</device>

XPath I have tried:
/collection/device/dcs/dc/nodes/node[not(contains(name,'test'))]

O/p:
 <node>
    <name>Host1</name>
</node>

Expected O/p:
<node>
      <name>Host1</name>
</node>
<node>
      <name>testing</name>
</node>

Actual output is ignoring testing also but that I need in output.
Can anyone help me?
Thanks in advance.

A: To filter out nodes having inner text exactly equals certain value, use = operator wrapped in not() instead of using contains() in the same way  :
/collection/device/dcs/dc/nodes/node[not(name='test')]


Q: MediaPlayer.OnCompletionListener and View.OnClickListener? I  am currently trying:
extends Activity implements MediaPlayer.OnCompletionListener
extends Activity implements View.OnClickListener

at the same time and its not working or rather im not sure how to implement it...how would I go about doing this?
edit: maybe it will help if I show you guys what I have now and its not working:
package com.vamp6x6x6x.rusty;

import java.io.IOException;

import com.vamp6x6x6x.rusty.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

public class rustyactivity extends Activity implements MediaPlayer.OnCompletionListener, View.OnClickListener {
    /** Called when the activity is first created. */

    ImageView display;
    int toPhone;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);

        display = (ImageView) findViewById(R.id.IVDisplay);
        ImageView image1 = (ImageView) findViewById(R.id.IVimage1);
        ImageView image2 = (ImageView) findViewById(R.id.IVimage2);
        ImageView image3 = (ImageView) findViewById(R.id.IVimage3);
        ImageView image4 = (ImageView) findViewById(R.id.IVimage4);
        ImageView image5 = (ImageView) findViewById(R.id.IVimage5);
         Button setWall = (Button) findViewById(R.id.bSetWallpaper);

        toPhone = R.drawable.guy1;

        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);
        image4.setOnClickListener(this);
        image5.setOnClickListener(this);
        setWall.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {

        case R.id.IVimage1:
        display.setImageResource(R.drawable.guy1);
        toPhone = R.drawable.guy1;
        break;
        case R.id.IVimage2:
            display.setImageResource(R.drawable.guy2);
            toPhone = R.drawable.guy2;
            break;
        case R.id.IVimage3:
            display.setImageResource(R.drawable.guy3);
            toPhone = R.drawable.guy3;
            break;
        case R.id.IVimage4:
            display.setImageResource(R.drawable.guy4);
            toPhone = R.drawable.guy4;
            break;
        case R.id.IVimage5:
            display.setImageResource(R.drawable.guy5);
            toPhone = R.drawable.guy5;
            break;

        case R.id.bSetWallpaper:

            Bitmap whatever = BitmapFactory.decodeStream(getResources().openRawResource(toPhone));
               try{
                   getApplicationContext().setWallpaper(whatever);
               }catch(IOException e){
                   e.printStackTrace();
               }
        }

        Button ending = (Button) findViewById(R.id.theme);
        ending.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playSound(R.raw.theme);
            }
 });
    }
        private void playSound(int resId) {
            MediaPlayer mp = MediaPlayer.create(this, resId);
            mp.setOnCompletionListener(this);
            mp.start();
        }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub

    }
    }

A: extends Activity implements MediaPlayer.OnCompletionListener, View.OnClickListener
Then you need to register your activity.
mediaPlayer.setOnCompletionListener(this);
someView.setOnClickListener(this);
Where 'this' is the activity you just created

A: Stick this code right up at the start as part of the onCreate():
MediaPlayer mp = MediaPlayer.create(this, pathToTheFile, web, whereverTheSoundIs);
mp.setOnCompletionListener(this);
mp.start();

If that doesn't work, then you have a problem locating the sound file, or it is in the wrong format.
From experience, cut things down to simple parts and try and get each part working first before moving on.
Another thing I do is put comments after each } for example:  '} // End of Case'
Oh, almost forgot, in the onCompletion you might like to close off the media player with
mp.release();

Cheers

A: try this! it works to me, i hope it helps you:
main:
package com.hairdryer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

import com.hairdryer.ServiceReproductor;

public class Reproductor extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageButton btnInicio = (ImageButton) findViewById(R.id.on);
        ImageButton btnFin = (ImageButton) findViewById(R.id.off);
        btnInicio.setOnClickListener(this);
        btnFin.setOnClickListener(this);
    }

    public void onClick(View src) {
        ImageButton btnInicio = (ImageButton) findViewById(R.id.on);

        switch (src.getId()) {
        case R.id.on:
            btnInicio.setBackgroundResource(R.drawable.on2);
            startService(new Intent(this, ServiceReproductor.class));
            break;
        case R.id.off:
            stopService(new Intent(this, ServiceReproductor.class));
            btnInicio.setBackgroundResource(R.drawable.on);
            break;
        }
    }
}

ServiceReproductor.java:
package com.hairdryer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.widget.Toast;

public class ServiceReproductor extends Service implements OnCompletionListener{
    private MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        //Toast.makeText(this, "Servicio Creado", Toast.LENGTH_LONG).show();
        player = MediaPlayer.create(this, R.raw.inicio);
        player.setOnCompletionListener(this);

    }

    @Override
    public void onDestroy() {
        //Toast.makeText(this, "Servicio Detenido", Toast.LENGTH_LONG).show();
        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        //Toast.makeText(this, "Servicio Iniciado", Toast.LENGTH_LONG).show();
        player.start();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        player = MediaPlayer.create(this, R.raw.secador);
        player.start();
        player.setLooping(true);
        // TODO Auto-generated method stub

    }

}

main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/secador"
        />

    <ImageButton    android:id="@+id/off"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:background="@drawable/off"

        />
    <ImageButton    android:id="@+id/on"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/off"
        android:layout_marginRight="10dp"
        android:background="@drawable/on"

        />

</RelativeLayout>


Q: py2app and python 2.7 OSX 10.6 Does py2app work with python 2.7 on Snow Leopard?
I can't even get a 'hello world' to compile properly.
Here's what I'm doing...
My script is
print "Hello World"

and then from a terminal:
cd myFolder
py2applet --make-setup helloWorld.py myIcon.icns
python setup.py py2app

The build hangs indefinitely at this point. If I add the -A switch it will build, but crashes with a Tick Count error.
If I edit the setup.py file and set argv_emulation to 'False' it'll build with the -A option and work (still hangs indefinitely without the -A).
So my real question is:
How can I get this to build without the -A option?

A: It seems as though py2app had some issues with the 32/64-bit install of python 2.7 I was using (the official one from python.org).
I downloaded a 32-bit only version of 2.7 and it works now.
On a related note, on another build I was using wxPython and to get it to work without the -A switch I had to import the package explicitly in my setup.py file.
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
           'packages' : ['wx', 'pubsub'],

          }

A: I've read that you need to leave the 'argv_emulation': True setting out of the options for a 64bit build.  Hope this helps.


Q: Reverse Regular Expression Matching in Javascript I have a file that contains basic examples of input and output:
[Database.txt]
Hello*==Hello. How are you?
How*are*you*==I am fine I guess.
Can you*die*==I can not die. I am software.

I will get an input string that does not have punctuation.
Example: "can you ever die in a million years"
I am trying to match the input with the first side of the database on the left of "==" and return the second side of the line the string matched the first side with.
So where input = "can you ever die in a million years", output = "I can not die. I am software."
I have to use native JavaScript. This is part of a personal project I have been working on and have not been able to get past in 4 months. It is part of an independent natural speech engine that could download the file, read it to a variable, and use it as a reference. I have tried combinations of looping through lines, splitting at "==", str.match(), and a lot of other stuff. I will manage case insensitivity. Any help would be greatly appreciated.

A: You can split it up into an array, and make each left side into a regexp.
then you can run a guantlet of tests to find the match.
the tricky part is that you need to make multiple tests, beyond just one super regexp. i used [].some() to terminate after the first match is found. you can change the some with filter and collect the output to get multiple matches.
var gaunlet=[],
 str="[Database.txt]\n\
Hello*==Hello. How are you?\n\
How*are*you*==I am fine I guess.\n\
Can you*die*==I can not die. I am software.";

str.split("\n").forEach(function(a,b){
    var r=a.split("==");
    gaunlet[b]=[RegExp(r[0].replace(/\*/g,"[\\w\\W]*?"), "i"), r[1]];
});

function lookup(inp){
  var out;
    gaunlet.some(function(a){
        if(a[0].test(inp)) return out=a[1];
    });
  return out;
}

alert(lookup("can you die in a million years?"));

fiddle: https://jsfiddle.net/joaze5u6/1/
i also wrote in a fix for the way js captures wildcards, the [\w\W]*? does what .*? should probably do but doesn't in js...


Q: Index was outside the bounds of the array This is my code where I am getting error "Index was outside the bounds of the array."
var objectData = new object[colRindas.Count, 4];
     int i = 0;
     foreach (DeArtIzm izm in colRindas)
     {
         objectData[i, 1] = izm.ArtCode;
         objectData[i, 2] = izm.ArtName;
         objectData[i, 3] = izm.Price;
         objectData[i, 4] = izm.RefPrice;
         i++;//Place where I get that error
     }

What seems to be the problem hare, cause I can't find the problem.

A: Arrays are 0-indexed instead of one.
foreach (DeArtIzm izm in colRindas)
     {
         objectData[i, 0] = izm.ArtCode;
         objectData[i, 1] = izm.ArtName;
         objectData[i, 2] = izm.Price;
         objectData[i, 3] = izm.RefPrice;
         i++;//Place where I get that error
     }

A: in C#, Arrays are Zero-based by default (i.e. The first element has the index 0).
So you need to start with objectData[i, 0], and end with objectData[i, 3].


Q: How to Create plus symbol with background-color in CSS? I want to create plus symbol using CSS.
this is the final output need to be shown.

But the challenge is, to create this icon using,

*

*only use one div tag

*use before/after pseudo-elements

*can't use keyboard '+' icon as a base.

A:

#plus {
  /* change this value to the desired width */
  --width: 40px;
  /* setting the background color */
  background-color: black;
  /* setting height and width with the value of css variable */
  width: var(--width);
  height: var(--width);
  /* perfect circle */
  border-radius: var(--width);
  /* centrering */
  display: grid;
  place-items: center;
  /* don't delete this, is important for the ::before and ::after pseudoelements */
  position: relative;
}

#plus::before,
#plus::after {
  content: "";
  /* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
  /* height and width relative to css variable, change to what you feel is good */
  height: calc(var(--width) / 1.5);
  width: calc(var(--width) / 5);
  /* coloring the pseudoelements */
  background-color: white;
  /* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
  transform: rotate(calc(var(--i) * 90deg));
  /* important don't delete */
  position: absolute;
}

#plus::before {
  --i: 1;
}

#plus::after {
  --i: 2;
}

this code is relative to the width of the element, so just change the width and all the elements inside will be changed automatically!
#plus {
  --width: 5rem; /* change this value if you need */
}

or here directly on your element (if you have multiple same buttons)

for this I am using CSS variables, make sure to see this before https://developer.mozilla.org/en-US/docs/Web/CSS/var

Example:

*

*smaller value

*higher value:

so now you can see, the div remain always the same as with big values

the code:

#plus {
  /* change this value to the desired width */
  --width: 5rem;
  /* setting the background color */
  background-color: black;
  /* setting height and width with the value of css variable */
  width: var(--width);
  height: var(--width);
  /* perfect circle */
  border-radius: var(--width);
  /* centrering */
  display: grid;
  place-items: center;
  /* don't delete this, is important for the ::before and ::after pseudoelements */
  position: relative;
}

#plus::before,
#plus::after {
  content: "";
  /* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
  /* height and width relative to css variable, change to what you feel is good */
  height: calc(var(--width) / 1.5);
  width: calc(var(--width) / 5);
  /* coloring the pseudoelements */
  background-color: white;
  /* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
  transform: rotate(calc(var(--i) * 90deg));
  /* important don't delete */
  position: absolute;
}

#plus::before {
  --i: 1;
}

#plus::after {
  --i: 2;
}


Q: How can I obfuscate only com.foo.* but excluding com.foo.bar.*? (Proguard) I tried:
-keep class !com.foo.** { *; }
-keep class com.foo.bar.** { *; }

but it obfuscates classes other than com.foo.* (which I don't want)
I also tried:
-keep class !com.foo.**, com.foo.bar.** { *; }

and it fails to parse.

A: From your description I understand that you want to keep everything in the com.foo.bar package (+ subpackages?). You can achieve this by the following rule:
-keep class com.foo.bar.** { *; }

The ** pattern will match also subpackages, if you only want to current package, use * instead.
If you use a rule like this:
-keep class !com.foo.** { *; }

you will actually keep everything but com.foo.**, so you should be careful with exclusion patterns. Always include at least one inclusion pattern afterwards. The exclusion pattern should be more specific as the inclusion pattern, see below.
This rule should parse correctly (just tested it), but will not work, as ProGuard will stop evaluating a rule once it finds a match:
-keep class !com.foo.**, com.foo.bar.** { *; }

The exclusion pattern !com.foo.** will match everything in com.foo and subpackages, thus it will also match com.foo.bar.


Q: Video trimming on Android using MediaCodec, Media Extractor and Media Muxer In my Android App I need a solution when the user can trim a video from internal storage. I am trying to achieve this without using any third-party library. I was referencing this Google's Gallery App source code  here. But I am getting the following error :
timestampUs 66733 < lastTimestampUs 133467 for Video track
There are few SO questions which talk about this timestamp issue, but I am really not being to figure out as I am new to using MediaCodecs, MediaMuxers etc. Would be great if any can hep
Here's my code :
 // Set up MediaExtractor to read from the source.
    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(srcPath);
    int trackCount = extractor.getTrackCount();
    System.out.println("tracl" + trackCount);
    // Set up MediaMuxer for the destination.
    MediaMuxer muxer;
    muxer = new MediaMuxer(dstPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

    // Set up the tracks and retrieve the max buffer size for selected
    // tracks.
    HashMap<Integer, Integer> indexMap = new HashMap<>(trackCount);
    int bufferSize = -1;
    for (int i = 0; i < trackCount; i++) {
        MediaFormat format = extractor.getTrackFormat(i);

        String mime = format.getString(MediaFormat.KEY_MIME);
        boolean selectCurrentTrack = false;
        if (mime.startsWith("audio/") && useAudio) {
            selectCurrentTrack = true;
        } else if (mime.startsWith("video/") && useVideo) {
            selectCurrentTrack = true;
        }
        if (selectCurrentTrack) {
            extractor.selectTrack(i);
            int dstIndex = muxer.addTrack(format);
            System.out.println(format);
            System.out.println("dstIndex" + dstIndex);

            indexMap.put(i, dstIndex);
            if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
                int newSize = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
                bufferSize = newSize > bufferSize ? newSize : bufferSize;
            }
        }
    }

    System.out.println(indexMap);

    if (bufferSize < 0) {
        bufferSize = DEFAULT_BUFFER_SIZE;
    }
    // Set up the orientation and starting time for extractor.
    MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
    retrieverSrc.setDataSource(srcPath);
    String degreesString = retrieverSrc.extractMetadata(
            MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
    if (degreesString != null) {
        int degrees = Integer.parseInt(degreesString);
        if (degrees >= 0) {
            muxer.setOrientationHint(degrees);
        }
    }
    if (startMs > 0) {
        extractor.seekTo(startMs * 1000, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
    }

  //  System.out.println(extractor.);
    // Copy the samples from MediaExtractor to MediaMuxer. We will loop
    // for copying each sample and stop when we get to the end of the source
    // file or exceed the end time of the trimming.
    int offset = 0;
    int trackIndex = -1;
    ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();

    try {
        muxer.start();
        while (true) {

            System.out.println("copying");
            bufferInfo.offset = offset;

            bufferInfo.size = extractor.readSampleData(dstBuf, offset);

            if (bufferInfo.size < 0 ) {
               // InstabugSDKLogger.d(TAG, "Saw input EOS.");
                System.out.println("Saw input EOS.");
                bufferInfo.size = 0;
                break;
            } else {

                /**
                 * The presentation timestamp in microseconds for the buffer.
                 * This is derived from the presentation timestamp passed in
                 * with the corresponding input buffer.  This should be ignored for
                 * a 0-sized buffer.
                 */

                /**
                 * Returns the current sample's presentation time in microseconds.
                 * or -1 if no more samples are available.
                 */
                bufferInfo.presentationTimeUs = extractor.getSampleTime();

                //1 sec = 1000000 micco sec

                if (endMs > 0 && bufferInfo.presentationTimeUs > (endMs * 1000)) {

                    break;
                } else {
                    bufferInfo.flags = extractor.getSampleFlags();
                    trackIndex = extractor.getSampleTrackIndex();

                    muxer.writeSampleData(indexMap.get(trackIndex), dstBuf, bufferInfo);

                    //System.out.println(muxer);
                    extractor.advance();
                }
            }
        }

        muxer.stop();

        File file = new File(srcPath);
        file.delete();
    } catch (IllegalStateException e) {

        System.out.println("The source video file is malformed");

    } finally {

        muxer.release();

    }