text:
Q: Codeigniter session SET on one server but not on another I'm stuck with a login function in Codeigniter which works on localhost and on my test server but session seems to be NOT SET on the 3rd server.
here's the do_login function of the 'home' controller :
public function do_login() {
        if ($this->session->userdata('is_admin_login')) {
            redirect('admin/home/dashboard');
        } else {
            $user = $_POST['username'];
            $password = $_POST['password'];

            $this->form_validation->set_rules('username', 'Username', 'required');
            $this->form_validation->set_rules('password', 'Password', 'required');

            if ($this->form_validation->run() == FALSE) {
                $this->load->view('admin/vwLogin');
            } else {
                $salt = '5&JDDGKGlwz%sRghewh!t2Yg-Igae@QxgakPzFTSId';
                $enc_pass  = md5($salt.$password);
                $sql = "SELECT * FROM tbl_admin_users WHERE username = ? AND password = ?";
                $val = $this->db->query($sql,array($user ,$enc_pass ));

                if ($val->num_rows) {
                    foreach ($val->result_array() as $recs => $res) {
                        $sess_array = array(
                            'id' => $res['id'],
                            'username' => $res['username'],
                            'email' => $res['email'],
                            'is_admin_login' => true,
                            'user_type' => $res['user_type']
                            );
                        $this->session->set_userdata($sess_array);
                    }
                    redirect('admin/dashboard');
                } else {
                    $err['error'] = 'Access Denied Invalid Username/Password';
                    $this->load->view('admin/vwLogin', $err);
                }
            }
        }
    }

On all 3 places (localhost, test server and production server) this function redirects to 'admin/dashboard' and there comes the difference.
Here's the dashboard controller :
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Dashboard extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        dump_exit($this->session->userdata);
        if (!$this->session->userdata('is_admin_login')) {
            redirect('admin/home');
        }
    }

    public function index() {
        $arr['page']='dash';
        $this->load->view('admin/vwDashboard',$arr);
    }

}

When I dump_exit the session data in the constructor, 'is_admin_login' is TRUE @ localhost and the test server BUT it is not set on the production server. SAME CODE. I have tried to modify $config['cookie_domain'], $config['sess_expiration'], I have tried to REFRESH redirect('URL', 'refresh') all without success...
In autoload.php I have :
$autoload['libraries'] = array('database', 'session', 'form_validation');
$autoload['helper'] = array('url', 'form', 'dump');

Any help or suggestion would be highly appreciated!


text:
Q: How to add hash history to a filterable portfolio? I am creating a filterable portfolio for my website. Once I click one of the filters it displays a hashtag at the end of my URL. For example if I click design it will display as www.yourdomain.com/#design.
Is it possible to make the browser back button work with that? That is, if I click this link, I add #design to my current address. Once I click the back button, the #design hash is removed and will display the last page or filter that was selected. Right now the back button works but it only displays all the filters that I selected in the URL but not on the page.
Is that somehow possible?
Here is a sample of the design that I am trying to work with http://www.jsfiddle.net/xnnnk/6/
$(document).ready(function () {
    $(".filter").click(function () {
        var filterText = $(this).attr('href').replace('#', '');
        $(".projectGrid").hide();
        $(".projectHolder").show();
        $(".projectHolder").not('.' + filterText).hide();
        $(".projectGrid").fadeIn(1500);
        $('.filter').not($(this).toggleClass('activeWork')).removeClass('activeWork');
    });
});

Thank you

A: You could detect the hash change e.g.
$(window).on('hashchange', function() {
  console.log('changed to:'+document.location.hash);
});

and act accordingly, possibly call the filtering code you have posted.
This seems to be widely supported,
http://caniuse.com/#search=hash
Simple demo of what i've described,
http://jsfiddle.net/3nA2p/1
http://jsfiddle.net/3nA2p/1/show

redpajama_set_name: RedPajamaStackExchange


text:
Q: Edit pdf page using pdfbox How can i edit a pdf page with java and pdfbox by writing in a specific position that i know already in pixels ?
I tried this but it overwrites :
PDDocument document = null;
try {
    document = PDDocument.load(new File("/x/x/x/mypdf.pdf"));
    PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    page.getContents().getStream();
    contentStream.beginText();
    contentStream.setFont(font, 12);
    contentStream.moveTextPositionByAmount(100, 100);
    contentStream.drawString("Hello");
    contentStream.endText();
    contentStream.close();
    document.save("/x/x/x/mypdf.pdf");
    document.close();
} catch (IOException e) {
    e.printStackTrace();
} catch (COSVisitorException e) {
    e.printStackTrace();
}

Thank you.

A: You could have used PDFBox, all you are missing is appending to the page. Just change this line:
PDPageContentStream contentStream = new PDPageContentStream(document, page);

to:
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

Starting from PDFBox 2.0, the boolean appendContent has been replaced by the AppendMode APPEND such that the equivalent of the previous code is now:
PDPageContentStream contentStream = new PDPageContentStream(
    document, page, PDPageContentStream.AppendMode.APPEND, true
);

A: I figure it out how to do it, instead of using pdfbox i used iTextpdf, this is the java code i used :
package ma;

import java.io.*;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;

public class editPdf {

public static void main(String[] args) throws IOException,
        DocumentException {

    PdfReader reader = new PdfReader("/Users/Monssef/Desktop/mypdf.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
            "/Users/Leonidas/Desktop/mypdfmodified.pdf"));
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
            BaseFont.NOT_EMBEDDED);

        PdfContentByte over = stamper.getOverContent(1);

        over.beginText();
        over.setFontAndSize(bf, 10);
        over.setTextMatrix(107, 107);
        over.showText("page updated");
        over.endText();

    stamper.close();
}

}

A: Anita is correct.  In fact it works quite well.  I would add that the line
page.getContents().getStream();

is possibly extraneous, and PDPage is being depreciated in favor of PDPageable in the newer releases (and is used primarily for printing), but the code will work for your purpose without going to the expense of iText (and after all, you originally asked about PDFBox).
Don't forget to include the fix Anita gave to create the extra bits in the creation of contentstream:
PDPageContentStream contentStream = new PDPageContentStream(
        document, page, true, true);

You should also remember that you will likely be creating and closing streams for each section of print that you place on top of the pdf you are overlaying text upon.  You will need to be sure to close both the streams and the document so that the buffers are written, otherwise you will not see your changes.
Also, for those trying this out, there are several options of downloading libraries from apache for pdfbox.  The easiest one to use, I think, is (currently) the one named pdfbox-app-1.8.10.jar (which I am currently using even in my JSF apps).  It already includes the other libraries that are hard-wired into pdfbox that you would also need to download to do anything meaningful.


text:
Q: Appending to an array while looping I've got the following:
Dim dupArray As Variant
dupArray = Array("dup")

For j = LBound(numArray) To UBound(numArray)

    If IsInArray(Range(numArray(j)).Text, dupArray) Then
        Range(numArray(j)).Interior.ColorIndex = 3
        MsgBox "Duplicate value"

    ElseIf IsInArray(Range(numArray(j)).Text, keyArray) Then
        Application.OnKey Range(numArray(j)).Text, comArray(j)
        ReDim Preserve dupArray(j)
        Dim cellEntry As String
        cellEntry = Range(numArray(j)).Text
        MsgBox cellEntry
        dupArray(j) = cellEntry

    Else
        Range(numArray(j)).Interior.ColorIndex = 3
        MsgBox "Unrecognized key code in " & numArray(j)
        End If
    Next j

In essence, I want VBA to read the contents of a cell and append them to an array for comparison. Code to read the contents of a cell is Range(numArray(j)).Text...  For some reason, cellEntry and dupArray(j) are not equal.  More specifically, for the cell A6, cellEntry is "b" (which is the correct contents), but dupArray(j) is "A6"... any thoughts?  There's no error code, it's just not putting the correct value in the array.
Thank you!
(Edit) Code for Function IsInArray:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

(Edit 2) Don't pay attention to much else... I'm just wondering why cellEntry doesn't match dupArray(j) for all values of j when they should clearly be the same thing.

A: Your code seems to work, but it depends on keyArray being populated.
I've run this demo code, including populating numArray and keyArray with test values, to illustrate what happens.
If how I've populated these arrays doesn't match your code, please add that info to your Q.
Sub Demo()
    Dim dupArray As Variant
    Dim numArray As Variant
    Dim keyArray As Variant
    Dim comArray As Variant
    Dim j As Long

    ' for testing
    numArray = Application.Transpose([A1:A6].Value)
    ReDim keyArray(1 To 3)
    keyArray(1) = "x"
    keyArray(2) = "a"
    keyArray(3) = "s"

    dupArray = Array("dup")

    For j = LBound(numArray) To UBound(numArray)
        If IsInArray(Range(numArray(j)).Text, dupArray) Then
            Range(numArray(j)).Interior.ColorIndex = 3
            'MsgBox "Duplicate value"

        ElseIf IsInArray(Range(numArray(j)).Text, keyArray) Then
            'Application.OnKey Range(numArray(j)).Text, comArray(j)
            ReDim Preserve dupArray(j)
            Dim cellEntry As String
            cellEntry = Range(numArray(j)).Text
            'MsgBox cellEntry
            dupArray(j) = cellEntry

        Else
            Range(numArray(j)).Interior.ColorIndex = 4 ' changed to be distinct for testing
            'MsgBox "Unrecognized key code in " & numArray(j)
        End If
    Next j
End Sub

Sheet, before

Sheet, after

Variable values at end of execution

As you can see, dupArray has been populated sparsley, in line with numArray.  This is fine for how it's used with IsInArray.  If it's used for something else too, you can change how it's populated.


text:
Q: How to convert assetImage to Uint8List/File I am trying to convert assetImage with link ("assets/image.png") into File/uint8List/
final ByteData byteData = await rootBundle.load(logoUrl);
final File assetLogoFile =
File("${(await getTemporaryDirectory()).path}/$logoUrl");

File markerLogoFile = await assetLogoFile.writeAsBytes(byteData.buffer
        .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

final Uint8List logoUint8List = await markerLogoFile.readAsBytes();

I am getting following error;
E/flutter ( 5136): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.example.project/cache/assets/images/flare.png' (OS Error: No such file or directory, errno = 2)
E/flutter ( 5136): #0      _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
E/flutter ( 5136): #1      _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 5136): #2      _CustomZone.runUnary (dart:async/zone.dart:1265:19)

A: You can use the following code to convert asset file to Uint8List;
 final ByteData bytes = await rootBundle.load('assets/image.jpg');
 final Uint8List list = bytes.buffer.asUint8List();


text:
Q: Android Webview: Is there a way to know what the previous URL is? Is there a way to access the history so that I know what URL the user is visiting when they hit the back button (which calls WebView.goBack())?

A: String historyUrl="";
myWebView = (WebView) findViewById(R.id.webViewContent);
WebBackForwardList mWebBackForwardList = myWebView.copyBackForwardList();
if (mWebBackForwardList.getCurrentIndex() > 0)
    historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex()-1).getUrl();

// Previous url is in historyUrl

A: This is probably the method you're looking for: WebView.copyBackForwardList


text:
Q: dotnet-reportgenerator is not able to find any coverage.cobertura.xml when running inside Gitlab CI pipeline I want to generate a single coverage report for my C# project based on this tutorial
https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage
When starting a Gitlab CI pipeline with the following configuration
image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build
  - unit-tests

build:
  stage: build
  script:
    - dotnet build --output build
  artifacts:
    paths:
      - build

unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --no-build --output build --collect:"XPlat Code Coverage";

      dotnet tool install -g dotnet-reportgenerator-globaltool;

      reportgenerator -reports:'**/coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    reports:
      cobertura: CoverageReports/Cobertura.xml
  dependencies:
    - build

I get the following error

The report file pattern '**/coverage.cobertura.xml' is invalid. No matching files found.

When using ls to inspect the directory before running the reportgenerator command I can see that there are no matching files (although they should exist).
I would expect to have one coverage.cobertura.xml file per test project e.g.

*

*...\myRepo\xUnitTestProject1\TestResults\380e65f7-48d5-468f-9cbc-550c8e0aeda8\coverage.cobertura.xml

*...\myRepo\xUnitTestProject2\TestResults\c96c55f7-40d3-483e-a136-573615e3a9c3\coverage.cobertura.xml

My current solution:
It seems I have to run the build again. So I replaced this line
dotnet test --no-build --output build --collect:"XPlat Code Coverage";
with
dotnet test --collect:"XPlat Code Coverage";
Now it's working fine but an additional build seems to be redundant because I already created a build artifact...

So do you have any ideas how to improve the configuration so that I don't have to build a second time?

A: It seems like you could combine the two steps since dotnet test will also trigger a build. You would have build problems reported from the same stage as tests, but both have similar responses.
image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - unit-tests

unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --output build --collect:"XPlat Code Coverage";

      dotnet tool install -g dotnet-reportgenerator-globaltool;

      reportgenerator -reports:'../coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    paths:
      - build
    reports:
      cobertura: CoverageReports/Cobertura.xml

Alternatively:
Coverlet Collector depends on CoreCompile. But, the Global tool does not (since it isn't an msbuild task).
image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build
  - unit-tests

build:
  stage: build
  script:
    - dotnet build --output build
  artifacts:
    paths:
      - build

unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --no-build --output build --collect:"XPlat Code Coverage";

      dotnet tool install -g coverlet.console;

      dotnet tool install -g dotnet-reportgenerator-globaltool;

      coverlet /path/to/test-assembly.dll --target "dotnet" --targetargs "test /path/to/test-project --no-build";

      reportgenerator -reports:'../coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    reports:
      cobertura: CoverageReports/Cobertura.xml
  dependencies:
    - build

Coverlet's global tool also supports a --format cobertura option that may help to simplify this further.


text:
Q: What is the difference between nhibernate and entity framework in batching? I want to select one of the above orm.
What is the difference between nhibernate and entity framework in batching?

A: NHibernate can:

*

*Send multiple updates/inserts/deletes at once

*Load multiple proxies of a type at once

*Load multiple collections of a type at once

*Execute object oriented DML statements

*Manually group queries in a single roundtrip (multiqueries, futures)

EF can:

*

*None of the above

A: The difference is that EF natively doesn't have any command batching so every update, insert or delete is executed in separate round trip to the database - but in my previous question are some links to workarounds. EF also doesn't have any alternative to NHibernate future queries (way to batch multiple queries to single database round trip).


text:
Q: named slot and slot-scope vue 3 How to move from slot and slot-scope in vue 3. Currently, the update and delete buttons don't work.
//CODE//
 **<template slot="cell(action)" slot-scope="data">**
        <b-button size="sm" variant="primary" :to="{ name:'editarProductos', params:id_producto: data.item.id} }">
    Editar
    </b-button>
    <b-button size="sm" variant="danger" :to="{ name:'eliminarProductos', params: {id_producto:data.item.id} }">
    Eliminar
    </b-button>
    </template>

A: See this documentation here: https://vuejs.org/guide/components/slots.html
We no longer need to define slot-scoped. We can define a slot like:-
Normal Defination:
<slot></slot>
Usage:
<Component> slot content </Component>
Named Slots:
<slot name="customSlot"></slot>
Usage:
<Component>
  <template #customSlot> Custom Content </template>
</Component>


text:
Q: Google Chrome eating borders (works fine on firefox) Please consider this snippet: http://fruple.com/kemper/test/categorie.html
Firefox screenshot:

Chrome screenshot

why are some of the right borders not showing up?

A: Try changing the display property for the li elements from inline to inline-block.

A: It's possibly related to this bug: http://code.google.com/p/chromium/issues/detail?id=58105
You should avoid triggering quirks mode in any case and add a DOCTYPE.


text:
Q: Getting error while adding custom java component in Mule I am getting below compile error after adding java component in mule process error
xml config
  <?xml version="1.0" encoding="UTF-8"?>
  <mule xmlns:http="http://www.mulesoft.org/schema/mule/http"      xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans-current.xsd
  http://www.mulesoft.org/schema/mule/core      http://www.mulesoft.org/schema/mule/core/current/mule.xsd
   http://www.mulesoft.org/schema/mule/http      http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
     <http:listener-config name="HTTP_Listener_Configuration_8082" host="0.0.0.0"    port="8082" doc:name="HTTP Listener Configuration"/>
  <flow name="custom-componentsFlow">
    <http:listener config-ref="HTTP_Listener_Configuration_8082" path="/"     doc:name="HTTP"/>
    <component class="org.Mule.transformers.helloWorldComponent"     doc:name="Java"/>
</flow>
 </mule>

class details
 package org.Mule.transformers;
 import org.mule.api.MuleEventContext;
 import org.mule.api.MuleMessage;
 import org.mule.api.lifecycle.Callable;
 import org.mule.api.transformer.TransformerException;
 import org.mule.transformer.AbstractMessageTransformer;

 public class helloWorldComponent implements Callable{
 @Override
public Object onCall(MuleEventContext eventContext) throws Exception {

    eventContext.getMessage().setInvocationProperty("myProperty", "Hello    World!");
    return eventContext.getMessage().getPayload();
 }
}

details are.
Caused by: org.springframework.beans.PropertyBatchUpdateException: Failed properties: Property 'objectClassName' threw exception; nested exception is java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: Cannot load class 'org.Mule.transformers.helloWorldComponent'
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:121) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:75) ~[spring-beans-4.1.6.RELEASE.jar:4.1.6.RELEASE]

Anypoint studio version 5.4.3
I just followed this link still giving error.

A: I've just tried your flow and I'm not getting any error.
The only reason that I can imagine is that the path of your Java class helloWorldComponent could be not correct.
Best regards.
Janthem.


text:
Q: Why popstate doesnt fire my function when back button is clicked? (mobile ios chrome) I'm trying to do that when the link is opened in new tab, there would able back to referrer page through back button.
const referrer = document.referrer;
const redirect = (e) => {
     if(e.state.goBack){
        window.location.href = window.location.href;
     }
 }

const _location = window.location.href
history.replaceState({goBack: true}, null, referrer);
history.pushState({}, null, _location);

window.addEventListener('popstate', redirect);

works fine in MacBook, android chrome/firefox.
Only in iPhone/iPad, it doesn't work. It just returns to himself. Even if I add an alert in redirect function it doesn't show up when I click the back button in iPad chrome. :(
Feels like back button click on iPad doesn't fire redirect function.

A: I've run into the same issue. The work around I've found is not to use replaceState but pushState instead: https://jsfiddle.net/6dayLhzs/1
const referrer = document.referrer;
const redirect = (e) => {
    if(e.state.goBack){
        window.location.href = window.location.href;
    }
 }

const _location = window.location.href
history.pushState({goBack: true}, null, referrer);
history.pushState({}, null, _location);

window.addEventListener('popstate', redirect);


text:
Q: Coeffaceable implies universial $\delta$-functor My question is essentially about Grothendieck's Tohoku paper Proposition 2.2.1 but in the context of coeffaceable instead of effaceable. Grothendieck's paper does not give much suggestions to my questions other than the words standard technique. Let me be more specific.
Let $\mathcal{A}, \mathcal{B}$ be two abelian categories. A functor $F:\mathcal{A} \to \mathcal{B}$ is coeffaceable if for every $A$ there is a surjection $u:P \to A$ such that $F(u) = 0$. If $F_*$ is a homological $\delta$-functor such that each $F_n$ is coeffaceable (except $F_0$), then $F_*$ is universal.
The proof goes by induction. Suppose that $T_*$ is a homological $\delta$-functor and that $\phi_0 : T_0 \to F_0$ is given. We want to show that there is a unique extension of $\phi_0$ to a morphism of $\delta$-functors $\phi:T_* \to F_*$. Suppose inductively that $\phi_i : T_i \to F_i$ are defined for $0 \leq i < n$. Given $A$ in $\mathcal{A}$, select a surjection $u: P \to A$ such that $F_n(u) = 0$. We have a short exact sequence $0 \to K \to P \to A \to 0$ and a commutative diagram
\begin{array}
\mbox{} & T_n(A) \stackrel{\delta_n}{\longrightarrow} & T_{n-1}(K) \stackrel{}{\longrightarrow} & T_{n-1}(P) \\
& & \downarrow{\phi_{n-1}(K)} & \downarrow{\phi_{n-1}(P)} \\
F_n(P) \stackrel{F_n(u)=0}{\longrightarrow} & F_n(A)  \stackrel{\delta_n}{\longrightarrow}& F_{n-1}(A) \stackrel{}{\longrightarrow} & F_{n-1}(P)
\end{array}
As $F_n(u)=0$, $\delta_n$ on the second row is injective. This implies that there exists a map $\phi_n(A):T_n(A) \to F_n(A)$.
The question I have is to show that $\phi_n(A)$ is defined independent of choice of $u : P \to A$. The idea suggested in Weibel's book (Exercise 2.4.5) goes as follow:
If there is another $u' : P' \to A$ such that $F_n(u') = 0$, there we have
\begin{array}
\mbox{} 0 \stackrel{}{\longrightarrow} & K' \stackrel{}{\longrightarrow} & P' \stackrel{}{\longrightarrow} & A \stackrel{}{\longrightarrow} & 0\\
& & & \downarrow{\mathrm{id}} &\\
\mbox{} 0 \stackrel{}{\longrightarrow} & K \stackrel{}{\longrightarrow} & P \stackrel{}{\longrightarrow} & A \stackrel{}{\longrightarrow} & 0\\
\end{array}
What I would like to see is a morphism from $P'$ to $P$, this is true if we assume $P'$ is projective (in the case when $F_n$ are left derived functors and assuming $\mathcal{A}$ has enough projectives). I have had a hard time figuring out why there should be a morphism. If there is not a morphism from $P'$ to $P$, how to proceed to show that $\phi_n(A)$ is well-defined (independent of choice of $u:P \to A$)? Any suggestions is welcome!
Thanks in advanced!

A: To fix notation, denote the map $T_n(A) \rightarrow F_n(A)$ defined using the epimorphism $u: P \rightarrow A$ by $\phi^u_n(A)$. The question is to show that $\phi^u_n(A) = \phi^{u'}_n(A)$ for any other epimorphism $u': P' \rightarrow A$ with $F_n(u')=0$. Let $u'': P'' \rightarrow A$ be the fiber product of $u$ and $u'$, and let $K''$ be the kernel of $u''$. Then $u''$ is epic, since $u$ and $u'$ are. Moreover, $F_n(u'')$ is zero since it factorizes via $F_n(u),$ and by assumption $F_n(u)=0$. The projection $P'' \rightarrow P$ induces a map $K'' \rightarrow K$ fitting into the commutative diagram with exact rows
\begin{array}
\mbox{} 0 \stackrel{}{\longrightarrow} & K'' \stackrel{}{\longrightarrow} & P'' \stackrel{}{\longrightarrow} & A \stackrel{}{\longrightarrow} & 0\\
& \downarrow & \downarrow & \downarrow{\mathrm{id}} &\\
\mbox{} 0 \stackrel{}{\longrightarrow} & K \stackrel{}{\longrightarrow} & P \stackrel{}{\longrightarrow} & A \stackrel{}{\longrightarrow} & 0\\
\end{array}
We now have the desired morphism of short exact sequences to which the argument on page 48 of Weibel's book applies. We find that $\phi_n^{u''}(A) = \phi_n^u(A)$, and by symmetry also $\phi_n^{u''}(A) = \phi_n^{u'}(A)$, so that as desired $\phi_n^{u}(A) = \phi_n^{u'}(A)$. In conclusion, the map $\phi_n^u: T_n(A) \rightarrow F_n(A)$ does not depend on the choice of the epimorphism $u: P \rightarrow A$ with $F_n(u)=0$, and may unambiguously be denoted $\phi_n(A)$, omitting the superscript.
To address Mykola's question in a comment to Martin's answer, suppose we have a morphism $f: A' \rightarrow A$. Let $0 \rightarrow K \rightarrow P \stackrel{u}{\rightarrow} A \rightarrow 0$ be the exact sequence chosen to define $\phi_n(A)$.
Since we are now at liberty to choose an epimorphism $u': P' \rightarrow A'$ with $F_n(u')=0$ of our liking, let us select one which by construction comes with a map $g: P' \rightarrow P$ making the right square of the diagram
\begin{array}
\mbox{} 0 \stackrel{}{\longrightarrow} & K' \stackrel{}{\longrightarrow} & P' \stackrel{u'}{\longrightarrow} & A' \stackrel{}{\longrightarrow} & 0\\
& \downarrow{h} & \downarrow{g} & \downarrow{f} &\\
\mbox{} 0 \stackrel{}{\longrightarrow} & K \stackrel{}{\longrightarrow} & P \stackrel{u}{\longrightarrow} & A \stackrel{}{\longrightarrow} & 0\\
\end{array}
commute. As before, $g$ will induce a map $h$ and the argument in Weibel will go through.
To define $P'$, let $Q$ be the fiber product of $u$ and $f$. Let $\pi_P: Q \rightarrow P$ and $\pi_{A'}: Q \rightarrow A'$ be the projections, satisfying $u\pi_{P} = f\pi_{A'}$. Let $v: P' \rightarrow Q$ be some epimorphism with $F_n(v)=0$, and set $g = \pi_Pv$ and $u' = \pi_{A'}v$. The right square commutes as $ug=(u\pi_P)v=(f\pi_{A'})v=u'v,$ and $F_n(u') = F_n(\pi_{A'})F_n(v)=0.$ Finally, $u'$ is epic, since $v$ and $\pi_{A'}$ are such, the latter because it is the pullback of the epimorphism $u$ along $f$.

A: Hint: Consider the fiber product $P \times_A P'$ and choose an epimorphism (not surjection) $Q \to P \times_A P'$ which is mapped to $0$ by $F$.


text:
Q: Pygame Get Value of Button I've got this problem with Pygame that I cannot seem to find a solution too. I'm trying to use a PS4 controller to control an RC car. I've got connecting to the controller to the program and seeing how many buttons it has, but I'm unable to get the value of a pushed button in a useable form.
Basically, I want to be able to get all of the values of the buttons on the controller. When a button is pressed, the program updates the value of that button and allows me to execute code based on the value of that button.
Here's what I've got so far:
import os
import pprint
import pygame
from time import sleep

class PS4Controller(object):
    """Class representing the PS4 controller. Pretty straightforward functionality."""

controller = None
axis_data = None
button_data = None
hat_data = None

def init(self):
    """Initialize the joystick components"""

    pygame.init()
    pygame.joystick.init()
    self.controller = pygame.joystick.Joystick(0)
    self.controller.init()

def listen(self):
    """Listen for events to happen"""

    if not self.axis_data:
        self.axis_data = {}

    if not self.button_data:
        self.button_data = {}
        for i in range(self.controller.get_numbuttons()):
            self.button_data[i] = False

    if not self.hat_data:
        self.hat_data = {}
        for i in range(self.controller.get_numhats()):
            self.hat_data[i] = (0, 0)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.JOYAXISMOTION:
                self.axis_data[event.axis] = round(event.value,2)
                #print(self.axis_data)
            elif event.type == pygame.JOYBUTTONDOWN:
                self.button_data[event.button] = True
                print (self.button_data)
                print("\n")
            elif event.type == pygame.JOYBUTTONUP:
                self.button_data[event.button] = False
                #print(self.button_data)
            elif event.type == pygame.JOYHATMOTION:
                self.hat_data[event.hat] = event.value
                #print(self.hat_data)

            # Insert your code on what you would like to happen for each event here!
            # In the current setup, I have the state simply printing out to the screen.

            #os.system('clear')
            #pprint.pprint(self.button_data)
            #pprint.pprint(self.axis_data)
            #pprint.pprint(self.hat_data)

if __name__ == "__main__":
    ps4 = PS4Controller()
    ps4.init()
    ps4.listen()

Here's the output when I press the "X" button on the controller:
{0: False, 1: True, 2: False, 3: False, 4: False, 5: False, 6: False, 7: False, 8: False, 9: Falselse, 12: False, 13: False}

This is good, but I'm unable to use the data from this output when it's in this format.
Right now, if the code is run, it will output which button was pressed, but the button_data is not in a usable state. How can I run, for example:
if button3 == True:
      #execute code
 esif button4 == True:
     #execute some different code

Thanks!


text:
Q: How to check if an object's value equals   in custom Tags in .tag file I am trying to create a custom tag using .tag file to check weather a value passed in attribute is equal to an html paragraph tag

Here is my code
checkEmptyBody.tag
<%@ taglib prefix="c"   uri="http://java.sun.com/jsp/jstl/core" %>

<%@ attribute name="pb_val"  required="true"  rtexprvalue="true" %>

 <c:if test="${pb_val eq '

'}">

 <%-- Do some action here--%>

 </c:if>

Code for usage of above defined Tag
bodyAndHeadingsAndTags.jsp
     <c:set var="processedBody">

             <c:choose>
               <c:when test="${inlineElement.content.articleTypeName == 'picture'}">

                   <%-- Unfortunately it is not possible to get the width/height of the inline image as it is in Content Studio
                        (by dragging the corners of the image), so therefore a hardcoded version is used instead. --%>
                     <img src="${inlineElement.content.fields.alternates.value.w300.href}"
                          width="${inlineElement.content.fields.alternates.value.w300.width}"
                          height="${inlineElement.content.fields.alternates.value.w300.height}"
                          alt="${fn:trim(inlineElement.content.fields.caption)}"
                          ${not empty fn:trim(inlineElement.content.fields.caption) ? 'class="captify"' : ''}
                          title="${inlineElement.content.fields.caption}"/>

               </c:when>
               <c:otherwise>
               <%-- do nothing!! --%>
               </c:otherwise>
             </c:choose>

       </c:set>

      <c:out value="${processedBody}"></c:out>111111111111111

     <%-- <tgam:substring input="GOODMORNING"  start="2" end="6"/>--%>

       <tools:checkEmptyBody pb_val="${processedBody}" />

       In bdyandheading <c:out value="${processedBody}"></c:out>

The problem is even if the value of pb_val is

, the if condition comes out to false and hence the action is not performed.
I think since the value is not a string, it's an html tag, the if condition fails.
How to test for such equality?? Do I have to use regular expression or is there some other way to do this??
Thanks


text:
Q: Can rgdal use an external GDAL installation? The README for rgdal contains the following text:
file.show(system.file("README", package="rgdal"))

For additional drivers, users of the CRAN Windows and CRAN OSX
  binaries can either convert to an available GDAL driver externally,
  read using CRAN rgdal binary - here you factor out mismatches,
  especially 32/64-bit questions among others, and can check the stages of
  the workflow. You can script the first step in R through system(). The
  PATH environment variable will need setting correctly to detect the
  external software properly.

But I can't find more detail about how to accomplish this, or what is entailed in setting the PATH environment variable "correctly".
I realize that rgdal binaries exist, but I need access to the PostgreSQL/PostGIS driver, so the internal GDAL that is statically linked is insufficient.

A: The answer is "No".
After poking around to see if changing the PATH led to rgdal finding the external GDAL (which it didn't) I reread the quoted section and came to the conclusion that what it is saying, somewhat obtusely, is that you should do the conversion completely externally. The steps would be:

*

*Identify a "bridge" format that rgdal's statically linked GDAL can read (e.g. ESRI shapefile).

*Use an external GDAL with additional drivers to convert your source format (e.g. PostGIS) to the bridge format.

*Read in from the bridge format with rgdal.

Not what I was hoping for.


text:
Q: Submit button float up in function by a condition I have a form that haves a condition that sounds like that: If the client choose YES another form will appear, if is choosing NO, he can submit the form.
But if he choose NO, the SUBMIT button stay down and it can be a little bit tricky.
So, the question it is, what condition I have to put in that way that the submit button comes closer when the NO answer is choose?
Here is the part of the html code where the condition it is:

If you need visa, please complete the following data:

    Full name(as written in the passaport):

            <input type="text" class="form-control" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" id="firstName" placeholder="First"  />

            <input type="text" class="form-control" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" id="lastName" placeholder="Last"/>

And here is the JS function:
function yesnoCheck() {
     if (document.getElementById('yesCheck').checked) {
         document.getElementById('ifYes').style.visibility = 'visible';
     } else  {
         document.getElementById('ifYes').style.visibility = 'hidden';
     }
 }

A: Use display to show/hide the "form"
What is the difference between visibility:hidden and display:none?

function yesnoCheck() {
  if (document.getElementById('yesCheck').checked) {
    document.getElementById('ifYes').style.display = 'block';
  } else {
    document.getElementById('ifYes').style.display = 'none';
  }
}
form {
  border: solid 1px black;
}
<form>

    <input type="checkbox" id="yesCheck" onchange="yesnoCheck()" />

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
    Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

If you need visa, please complete the following data:

    Full name(as written in the passaport):

        <input type="text" class="form-control" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" id="firstName" placeholder="First" />

        <input type="text" class="form-control" required data-parsley-pattern="^[a-zA-Z ]+$" data-parsley-trigger="keyup" id="lastName" placeholder="Last" />

</form>


text:
Q: android PrintManager pdf print Incomplete display class MyPrintPdfAdapter(private val mFilePath: String) : PrintDocumentAdapter() {
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    override fun onLayout(
        oldAttributes: PrintAttributes, newAttributes: PrintAttributes,
        cancellationSignal: CancellationSignal,
        callback: LayoutResultCallback, extras: Bundle
    ) {
        if (cancellationSignal.isCanceled) {
            callback.onLayoutCancelled()
            return
        }
        val info = PrintDocumentInfo.Builder("name")
            .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
            .build()
        callback.onLayoutFinished(info, true)
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    override fun onWrite(
        pages: Array<PageRange>, destination: ParcelFileDescriptor,
        cancellationSignal: CancellationSignal,
        callback: WriteResultCallback
    ) {
        var input: InputStream? = null
        var output: OutputStream? = null
        try {
            input = FileInputStream(mFilePath)
            output = FileOutputStream(destination.fileDescriptor)
            val buf = ByteArray(1024)
            var bytesRead: Int
            while (input.read(buf).also { bytesRead = it } > 0) {
                output.write(buf, 0, bytesRead)
            }
            callback.onWriteFinished(arrayOf(PageRange.ALL_PAGES))
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if(output != null) {
                try {
                    output.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            if(input != null) {
                try {
                    input.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

fun printPDFFile(context: Context, pdfPath: String) {
        val printManager = context.getSystemService(Context.PRINT_SERVICE) as PrintManager
        val myPrintAdapter = MyPrintPdfAdapter(pdfPath)
        val att = PrintAttributes.Builder()
            .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
            .setMinMargins(PrintAttributes.Margins(0, 0, 0, 0))
            .setResolution(PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 300, 300))
            .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
            .build()

        printManager.print("jobName", myPrintAdapter,att)
    }


text:
Q: Make Octave set a figure to be the active window (come to the "front of the screen") When Octave draws a plot, I would like it to set that to be the active window automatically, so that it becomes visible and I don't have to click back and forth between windows to see if the code and plot have finished. Is this possible? Since it would require reaching outside of Octave and controlling the OS, I'm not sure; it depends on whether or not that capability is part of Octave but I haven't found a reference for it yet.
I can always tell Octave to close the figure before opening a new one in the code, but that could prevent me from drawing multiple plots on the same axes, and it would require me to code that command in every time. It would be nice if there were a direct way just to bring the plot to be visible and take dominance over other windows.
EDIT: Somehow, although I noted that Octave would be required to control the OS to achieve this, I completely forgot to mention what that was... I'm running Windows 10 with the default window manager; I believe that would be the Desktop Window Manager.

A: When you plot something on a figure (whether you specify the figure you're plotting to within the plot command explicitly or simply let it plot into the currently active figure implicitly), this does not automatically raise the figure window to the forefront.
To do so, call the figure again using the figure function, along with the handle that you want to raise.
Alternatively, if you're sure that the figure you want to raise is the currently active one, you can simply use the shg command (which is effectively equivalent to figure(gcf))
E.g.
Fig1 = figure; % (or figure(1) if you want to be explicit)
Fig2 = figure; % (or figure(2) if you want to be explicit)

figure(Fig1); plot(1:10); % raise Fig1 to the forefront, and plot.

PS: Note that there was a bug affecting this behaviour until recently (coincidentally submitted by yours truly :p See https://savannah.gnu.org/bugs/?45943 ). This is fixed in the latest version of octave though (i.e. 5.1.0)


text:
Q: Can Dojo request/iframe read response Receiving JSONObject but unable to read JSONOject response. It's in the body and cannot be accessed after passing a post to servlet. Why iframe, because i don't know any other way to upload file in form while using asynch. Please help. I'm really confused.
 require(["dojo/request/iframe", "dojo/dom", "dojo/dom-form", "dojo/dom-construct",
   "dojo/json", "dojo/on", "dojo/domReady!"],
 function(iframe, dom, domForm, domConst, JSON, on){

 on(dom.byId("startButton"), "click", function(){

  iframe("addUser",{
  form: "myForm",Ca
  handleAs:"json",

  }).then(function(response){
  alert(response);
  alert("data received!");

  }, function(err){
  alert("data denied!!!");
   alert(err);

*********************** Servlet JSON response********************************
      JSONObject cert = new JSONObject();
        cert.put("version", x509certificate.getVersion());
        cert.put("valid from", x509certificate.getNotBefore());
        cert.put("valid to", x509certificate.getNotAfter());
        cert.put("issuer", x509certificate.getIssuerDN().getName());
        cert.put("Thumbprint", getThumbPrint(x509certificate));

        System.out.println(cert);
        System.out.println(cert.toString());
        out.print(cert.toString());


text:
Q: Access $block inside Block body field that has PHP evaluator enabled In template.php, I've added a variable to $block via $vars['block']->member_login_url, inside theme_preprocess_block.
I can access this variable in the block.tpl.php by: <?php print $block->member_login_url; ?>, but I would like to access it in the GUI block edit screen in Drupal (screenshot below of where I'm getting undefined variable errors).
The body field is using a text type with 'PHP Evaluator' enabled, but for some reason I can't figure out how to access Drupal variables, or block variables.

A: I am not sure why you are assigning the value using object notation. I would have used $vars['block']['member_login_url'] = blah and then access the variable using $member_login_url in the tpl file, but you can output the available variables in the template using the php function get_defined_vars()


text:
Q: Passing ManagedObject collection from fetch result to closure up to ViewController I want to perform a background fetch and pass the result to closure. Currently I'm using performBackgroundTask method from NSPersistentContainer which is giving a NSManagedObjectContext as a closure. Then using that context I'm executing fetch request. When fetch is done I'm, passing the result to the completion handler.
func getAllWorkspacesAsync(completion: @escaping ([Workspace]) -> Void) {
    CoreDataStack.shared.databaseContainer.performBackgroundTask { childContext in
        let workspacesFetchRequest: NSFetchRequest<Workspace> = NSFetchRequest(entityName: "Workspace")
        workspacesFetchRequest.predicate = NSPredicate(format: "remoteId == %@", "\(UserDefaults.lastSelectedWorkspaceId))")
        do {
            let workspaces: [Workspace] = try childContext.fetch(workspacesFetchRequest)
            completion(workspaces)
        } catch let error as NSError {
            // Handle error
        }
    }
}

I'm going to call this method from ViewModel and use Combine PassthroughSubject to notify the ViewController about the event.
class WorkspaceViewModel {

    private var cancellables: Set<AnyCancellable> = []
    let resultPassthroughObject: PassthroughSubject<[Workspace], Error> = PassthroughSubject()

    private let cacheManager = WorkspaceCacheProvider.shared

    static public let shared: WorkspaceViewModel = {
        let instance = WorkspaceViewModel()
        return instance
    }()

    func fetchWorkspaces() {
        cacheManager.getAllWorkspacesAsync { [weak self] workspaces in
            guard let self = self else { return }
            self.resultPassthroughObject.send(workspaces)
        }
    }
}

And the ViewController code:
class WorkspaceViewController: UIViewController {

    private var cancellables: Set<AnyCancellable> = []

    override func viewDidLoad() {
        super.viewDidLoad()

        WorkspaceViewModel.shared.resultPassthroughObject
            .receive(on: RunLoop.main)
            .sink { _ in } receiveValue: { workspaces in
            // update the UI
        }
        .store(in: &cancellables)

    }
}

My question is: is it safe to pass NSManagedObject items?

A: No, it is not

Do not pass NSManagedObject instances between queues. Doing so can result in corruption of the data and termination of the app. When it is necessary to hand off a managed object reference from one queue to another, use NSManagedObjectID instances.

You would want something like:
func getAllWorkspacesAsync(completion: @escaping ([NSManagedObjectID]) -> Void) {
    CoreDataStack.shared.databaseContainer.performBackgroundTask { childContext in
        let workspacesFetchRequest: NSFetchRequest<Workspace> = NSFetchRequest(entityName: "Workspace")
        workspacesFetchRequest.predicate = NSPredicate(format: "remoteId == %@", "\(UserDefaults.lastSelectedWorkspaceId))")
        do {
            let workspaces: [Workspace] = try childContext.fetch(workspacesFetchRequest)
            completion(workspaces.map { $0.objectID } )
        } catch let error as NSError {
            // Handle error
        }
    }
}

You will need to make corresponding changes to your publisher so that it publishes [NSManagedObjectID].
Once you have received this array in your view controller you will need to call object(with:) on your view context to get the Workspace itself.  This will perform a fetch in the view context for the object anyway.
You may want to consider whether the time taken to fetch your workspaces warrants the use of a background context.  By default Core Data objects are retrieved as faults and the actual attribute values are only fetched when the fault is triggered by accessing an object's attributes.
Alternatively, if the purpose of the view controller is to present a list of workspaces that the user can select from, you could return an array of tuples or structs containing the workspace name and the object id.   However, this all sounds like pre-optimisation to me.


text:
Q: Prove the equality $\sum_{n=0}^\infty\frac{(-1)^n}{a+nb}=\int_{0}^1\frac {t^{a-1}}{1+t^p}dt$
Prove the equality
  $$\sum_{n=0}^\infty\frac{(-1)^n}{a+nb}=\int_{0}^1\frac {t^{a-1}}{1+t^p}dt$$

I saw a similar problem (the case where $a=1$) with a solution which I thought it could help but what I don't understand is how they found the integral.

A: Following the same approach, a similar equality holds:
$$\sum_{n=0}^\infty\frac{(-1)^n}{a+nb}=\int_{0}^1\frac {t^{a-1}}{1+t^b}dt$$
where $a$ and $b$ are positive numbers.
We have that
$$\sum_{n=0}^N\frac{(-1)^n}{a+nb}=\sum_{n=0}^N(-1)^n\int_{0}^1t^{a-1+nb}dt=\int_{0}^1t^{a-1}\sum_{n=0}^N(-t^{b})^ndt=\int_{0}^1t^{a-1}\frac{1-(-t^{b})^{N+1}}{1+t^b}dt.$$
Then
$$\left|\sum_{n=0}^N\frac{(-1)^n}{a+nb}-\int_{0}^1\frac{t^{a-1}}{1+t^b}dt\right|=
\int_{0}^1\frac{t^{(N+1)b+a-1}}{1+t^b}dt\leq \int_{0}^1 t^{(N+1)b+a-1}dt
=\frac{1}{(N+1)b+a}$$
which goes to zero as $N$ goes to infinity (note that the $=$ pointed by the red arrow should be replaced by $\leq$).
In order to evaluate the integral see The integral $\ J(m,n):=\int_0^1 \frac{x^m}{x^n+1}dx$ and we may conclude that
$$\sum_{n=0}^{\infty}\frac{(-1)^n}{a+nb}=\frac{\psi\left(\frac{a+b}{2b}\right)-\psi\left(\frac{a}{2b} \right)}{2b}.$$


text:
Q: Transform a Fixed width file in Mule What is the best way to transform a fixed width file. Based on certain criteria i need to skip certain rows in the fixed width file. Should a custom java component be written for this or can some inbuilt transformers be used. I tried to search in the Mule docs but unable to find a suitable answer hence posting the question here.

A: If your file has common delimiters for the fields and supported file extension then data-mapper will be able to transform to csv, json etc. You may be able to use the other hard coded transformers.
For anything else you can extend the transform class.

A: Assuming you have following content in your file .
001MONSTARTWORK
001TUEPROGRESSWORK
001WEDTAKEABREAK
001THURESUMEWORK
001FRIFINISHWORK
001SATCHILLDOWN
001SUNGRABABEER
Below DW Script ll split the data and ll format it as JSON.
%dw 1.0
%output application/json
---
(payload splitBy "\n") map {
    Id:$[0..2],
    Day:$[3..5],
    Shout:$[6..18]
}


text:
Q: ActiveX, installation doesn't work I want to create and deploy an ActiveX plugin, somethign really small. I just want to display a message box.
I've created a library project for it and compile it to a DLL. The plugin works when I register the dll via command line (regasm) on one machine.
So I now need to create an installer, put it inside a CAB file and sign it.
I've installed Visual Studio 2008 to use Setup Project project (but I can use the InstallShield from 2010+ if anyone can explain how to do it). I add my dll to the Application Folder and mark it as Register = vsdrpCOM and I build it and I get a .msi and .exe.
I think I only need the msi file and not the exe. I created a setup.inf file with the fallowing content :
[version]
signature="$CHICAGO$"
AdvancedINF=2.0

[Setup Hooks]
hook1=hook1

[hook1]
run=msiexec.exe /i "%EXTRACT_DIR%\ActiveInstaller.msi" /qn

To build the .cab file I use the command makecab /f build.ddf.
Here is my .ddf file :
.Set DiskDirectoryTemplate=;
.Set CabinetNameTemplate=ActiveInstaller.cab
../ActiveInstaller.msi
../setup.inf

This generated the cab file. Now I need to sign it. At the moment I used a self signed certificate that I generated and installed on my pc (when I check the sign cab file, windows says it's safe). I use another command line which is signtool signwizard (I also try to sign it manually from here). Then the file is signed and I upload it to my website, I launch the website, I'm prompted to install the plugin and I install it.
But then, it does not work, I have no idea why. I've tried so much stuff, with different installer, different options, different inf file, different signing method, etc.
The only tutorial that I found are at least three years old, I don't know if anything as changed since they were wrote.
Here are the main link that I used : http://blogs.msdn.com/b/asiatech/archive/2011/12/05/how-to-develop-and-deploy-activex-control-in-c.aspx and another one http://www.codeproject.com/Articles/24089/Create-ActiveX-in-NET-Step-by-Step
SOLUTION :
So, everything Pepo said is true so I marked his answer as accepted.
I also found someone who the whole source code (including how to create the .exe which runs the msi) here.

A: The problem might be that you try to run msiexec.exe and this exe is not in the cab file. See this question (be sure to scroll down to the incredibly helpful sample code posted by Roey 5 Aug 2009).
Try to either create a setup.exe that will run process msiexec.exe and install your msi or make an installer with a bootstrap setup.exe file and include both in the cab.
Also, you might want to read about non-admin activex installations.
Your activex dll has to be signed and your activeX should implement this interface
/// <summary>
/// Options supported for the IObjectSafety interface
/// </summary>
[Serializable]
[ComVisible(true)]
public enum ObjectSafetyOptions
{
    /// <summary>
    /// Indicates that the caller of the interface identified by riid might be untrusted.
    /// </summary>
    INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001,
    /// <summary>
    /// Indicates that the data passed into the interface identified by riid might be untrusted.
    /// </summary>
    INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002,
    /// <summary>
    /// Indicates that the caller of the interface identified by riid knows to use IDispatchEx.
    /// </summary>
    INTERFACE_USES_DISPEX = 0x00000004,
    /// <summary>
    /// Indicates that the data passed into the interface identified by riid knows to use IInternetHostSecurityManager.
    /// </summary>
    INTERFACE_USES_SECURITY_MANAGER = 0x00000008
};

/// <summary>
/// Provides methods to get and set safety options.
/// The IObjectSafety interface should be implemented by objects that have interfaces which support "untrusted" clients, such as scripts.
/// It allows the owner of the object to specify which interfaces must be protected from "untrusted" use.
/// </summary>
[ComImport()]
[Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IObjectSafety
{
    /// <summary>
    /// Gets the safety options supported by an object and the safety options that are currently set for that object.
    /// </summary>
    /// <param name="iid">An interface identifier for a given object</param>
    /// <param name="pdwSupportedOptions">Receives the address of a DWORD representing all the options supported for the interface identified by riid.</param>
    /// <param name="pdwEnabledOptions">Receives the address of a DWORD representing all the options currently enabled for the interface identified by riid.</param>
    /// <returns>Returns one of the following values:
    /// S_OK - the object is safe for loading
    /// E_NOINTERFACE - the riid parameter specifies an interface that is unknown to the object</returns>
    [PreserveSig]
    long GetInterfaceSafetyOptions(ref Guid iid, out int pdwSupportedOptions, out int pdwEnabledOptions);

    /// <summary>
    /// Returns whether an object is safe for initialization or scripting, as specified.
    /// </summary>
    /// <param name="iid">An iInterface identifier for the object to be made safe.</param>
    /// <param name="dwOptionSetMask">A mask representing the options to be validated.</param>
    /// <param name="dwEnabledOptions">A DWORD representing all the options currently enabled for the interface identified by riid. </param>
    /// <returns>Returns one of the following values:
    /// S_OK - the object is safe for loading
    /// E_NOINTERFACE - the riid parameter specifies an interface that is unknown to the object
    /// E_FAIL - the dwOptionSetMask parameter specifies an option that is not supported by the object</returns>
    [PreserveSig]
    long SetInterfaceSafetyOptions(ref Guid iid, int dwOptionSetMask, int dwEnabledOptions);
};

I used advanced installer to create msi installer and I set dll registration. Advanced installer then generated all necessary registry keys.
In my test the final inf file was
[version]
signature="$CHICAGO$"
AdvancedINF=2.0
[Deployment]
InstallScope=user|machine
[Setup Hooks]
install=install
[install]
run="""%EXTRACT_DIR%\runmsi.exe""" """%EXTRACT_DIR%\simpleactivex.msi"""

Please note the triple quotes. They are important.
I used this ddl
.Set DiskDirectoryTemplate=.
.Set CabinetNameTemplate=simpleactivex.cab
runmsi.exe
simpleactivex.msi
simpleactivex.inf

And I build cab using this commands
"c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\signtool.exe" sign /sha1 9A15DC8F51773C557BA2F75CF155F8CBD367A8E1 /tr http://tsa/tsa /d SimpleActiveX /du "http://yourcompany.com" /v runmsi.exe simpleactivex.msi

makecab /V3 /F make.ddl

"c:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\signtool.exe" sign /sha1 9A15DC8F51773C557BA2F75CF155F8CBD367A8E1 /tr http://tsa/tsa /d simpleactivex /du "http://yourcompany.com" /v simpleactivex.cab

runmsi.exe is a dummy exe file that runs msiexec with given parameters. Alternatively you could use exe installer or bootstrap exe and msi installer. The important part to note is that IE will not allow to run anything outside the cab file. Therefore you have to do this hack.
When debugging I used this dummy html page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<html>
  <head>
    <title>WebForm1</title>
  </head>
  <body style="margin-top: 0px; margin-left: 0px;">
  <OBJECT id="SimpleActiveXCtrl" classid="clsid:C0082E22-8A19-4600-8332-D31C4055291A" codebase="SimpleActiveX.CAB"></OBJECT>

<script language="javascript">
    // da sa volat z JS metody ActiveXu alebo nastavit property
function OpenActiveX()
{
    try
    {
        alert(document.SimpleActiveXCtrl.HelloWorld("hello"));
    }
    catch(Err)
    {
        alert(Err.description);
    }
}

</script>

  </body>
</html>


text:
Q: How to conditionally remove value attribute using react I want to remove value property from input field in react. How can I achieve this?
For ex. I want to remove value property from below input field
<input type="text" value={this.state.value} />

A: It's easy to handle to show or not value in input.
You may have got a flag to handle it.
Then:
<input type="text" value={isShow ? this.state.value : ""} />

A: If you want to remove the value attribute completely, you can have its key and value come from an object to be spread onto the element
https://stackblitz.com/edit/react-2vreml
In this example, only input 5 will have no value attribute
class App extends Component {
  state = {
    value1: 'React',
    value2: null,
    value3: undefined,
    input4: { type: 'text', value: '123' },
    input5: { type: 'text' }
  };

  render() {
    const { value1, value2, value3, input4, input5 } = this.state;
    return (
      <div>
        <input type="text" value={value1} />
        <input type="text" value={value2} />
        <input type="text" value={value3} />
        <input {...input4} />
        <input {...input5} />
      </div>
    );
  }
}


text:
Q: SharePoint 2010 Sandbox Solution - Cookies support In SharePoint 2010 Sandbox solution, whether cookie is supported?
When I'm trying to set cookie by
HttpCookie myCookie = new HttpCookie("Test","Hello"); HttpContext.Current.Response.Cookies.Add(myCookie);
The value is not passed to browser and the Request.Cookies["Test"] is null on next request.
The same code works fine in farm based solution. Please confirm.

A: No you cannot set cookies in the sandbox, the data are not transferred back between the sandbox and the IIS. The Sandbox lives in it's own process and the HttpContext.Current is different from the HttpContext.Current in ASP.NET (that lives in IIS and the w3wp.exe process)
For more limitations see: http://www.wictorwilen.se/Post/Understanding-the-SharePoint-2010-Sandbox-limitations.aspx

A: Regarding cookie support in Sandbox Solutions, let me break it into two parts:
Write a cookie : Not Supported via HTTPContext(Unless you set and use cookie in same sandbox webpart and in same request- which will obviouly not be the case :-))
Read a cookie : You are free to consume cookies in Sandbox Solutions! Assume, you have a cookie which is set already, the below code will work :
string cookieValue= HttpContext.Current.Request.Cookies["Test"].Value;

Another solution which don't need server-side deployment is the JQuery plugin: http://plugins.jquery.com/project/cookie


text:
Q: Handle exceptions over class library without Try Catch I am working with ASP.NET MVC 4, .Net 4.5, Windows Azure. I handled all exceptions with out writing try catch blocks in Frontier(Web Application) using OnException() controller base class method. I am thinking to handle all exceptions in middle layers(BLL, DAL) in similar fashion without writing try catch blocks, because million lines of code already done without exception handling. Is this possible ? looking for suggestions.

A: There are a number of Exception Handling Frameworks which can intercept exceptions and perform various tasks (log them, send a notification mail etc...)
ELMAH is a good option for your web application though it sounds like you have that side covered.
You could also look at the Microsoft Patterns & Practices Enterprise Library Exception Handling & Logging Blocks
In general though, it's good practice to bubble your exceptions back to the highest calling application block and let it take care of application logging in one place.


text:
Q: AngularJS not updating template variable when scope changes This will be one of those stupid questions that is very obvious to the experts.
I have a websocket pushing data to a service where I'm trying to store the data and have it pushed to a template via my controller.
The data is coming in and updating the variable but the UI only updates is I perform a action on that data:
services.factory('Summary', ['$q','$rootScope','$http', '$location', function ($q, $rootScope,$http, $location) {

var Service = {};
Service.dataObj = {};
Service.dataObj.d = {"gello":"goodbye"};
....
function listener(data) {
   messageObj = data;
    Service.dataObj.d = data;
  console.log("Received data from websocket: ", messageObj);

}
})]);

controllers.controller('UserCtrl', ['$scope', 'Summary',
function ($scope, Summary) {

    $scope.click = function(){
        alert(JSON.stringify($scope.summaryinfo));
    }
    $scope.summaryinfo = [Summary.dataObj];
    $scope.summarygridOptions = {
        data: 'summaryinfo'
    };
    console.log("hello");
}]);

The data gets pumped in and as far as I was aware because its being stored in Service.dataObj.d if I point my HTML template at Service.dataObj that object is being updated and not replaced so the pointer should remain and the object be watched.
But it doesn't change unless I run the click() method, in which case the UI is affected even though Im just triggering an alert.
What am I missing?

A: You probably need to use $apply():

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

function listener(data) {
   $scope.$apply(function() {
       Service.dataObj.d = data;
   });
}


text:
Q: How to change miillisecond to Date Object in yyyy-MM-dd HH:mm:ss format How to change milliseconds to Date object in yyyy-MM-dd HH:mm:ss format like 2017-04-12 23:14:52?

A: You cannot do that. For a couple of reasons.
TL;DR: Don't use Date, use Instant. Neither of these can have a format in them. Formatting into a string is dependent on time zone, so you need to choose a time zone.
First, I understand from the discussion that you are asking for a java.util.Date object having the format yyyy-MM-dd HH:mm:ss. A Date object does not have and cannot have a format in it. The thing you should try to understand here is the difference between data itself and presentation of data to a user. An int may hold the value 25389, but it doesn't hold it in the format 25389 (in fact the internal representation is quite different from 25389). The same int may be presented to a user as 25389, 000025389, 25,389 or +25389, just to mention a few out of many possibilities. The formatting happens outside the int while the int stays just the same.
Similarly, a Date object holds a point in time. The same date may be formatted into for example 2017-04-12 23:14:52 or April 12, 2017 11:14:52 PM. It may even be formatted for different time zones, which would be a good idea if the system has users in different time zones. Alternatively we may show the user a calendar leaf and/or a clock showing the time. Again, formatting happens outside of the Date while the Date stays just the same.
Elaborating on the time zone issue, the same point in time represented by the same millisecond value could be formatted to 2017-04-12 17:44:52 in UTC, 2017-04-12 19:44:52 in my time zone, 2017-04-12 23:14:52 in Asia/Kolkata time zone or even 2017-04-13 05:44:52 in Pacific/Auckland time zone. Note that in the last case not even the date is the same. So there is not just one way to change your milliseconds into the format you asked for. We need to know which time zone you want it for before we can help you.
So what I believe you need is not one thing, but two

*

*A way to store your point in time in your program.

*A way to format your point in time into a string in yyyy-MM-dd HH:mm:ss format for a user in some time zone.

For storing your point in time, use either of

*

*A long for the milliseconds value you already have

*A java.time.Instant object.

Why didn't I mention java.util.Date? Because this class is long outdated. Its design turned out to be troublesome very quickly. They tried to repair it by deprecating most of the methods and introducing java.util.Calendar, but that didn't work very well either. Finally, drawing on the experiences from a library known as Joda-Time they introduced the java.time classes in Java 8 in 2014. That's three years ago as of writing, and counting. So IMHO we should by now have thrown Date and friends overboard and started using the newer classes. So prefer Instant over Date.
Changing your milliseconds to an Instant is straightforward:
    long milliseconds = 1492019092000L;
    Instant pointInTime = Instant.ofEpochMilli(milliseconds);

For formatting your instant into a string for the user, as I said, we require a time zone. Then do
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String formattedDateTimeString = pointInTime.atZone(ZoneId.of("Asia/Kolkata"))
            .format(formatter);

So you need to fill in the desired time zone where I put ZoneId.of("Asia/Kolkata"). If you want to use the JVM's current time zone setting, just fill in ZoneId.systemDefault(). Beware, though, that the time zone setting may be changed, even by an unrelated program running in the same JVM, so relying on this may be fragile.
The result of the above code snippet is a string like
2017-04-12 23:14:52

PS If after reading the above you really insist, here's how to get a java.util.Date from the above:
    Date myOutdatedDateInstance = Date.from(pointInTime);

(and excuse me for repeating, it still doesn't have the desired format, that is not possible).

A: You can try this sample code.
public class MillDateConverter {

    public static String dFormat = "yyy-MM-dd HH:mm:ss";
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dFormat);

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        long milliSec=Long.parseLong("1086073200000");
        System.out.println(milliSec);
        calendar.setTimeInMillis(milliSec);
        System.out.println(simpleDateFormat.format(calendar.getTime()));

    }

}


text:
Q: How can I accept pastes from the clipboard in my UserControl? I've got a UserControl that, oddly enough, bundles a bunch of other controls and logic into a tidy little package.  It has a Text property that accepts a string and does magic, displaying the results for the user.  Awesome.
I get that text from a TextBox.  The user pastes text from the clipboard in the textbox, which is bound to a DP on my UserControl.
What I'd like to do is cut out the middle man and accept pastes within my UserControl.
I've already tried using the DataObject.Pasting attached event, but that appears not to work.
How do you do it?

Answered my own question with my current solution, but honestly it "smells".  If anybody has a better answer, please add it and if it works and is better I'll select it.

A: My brain fired.  Command Bindings.  Now I know when someone tries to paste and can take it from there.
XAML:
<UserControl.CommandBindings>
    <CommandBinding
        Command="Paste"
        Executed="CommandBinding_Executed"/>
</UserControl.CommandBindings>

(excuse the bad code; trying to get this working for now) And the event handler:
try
{
    var text = Clipboard.GetData(DataFormats.Text) as string;
    if (string.IsNullOrWhiteSpace(text))
        return;
    Lines = new Lines(text);
    e.Handled = true;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Paste failed", MessageBoxButton.OK);
}

This smells, IMHO.  But I'm not sure how else to handle this.


text:
Q: Error while pasting object from Clipboard This is my code for copying and pasting an object to the clipboard:
private void CopyObject()
{
    Clipboard.SetData(ClipboardDataFormats.SampleData, this.SelectedSampleObject);
}

private void PasteObject()
{
    if (Clipboard.ContainsData(ClipboardDataFormats.SampleData) == true)
    {
        var sampleObject = (SampleClass)Clipboard.GetData(ClipboardDataFormats.SampleData); // exception
    }
}

I receive following exception when I call Clipboard.GetData()

System.Runtime.InteropServices.COMException Data on clipboard is invalid.
HRESULT 0x800401D3 (CLIPBRD_E_BAD_DATA)

Maybe the reason for the error is that SelectedSampleObject is an entity framework proxy object, when calling Clipboard.SetData(). Is this possible? Do you have any other idea? Unfortunately i really don't understand this exception.

A: Not sure about this specific exception, but your code will not work with EF proxy objects anyway, because objects you put to clipboard must be serializable (for example marked with Serializable attribute), and EF proxy classes are not. You can of course disable proxy creation and mark all your entity classes with [Serialiable] but I doubt you want to do this. Instead, create some another class with only required properties, mark it with Serialiable and use that for clipboard operations. Or serialize your object to json\xml whatever yourself and set that to clipboard.


text:
Q: Rust lifetimes when closure created by struct method takes a mutable referece to that struct I am new to rust, and especially to embedded rust. I have written something which maintains an 'alarm system', which can be in a variety of defined states. The Alarm struct, when transitioning to the armed state, sets up a GPIO pin interrupt with a closure that should be able to set the alarm's state to Alarm when triggered. The compiler complains that there is no guarantee that the closure will not outlive the struct. I understand the issue, but I am not clear on how to fix it.
use crate::pins::CustomPin;
use sysfs_gpio::Pin;
#[derive(Debug)]
pub enum States {
    Disarmed,
    Armed,
    Alarm,
    Error,
}
pub struct Alarm {
    pub state: States,
    pub trigger_pin: Pin,
}
impl Alarm {
    pub fn arm(&mut self) -> () { // `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
        match self.trigger_pin.set_interrupt(Box::new(|| self.trigger())) { //...is captured and required to live as long as `'static` here
            Ok(_) => self.update(States::Armed),
            Err(_) => self.update(States::Error),
        };
    }
    pub fn disarm(&mut self) -> () {
        self.update(States::Disarmed);
    }
    pub fn trigger(&mut self) -> () {
        self.update(States::Alarm);
    }
    pub fn new(trigger_pin: u64) -> Alarm {
        let input = Pin::new(trigger_pin);
        Alarm {
            state: States::Disarmed,
            trigger_pin: input,
        }
    }
    fn update(&mut self, state: States) -> () {
        self.state = state;
    }
}

--
extern crate sysfs_gpio;
use sysfs_gpio::{Direction, Edge, Pin};
pub trait CustomPin {
    fn set_interrupt(&self, callback: Box<dyn Fn() -> ()>) -> sysfs_gpio::Result<()>;
}
impl CustomPin for Pin {
    fn set_interrupt(&self, callback: Box<dyn Fn() -> ()>) -> sysfs_gpio::Result<()> {
        self.with_exported(|| {
            self.set_direction(Direction::In)?;
            self.set_edge(Edge::FallingEdge)?;
            let mut poller = self.get_poller()?;
            loop {
                match poller.poll(1000)? {
                    Some(_) => callback(),
                    None => (),
                }
            }
        })
    }
}

I understand the compiler message, but I don't know how to fix it. I considered a RefCell, but my understanding is that this would force the Alarm to live for as long as the closure, when in fact, the closure should not outlive the Alarm.
I suppose the point fundamentally is that I don't know how to drop that closure explicitly.

A: Your problem is that Box assumes a static lifetime unless explicitly stated otherwise. Consequently, the lifetime problem in your example can be fixed by defining an explicit lifetime parameter to the trait like:
pub trait CustomPin {
    fn set_interrupt<'a>(&self, callback: Box<dyn FnMut() -> () + 'a>) -> sysfs_gpio::Result<()>;
}

Unfortunately, there are more fundamental ownership issues in your example that the borrow checker will reject. Your essential problem is that you're referencing self from every closure, especially even from functions requiring &mut self. This will always fail, you need an Rc or similar constructs to reference the same Alarm struct from multiple places following the "average C++ construct" you're probably migrating from.


text:
Q: Confirm preceding and following sibling in XPATH I've got the below statement to check that 2 conditions exist in a
an element:
 if len(driver.find_elements(By.XPATH, "//span[text()='$400.00']/../following-sibling::div/a[text()='Buy']")) > 0:
   elem = driver.find_element(By.XPATH, "//span[text()='$400.00']/../following-sibling::div/a[text()='Buy']")

I've tried a few variations, including "preceding sibling::span[text()='x'", but can't seem to get the syntax correct or if I'm going about it the right way.
HTML is below. the current find_elements(By.XPATH...) correctly finds the "Total" and "Buy" class, I would like to add $20.00 in the "price" class as a condition also.

"$20.00"

10

0%

                   $400.00

                   Buy

A: Using built in ElementTree
import xml.etree.ElementTree as ET

html = '''

"$20.00"

10

0%

$400.00

Buy

"$27.00"

10

0%

$400.00

Buy

'''

items = {'Total':'$400.00','Buy':'Buy','Price':'"$20.00"'}

root = ET.fromstring(html)
first_level_divs = root.findall('div')
for first_level_div in first_level_divs:
    results = {}
    for k,v in items.items():
        div = first_level_div.find(f'.div[@class="{k}"]')
        one_level_down = len(list(div)) > 0
        results[k] = list(div)[0].text if one_level_down else div.text
    if results == items:
        print('found')
    else:
        print('not found')
    results = {}

output
found
not found

A: Given this HTML snippet

"$20.00"

10

0%

$400.00

Buy

I would use this XPath:
buy_buttons = driver.find_elements(By.XPATH, """//div[
    contains(@class, 'List-Content')
    and div[@class = 'Price'] = '$20.00'
    and div[@class = 'Total'] = '$400.00'
]//a[. = 'Buy']""")

for buy_button in buy_buttons:
   print(buy_button)

The for loop replaces your if len(buy_buttons) > 0 check. It won't run when there are no results, so the if is superfluous.


text:
Q: Formula for product of two polynomials I have found such a formula
$$
\left(\sum_{k=0}^n a_k z^k \right)\cdot \left(\sum_{j=0}^m b_j z^j \right)=\sum_{k=0}^{n+m} \left( \sum_{j=k-\min(n,m)}^{\min(k,\max(n,m))}a_j b_{k-j} \right)z^k,
$$
but seems it's  too complicated. Is there any other formulas?

A: You may simplify a little by omitting the extremes of summation.
Define $a_i=0$ if $i\not\in\{0,1,\dots,n\}$ and $b_j=0$ if $j\not\in\{0,1,\dots,m\}$.
Let $c_k$ be the coefficient of $z^k$ in the product. Then the formula is saying that
$$
c_k = \sum_{\substack{i,j\in\mathbb N\\i+j=k}} a_ib_j
= \sum_{i\in\mathbb N}a_i b_{k-i} .
$$
This is as simple as it gets.
This way you can extend the formula to Laurent series.


text:
Q: Using core location on iphone simulator I am developing an GPS based app. So I was wondering how could I simulate location on iphone simulator?
I downloaded an sample app locateMe. This app does not work on simulator. Does simulator not support location api?
Any help would be appreciated.

A: According to the documentation, when using the simulator:

"The relocation reported by the
  CoreLocation framework in the
  simulator is fixed at the following
  coordinates (accuracy 100 meters),
  which correspond to 1 Infinite Loop,
  Cupertino, CA 95014.
Latitude: 37.3317 North Longitude:
  122.0307 West"

So, in practical terms, you should be able to build the app but you'll be unlikely to do anything useful with it.

A: You might wanna check out my FTLocationSimulator at http://github.com/futuretap/FTLocationSimulator
It reads a KML file generated by Google Earth to provide faked location updates. It also updates the blue userLocation dot in a MKMapView with the simulated location updates.

A: In Xcode 4.2 we can simulate . There is a location symbol on the debug area (while you run the app). There are some predefined locations . Also we can add new GPX files

A: Update:
Xcode 4.2 with iOS 5 supports GPS positioning.
Select the Simulator -> Debug -> Location -> Custom Location...
Previous Version
No the simulator does not support it. So for GPS you have to install the application in the device to check it.
Simulator is gonna give you longitude and latitude as the address of Cupertino Where the headquaters of apple is.
So you have to use device only.
Happy Coding

A: The solution was to subclass CLLocationManager and define a new delegate @protocol, called DLocationManagerDelegate.
It is designed to be a simple drop-in replacement for CLLocationManagerDelegate that compiles down to a very thin layer when deployed on an actual device.
When running on the device it will return data as normal using CoreLocation, but in the simulator it will read latitude and longitude from a text file (defined in the DLocationManager.h file).
I hope this helps, the implementation is on the simple side and you have to startUpdatingLocation and stopUpdatingLocation to update the display.
http://code.google.com/p/dlocation/


text:
Q: Rails: DropDown Selection to Controller Action Good Day, i have this form view/startseites/index.html.erb and i specified a methode in my people_controller, she doesnt go. I prepared some ghost code for understanding. I want to  give the entries from dropdowns with the button_to tag to the controller action checkValid. There i want to validate the entries against the database. I have to read and write from and to the table. I hope its clearly enough.
 class PeopleController < ApplicationController

   def checkValid
      @trainerName = params[:trainer_name]
      @sportlerName = params[:sportler_name]
      @trainerPID = params[:trainer_pid]
      @sportlerPID = params[:sportler_pid]

      #checks if sportlerID is null
       @person = Person.find(params[:sportler_pid])
        id = Person.sportler_id
        if id = nil then
             Person.sportler_id = params[:trainerPID]
         else
           puts "Sportler can have only one Trainer!"
        end

   end
   ...

view/startseites/index.html.erb: this code doesnt go
this should send the drop down selection to the controller action checkValid(). how can i use parameters?
 <%=button_to( "Zuordnung erstellen", :action => "checkValid", :controller =>"people" %>**

       Jeder Sportler kann ein Trainer haben.

       Trainer

          <%= collection_select(:trainer, :trainer_id, Trainer.all, :id, :name) %>

         <%= link_to 'Neuer Trainer', new_person_path(:type => "Trainer") %>

       Sportler

           <%= collection_select(:sportler, :sportler_id, Sportler.all, :id, :name) %>

         <%= link_to 'Neuer Sportler', new_person_path(:type => "Sportler") %>

        **<%=button_to( "Zuordnung erstellen", :action => "checkValid", :controller => "people") %>**

i added this line to my routes
  match '/people/checkValid', :controller => 'people', :action => 'checkValid'

but: No route matches {:controller=>"people/checkValid", :method=>:checkValid}
no i think it goes but
Template is missing
 Missing template people/checkValid, application/checkValid with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "C:/Users/jord/testmood/app/views"

A: The Missing template error refers to a missing view. You should have check_valid.html.erb view file in app/views/people/ directory.
Also, run rake routes on the command line anywhere within your app's directory. You will receive a list routes that are generated by your routes.rb file. You can double-check there if people#checkValid exists.
Btw, you might want to change checkValid to check_valid so you follow the naming convention for actions in Rails.


text:
Q: How do YOU handle bad parameters in functions? Let's say you have some function that has one int parameter that can be good or bad. Let's say that it's bad when it's less than 5. And if it's bad you should get out of function. I think you already made up that function in your mind. Now tell me which of these functions is what you would've written.
1.
void abc(int a)
{
    if (a < 5) return;
    //...
}

2.
void abc(int a)
{
    if (a >= 5)
    {
        //...
    }
}

This may sound like a really stupid question. But I often have hard time deciding between these two lol.

A: I prefer the first way:
if a < 5
    // return error or throw exception

To me it looks like some kind of "guard". Also you should handle this "bad" variable somehow (return error, throw exception) and it will be harder to follow if this is in some else block somewhere in the function.


text:
Q: How to show this series converges $\sum\limits_{n=1}^\infty n^{-1/2}\sin(n)\sin(n^2)$ I want to see if this series converges or not:
$$
\sum_{n=1}^\infty n^{-1/2}\sin(n)\sin(n^2).
$$
I tried comparison tests but nothing. I saw that integral criteria works but I don't know how to show that.
Thank you

A: As indicated by Todd Trimble in comments, we can use the Dirichlet test; here, since $$\sin(n)\sin(n^2)=\frac12\big( \cos n(n-1)   - \cos n(n+1) \big)$$
we have a telescopic sum $$\sum_{n=1}^M \sin(n)\sin(n^2)=\frac12-\frac12  \cos M(M+1)=\sin^2\Big(\frac{M(M+1)}2\Big),$$
that does not exceed $1$ in absolute value.


text:
Q: Set Dynamic Cell's Table View Content height to table view height constraints ios I have tableview(A)'s every custom cell having tableview(B) with dynamic table view cell.
At tableview(A) cellForRowAtIndex.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

     MainMessageTVCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgMainCell"];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        NSInteger index = indexPath.row;

        MessageMain *result = tableData[index];

        cell.dateLabelTC.text = [NSString stringWithFormat:@"Date : %@",result.createdTime];
        cell.subjectLabelTC.text = [NSString stringWithFormat:@"Subject : %@",result.subject];

        NSArray *arrList = result.messageList;
        [cell setupTableData:(NSMutableArray *)arrList];

        [cell setNeedsUpdateConstraints];
}

At tableview(A)'s custom cell reload tableview(B).
-(void)setupTableData:(NSMutableArray *)tableData{

    _tableData = tableData;

    [self.tableView reloadData];
}
-(void)updateConstraints{
    [super updateConstraints];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView layoutIfNeeded];
        CGFloat height = self.tableView.contentSize.height;//+1000;
        tableBHeightConstraints.constant  = height;
    });
}

tableBHeightConstraints is height constraints of table view(B) in tableview(A)'s cell's child.
tableBHeightConstraints.constant not getting correct value with all calculate constraints.
what is the best place or method to get tableView.contentSize.height exact after dynamic table cell's height set.
This is tableview(A)'s Cell

This is tableview(B)'s Cell
Please Help guys.

A: Add the following code in you viewDidLoad method.
   self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView setEstimatedRowHeight:85.0];

Also include the estimatedHeightForRowAtIndexPath method and return a estimated row height as follows,
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

Assign  an automatic dimension for heightForRowAtIndexPath.The method asks the delegate for the height to use for a row in a specified location.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

NOTE
For your table row to be of dynamic height, the labels within the contentview  has to be pinned to the top and bottom so that they can shrink or grow as per the contents. Do update me in case if you are facing any difficulty.

A: Try This :
take a height constraint of UItableView
_tableViewHieghtConstraint.constant = height of row *count of array.
in tableview number of section method.

A: If you can't get this to work, then why not try something different. Instead of trying to stick a tableView in a tableCell, why not just modify your datasource to govern the two tables as one. That is probably a better solution as is should be more efficient and work better as a single table.
If you use grouped style, then effectively each group is an individual tableView with a header and footer.

A: It's better to simply set the constraint to equal height:
tableA_cell.contentView height = TableB height

With visual constraints it would be something like this:
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(tableB);
[cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V|[tableB|" options:0 metrics:0 views:viewsDictionary];

Then the magic should happen by itself.
If you make any changes to tableB, just call
[self.tableView beginUpdates]
[self.tableView endUpdates]

on table A to automatically update the height of it's cells

A: Try moving your changes from -(void) updateConstraints into -(void) viewDidLayoutSubviews.
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView layoutIfNeeded];
    CGFloat height = self.tableView.contentSize.height;//+1000;
    tableBHeightConstraints.constant  = height;
});

}


text:
Q: How to solve System.DateTime does not contain a definition for TryParseExact" on Windows CE and C# I have a block of C# code here.. Basically, what it does is, user input a string in textbox1, on button click, C# will check what date format it is with my declared formats, then add 6 months on the date and output it in the textbox2 to string format yyyyMMdd. I am trying to run this on Windows CE..
And I am having an error of "System.DateTime does not contain a definition for TryParseExact".
            DateTime dateValue;
            string inputString = textBox1.Text;
            string[] formats = {"yyyyMMdd", "yyyy.MM.dd", "dd-MMM-yy", "yyyy/MM/dd", "yyyy-MM-dd", "yy/MM/dd"};

            try
            {
                if (DateTime.TryParseExact(inputString, formats,
                                           null,
                                           DateTimeStyles.None,
                                           out dateValue))
                {
                    dateValue = dateValue.AddMonths(6);
                    textBox2.Text = dateValue.ToString("yyyyMMdd");
                }
                else
                {
                    MessageBox.Show("Invalid Date Format.");
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }

THANKS EVERYONE!

A: Checkout this explanation, it shows how to make your own tryparse, because compact framework does not have it's own.
http://www.yortondotnet.com/2009/11/tryparse-for-compact-framework.html


text:
Q: cellForRowAtIndexPath not returning cell objective c Iam facing a issue with the cellForRowAtIndexPath not returning cell.
Below is my service output
(
 {
     AcNo = 667;
     Avg = 2;
     Address = New York;
     busReviews =         (
                           {
                               Id = 270;
                               businessName = "Pharmacy Inc";
                               comment = "Good Product.";
                           },
                           {
                               Id = 269;
                               businessName = "Agro Buss Inc";
                               comment = "Looks like a great product.";
                               }
                           );
 }
 )

When i tried to retrieve the data in a table view for busReviews. It only displays the first record not the second record.
Below is what i have tried. Please help me to find the issue. TIA
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
 }
 NSMutableDictionary * thisRow = [detailsarr objectAtIndex:indexPath.row];

        times = [thisRow objectForKey:@"busReviews"];

        NSMutableDictionary* refilldict = [times objectAtIndex:0];

        NSString *column1 = [refilldict objectForKey:@"businessName"];

         NSString *column2 = [refilldict objectForKey:@"comment"];

        reviewname.text=[NSString stringWithFormat:@"%@%@",@"-by ",column1];
        review.text= [NSString stringWithFormat:@"%@",column2];

        cell.selectionStyle=UITableViewCellSelectionStyleGray;

       return cell;
    }
    return nil;
}


text:
Q: ausearch to filter audit logs to show only read, write , attribute changes in file I want to filter audit logs for changes made to /etc/hosts file using ausearch (audit).
I can see multiple entries for single modify action for file in ausearch like syscall=chmod, syscall=open etc.
Please help me to understand exact filter required for confirm there is change in file or its attributes.

A: Have you placed a file watch for writes and attribute changes? As per
auditctl -a always,exit -F path=/etc/hosts -F perm=wa
With this you can see who has modified the files attributes or has written to it.
To see what the change is requires some kind of file content monitoring capability.


text:
Q: jQuery Select HTML Option from Output String of Options I've got a loop building an option set that I fill up an empty  node with using jQuery.
i.e;
var optList = function(){
    var list;
    for(i=0;i<5;i++){
        list += '<option>'+i+'</option';
    }
    return optList;
}
$('#mySelect').html(optList());

My question is, given my output string from optList is there a way of having adding "selected" to a predetermined value? like: <option selected>4</option> using my string?  I'm asking because I build my optList BEFORE I am aware of what that predetermined value will be.

A: You can't return the function, you have to return the list
var optList = function(selected_value){
    var list;
    for(var i=0; i<5; i++){
        var selected = i == selected ? ' selected="selected"' : '';
        list += '<option value="+i+" '+selected+'>'+i+'</option';
    }
    return list;
}

$('#mySelect').html(optList(4));

Or you could use what you have and just do
$('#mySelect').html(optList()).val(4);


text:
Q: iOS - reference active storyboard view controller from external class I'm really new to Objective C and I've got an application with a storyboard with a ViewController with the MyViewController class. I then have CDVPlugin (for my cordova application). From one of the methods in my cordova application I want to be able to reference the Active ViewController and call one of the functions from it. I have imported the MyViewController.h header and I was thinking maybe there is a way to make one a delegate for the other but I feel like this is the wrong way to approach this?
Any ideas?

A: You can get the current root view controller for the application using:
[UIApplication sharedApplication].delegate.window.rootViewController

The root view controller might be the active view controller, or it might be a navigation controller, in which case you might want something like:
UIViewController *active = ((UINavigationController *)[UIApplication sharedApplication].delegate.window.rootViewController).visibleViewController
if [active isKindOfClass: [MyViewController class]] {
    MyViewController *myViewController = (MyViewController *)active
    // Call any methods you need to on myViewController
}