text:
Q: Angular - access dynamically created form elements from controller I have a simple form, generated with ng-repeat:
<form name="myForm">
    <button ng-click="addFormElement()">+</button>

    <div ng-repeat="model in models">
        <input type="text" name="formElement{{$index}}" ng-model="model.value" />
    </div>
</form>

New elements are added by clicking the "plus" button. Here is the code:
$scope.addFormElement = function() {
    $scope.models.push({ value: "test"});

    console.log($scope.myForm);
    for (var i = 0; i < $scope.models.length; i++) {
        console.log($scope.myForm["formElement"+i]);
    }
};

The problem: in the first console log I can see the currently added new input field, but when I try to print the concrete element in the for cycle it logs "undefined". When I add more elements, the last one (currently added) is always defined in first log, but undefined in second. Do you have any idea why?
Printscreen of logs here

A: I made a plnkr where you will find a solution:
$timeout(function(){
  for (var i = 0; i < $scope.models.length; i++) {
    console.log($scope.myForm["formElement"+i]);
  }
});

https://plnkr.co/edit/oTttVJrAOiSRn3jfde5q
You should call it within a $timeout. You need it for waiting to the next digest cycle of angular. Internally $timeout will call $apply and it will force to synchronize the two way data binding.


text:
Q: rails 3, can I create a route that includes a url param? we have
match '/m/:id' => 'foo#mobilemethod'

mobilemethod accepts a url param ?find=true that puts it in 'find mode'
is there a way to add a route /f/:id that will call mobilemethod with the url param ?find=true
(or, is there a way for a method to know WHICH route was originally invoked, in which case I could simply map both /m and /f to the same method then inside the method check which one was invoked on the url)
I tried
match '/f/:id' => 'foo#mobilemethod?find=true'

and
match '/f/:id' => 'foo#mobilemethod/:id?find=true'

but get 'unknown action' errors

A: This should do this trick:
match '/f/:id' => 'foo#mobilemethod', :defaults => {:find => true}

A: match '/f/:id' => 'foo#mobilemethod'
                    ^       ^
             controller    action

match '/f/:id/find/:find' => 'foo#mobile_method'

presents the params id and finding
or do you want a default value?
match '/m/:id' => 'foo#mobilemethod', :defaults => { :find => true }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chain commands after "IF" Condtitional using & I am trying to check if a folder has been created IF NOT create the folder
IF NOT EXIST dist\\js (MKDIR dist\\js)

then regardless if it did or did not create the folder i want to run
& uglifyjs dev/*.js -m -o dist/js/app.js

now it seems that the & is not working. The second command is not executed if the folder exists.
If i use the following as my first statement:
IF NOT EXIST dist\\js (MKDIR dist\\js) ELSE (Echo exist)

the first time around I run the two together as in:
IF NOT EXIST dist\\js (MKDIR dist\\js) ELSE (Echo hate) & echo Love & uglifyjs dev/*.js -m -o dist/js/app.js

The folder gets created BUT the app.js file is not created.
Only when i run the command again it does create the app.js file.
Now how would i preferably check if theres a folder and then regardless continue with the next command.

A: (IF NOT EXIST dist\\js (MKDIR dist\\js) ELSE (Echo hate)) & echo Love & uglifyjs dev/*.js -m -o dist/js/app.js

Parentheses enclose all the code before the & to make it operate as 1 complete condition.
Once the condition is done, then the code after the & will execute regardless
of the result of the previous condition.
The doubling up of backslashs are not needed for paths in batch-file as escapes such as \n for newline are not a part of the batch-file language.


text:
Q: Execute a function based on a specific scroll position in React native I am trying to call an api base on scroll View current position but not sure how to I achieve that.
This is my code
    <ScrollView
           ref={scrollViewRef}
            scrollEventThrottle={0}
            onScroll={({nativeEvent}) => {
              console.log(
                nativeEvent.contentSize.height -
                  nativeEvent.layoutMeasurement.height,
              );
              console.log(nativeEvent.contentOffset);
            }}>

I tried to call the api inside onScroll but that didnt work well.

A: Try adding an event listener at the particular scroll location you want the function to execute.
useEffect(() => {
     Window.addEventListener('scroll'_.debounce(setScroll,1000));},[]);

A: I have solved the issue by using adding an if check. If the api data exist then the function wont execute anymore.
here's the code

const [apiData, setApiData] = useState();

onScroll={({nativeEvent}) => {
          if (!apiData) {
            if (
              nativeEvent.contentSize.height -
                nativeEvent.layoutMeasurement.height -
                nativeEvent.contentOffset.y <
              250
            ) {
              getApiDataHandler();
            }
          }
        }}


text:
Q: Handle website scroll offset based on mobile screen size I need to make this div visible if can scroll to left ,

 public showFadeLeft() {
    return this.boxToolbarElement.nativeElement.scrollWidth -
           Math.abs(this.boxToolbarElement.nativeElement.scrollLeft) !==
           this.boxToolbarElement.nativeElement.clientWidth;
   }

this.boxToolbarElement is the container of overflowing content .

The problem is when I open site in mobile the "fade-left" div be always shown , because display size (screen zoom) make "showFadeLeft() method" return different values , how can I handle any screen size .

A: NOTE: you should never use a FUNCTION inside HTML. It may cause some side effects and will decrease your application performance.
Solution

App.component.ts
isVisible = false;                  // initial value can be false or tru;

ngAfterViewInit(){                  // This life cycle hook will make sure that nativeElement is available for further operation.

   this.showFadeLeft();

}

private showFadeLeft() {           // Added private keyword

    this.isVisible = this.boxToolbarElement.nativeElement.scrollWidth -
           Math.abs(this.boxToolbarElement.nativeElement.scrollLeft) !==
           this.boxToolbarElement.nativeElement.clientWidth;
}


text:
Q: Jquery dragging two classes together at the same time I am trying to create my own timeline which has two separate divs with the same class. What I would like to do is group these two classes so they can both be dragged at the same time, no matter which one you select.
Reason for this, is because I will have one div which displays the timeline of the years, and another with the content for the corresponding years. So as you scroll from left to right, both elements must move together at the same time.
This is currently what I have...
HTML

1900

1980

1990

2000

2010

2020

This text needs to drag with the timeline

JS
$('.draggable').draggable({
    axis: 'x'
});

Fiddle
http://jsfiddle.net/kze6bqzk/
Any help on this would be appreciated.

A: You could wrap both of those divs in a single "draggable" block.
This keeps the two content divs seperate which will allow you to use them in code as you see fit, however the wrapper "draggable" div ensures they are moved together.

1900

1980

1990

2000

2010

2020

This text needs to drag with the timeline

JSFiddle


text:
Q: sorting based on alphabetical order I've the below XML document.
<case.considered>
    <case.ref BVtable="yes">
        <citetitle type="case" full="Lee Ting Lam v Leung Kam Ming" legtype="ord">Lee Ting Lam v Leung Kam Ming</citetitle>
        <citecitation full="[1980] HKLR 657">[1980] HKLR 657</citecitation>
    </case.ref>
</case.considered>
<case.considered>
    <case.ref BVtable="yes">
        <citetitle type="case" full="Chan Pui Ki v Leung On" legtype="ord">Chan Pui Ki v Leung On</citetitle>
        <citecitation full="[1996] 2 HKLR 401, [1996] 2 HKC 565">[1996] 2 HKLR 401</citecitation>
    </case.ref>
</case.considered>
<case.considered>
    <case.ref BVtable="yes" annotation="considered">
        <citetitle type="case" full="Sung Fuk Wah v Lam Wai Leuk" legtype="ord">Sung Fuk Wah v Lam Wai Leuk</citetitle>
        <citecitation full="(unrep., HCA 3676/1994, [1995] HKLY 527)">(unrep., HCA 3676/1994)</citecitation>
    </case.ref>
</case.considered>
<case.considered>
    <case.ref BVtable="yes" annotation="distinguished">
        <citetitle type="case" full="Blamire v South Cumbria Health Authority" legtype="ord">Blamire v South Cumbria Health Authority</citetitle>
        <citecitation full="[1993] PIQR Q1">[1993] PIQR Q1</citecitation>
    </case.ref>
</case.considered>
<case.considered>
    <case.ref BVtable="yes" annotation="distinguished">
        <citetitle type="case" full="W (A child) v Hammersmith Hospitals NHS Trust" legtype="ord">W (A child) v Hammersmith Hospitals NHS Trust</citetitle>
        <citecitation full="[2002] 3 QR 5, [2002] All ER (D) 397">[2002] All ER (D) 397</citecitation>
    </case.ref>
</case.considered>

and the below XSLT
    <xsl:template match="ref.group" name="ref.group">
        <xsl:if test="leg.mentioned">
            <xsl:for-each select="./leg.ref">
                <xsl:if test="./@considered='no'">

                        <xsl:text>Legislation mentioned in the judgment</xsl:text>

                        <xsl:value-of select="citetitle"/>
                        <xsl:text>, </xsl:text>
                        <xsl:for-each select="./leg.ptr.group/leg.ptr">
                            <xsl:value-of select="."/>
                            <xsl:if test="not(position() = last())">
                                <xsl:text disable-output-escaping="yes">, </xsl:text>
                            </xsl:if>
                        </xsl:for-each>

                </xsl:if>
            </xsl:for-each>
        </xsl:if>
        <xsl:if test="//case.considered">

                <xsl:text>Case cited in the judgment</xsl:text>

            <xsl:apply-templates select="//case.considered" mode="x"/>
        </xsl:if>
        <xsl:if test="./other.mentioned">

                <xsl:text>Other materials mentioned in the judgment</xsl:text>

            <xsl:apply-templates select="./other.mentioned"/>
        </xsl:if>
        <xsl:apply-templates select="//judgment"/>
    </xsl:template>

  <xsl:template match="case.considered" mode="x">

            <xsl:apply-templates select="case.ref" mode="x"/>

    </xsl:template>

    <xsl:template match="case.ref" mode="x">

            <xsl:value-of select="./citetitle[@full]"/>

        <xsl:text> </xsl:text>
        <xsl:value-of select="./citecitation/@full"/>
    </xsl:template>

here i'm unable to know how to sort the data based on the text in citetitle
please let me know how to sort the data.
Thanks

A: I am guessing it is the case.considered you wish to add the sorting to. Currently, you are doing this
<xsl:apply-templates select="//case.considered" mode="x"/>

To do sorting, you would need to change it to this
<xsl:apply-templates select="//case.considered" mode="x">
    <xsl:sort select="case.ref/citetitle" />
</xsl:apply-templates>

This does assume only one case.ref element per case.considered element though. If there are more than one, only the first one is used in the sorting.


text:
Q: What is a "current load" on a 24 V input used for? The MAX14821 (datasheet) is a 24 V IO device that features selectable current loads for use in actuators on the inputs.
What would this be used for? It's not just to load a 24 V "high" signal coming from a PNP-logic output, i.e. pull the input down of there's no signal? If it were, where's the equivalent high side current source for use with NPN signals?

A: Their reasoning:

The C/Q and DI inputs have selectable current sinks that can be
  enabled for use in actuators where the master requires a Type 2 load.

What is a Type 2 load?
I'm not so sure on this one, but the hint I found was on the Pepperl and Fuchs page:

Switching point   according to DIN EN 61131-2 (Type 2)
0 (unattenuated)  ≤ 3 mA
1 (attenuated)    ≥ 5 mA

I don't have access to the DIN EN 61131-2, so I cannot give a more detailed explanation. Seems like there is a digital input standard related to current and 7 mA seems like a safe number to make something go high.

A: PLC Standards Compliance Ensures Future-Proof Solutions
 ( two slightly different stds )
IO-Link Versions 1.0 and 1.1.2
IEC IEC61131.9 SDCI

Selectable means USA or EU stds for C/Q IO interfaces.  (clk & data high voltage long wire bus standards)
Optional 6mA/7mA Current Loads at Both 24V Inputs is the selection
For use with hi-side logic in 500m communication buswire pairs up to 400Kbaud ??
ie. 4k load to ground from 24V/4k = 6mA
e.g. IEC 61131 Type 1 uses 7mA with noise margins that @Arsenal pointed out for Type 2

Ref: IO-Link is the first standardised IO technology worldwide (IEC 61131-9) for the communication with sensors and also actuators.  http://io-link.com/share/Downloads/At-a-glance/IO-Link_System_Description_engl_2013.pdf
A logic "1" is defined by the received voltage from a defined current in a selected load resistor to ground.  If IO link is 6mA * 4k =24V then  IEC611131.9 is 7mA * ?? ....  and the thresholds are used for noise margins.
If you search hard enough you can read all the IEC standards free.
http://www.plcopen.org/pages/tc1_standards/  what each dash number means


text:
Q: Find the average acceleration Find the average acceleration of the tip of the 2.4-cm long hour hand in the interval noon to 6pm.
I found the average velocity is -2.2x10^6 but I'm not sure how to go about finding acceleration. If someone has a few minutes can we chat and you can explain the set up to me?

A: Average velocity is displacement over time: in this case, $4.8$ cm in $6$ hours.
That won't help much with computing average acceleration.
Average acceleration is change in velocity over time. The speed of the tip of the hand doesn't
change, but between noon and $6$ pm its direction reverses. So the change in velocity is
equal to twice the speed. Divide by $6$ hours.


text:
Q: Is it possible to compile a Rails app to a Java VM JAR file? Essentially the only thing I can deploy to my deployment machine is a JAR file.  I can't install JRuby, nor can I install Glassfish or Tomcat.
Is it possible to package up a Rails application (including Rails, vendored, of course) to a JAR file such that I can do
c:\my_server> java rails_app.jar

and have it run WEBRick or Mongrel within the JVM?

A: I wrote an article a year ago about how to embed your ruby sources with jruby and everything else you want into one jar file, and then run it with "java -jar myapp.jar".
It will need some work to make it boot rails I guess, but it should not be too hard. And with the complimentary jruby documentation on their wiki, i guess you can run a jetty+war thing fairly easily with this technique.
The article is here:
http://blog.kesor.net/2007/08/14/jruby-in-a-jar/

A: I'd recommend that you checkout Jetty.  The process for Embedding Jetty is surprisingly easy, and it should be possible to give it your servlets from your current jar file.  I haven't used Ruby/Rails, though, so I'm not sure if there are any complications there.
Is it normally possible to embed all of your rails templates/models into a jar inside of a war file for deployment on Tomcat?  If so, then you should be able to get embedded Jetty to pull it from your single jar as well.

A: It may be a bit dated, but Nick Sieger, one of the JRuby contributors wrote about warbler a while ago.
Warbler is about packaging a Rails app into a .war file. Now I'm not a big Java guy, so I'm not sure where your .jar restriction comes from. war files are similar to jars but they're for whole websites or something.
Worst case, I'm pretty sure the JRuby wiki has something about the state of packaging Rails apps to be run on Java architectures. It's in their best interest to have info about that.

A: I don't think you can run Mongrel within the JVM. Trying to run a webserver of any kind without Tomcat or Jetty is probably way more trouble than it's worth. jsight's answer looks helpful for that problem. If you can get that far, here's a page on JRuby's site about running JRuby on Rails in Tomcat.

A: you might want to try asking this question on the JRuby mailing list/forum(http://xircles.codehaus.org/lists/user@jruby.codehaus.org).
Another place someone would have done the same is the glassfish mailing list
Yet another thing you might want to do is to bundle winstone embeddable servlet container AND jruby AND rails and use jarjar to create one big jar. You might be able to build an ant build file to build such a BIG jar that also includes your rails application. One project that used this approach is hudson(https://hudson.dev.java.net/) -- you may get some info on how to go about doing that.
BR,
~A

A: I just ran across this blog today, and I intend on giving it a try, if anyone else has let me know
http://matthewkwilliams.com/index.php/2010/03/02/rails-jruby-in-a-jar/


text:
Q: How to get logical ID of resource with CDK? I'm attempting to write some tests for a CDK Construct that validates security group rules defined as part of the construct.
The Construct looks something like the following.
export interface SampleConstructProps extends StackProps {
  srcSecurityGroupId: string;
}

export class SampleConstruct extends Construct {
  securityGroup: SecurityGroup;

  constructor(scope: Construct, id: string, props: SampleConstructProps) {
    super(scope, id, props);

    // const vpc = Vpc.fromLookup(...);
    this.securityGroup = new SecurityGroup(this, "SecurityGroup", {
      vpc: vpc,
      allowAllOutbound: true,
    });

    const srcSecurityGroupId = SecurityGroup.fromSecurityGroupId(stack, "SrcSecurityGroup", props.srcSecurityGroupId);

    this.securityGroup.addIngressRule(srcSecurityGroup, Port.tcp(22));
  }
}

And I want to write a test that looks something like the following.
test("Security group config is correct", () => {
  const stack = new Stack();
  const srcSecurityGroupId = "id-123";
  const testConstruct = new SampleConstruct(stack, "TestConstruct", {
    srcSecurityGroupId: srcSecurityGroupId
  });

  expect(stack).to(
    haveResource(
      "AWS::EC2::SecurityGroupIngress",
      {
        IpProtocol: "tcp",
        FromPort: 22,
        ToPort: 22,
        SourceSecurityGroupId: srcSecurityGroupId,
        GroupId: {
          "Fn::GetAtt": [testConstruct.securityGroup.logicalId, "GroupId"], // Can't do this
        },
      },
      undefined,
      true
    )
  );
});

The issue here is that the test is validated against the synthesized CloudFormation template, so if you want to verify that the security group created by this construct has a rule allowing access from srcSecurityGroup, you need the Logical ID of the security group that was created as part of the Construct.
You can see this in the generated CloudFormation template here.
{
  "Type": "AWS::EC2::SecurityGroupIngress",
  "Properties": {
    "IpProtocol": "tcp",
    "FromPort": 22,
    "GroupId": {
      "Fn::GetAtt": [
        "TestConstructSecurityGroup95EF3F0F", <-- This
        "GroupId"
      ]
    },
    "SourceSecurityGroupId": "id-123",
    "ToPort": 22
  }
}

That Fn::GetAtt is the crux of this issue. Since these tests really just do an object comparison, you need to be able to replicate the Fn::Get invocation, which requires the CloudFormation Logical ID.

Note that the CDK does provide a handful of identifiers for you.

*

*Unique ID provides something very close, but it's not same identifier used in the CloudFormation stack. For example, securityGroup.uniqueId returns TestStackTestConstructSecurityGroup10D493A7 whereas the CloudFormation template displays TestConstructSecurityGroup95EF3F0F. You can note the differences are the uniqueId prepends the Construct ID to the logical identifier and the appended hash is different in each.

*Construct ID is just the identifier that you provide when instantiating a construct. It is not the logical ID either, though it is used as part of the logical ID. I also have not seen a way of programmatically retrieving this ID from the construct directly. You can of course define the ID somewhere and just reuse it, but this still doesn't solve the problem of it not fully matching the logical ID. In this case it's a difference of SecurityGroup as the construct ID and TestConstructSecurityGroup95EF3F0F as the logical ID in the synthesized template.

Is there a straightforward way getting the logical ID of CDK resources?

A: From my testing, it seems that stack.getLogicalId will always return the original, CDK allocated logicalId, it won't change if you call overrideLogicalId, so it won't always match the synthed output.
This worked for me, even with a logicalId override set:
stack.resolve((construct.node.defaultChild as cdk.CfnElement).logicalId)

stack.resolve is necessary because .logicalId is a token.

A: In addition to the excellent answer from jaredready, you can also explicitly set the logical ID using resource.node.default_child.overrideLogicalId("AnyStringHere")
This may make it easier as you can set it once and use hard-coded strings rather than looking up the value for every test.

A: After writing up this whole post and digging through the CDK code, I stumbled on the answer I was looking for. If anybody has a better approach for getting the logical ID from a higher level CDK construct, the contribution would be much appreciated.
If you need to get the logical ID of a CDK resource you can do the following:
const stack = new Stack();
const construct = new SampleConstruct(stack, "SampleConstruct");
const logicalId = stack.getLogicalId(construct.securityGroup.node.defaultChild as CfnSecurityGroup);

Note that you you already have a CloudFormation resource (eg something that begins with with Cfn) then it's a little easier.
// Pretend construct.securityGroup is of type CfnSecurityGroup
const logicalId = stack.getLogicalId(construct.securityGroup);


text:
Q: Problema login Java y MYSQL hoy vengo con ustedes porque me surgio un problema con un login que estoy haciendo en Java con conexion a BD MYSQL.
Mi clase conexion:
public class Conexion {
Connection conectar = null;
    public Connection conexion(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            System.out.println("Registrado");
            System.out.println("");

            conectar=DriverManager.getConnection("jdbc:mysql://localhost/matematicas?" + "useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&user=root&password=Csgo1997" );
        } catch(Exception ex){
                System.out.println(ex + "Error en la conexion");
                ex.printStackTrace();
            }
         return conectar;
    }

    public void cerrarConexion(){
       try {
           conectar.close();
       } catch (SQLException ex) {
            ex.printStackTrace();
       }
    }

}
Ahora, el metodo que uso para el boton de "logueo"
private void validar() {
    //FIXME: Arreglar este metodo porque no entra a BD
Conexion conexion = new Conexion();
conexion.conexion();
    Connection connection = null;
    int resultado = 0;

    try {
        String usuario = txtUsuario.getText();
        String pass = String.valueOf(txtPassword.getPassword());

        String sql = "SELECT * FROM profesor WHERE usuario = '" + usuario + "' and password = '" + pass + "' ";
        Statement statement = connection.createStatement();
        ResultSet resultset = statement.executeQuery(sql);

        if(resultset.next()){
            resultado = 1;

            if (resultado == 1) {
                ventanaOpcionesProfesor voProfesor = new ventanaOpcionesProfesor();
                voProfesor.setVisible(true);
                this.dispose();
            }else{
                JOptionPane.showMessageDialog(null, "Error, vuelve a intentarlo");
            }
        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, " Error en el codigo, metodo validar "  +  e.getMessage());
    }
}

Al parecer no entra a la consulta sql, se va de largo al catch y me marca ese error. Llevo varios dias intentando solucionarlo pero, no doy con el error. ¿Alguna idea de lo que pueda estar pasando?

A: Estás usando una clase que no hereda los métodos de la clase Connection. Mi sugerencia es convertir el método public Connection conexion() en un método estático, o inicializar la conexión directamente desde la función validar().
public class Conexion {
    private static Connection conectar = null;
    public static Connection conexion(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            System.out.println("Registrado");
            System.out.println("");

            Connection conectar = DriverManager.getConnection("jdbc:mysql://localhost/matematicas?" + "useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&user=root&password=Csgo1997" );
        } catch(Exception ex){
            System.out.println(ex + "Error en la conexion");
            ex.printStackTrace();
        }
        return conectar;
    }

    public static void cerrarConexion(){
         try {
             conectar.close();
         } catch (SQLException ex) {
             ex.printStackTrace();
         }
    }
}

Debés tener cuidado con las instancias de las clases, así como la herencia de métodos y propiedades.


text:
Q: use recursion to find values of nested dict and return keys of the dict I have an exercise where a dictionary of birthdays is given as follows:
    birthdays =
    {"Anne": {"month":"Jan","day":"27"},
    "Mike":{"month":"Feb","day":"13"},
    "Nicolas":{"month":"Jun","day":14},
    "Marta": {"month":"Jan","day":16}}

The question is to define a function which, given a month, prints a list of all the people who have birthdays in that month, with the dates.
Here's what I've got so far:
    def birthbymonth(book, month):
        for k,v in book.items():
            if isinstance(v, dict):
                birthbymonth(v,month)
            else:
                if month == v:
                    print(book)

Which when called birthbymonth(birthdays,"Jan") prints:
    {'month': 'Jan', 'day': '27'}
    {'month': 'Jan', 'day': 16}

Yet I dont know how to also print the names of the people that have birthdays then.

A: I don't see any reason to use recursion here.
def birthbymonth(book, month):
    for person,birthday in book.items():
        if birthday['month'] == month:
            print('{}: {} {}'.format(person, birthday['month'], birthday['day']))

A: As others have pointed out, there is no need for recursion. Instead, use a list comprehension:
birthdays = {"Anne": {"month":"Jan","day":"27"},
"Mike":{"month":"Feb","day":"13"},
"Nicolas":{"month":"Jun","day":14},
"Marta": {"month":"Jan","day":16}}
def dates(birthdays, month):
   return ["{}: {}".format(a, b['day']) for a, b in birthdays.items() if b['month'] == month]

print(dates(birthdays, 'Jan'))

Output:
['Marta: 16', 'Anne: 27']

A: If you really wanted to use recursion (not recommended for this problem), you can make a few modifications to your existing code:
birthdays = {
    "Anne": {"month":"Jan","day":27},
    "Mike": {"month":"Feb","day":13},
    "Nicolas": {"month":"Jun","day":14},
    "Marta": {"month":"Jan","day":16}
}

def birthbymonth(book, month):
    names = []
    for k,v in book.items():
        if isinstance(v, dict):
            names += [(k, book[k]["day"])] if birthbymonth(v,month) is True else []
        else:
            if month == v:
                return True
    return names

print(birthbymonth(birthdays, 'Jan'))
#[('Marta', 16), ('Anne', 27)]

A: Here is one solution:
birthdays = {"Anne": {"month":"Jan","day":"27"},
             "Mike": {"month":"Feb","day":"13"},
             "Nicolas": {"month":"Jun","day":14},
             "Marta": {"month":"Jan","day":16}}

{k: v['day'] for k, v in birthdays.items() if v['month']=='Jan'}

# {'Anne': '27', 'Marta': 16}


text:
Q: NSOperationQueue queue waitUntilAllOperationsAreFinished hangs I have an iphone app where on the loading of a view controller, I want to call a web service , get and parse XML all on the background thread. Then update the ui after the thread is done, then fire off another thread to do a secondard operation in another background thread.
Sort of like chaining threading calls:

*

*UI Thread -> Create BG Thread

*BG Thread -> Call XML service and get results

*UI Thread -> Update UI of the success of the BG Thread operation

*BG Thread -> Fire off part 2 of the operation

All on load of the app.
The issue is that my first, BG Thread operation never seems to end. I added in a waitUntilAllOperationsAreFinished call after step 2 is done, just to see whats going on and my app never seems to get past that point.
This is sort of the basic skeleton implementation:
- (void) viewDidLoad
{
    queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];

    //other stuff

    [self loadFriendsInBackgroundThread];
}

- (void) loadFriendsInBackgroundThread
{
    NSInvocationOperation *operation = [NSInvocationOperation alloc];
    operation = [operation initWithTarget:self selector:@selector(invokeLoadingOfFriends:) object: nil];

    [queue addOperation:operation];
[operation release];
}

- (void) invokeLoadingOfFriends: (id) obj
{
    //webservice calls and results

    [self performSelectorOnMainThread:@selector(invokeRefreshAfterLoadingFriends:)
                       withObject:nil
                    waitUntilDone:YES];
}

- (void) invokeRefreshAfterLoadingFriends: (id) obj
{
    //this line is where is hangs
    [queue waitUntilAllOperationsAreFinished];

    //never gets here
    [self refresh: NO];
}

Any ideas as to why the first thread call never seems to end?
Thanks for any help you can give
Mark

A: Here, you are calling a method on the main thread that waits until the called method is done (waitUntilDone:YES):
[self performSelectorOnMainThread:@selector(invokeRefreshAfterLoadingFriends:)
                   withObject:nil
                waitUntilDone:YES];

You then call -invokeRefreshAfterLoadingFriends: which holds up the main thread until the operation finishes, so the method never gets "done". From the documentation for -waitUntilAllOperationsAreFinished:
When called, this method blocks the current thread and waits for the receiver's current and queued operations to finish executing.
As a result, the -invokeLoadingOfFriends: operation method sits waiting for the main thread's method to finish, which never happens because you held up the main thread with [queue waitUntilAllOperationsAreFinished].
Try setting waitUntilDone to NO and see if this helps the operation finish.


text:
Q: Which interface does a specific IP address will get routed over? Is there a way to determine which netdev or IP link interface that a given IP address will route over … in bash/shell language?
This is not about what an IP address is, given a network device name.
Given a destination IP address, bash would automagically determine (with OS assist from its internal IP route table, netstat -i -n) in printing the network device name.

A: ip route get is what you're looking for; maybe it's ip route show to, depending on whether you checking should be allowed to change the routing state.
See man ip-route for more details.


text:
Q: DataGrid column selection events What event is called when you click on an editable field to edit it, and then click off of the field? in a datagrid using Flex 4? If I'm not making much sense I'm trying to make a datagrid where you can edit the fields and once you're done editing those fields the application calls an event listener which triggers a save method.

A: Here is the answer for future reference:
DataGridEvent.itemEditBegin and DataGridEvent.itemEditEnd.
From the flex docs.


text:
Q: Ошибка считывания и обработки данных HTML-формы на JS Помогите, функция рабочая, но нужно, чтобы при нажатии кнопки проверить считывались заполненные данные в input-ах и выполнялся скрипт. Не понимаю, почему не работает.

function validate(form) {
  if (Math.pow((x - x0), 2) + Math.pow((y - y0), 2) > Math.pow(R, 2) && x > x0 - R && x < x0 + R && y > y0 - R && y < y0 + R) {
    alert("Точка находится между окружностью и сторонами квадрата");
  } else {
    alert("Точка не находится между окружностью и сторонами квадрата");
  };
<!DOCTYPE html>

  <meta charset="utf-8">

  <form>

        x

          <input name="x" type="text">

      y

        <input name="y" type="text">

        x0

          <input name="x0" type="text">

        y0

          <input name="y0" type="text">

        R

          <input name="R" type="text">

    <input type="button" onclick="validate(this.form)" value="Проверить">
  </form>

A: Для начала у вас есть ошибка в HTML-коде. У вас пропущен открывающий тег
.
Во-вторых, в самом конце JS-кода лишняя точка с запятой.
В-третьих, пропущена закрывающая фигурная скобка для функции в конце кода.
И наконец - откуда вы берёте эти переменные x, x0, и т.д.? Вы их не создали и не присвоили им значение. Да, у вас есть форма в объекте, но вы не можете обращаться к элементам внутри этого объекта. Вам надо их сначала "найти". Но так как мы используем нативный JS, то будем искать не в самом объекте form, а в DOM-дереве страницы.
Вот ваш код полностью исправленный:

function validate(form) {
  var x = document.getElementsByName("x");
  var y = document.getElementsByName("y");
  var x0 = document.getElementsByName("x0");
  var y0 = document.getElementsByName("y0");
  var R = document.getElementsByName("R");
  if (Math.pow((x - x0), 2) + Math.pow((y - y0), 2) > Math.pow(R, 2) && x > x0 - R && x < x0 + R && y > y0 - R && y < y0 + R) {
    alert("Точка находится между окружностью и сторонами квадрата");
  } else {
    alert("Точка не находится между окружностью и сторонами квадрата");
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">

  <form>

        x

          <input name="x" type="text">

        y

          <input name="y" type="text">

        x0

          <input name="x0" type="text">

        y0

          <input name="y0" type="text">

        R

          <input name="R" type="text">

    <input type="button" onclick="validate(this.form)" value="Проверить">
  </form>


text:
Q: Using $this when not in object context with ReflectionFunction->invoke() class someClass {
    private $success = "success\n";
    function getReflection() {
        return new ReflectionFunction(function() {
            print $this->success;
        });
     }
}
$reflection = (new someClass)->getReflection();
$reflection->invoke();

When I run this, I get a
Fatal error: Using $this when not in object context in Command line code on line 5

What's happening here? Why is $this not defined there...?
As I'm in a Closure inside a method, $this normally should be defined. And yes, I'm on a newer version than PHP 5.4.
How can I fix it?

A: ReflectionFunction is operating on unbound Closures. That's why after the ReflectionFunction::invoke() call, there's no defined $this variable inside the Closure and as such your fatal error appears.
But there's a way around it.
ReflectionFunction offers you three necessary methods to call it with the $this binding:

*

*ReflectionFunctionAbstract::getClosure()

*ReflectionFunctionAbstract::getClosureThis()

*ReflectionFunctionAbstract::getClosureScopeClass()
The ReflectionFunctionAbstract::getClosure() is still unbound, but we can bind it via Closure::bind().
All Closure::bind() needs is the Closure, the wished object to be bound to and the class scope.
Then the solution is:
call_user_func(\Closure::bind(
    $reflection->getClosure(),
    $reflection->getClosureThis(),
    $reflection->getClosureScopeClass()->name));

I initially wanted to post this as a question only, but I had found the solution myself just before posting, so just adding the answer. Context was this issue: https://github.com/rdlowrey/Auryn/pull/72


text:
Q: Filter output of windbg I'm trying to filter the output of a command, e.g the output of lm is too long.
Something similar to lm | find "some_string".
Does windbg support that? I can't find any document online talking about it.

A: I just wrote a Grep-like WinDbg extension, please try it and reply to me if it meets your requirement.
The supported commands are as below:
!silent               : Switch On/Off silent mode
!grep                 : Filter lines by regular expression
!igrep                : Filter lines by regular expression, case-insensitive
!grep_format          : Do regular expression searching, output formatted result upon captured groups
!igrep_format         : Do regular expression searching, output formatted result upon captured groups, case-insensitive
!grep_formatx         : Do regular expression searching, output formatted result upon captured groups, then execute formatted string as windbg commands
!igrep_formatx        : Do regular expression searching, output formatted result upon captured groups, case-insensitive, then execute formatted string as windbg commands

A: If you cant use shell there are few extensions like domdbg  by denis.  Mex by microsoft etc that offers  grep / findstr implementations. So you can use it like.  !grep foo "lm"

A: I usually use the .shell command, either with windows tools (like findstr) or binaries installed with cygwin. .shell command help from MSDN
Example :
Windbg version, although this should work with older versions too:
0:000> version
[snip]
Microsoft (R) Windows Debugger Version 10.0.14321.1024 X86
Copyright (c) Microsoft Corporation. All rights reserved.

Started notepad
0:000> |
.  0    id: 31a0    create  name: notepad.exe

list modules :
0:000> lm
start    end        module name
00030000 0006e000   notepad    (deferred)
52270000 52280000   FeClient   (deferred)
6d360000 6d4af000   PROPSYS    (deferred)
6f650000 6f879000   iertutil   (deferred)
6f880000 6fa14000   urlmon     (deferred)
73c40000 73c5b000   bcrypt     (deferred)
73dc0000 73e2a000   WINSPOOL   (deferred)
73ee0000 740ea000   COMCTL32   (deferred)
74130000 7413a000   CRYPTBASE   (deferred)
74140000 7415e000   SspiCli    (deferred)
746b0000 7472b000   msvcp_win   (deferred)
74730000 7488f000   USER32     (deferred)
74890000 74970000   KERNEL32   (deferred)
749d0000 74a58000   shcore     (deferred)
[snip]

Use Windows findstr to get all module with "kern" (case insensitive)
0:000> .shell -ci "lm" findstr /i kern
74890000 74970000   KERNEL32   (deferred)
76ac0000 76acd000   kernel_appcore   (deferred)
77530000 776d1000   KERNELBASE   (deferred)
.shell: Process exited

The same with grep.exe (from cygwin, which is in my %PATH%)
0:000> .shell -ci "lm" grep.exe -i kern
74890000 74970000   KERNEL32   (deferred)
76ac0000 76acd000   kernel_appcore   (deferred)
77530000 776d1000   KERNELBASE   (deferred)
.shell: Process exited

[edit]
This command is very powerful as you can easily send windbg's command outputs to script interpreters (I use python a lot at work) :
.shell -ci "<windbg command>" python mypythonscript.py

A: WinDbg has built-in support for filtering for some commands, such as the lm command you gave as an example:
lm m *kern*

The advantage over Neitsa's answer is that the clickable links in the output still exist, so that you can see the path to the modules for example.


text:
Q: Detect telephone tap, i.e.:  on UIWebview I am trying to get a function to be called when a phone number is tapped on my UIWebView but this seems a little tricky.
The link is pretty straightforward, it looks like 23231343
So All I need to do is simply emit an ajax to googleAnalytics so I can tell a phone call was placed. (I know it might not be actually placed, if the user declines, but I'd like to get the ajax nonetheless)
I was expecting to receive a call in the callback: webView:shouldStartLoadWithRequest:navigationType, but it doesn't fire.

A: Inject this script into the view:
(function(){
    window.addEventListener("click", function(event) {
        var element = event.target;
        do{
            if(element.href && element.href.indexOf("tel:") === 0){
                var request = new XMLHttpRequest();
                request.open("GET", "https://www.example.org");
                request.send();
            }
        }while(element = element.parentNode);
    });
})();


text:
Q: Deleting in linked lists? I wrote the following code:
#include<stdio.h>

struct student{
char name[25];
double gpa;
struct student *next;
};

struct student *list_head;

struct student *create_new_student(char nm[], double gpa)
{
         struct student *st;
         printf("\tcreating node\t");
         printf("\nName=%s \t Gpa= %.2f\n", nm, gpa);

         st = (struct student*)malloc(sizeof (struct student ));
         strcpy(st->name, nm);
         st->gpa = gpa;
         st->next = NULL;
         return st;
}

void printstudent(struct student *st)
{
         printf("\nName %s,GPA %f\n", st->name, st->gpa);
}

void insert_first_list(struct student *new_node)
{
         printf("\nInserting node: ");
         printstudent(new_node);
         new_node->next = list_head;
         list_head = new_node;
}

struct student *delete_first_node()
{
         struct student *deleted_node;
         printf("\nDeleting node: ");
         printstudent(deleted_node);
         list_head = list_head->next;
         return deleted_node;
}

void printlist(struct student *st)
{
         printf("\nPrinting list: ");
         while(st != NULL) {
             printstudent(st);
             st = st->next;
         }
}

int main()
{
         struct student *other;
         list_head = create_new_student("Adil", 3.1);
         other = create_new_student("Fatima", 3.8);
         insert_first_list(other);
         printlist(list_head);
         other = delete_first_node();
         printlist(list_head);
         return 0;
}

When I run it, there are no errors or warnings. However, it stops at the delete part.The message says the program has stopped working.
Can you please help me find the problem?

A: In function delete_first_node the node deleted_node is not initialized and passed to function printstudent which try to access its member, results in undefined behavior.
The function should be
struct student *delete_first_node(){
    struct student *deleted_node = list_head;
    printf("\nDeleting node: ");
    if(deleted_node != NULL)
    {
        printstudent(deleted_node);
        list_head= list_head->next;
        free(deleted_node);
    }
    else
       printf("List is emty\n");

    return list_head;
}


text:
Q: How can I create a method that can intelligently create or update an entity? I am currently experiencing the following error with Entity Framework Core 6:

System.InvalidOperationException: The instance of entity type 'PromiseRecord' cannot be tracked because another instance with the same key value for {'ID'} is already being tracked. When attachi
ng existing entities, ensure that only one entity instance with a given key value is attached.

The intent of the following function is to reduce code duplication and create a method that can either create or update an existing entity. I based my implementation off the following resource https://entityframework.net/add-or-update. The initial record creation works however I receive the error described above when updating an existing record. Why is this occurring and how can I fix it?
public async Task<Promise?> SavePromiseAsync(Promise promise)
{
    var promiseRecord = new PromiseRecord
    {
        ID = promise.ID,
        LovedOneRecordID = promise.LovedOneID,
        Description = promise.Description,
        CompletedAt = promise.CompletedAt,
        DueBy = promise.DueBy
    };

    _context.Entry(promiseRecord).State = promise.ID == 0 ? EntityState.Added : EntityState.Modified;
    await _context.SaveChangesAsync();

    return MapPromise(promiseRecord);
}

I have verified using the debugger that domain model is passed in correctly with the proper ID and other related data.
Thank you in advance!

A: It means that your dbContext already has an entity with the specified ID and you can't add second entity with the same ID. If you really need to insert a new entity or update it if you have an existing one you can use this library to UpSert an entity:
await _context.PromiseRecords
    .Upsert(new PromiseRecord
    {
        LovedOneRecordID = promise.LovedOneID,
        Description = promise.Description,
        CompletedAt = promise.CompletedAt,
        DueBy = promise.DueBy
    })
    .On(v => v.ID)
    .WhenMatched(v => new PromiseRecord
    {
        LovedOneRecordID = promise.LovedOneID,
        Description = promise.Description,
        CompletedAt = promise.CompletedAt,
        DueBy = promise.DueBy
    })
    .RunAsync();


text:
Q: Removing old kernels My boot partition is full and I can't install new kernel versions. So I tried to remove some old versions like this:

*

*get active kernel
uname -a
Linux Ubuntu-1404-trusty-64-minimal 3.13.0-43-generic #72-Ubuntu SMP Mon Dec 8 19:35:06 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

*get installed kernels
dpkg -l linux-image-* | grep ^ii
output: http://pastebin.com/X9P81W22

*now i try to remove linux-image-3.13.0-24-generic
aptitude purge linux-image-3.13.0-24-generic
output: http://pastebin.com/J4Zmhf9Y
I'm not shure because aptitude will delete linux-generic{a} and linux-image-generic{a} as well. Over 420MB will be freed. But my boot partition looks like this:
/dev/md1        488M  484M     0 100% /boot
is this normal??

A: That seems normal to me.  For each kernel package, most of the kernel code (modules such as drivers) is stored in /lib/modules/ (with some in /lib/firmware/).
On the other hand, the images in /boot require less than 10MB of disk space between them. The following lists the kernel image files for version 3.2.0-87 with sizes in kB.
4892    /boot/vmlinuz-3.2.0-87-generic
2836    /boot/System.map-3.2.0-87-generic
784     /boot/abi-3.2.0-87-generic
144     /boot/config-3.2.0-87-generic

Automatic removal of older / unused kernel packages
The following command is useful for automatically removing some (but not all) older / unused kernel packages:
sudo apt-get autoremove

Edit: I noticed that you are currently using the 3.13.0-43-generic kernel. It would be best to reboot the system to use the latest installed kernel, 3.13.0-55-generic. The above command would be most effective if you are already using the most recently installed kernel.

A: Askubuntu has questions (and answers) for that

*

*Why aren't old linux-images removed when installing new kernel updates?

*How do I remove or hide old kernel versions to clean up the boot menu?


text:
Q: e-modifier in javascript? (converting regex from php to js) I have the following regular expression in PHP

$url = 'http://www.amazon.com/dp/B002JCSBE4/ref=sr_1_1?ie=UTF8&s=tv&qid=1264738369&sr=1-1/';
$url=preg_replace(
'/http:\/\/[^>]*?amazon.(.*)\/([^>]*?ASIN|gp\/product|exec\/obidos\/tg\/detail\/-|[^>]*?dp)\/([0-9a-zA-Z]{10})[a-zA-Z0-9#\/\*\-\?\&\%\=\,\._;]*/i',
'http://www.amazon.$1/dp/$3/?tag='.'someone-20',$url );

I'm trying to do the same thing, just with javascript.
I can't figure out how to use parameters with something like
search = new RegExp(regex);

How can I convert this to Javascript?

A: The /e modifier is used to execute code. In Javascript, you can do so by passing a function.
For example:
preg_replace("/(<\/?)(\w+)([^>]*>)/e",
         "'\\1'.strtoupper('\\2').'\\3'",
         $html_body);

becomes
html_body.replace(/(<\/?)(\w+)([^>]*>)/, function(s, x1, x2, x3) {
  return x1 + x2.toUpperCase() + x3;
});

in Javascript. (But again, you did not using the /e flag in that PHP code.)

A: You're not not using the e modifier in that PHP regex.
The following JavaScript should do the same as your PHP:
var url = 'http://www.amazon.com/dp/B002JCSBE4/ref=sr_1_1?ie=UTF8&s=tv&qid=1264738369&sr=1-1/';
var amazon_re = /http:\/\/[^>]*?amazon.(.*)\/([^>]*?ASIN|gp\/product|exec\/obidos\/tg\/detail\/-|[^>]*?dp)\/([0-9a-zA-Z]{10})[a-zA-Z0-9#\/\*\-\?\&\%\=\,\._;]*/i;
url = url.replace(amazon_re, 'http://www.amazon.$1/dp/$3/?tag=someone-20');


text:
Q: Incorrect elements being accessed during momentum scroll using webkit-overflow-scrolling on iOS Been stuck with webkit-overflow-scrolling touch for a couple of days now. I'm trying to do something very straight forward - however it's proving tricky!
When I click on a certain element, I want to grab that by JS and do something with it. However when it's in a 'webkit-overflow-scrolling: touch' div, as soon as iOS's momentum scrolling takes over, the elements don't seem to keep up. IE I start scrolling, and while the list is still scrolling, I tap one and it it seems to access an incorrect element? Ideally, I want to identify when momentum scrolling has started, and if it's still in progress - a tap just stops it rather than selecting an element at first, but I can't even get the basics to work yet.
I am testing this on an iPad 3 with iOS 6.01. Just seems that the webkit scrolling is very buggy, as the onscroll event seems temperamental too and sometimes triggers at times other than the end of scrolling, unlike the universal iOS use.
If anyone has any ideas about how to get this behaviour working correctly, without using iScroll or turning webkit-overflow-scroll off, it would be greatly appreciated!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

A: I have seen the momentum scrolling to be pretty buggy in my projects as well. Bugs like these are sometimes fixed by hardware accelerating the elements inside the scroller. Try that and see if it works for you. Here's more info on how to HW accelerate elements : http://davidwalsh.name/translate3d

A: Almost three years after you posted this, but here is how to approach this problem. Firstly don't try and control the momentum scroll, once the device has entered momentum scrolling (200ms), the device stops sending touch events to webview.
this code attaches a touchend event once the touchstartevent has fired, and removes it in 150ms, so the "tap" must fire within 150ms.
element.addEventListener('touchstart', function(e)) {
    var target = this;
    var handler = function(evt) {
        e.preventDefault();
        e.stopImmediatePropagation();
        evt.preventDefault();
        evt.stopImmediatePropagation();
        /*
         Your tap event handler code here
         */
    };
    target.addEventListner('touchend', handler);
    setTimeout(function() {
        target.removeEventListener('touchend', handler)
    }, 150);
});

Hope this helps :)


text:
Q: Registering models from Databricks to Azure ML and save Azure ML image into provided ACR(Non Default ACR of AML Workspace) I'm trying to register a data bricks model tp Azure ML workspace with mlflow.azure.base_image model. But with this method, we can save the Azure ML image to default ACR connected to the Azure ML workspace.
But I want to save the Azure ML image to another existing ACR. Need help in figuring out the design.
The method I'm using is as follows
    workspace = Workspace.create(name = workspace_name,
                                 location = workspace_location,
                                 resource_group = resource_group,
                                 subscription_id = subscription_id,
                                 auth=svc_pr,
                                 exist_ok=True)

    import mlflow.azureml

    model_image, azure_model = mlflow.azureml.build_image(model_uri=model_uri,
                                                          workspace=workspace,
                                                          model_name="winequality",
                                                          image_name="winequality",
                                                          description="Sklearn ElasticNet image for predicting wine quality",
                                                          synchronous=True)

    #model_image.wait_for_creation(show_output=True)
    print("Access the following URI for build logs: {}".format(model_image.image_build_log_uri))

A: Attach existing ACR while creating Azure ML workspace and providing necessary permissions(contributor) role to service principal used.
workspace = Workspace.create(name = workspace_name,
                                 location = workspace_location,
                                 resource_group = resource_group,
                                 subscription_id = subscription_id,
                                 auth=svc_pr,
                                 container_registry=<resource_id>,
                                 exist_ok=True)
import mlflow.azureml

model_image, azure_model = mlflow.azureml.build_image(model_uri=model_uri,
                                                      workspace=workspace,
                                                      model_name="winequality",
                                                      image_name="winequality",
                                                      description="Sklearn ElasticNet image for predicting wine quality",
                                                      synchronous=True)

#model_image.wait_for_creation(show_output=True)
print("Access the following URI for build logs: {}".format(model_image.image_build_log_uri))


text:
Q: Search by owner with ansible playbook I want to list all files of a directory with the owner of the file her name start with 'a',
i have a ansible playbook like this
- name: Recursively find
   find:
    paths: "/tmp"
    age: "6d"
    age_stamp: ctime
    file_type: any
    patterns: "*"
    recurse: no
   register: output

A: Q: "List all files of a directory with the owner of the file her name starts with 'a'."
A: For example, given the tree
shell> tree -u tmp
tmp
├── [admin   ]  file1
├── [admin   ]  file2
└── [user1   ]  file3

Find all files in the first task and select the owner in the second task
    - find:
        paths: tmp
      register: output
    - debug:
        msg: "{{ item.path }}"
      loop: "{{ output.files|selectattr('pw_name', 'match', '^a.*$')|list }}"

give
  msg: tmp/file2
  msg: tmp/file1


text:
Q: Problem with displaying Tkinter Frames inside another frame Hi I am having troubles with tkinter frames. I was hoping to have a window with a main frame. In that main frame I have a title label, top frame, and a bottom frame. I was hoping to use grid to place the title label and the top and bottom frame one after each other. The issue I came across was the title label and the bottom frame was not displaying.
heres my code:
    from tkinter import *

def addLabels(frame):
    lbl_date = Label(frame, text="DATE(DD/MM/YYYY)").grid(row=0,column=0)
    lbl_po = Label(frame, text="PO #").grid(row=0,column=1)
    lbl_nikls = Label(frame, text="NIKLS").grid(row=0,column=2)
    lbl_sro = Label(frame, text="SRO").grid(row=0,column=3)
    lbl_hours = Label(frame, text="HOURS").grid(row=0,column=4)
    lbl_otHours = Label(frame, text="OT HOURS").grid(row=0,column=5)
    lbl_dot = Label(frame, text="D-OT HOURS").grid(row=0,column=6)
    lbl_invoice = Label(frame, text="INVOICE #").grid(row=0,column=7)

def addEntry(frame):
    entry_date = Entry(frame).grid(row=1,column=0)
    entry_po = Entry(frame).grid(row=1,column=1)
    chk_nikls = Checkbutton(frame, text="").grid(row=1, column=2)
    chk_sro = Checkbutton(frame, text="").grid(row=1, column=3)
    entry_hours = Entry(frame).grid(row=1,column=4)
    entry_otHours = Entry(frame).grid(row=1,column=5)
    entry_dot = Entry(frame).grid(row=1,column=6)
    entry_invoice = Entry(frame).grid(row=1,column=7)

##create window
window = Tk()

#main fraime
mainframe = Frame(master=window, borderwidth=1, highlightbackground="black", highlightthickness=1)
##create and pack trinity header
lbl_title = Label(master=mainframe, text="Trinity Menu").grid(row=0)

##create frame for top view
top = Frame(master=mainframe, borderwidth=1, highlightbackground="black", highlightthickness=1).grid(row=1)
addLabels(top)
addEntry(top)

##create frame for bottom view
bottom = Frame(master=mainframe, borderwidth=1, highlightbackground="black", highlightthickness=1).grid(row=2)
addLabels(bottom)

## run program
window.mainloop()

If you could please help that would be greatly appreciated. Thanks in advance.

A: The first problem is: you never use place, pack or grid on mainframe. Use something like:
mainframe = Frame(master=window, borderwidth=1, highlightbackground="black", highlightthickness=1)
mainframe.pack()

The second one: you create a frame by using e=Entry(...). Then e is an object of class Entry. You place it py using a=e.grid(...) etc. But then a is of type None. So a=e.grid(...) returns the same a (NoneType) as a=Entry(...).grid(...), but you are not interested in that but in e. This is nor jQuery. So use:
lbl_title = Label(master=mainframe, text="Trinity Menu")
lbl_title.grid(row=0)

Hope that's helpful!


text:
Q: Deleting records with mysql triggers So my hosting provider has informed me that i can not use Events as i need a super privilege to access it. So i have tried to replicate the same code into a trigger and still have no idea how to get it working.
i have a TIMESTAMP in my table called timer. So after a given time i want to delete the records older than 1 minute.

A: The body of the trigger attempts to perform a DELETE from table wp_wpgmza.  But that is the table the trigger is defined on. This violates the restriction documented in the MySQL Reference Manual

A stored function or trigger cannot modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

https://dev.mysql.com/doc/refman/5.7/en/stored-program-restrictions.html
The DELETE statement appears to be valid. But it can't be executed from the context of a trigger on the wp_wpgmza table. The statement will need to be executed in some other context.


text:
Q: Reproducing simple example for Kernel PCA with Poly Kernel I am trying to reproduce the results from this Wikipedia example about Kernel PCA
Here is a minimal code sample to reproduce. You should be able to copy-paste the code and execute it as long as you have all the libraries installed.
import math
from random import uniform
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid.axislines import SubplotZero
from sklearn.decomposition import KernelPCA

def circular_points(r, n=100):
    return [(math.cos(2 * math.pi / n * x) * r, math.sin(2 * math.pi / n * x) * r) for x in range(n)]

def noisy_points(points, a=0.2):
    return [p[0] + uniform(-a, a) for p in points], \
           [p[1] + uniform(-a, a) for p in points]

def get_sublist(points, start, end):
    return [x for x, _ in points[start:end]], [y for _, y in points[start:end]]

def plot(name, points_a, points_b, points_c):
    fig = plt.figure(name)
    ax = SubplotZero(fig, 111)

    ax.plot(points_a[0], points_a[1], 'o', color='#BA2A27')
    ax.plot(points_b[0], points_b[1], 's', color='#3C75B7')
    ax.plot(points_c[0], points_c[1], 'd', color='#F6A022')
    fig.add_subplot(ax)

def main():
    blue_points = noisy_points(circular_points(1, 50))
    red_points = noisy_points(circular_points(4, 50))
    yellow_points = noisy_points(circular_points(7, 50))

    pca_points = [(p[0], p[1]) for p in zip(blue_points[0], blue_points[1])]
    pca_points += [(p[0], p[1]) for p in zip(red_points[0], red_points[1])]
    pca_points += [(p[0], p[1]) for p in zip(yellow_points[0], yellow_points[1])]
    pca_points = np.array(pca_points)

    poly_kernel_pca = KernelPCA(n_components=2, kernel='poly', degree=2, coef0=1)
    poly_pcs = poly_kernel_pca.fit_transform(pca_points)

    rbf_kernel_pca = KernelPCA(n_components=2, kernel='rbf', gamma=0.1)
    rbf_pcs = rbf_kernel_pca.fit_transform(pca_points)

    poly_blue_pcs = get_sublist(poly_pcs, 0, 50)
    poly_red_pcs = get_sublist(poly_pcs, 50, 100)
    poly_yellow_pcs = get_sublist(poly_pcs, 100, 150)

    rbf_blue_pcs = get_sublist(rbf_pcs, 0, 50)
    rbf_red_pcs = get_sublist(rbf_pcs, 50, 100)
    rbf_yellow_pcs = get_sublist(rbf_pcs, 100, 150)

    plot('Initial Points', blue_points, red_points, yellow_points)
    plot('Poly Kernel', poly_blue_pcs, poly_red_pcs, poly_yellow_pcs)
    plot('RBF Kernel', rbf_blue_pcs, rbf_red_pcs, rbf_yellow_pcs)

    plt.show()

if __name__ == '__main__':
    main()

Where the Kernel PCA with RBF works as expected, the Poly Kernel barely changes the initial point cloud. The result from Wikipedia looks like this:

Note that they have used the Kernel k(x,y)= (x^T y + 1)^2, which from my understanding corresponds to a degree=2 and coef0=1 in scikit-learn.
Does anyone have an idea what I have done wrong?

A: I believe Wikipedia claim that the Kernel used in the example is the polynomial Kernel is wrong.
If you use the kernel
eq1
K(x,y) = x.T y + |x|²|y|²

the output seems to the one in the example. This kernel comes from the featue map
eq1
phi((x1, x2)) = (x1, x2, x1² + x2²)

which includes the polar coordinate r=x1² + x2².
You can use this kernel in Scikit-learn specifying the kernel='precomputed' option in KernelPCA and passing the kernel matrix to the fit_transform function.


text:
Q: SQL Server : optimization table design recommandation with huge data records Somehow my database is too slow when writing.
Currently I have used 319MB which has 2,127,227 rows within it. The first couple days my computer was able to insert couple thousand rows per second and now it taking me forever to insert 1 thousand rows. Now it taking 165 seconds to insert 1 thousand rows (0.165 per row). I need to be able to insert 10,000 per minutes (0.006 per row)
Please see the design of my table  and server specs below and let me know if you can help me to optimize this.  Thank you.
Current usage report
Records 2,127,227
Reserveed KB 323,088
Data(KB) 177,088

My table designed is like this, I did index [LoginID] ASC,[ProductID] ASC, [ProductModifiedDate]
CREATE TABLE [dbo].[ProductTable](
    [ID] [uniqueidentifier] NOT NULL,
    [LoginID] [int] NULL,
    [ProductID] [int] NULL,
    [ProductPrice] [decimal](18, 4) NULL,
    [ProductModifiedDate] [datetime] NULL,
    [ProductCreatedDate] [datetime] NULL,
 CONSTRAINT [PK_ProductTable] PRIMARY KEY CLUSTERED
([ID] ASC)

CREATE NONCLUSTERED INDEX [IX_ProductTable] ON [dbo].[ProductTable]
(
    [LoginID] ASC,
    [ProductID] ASC,
    [ProductModifiedDate] ASC
)

My insert statement is just a normal simple sql statement, there was nothing special to it.
My hardware:
I have a 2 Quad 2.83 Ghz with 16GB DDR3 RAM with SQL Server 2008 R2 express edition. The CPU is running at 25% capacity when insert these rows.
Please let me know how to optimize this table. I really need to be able to search through all of these columns so I think indexing these columns are very importance and I have to keep the row up to 30 days.
I thought the SQL Server Express edition can support 10GB of data.

A: When you add a new record, how are you generating the UUID?
Using a truly random UUID can result in very bad index fragmentation. This is extra painful when it is a Clustered Index because the data (row) layout itself is affected.
See NEWID vs NEWSEQUENTIALID

The most striking is the number of writes required by the NEWID system function. This, coupled with the average page density of 69%, is evidence of the page splitting caused by the random distribution of inserts at the leaf level. As soon as a page fills up, it needs to be split into two pages of 50% each for the insert to complete. Not only has page splitting resulted in poor page density, it has fragmented the data pages quite badly (there is a 99% probability that the next data page is not next to the current one).

And that is for only 50k records :-) The above link also provides a TSQL snippet to show the table statistics.
Similarly, check the auxiliary index (and rebuild if required).


text:
Q: Difficulties trying to understand ruby's precedence rules a=[]

a << 4 && a[0]+=1 && a[0]+=1 if a==[]

puts a.inspect

output [9]

I'm new in ruby and I was just trying things out.
I want to know what operations are being perfomed to get this result and in what order.

A: I'm going to vastly simplify your example. I'm guessing your confused about why you get 9, instead of 6 (4+1+1). It's all because of && precedence being higher than +.
Here's a simplified version of your code.
a = 4
a += 1 && a += 1
puts a.inspect #=> 9

What's happening is that your && is binding first, then the + operation is binding after. Which means that your code is actually more like this:
a = 4
a += (1 && a += 1)
puts a.inspect #=> 9

If you add parenthesis yourself, you get more what you might expect.
a = 4
(a += 1) && (a += 1)
puts a.inspect #=> 6

Really though, you would never use && like this, as you don't always get what you would expect...

The other tricky thing, that if statement is shorthand. It's the same as this:
if a == []
  a << 4 && a[0]+=1 && a[0]+=1
end


text:
Q: Wrapping a C++ function using extern "C" I've been following this tutorial to try and wrap a C++ function using extern "C". I want to access this function using ctypes in Python. In the tutorial, the author creates a class "Foo" and then wraps it with C using extern. I'm having a hard time implementing it correctly because I can't understand what the code in extern "C" here does:
extern "C" {
    Foo* Foo_new(){ return new Foo(); }
    void Foo_bar(Foo* foo){ foo->bar(); }
}

Can someone explain what the author is doing in these two lines? Specifically, I'd like to know how pointers are being used here, what is the point of creating Foo_new() and what does the syntax in foo->bar() mean.
How would you implement this on a simple fibonacci function like the one that follows?
int fib(int a){
    if (a<=0)
        return -1;
    else if (a==1)
        return 0;
    else if ((a==2)||(a==3))
        return 1;
    else
        return fib(a-2) + fib(a-1);
};

extern "C" int fib(int a){
// what do I do here?
}


text:
Q: Sleep function is IIS I write the php code in iis to serve file for download with speed limit, so i need to use sleep function for the speed limit.
Here, few lines of my code:
set_time_limit(0);
while(!feof($file))
{
    echo fread($file, 1024*10);
    ob_flush();
    flush();
    sleep(1);
    if (connection_status()!=0)
    {
        @fclose($file);
        exit;
    }

}

But the browser say: 'Waiting for mysite'. If i remove sleep(1) everything is right. I also test in apache and everything is right too.
So I have a problem in IIS with the sleep function.

A: You need to have your server properly configured for that. TBH you should use something on the server to do that, rather then relying on PHP, the sleep(1); causes it to send a chunk, pause, send a chunk pause, etc. It does not maintain 10kbps but goes from like 500kbps for a second to 0 kbps for a second, it may average out to 10kbps, but it is not the same and some programs won't treat it correct and may terminate the download. You should look into QoS (How to Limit Download Speeds from my Website on my IIS Windows Server?)

A: What exactly is the problem with IIS? Note that waiting for 1 second will mean that your script may exceed the timeout limit (this can be as low as 30 seconds) so IIS will kill your script.
If you want to serve large files, I recommend serving them directly from IIS and using IIS' built-in rate limiter rather than via PHP.
See here: http://www.iis.net/configreference/system.applicationhost/sites/site/limits


text:
Q: ConverseJs modals not displaying properly when bootstrap 4 is being used already in website I'm pretty new to ConverseJs, so please be patient with me.I have set up a Ejabberd server, and can connect to it happily with the ConverseJs plugin.
However, when it comes to clicking any of the options that would display a modal, I am presented with the grey overlay (which is normally behind the modal) on top of the modals content.
I am already using Bootstrap 4 within the site, and have the bootstrap css file on the server.Is this just a case of adjusting the z-index of the modals content/overlay within the ConverseJs/Bootstrap css file?

A: I just found a workaround here:
https://github.com/conversejs/converse.js/issues/1240
Just add this to your pages:
.modal-backdrop {
   z-index: 1030!important;
   display: none;
}

A: ConverseJs use Bootstrap Native, so every time you load conversejs, its Modal, Dropdown and others mess with your DOM attaching another handler.
I have the same problem, but not just only with modals, with Dropdown too and I still don't find how to replace Bootstrap native with Bootstrap.


text:
Q: How do you combine two scenes into one scene? Is there a way to combine two javaFx scenes into one scene (then assign that scene to a stage) or, assign two scenes to a stage simultaneously so they are side by side on a stage.
Aim: I have a scene that shows a calculator, I have a scene that shows a clock. I want to have them side by side (calculator on left, clock on right) on the same stage (without using scene builder).
Any help would be appreciated.

A: yes you can do this in javafx with subscenes,
a subscene is like a scene that can be added into layouts
you can do something like this
    @Override
    public void start(Stage primaryStage) throws Exception {
        StackPane layoutOne = new StackPane();
        Label labelOne = new Label("One");
        layoutOne.getChildren().add(labelOne);
        SubScene subSceneOne = new SubScene(layoutOne,300,100);

        StackPane layoutTwo = new StackPane();
        Label labelTwo = new Label("Two");
        layoutTwo.getChildren().add(labelTwo);
        SubScene subSceneTwo = new SubScene(layoutTwo,300,100);

        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(subSceneOne,subSceneTwo);
        Scene mainScene = new Scene(root,300,210);
        primaryStage.setScene(mainScene);
        primaryStage.show();
    }

hope this what you were looking for, you can also check this for more


text:
Q: How can I authenticate against Azure AD from a browser in a non-interactive workflow? I have a website hosted as Azure App Service with Azure Active Directory authentication enabled. Users can sign in from their browser using the interactive workflow.
The website must run as a dashboard on a big screen 24/7. There it is not possible to use the interactive workflow for authentication there, since there is no user to enter credentials.
How can I achieve this?
Is it possible to use a service principle with a client certificate? If so: How?

A: You can use the client credential flow to obtain a token to call the Web API hosted in your App Service on your behalf (not on behalf of the user). This solution is useful for non-interactive daemon applications that perform tasks without logged in users.
Since you have enabled Azure AD authentication in the app service, you only need to register the daemon app in the Azure portal. When you use the  client credential flow to request the application hosted by the APP service, Just replace resource with the application ID URL hosted by APP service.
please see:here.


text:
Q: Is it more reasonable to remove "IDK" from a survey in SPSS for rudimentary analyses? I attached a graph showing the typical array of responses to a survey measured ordinally in SPSS. While generally, the answers are quantifiable/compared as 1–5 corresponding to answers ranging from "Not Satisfied" to "Very Satisfied," many questions have a 6 (equating to "IDK"), although it's usually a minority response. I worry that for my purposes it's just noise and distracting from the 'weight' of other, more certain answers.
So, does it make statistical sense to measure opinions this way if I'm looking for ordinal certainty on a 0-6 scale? I'm wondering now if it's best to recode anything, change the Measure, or remove all 6s from the data totally.
Thanks for checking this post out!

A: A Likert scale assumes that response categories have a rank order. The survey question is apparently measuring the satisfaction of Monk Seal Resting and Sea Turtle Nesting, and you can't really rank "I don't know" on a satisfaction scale, where, for instance, 1 might represent "Not Satisfied" and 5 might represent "Very Satisfied".
If the purpose of your analysis is to measure statistical differences or levels of agreement between groups, then you probably want to remove "blank" and "I don't know". If you are creating a visualization to show the survey responses, and it would be helpful for your audience to know that a number of people chose "I don't know", and a number of people chose not to respond to the question, then it might make sense to keep those responses in your analysis.  I would recommend reordering them so that they appear together at the beginning or end of your graph, instead of sandwiching the true Likert scale responses.


text:
Q: Reading content of a InMemoryRandomAccessStream into a Buffer using C++/WinRT I'm trying to serialise the content of an winrt::Windows::UI::Input::Inking::InkStrokeContainer. Microsoft provides the very convenient ISF format to do this.
Now I want to store the content of InkStrokeContainer into a winrt::Windows::Storage::Streams::Buffer object as follows:
// This code is running in a worker thread
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::UI::Input;
using namespace winrt::Windows::UI::Input::Inking;
using namespace winrt::Windows::Storage::Streams;

InkStrokeContainer inkContainer;

// Add some strokes to the inkContainer

InMemoryRandomAccessStream stream;
inkContainer.SaveAsync(stream, InkPersistenceFormat::Isf).get();

Buffer buffer(stream.Size());
stream.ReadAsync(buffer, buffer.Capacity(), InputStreamOptions::None).get();

std::cout << "Buffer size: " << buffer.Length() << "Stream size: " << stream.Size() << std::endl;

However, this code doesn't work and the output of the last line is always:

Buffer size: 0 Stream size: 1102

It seems that nothing is being written into the buffer and I cannot figure out why.


text:
Q: Modifying existing edit tool to make new tool using ArcObjects? I want to create versions of the edit tools that will add a parallel, offset segment each time I add a segment regularly. Is it possible to put a wrapper around the existing tools? Or otherwise add to their functionality?
e.g. Using the sketch tool I click twice on the screen. Code that I write would add a perpendicular segment on the front of a specified length and a parallel segment. I add another segment and it adds another parallel segment. I add a curve and it adds a parallel curve.
Do I have to make the tools from scratch or can I use the existing ones to add the segments and just tack on code to add the extra segments? Recreating the sketch tool wouldn't be so bad but the other tools are more complicated.

A: I think this could be done with an Editor Extension.  When IEditEvents.OnSketchFinished fires, depending on what the currenttask is modify the sketch by adding parallel segments etc.

A: I am surprised that copy parallel does not work for you.
Understand that you would first digitize one side, then, when you are done select them all and copy parallel.
Unless I am missing something in your question.


text:
Q: Why does /proc/mounts show a line with 7 columns (type overlay)? I am trying to troubleshoot https://github.com/minio/minio/issues/12047, which seems to happen because one of the lines in the output of cat /proc/mounts inside a Docker container of mine seems to be very special: it has 7 columns, not 6.
Here is what that line looks like:
rootfs overlay / overlay rw,relatime,lowerdir=/var/lib/docker/overlay2/l/PPDEP2NMRVDPT5KD5MWUXRVCC7:/var/lib/docker/overlay2/l/74ZMIOZ4PCTUODVBBM5HPKA2VD:/var/lib/docker/overlay2/l/OI4LL4AG2CMZFQ2NOBA4WAGO2D:/var/lib/docker/overlay2/l/XNVOJIJBXWDYAMHKQVV36C75V7:/var/lib/docker/overlay2/l/OV7JOV3TW5MJUIXZ3D5INLWP2S:/var/lib/docker/overlay2/l/HESJLWTHRG6WS3ATRQZ53LHTHR:/var/lib/docker/overlay2/l/APVFQLQRINYD73WECQN5743O64:/var/lib/docker/overlay2/l/4XZCFLNC4XES6EMPFMVIDVCDZG:/var/lib/docker/overlay2/l/QXPY3J5KFA225KY2UQ2ZMSFQL6:/var/lib/docker/overlay2/l/J2FZIZQJRJILGLDETPYG3LUO36:/var/lib/docker/overlay2/l/6SQYUEBL4UYK7LOSPVWHY2VSTO:/var/lib/docker/overlay2/l/HEM6EMXICNYBE7NFCL66QLRN7F:/var/lib/docker/overlay2/l/FKCJWEQK6MTE7ZGGAQKRIIAQ2S:/var/lib/docker/overlay2/l/2CQEUDLJPSF5QYSHUP3FZZP2NG:/var/lib/docker/overlay2/l/RPHBJZTVMCPKW5YO4DLXDDEMG6:/var/lib/docker/overlay2/l/7CK3YF2F3UPMWJEDMJSPF4BUVM:/var/lib/docker/overlay2/l/6VNPYNFDWXULE3DHTTOKVK4TEV:/var/lib/docker/overlay2/l/FHGM5ZCKKZXU3ILXNLACVEEVJV:/var/lib/docker/overlay2/l/QTUW3G342VYWBSHCJKOUFBW67D:/var/lib/docker/overlay2/l/NUWVWRCIWNNIPY6HFOFLS7PUMK:/var/lib/docker/overlay2/l/7GGMDSIT66JJAT7WXHJKYZ5YZT:/var/lib/docker/overlay2/l/XWKJI2UXVR27CWTCN5EH7BB6UH:/var/lib/docker/overlay2/l/BMY5J7APK7EU25PJFBSRH2Q34L,upperdir=/var/lib/docker/overlay2/7a60705c89c815e9c7df7a76ebc7aa10a7c9c8f82d6cba59f193542753bd1570/diff,workdir=/var/lib/docker/overlay2/7a60705c89c815e9c7df7a76ebc7aa10a7c9c8f82d6cba59f193542753bd1570/work,index=off,xino=off 0 0

Is that format normal? The overlay after rootfs looks like it shouldn't be there, according to man 5 fstab. Why is there an extra word?


text:
Q: Suspended mode in the UWP application I have the UWP application that uses ReactiveUI for viewmodel to view binding. When the user gets logged in to the app the (when the log in command is executed) the following method is called:
private void RegisterActivityTrackingFunctionality()
    {
        Container = _container;
        Container.Resolve<IDialogService>().IsActive = true;
        _dispatcher = Window.Current.Dispatcher;

        Window.Current.CoreWindow.PointerPressed += CoreWindow_PointerPressed;
        Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
        _timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(30)).Subscribe(_ => CheckActivityTime());
    }

The timer is created to monitor users activity in the application. If the user is inactive for more than 15 minutes he is logged off from the application. Basically method CheckActivityTime() is called for this purpose:
private void CheckActivityTime()
    {
        _logger.Info("In a CheckActivityTime Method");
        if (Container.Resolve<TokenHolder>().IsActivityTimeElapsed)
        {
            if (_timer != null)
            {
                _timer.Dispose();
            }

            Task.Run(async () => await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                try
                {
                    Container.Resolve<IDialogService>().IsActive = false;

                    var dialogService = Container.Resolve<IContentDialogService>();

                    if (dialogService.CurrentContentDialog != null)
                    {
                        dialogService.CurrentContentDialog.Hide();
                    }

                    var shellViewModel = Container.Resolve<ShellViewModel>();

                    if (shellViewModel.Router.NavigationStack.Count > 1)
                    {
                        shellViewModel.Router.NavigateBack.Execute(null);
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error("The unhandled exception occured in UI thread for logout mechanism", ex);
                }
            }
            ));
        }
    }

The problem is like that: When app goes to suspended mode it does not always logout the user if the inactivity time exceeds 15 minutes.
Could anyone explain to me, what is the problem?
Maybe there is something wrong with timer setting? Or maybe I should not do the logout operation on the UI thread?

A: What you can do is attach a handler to OnResuming event of App which is called each time app is resumed from suspended state and then check for the Activitytime and lock your app from there.
Application.Current.Resuming += new EventHandler<Object>(App_Resuming);


text:
Q: iPhone - detect nearby bluetooth devices Is it possible to find bluetooth-enabled devices near my iphone from an app? I am able to do it using the GameKit framework, but that has a limitation that both devices must have my app installed and running.
Is there a way to detect iPhone devices nearby using bluetooth even if they are not running the same app?
Thanks.

A: Not really. Apple doesn't give the iPhone much Bluetooth interactivity, except for the wireless headphones and what you can do with GK.


text:
Q: How to create a file based on Database Values? I want to create a .INI file based on the values I get from database.
This are the values in my database for :

Now in the field parameter filed is the value i want to write in file each in new line.
I fetch the values like this:
$this->data['params'] = $this->parameter_m->get();

So I get all the values from the table.
I want to write values in file like this:
[INIDetails]
SipUserName=
Password=
Domain=
Proxy=
Port=
SipAuthName=
DisplayName=
ServerMode=
UCServer=
UCUserName=
UCPassword=

[DialPlan]
DP_Exception=
DP_Rule1=
DP_Rule2=

[Advanced]
OperationMode=
MutePkey=
Codec=
PTime=
AudioMode=
SoftwareAEC=
EchoTailLength=
PlaybackBuffer=
CaptureBuffer=
JBPrefetchDelay=
JBMaxDelay=
SipToS=
RTPToS=
LogLevel=

I have WRITE Function that writes into file
function write($file = NULL, $file_content = array(), $sections = TRUE) {
    $this->file_content = (!empty($file_content)) ? $file_content : $this->file_content;
    $this->file = ($file) ? $file : $this->file;
    $this->sections = $sections;
    $content = NULL;

    if ($this->sections) {
        foreach ($this->file_content as $section => $file_content) {
            $content .= '[' . $section . ']' . PHP_EOL;
            foreach ($file_content as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $v) {
                        $content .= $key . '[]=' . (is_numeric($v) ? $v : $v ) . PHP_EOL;
                    }
                } elseif (empty($val)) {
                    $content .= $key . '=' . PHP_EOL;
                } else {
                    $content .= $key . '=' . (is_numeric($val) ? $val : $val ) . PHP_EOL;
                }
            }
            $content .= PHP_EOL;
        }
    } else {
        foreach ($this->file_content as $key => $val) {
            if (is_array($val)) {
                foreach ($val as $v) {
                    $content .= $key . '[] = ' . (is_numeric($v) ? $v : '"' . $v . '"') . PHP_EOL;
                }
            } elseif (empty($val)) {
                $content .= $key . ' = ' . PHP_EOL;
            } else {
                $content .= $key . ' = ' . (is_numeric($val) ? $val : '"' . $val . '"') . PHP_EOL;
            }
        }
    }

    return (($handle = fopen($this->file, 'w+')) && fwrite($handle, trim($content)) && fclose($handle)) ? TRUE : FALSE;
}

And i use that function like this :
$path = "./uploads/";
        $filename = "default.ini";
        $this->load->helper('file');
        $file = $path.$filename;
        $this->load->library('ini');
        $ini = new INI($file);
        $ini->write($file, $this->data['params']);

So i how to write the array of values i get from database into file ?
As you can see there is a filed called Parameter_Type i want to set it as section in INI file.

A: I'm guessing that your parameter_m is your model which have get() function where it returns array values from your table. What I think, the problem is that your model return incorrect structure of your array. Your array should have structure like:
array(
   "parameter_type" => array(
       "parameter" => value
   )
)

in your model's get function, there should be something like:
class parameter_m extends CI_Model {

        public function get()
        {
                $query = $this->db->get('your_parameter_table');

                $assoc_arr = array();

                foreach ($query->result() as $row)
                {
                    $assoc_arr[$row->parameter_type][$row->parameter] = '';
                }

                return $assoc_arr;
        }

}

Using the get() it should output:
array(
    "INIDetails" => array(
        "SipUserName" => '',
        "Password"    => '',
        "Domain"      => '',
        "Proxy"       => '',
        "Port"        => '',
        "SipAuthName" => '',
        "DisplayName" => '',
        "ServerMode"  => '',
        "UCServer"    => '',
        "UCUserName"  => '',
        "UCPassword"  => ''
    ),
    "DialPlan"   => array(
        "DP_Exception" => '',
        "DP_Rule1"     => '',
        "DP_Rule2"     => ''
    ),
    "Advanced"   => array(
        "OperationMode"   => '',
        "MutePkey"        => '',
        "Codec"           => '',
        "PTime"           => '',
        "AudioMode"       => '',
        "SoftwareAEC"     => '',
        "EchoTailLength"  => '',
        "PlaybackBuffer"  => '',
        "CaptureBuffer"   => '',
        "JBPrefetchDelay" => '',
        "JBMaxDelay"      => '',
        "SipToS"          => '',
        "RTPToS"          => '',
        "LogLevel"        => ''
    )
);


text:
Q: Perl6: why does substr-rw behave this way? Why does here substr-rw cut off the trailing 6?
#!/usr/bin/env perl6
use v6;

my $str = '123';
$str ~= '.' x 30;
$str ~= '456';

say $str;       #   123..............................456
$str.substr-rw( 0, 10 ) = '';
say $str;       #   ........................45

perl6 --version
This is Rakudo version 2016.03-38-g8df1a69 built on MoarVM version 2016.03-46-g50c7f6a implementing Perl 6.c.

A: UPDATE: A Rakudo/MoarVM built after 2016-07-21 should behave correctly.
Looks like a bug to me. Note that it matters how the string is constructed:
my $a = '.' x 3 ~ 'x';
my $b = sprintf('%s', $a); # or just '...x', but not "$a"

say $a; #=> ..x
say $b; #=> ..x

$a.substr-rw( 0, 2 ) = '';
$b.substr-rw( 0, 2 ) = '';

say $a; #=> ..
say $b; #=> .x

Update: The bug has been reported: RT#127782


text:
Q: properties of mutual singular measures and sequences of uniform convergent measures suppose that ${\mu}_n$ is a sequence of finite measures on measurable space
$(X,M)$ where uniformly convergence to $\mu$.
and $\theta$ is a measure on $(X,M)$.

prove that if $\theta$$\bot$$\mu_n$ then $\theta$$\bot$$\mu$.
  my work : $\theta$ $\bot$ $\mu_n$ its mean there exist $E_n$ , $F_n$ $\in$ $M$ , where $E_n$ $\cup$ $F_n$ $=$ $X$ and $E_n$ $\cap$ $F_n$ $=$ $\varnothing$ and $E_n$ is $\mu$ null and $F_n$ is $\theta$ null.
  now we shall found two appropriate set in $M$ where has above property for $\theta$ and $\mu$.
  please help


text:
Q: findHomography, getPerspectiveTransform, & getAffineTransform This question is on the OpenCV functions findHomography, getPerspectiveTransform & getAffineTransform

*

*What is the difference between findHomography and getPerspectiveTransform?. My understanding from the documentation is that getPerspectiveTransform computes the transform using 4 correspondences (which is the minimum required to compute a homography/perspective transform) where as findHomography computes the transform even if you provide more than 4 correspondencies (presumably using something like a least squares method?).
Is this correct?
(In which case the only reason OpenCV still continues to support getPerspectiveTransform should be legacy? )

*My next concern is that I want to know if there is an equivalent to findHomography for computing an Affine transformation? i.e. a function which uses a least squares or an equivalent robust method to compute and affine transformation.
According to the documentation getAffineTransform takes in only 3 correspondences (which is the min required to compute an affine transform).
Best,

A: Q #1: Right, the findHomography tries to find the best transform between two sets of points. It uses something smarter than least squares, called RANSAC, which has the ability to reject outliers - if at least 50% + 1 of your data points are OK, RANSAC will do its best to find them, and build a reliable transform.
The getPerspectiveTransform has a lot of useful reasons to stay - it is the base for findHomography, and it is useful in many situations where you only have 4 points, and you know they are the correct ones. The findHomography is usually used with sets of points detected automatically - you can find many of them, but with low confidence. getPerspectiveTransform is good when you kn ow for sure 4 corners - like manual marking, or automatic detection of a rectangle.
Q #2 There is no equivalent for affine transforms. You can use findHomography, because affine transforms are a subset of homographies.

A: Re Q#2, estimateRigidTransform is the oversampled equivalent of getAffineTransform. I don't know if it was in OCV when this was first posted, but it's available in 2.4.

A: There is an easy solution for the finding the Affine transform for the system of over-determined equations.

*

*Note that in general an Affine transform finds a solution to the over-determined system of linear equations Ax=B by using a pseudo-inverse or a similar technique, so

x = (A At )-1  At  B
Moreover, this is handled in the core openCV functionality by a simple call to solve(A, B, X).

*Familiarize yourself with the code of Affine transform in opencv/modules/imgproc/src/imgwarp.cpp: it really does just two things:
a. rearranges inputs to create a system Ax=B;
b. then calls solve(A, B, X);
NOTE: ignore the function comments in the openCV code - they are confusing and don't reflect the actual ordering of the elements in the matrices. If you are solving [u, v]'= Affine * [x, y, 1] the rearrangement is:
         x1 y1 1 0  0  1
         0  0  0 x1 y1 1
         x2 y2 1 0  0  1
    A =  0  0  0 x2 y2 1
         x3 y3 1 0  0  1
         0  0  0 x3 y3 1

    X = [Affine11, Affine12, Affine13, Affine21, Affine22, Affine23]'

         u1 v1
    B =  u2 v2
         u3 v3

All you need to do is to add more points. To make Solve(A, B, X) work on over-determined system add DECOMP_SVD parameter. To see the powerpoint slides on the topic, use this link. If you'd like to learn more about the pseudo-inverse in the context of computer vision, the best source is: ComputerVision, see chapter 15 and appendix C.
If you are still unsure how to add more points see my code below:
// extension for n points;
cv::Mat getAffineTransformOverdetermined( const Point2f src[], const Point2f dst[], int n )
{
    Mat M(2, 3, CV_64F), X(6, 1, CV_64F, M.data); // output
    double* a = (double*)malloc(12*n*sizeof(double));
    double* b = (double*)malloc(2*n*sizeof(double));
    Mat A(2*n, 6, CV_64F, a), B(2*n, 1, CV_64F, b); // input

    for( int i = 0; i < n; i++ )
    {
        int j = i*12;   // 2 equations (in x, y) with 6 members: skip 12 elements
        int k = i*12+6; // second equation: skip extra 6 elements
        a[j] = a[k+3] = src[i].x;
        a[j+1] = a[k+4] = src[i].y;
        a[j+2] = a[k+5] = 1;
        a[j+3] = a[j+4] = a[j+5] = 0;
        a[k] = a[k+1] = a[k+2] = 0;
        b[i*2] = dst[i].x;
        b[i*2+1] = dst[i].y;
    }

    solve( A, B, X, DECOMP_SVD );
    delete a;
    delete b;
    return M;
}

// call original transform
vector<Point2f> src(3);
vector<Point2f> dst(3);
src[0] = Point2f(0.0, 0.0);src[1] = Point2f(1.0, 0.0);src[2] = Point2f(0.0, 1.0);
dst[0] = Point2f(0.0, 0.0);dst[1] = Point2f(1.0, 0.0);dst[2] = Point2f(0.0, 1.0);
Mat M = getAffineTransform(Mat(src), Mat(dst));
cout<<M<<endl;
// call new transform
src.resize(4); src[3] = Point2f(22, 2);
dst.resize(4); dst[3] = Point2f(22, 2);
Mat M2 = getAffineTransformOverdetermined(src.data(), dst.data(), src.size());
cout<<M2<<endl;

A: I concur with everything @vasile has written. I just want to add some observations:
getPerspectiveTransform() and getAffineTransform() are meant to work on 4 or 3 points (respectively), that are known to be correct correspondences. On real-life images taken with a real camera, you can never get correspondences that accurate, not with automatic nor manual marking of the corresponding points.
There are always outliers. Just look at the simple case of wanting to fit a curve through points (e.g. take a generative equation with noise y1 = f(x) = 3.12x + gauss_noise or y2 = g(x) = 0.1x^2 + 3.1x + gauss_noise): it will be much more easier to find a good quadratic function to estimate the points in both cases, than a good linear one. Quadratic might be an overkill, but in most cases will not be (after removing outliers), and if you want to fit a straight line there you better be mightily sure that is the right model, otherwise you are going to get unusable results.
That said, if you are mightily sure that affine transform is the right one, here's a suggestion:

*

*use findHomography, that has RANSAC incorporated in to the functionality, to get rid of the outliers and get an initial estimate of the image transformation

*select 3 correct matches-correspondances (that fit with the homography found), or reproject 3 points from the 1st image to the 2nd (using the homography)

*use those 3 matches (that are as close to correct as you can get) in getAffineTransform()

*wrap all of that in your own findAffine() if you want - and voila!

A: getAffineTransform:affine transform is combination of translation, scale, shear, and rotation
https://www.mathworks.com/discovery/affine-transformation.html
https://www.tutorialspoint.com/computer_graphics/2d_transformation.htm
getPerspectiveTransform:perspective transform is project mapping
enter image description here


text:
Q: Invalid argument supplied for foreach() in shopping cart I am trying to create a shopping cart to my php application i already write this code it gives me this error Invalid argument supplied for foreach() and it doesn't retrive the data that are in the database
code is looks like this
<?php

     include('../Neo/assets/session.inc.php');
     include 'config/config.php';

if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$last_id = mysqli_insert_id($con);
$_SESSION['last_id'] = $last_id;
$sql = "SELECT * FROM product_order WHERE ord_id =" . $last_id;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);

?>

<?php
                        foreach($row as $i){
                            echo
                                '

                                 '.$i['ord_id'].'
                                 '.$i['card_id'].'
                                 '.$i['field1'].'
                                 '.$i['field2'].'
                                 '.$i['field3'].'
                                 '.$i['field4'].'
                                 '.$i['field5'].'
                                 '.$i['ord_qty'].'
                                 '.$i['card_price'].'
                                 '.$i['ord_total'].'

';
                        }
                        ?>

A: The mysqli_fetch_assoc function, based on documentation, Fetch a result row as an associative array. For each row, you should call this call this function once:
while($row = mysqli_fetch_assoc($result)) {
    echo $row['ord_id'];
}

But of course, before using this function, it would be better to check the $result and to debug such an error in your code, you can always use var_dump/print_r to see what is the type/value of a variable and also check that the given query is correct or not.


text:
Q: Multiple BLE connection is very slow in python (bleak) I try to connect two M5StickC to PC via BLE to upload their sensor data.
I wrote a data acquisition python script using bleak library.
The data acquisition rate is very slow when I connect 2 devices.
How to improve data acquisition rate on my script ?
I hope to get 20 data per second.
import asyncio
from bleak import BleakClient

address1 = "D8:A0:1D:55:EE:8A"
UUID1 = "beb5483e-36e1-4688-b7f5-ea07361b26a8"

address2 = "94:B9:7E:93:21:76"
UUID2 = "beb5483e-36e1-4688-b7f5-ea07361b26a2"

async def main():
    client1 = BleakClient(address1)
    client2 = BleakClient(address2)
    print(client1.address)
    print(client2.address)
    await client1.connect()
#    await client2.connect()
    while(True):                                     # very slow when comment out client2
        print(await client1.read_gatt_char(UUID1))
#        print(await client2.read_gatt_char(UUID2))

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

edit:
Thank you for your comments.
I have updated my script following ukBaz's link.
Data upload rate is much improved, but I could get almost only single M5StickC data, the data from another one available sparsely...
I will ask this question to bleak maintainer.
from bleak import BleakClient
import asyncio

address1 = "D8:A0:1D:55:EE:8A"
UUID1 = "beb5483e-36e1-4688-b7f5-ea07361b26a8"

address2 = "94:B9:7E:93:21:76"
UUID2 = "beb5483e-36e1-4688-b7f5-ea07361b26a2"

def callback(sender, data):
    print(sender, data)

def run(addresses, UUIDs):
    loop = asyncio.get_event_loop()
    tasks = asyncio.gather(*(connect_to_device(address, UUID) for address, UUID in zip(addresses, UUIDs)))
    loop.run_until_complete(tasks)

async def connect_to_device(address, UUID):
    print("starting", address, "loop")
    async with BleakClient(address, timeout=5.0) as client:
        print("connect to", address)
        while(True):
            try:
                print(await client.read_gatt_char(UUID))
            except Exception as e:
                print(e)

if __name__ == "__main__":
    run([address1, address2], [UUID1, UUID2])


text:
Q: XSLT Count using variable and for-each I am trying to get the count using the for-each and counter variable but I am getting an incorrect values. Any help with this would be great.
XML
<ProjectFileManagers>
    <ProjectFileManagers>
      <ProjectFileManagerId>34</ProjectFileManagerId>
      <ProjectId>39352</ProjectId>
      <FileManagerId>11</FileManagerId>
    </ProjectFileManagers>
    <ProjectFileManagers>
      <ProjectFileManagerId>35</ProjectFileManagerId>
      <ProjectId>39352</ProjectId>
      <FileManagerId>12</FileManagerId>
    </ProjectFileManagers>
  </ProjectFileManagers>

XSLT

      <xsl:text>Material Attached</xsl:text>

    <xsl:variable name="materialCount" select="0"></xsl:variable>
      <xsl:for-each select="ProjectFileManagers/ProjectFileManagers/ProjectFileManagerId">
            <xsl:value-of select="$materialCount + 1"/>
      </xsl:for-each>
    <xsl:value-of select="$materialCount" disable-output-escaping="yes" />

A: in stead of
<xsl:value-of select="$materialCount + 1"/>

use:
<xsl:value-of select="position()"/>