text:
Q: Leaflet Draw Plugin: How to draw polygon by one click? I'm using Leaflet in Android so I want to draw polygon by one click because it is too hard to draw by clicking two times to the same point on tablet.
I'm using Leaflet.draw plugin and this demo is working on browser perfectly and you can draw polygon on browser by one click.
https://github.com/Leaflet/Leaflet.draw/
But if I use the same demo on android, I have to click two times on the same point for drawing polygon.
This is not user friendly.
How can i do that ?
Sample code is shown below.
Note: I'm using cordova 2.9.0 for webview
MainActivity.java
package com.example.testdrawing;

import org.apache.cordova.CordovaWebView;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.webkit.WebSettings;

public class MainActivity extends DroidGap {

    public void onCreate(Bundle savedInstanceState) {
        super.setBooleanProperty("showTitle", true);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        appView = (CordovaWebView) findViewById(R.id.tutorialView);
        appView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        appView.getSettings().setJavaScriptEnabled(true);

        super.setIntegerProperty("loadUrlTimeoutValue", 70000);
        appView.loadUrl("file:///android_asset/Leaflet.draw-master/examples/basic.html");

    }

}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

      <org.apache.cordova.CordovaWebView
            android:id="@+id/tutorialView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

</RelativeLayout>

Leaflet side was taken from here and I'm using basic.html example.
basic.html
<!DOCTYPE html>

    <title>Leaflet.draw drawing and editing tools</title>

    <link rel="stylesheet" href="libs/leaflet.css" />
    <link rel="stylesheet" href="../dist/leaflet.draw.css" />

    <button id="changeColor">Rectangle -> Blue</button>


text:
Q: Java gregorian calendar and removing time and timezone I have a gregorian calendar that serializes to the string below during a soap request
2079-07-07T00:00:00.000-07:00

The .NET webservice reads it as the string below
07/07/2079 01:00:00

Is the 07:00 causing the issue?  If so how can I get rid of this?

A: Someone might be able to give you an affirmative answer if you tell us which time zone is configured on your system, but I would assume a mismatch in the DST rules.
The JVM comes with its own timezone and DST rule database, while Windows (and .NET) uses a different database. In theory, the two databases should of course contain the same rules, but I have ran into differences in the DST rules for historical dates. I would assume there might be differences for dates far in the future as well.
If you actually want to transport a date value (no time component) over the SOAP service, the easiest solution would be to use the appropriate XML Schema datatype instead of a datetime type.

A: Use a DateTimeOffset in your .net code and it will work just fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HERE Maps Route Matching v8 Can't Set Preferred Route Hi all and thanks in advance,
I am trying to use Route Matching v8 to set a road as a preferred route so that it will try and take that road when possible.
I have followed the documentation guidelines and have tried to do this using the demo suite provided in the documentation.
https://demo.support.here.com/examples/v3/custom_routing_basic
I have tried using the code suggested in the documentation and it is not working. Can anyone help me understand why this is?
#1 - Submit Overlay
/2/overlays/upload.json
?map_name=OVERLAYNEWBRIDGE&overlay_spec=[
  { "op":"create",
    "shape":[[50.10953,8.68643],[50.10726,8.68697]],
    "layer": "LINK_ATTRIBUTE_FCN",
    "data":{"NAMES":"ENGBNDemo Road"}
  },
  {"op":"restrict",
   "shape":[[50.10953,8.68643],[50.10726,8.68697]],
   "type":"preferred",
   "data":{"PREFERRED_ROUTE_TYPE":"201","ENTRY_PENALTY":-1,"DRIVE_PENALTY":-0.1}
  }
]
&app_id=akl066ieG9nLbhXEWANd&app_code=zKCsydHYhOY17rbzvhq4KQ
&storage=readonly

#2 - Display Overlay
/2/search/all.json
?map_name=OVERLAYNEWBRIDGE&geom=full
&layer_id=LINK_ATTRIBUTE_FC1,LINK_ATTRIBUTE_FC2,LINK_ATTRIBUTE_FC3,LINK_ATTRIBUTE_FC4,LINK_ATTRIBUTE_FC5
&acceptMissingLayers=true
&app_id=akl066ieG9nLbhXEWANd&app_code=zKCsydHYhOY17rbzvhq4KQ

#3 - Calculate Route
/2/calculateroute.json
?waypoint0=50.11089,8.68809&waypoint1=50.10703,8.68222
&mode=fastest;car;traffic:disabled&overlays=OVERLAYNEWBRIDGE
&app_id=akl066ieG9nLbhXEWANd&app_code=zKCsydHYhOY17rbzvhq4KQ

#4 - Delete Overlay
/2/maps/delete.json?map_name=OVERLAYNEWBRIDGE
&app_id=akl066ieG9nLbhXEWANd&app_code=zKCsydHYhOY17rbzvhq4KQ
&storage=readonly

A: I see you make preferred to shortly created shape. It seems doesn't work currently. Development team is already working on it.
Workaround if set penalty for the standard bridge like:
#1
/2/overlays/upload.json
?map_name=OVERLAYNEWBRIDGE&overlay_spec=[
{ "op":"create",
"shape":[[50.10953,8.68643],[50.10726,8.68697]],
"data":{"NAMES":"ENGBNDemo Road"}
},
{"op":"restrict",
"shape":[[50.109569,8.687733],[50.107257,8.687765]],
"type":"preferred",
"data":{"VEHICLE_TYPES":"1023", "PREFERRED_ROUTE_TYPE":"201","ENTRY_PENALTY":10,"DRIVE_PENALTY":0.5}
}
]
&app_id=akl066ieG9nLbhXEWANd&app_code=zKCsydHYhOY17rbzvhq4KQ
&storage=readonly


text:
Q: Parse GML with OpenLayers In our project we do a GetFeature request to a WFS service. This service returns some GML. To parse this GML, we are playing with the GML parser of OpenLayers. This is working as long the GML isn't 'complex'. It isn't returning everything.
This is how a GML object looks like:
<gml:featureMember>
  <mag:keywords gml:id="TopografischElement_Trefwoord.fid--255d1722_146cd32a493_b9c">
    <mag:keywordid>1</mag:keywordid>
    <mag:keyword>Vlees</mag:keyword>
    <mag:keywordtopografischelement>
      <mag:keywordtopolink gml:id="1">
         <mag:keywordid>1</mag:keywordid>
         <mag:topografischelementid>4</mag:topografischelementid>
         <mag:typologie1>Wegennet</mag:typologie1>
         <mag:typologie2>Straat</mag:typologie2>
         <mag:typology1>Road network</mag:typology1>
         <mag:typology2>Street</mag:typology2>
      </mag:keywordtopolink>
   </mag:keywordtopografischelement>
 </mag:keywords>
</gml:featureMember>

This the code we use to parse it:
var content = _this.format.read(data);

and _this.format is:
this.format = new OpenLayers.Format.GML();

So when looping through "content", each object has a data property. When looking that property, we can find the keywordid and keyword (in this example 1 and 'Vlees'). The problem is, I need the data below that, I need the mag:topografischelementid. How can I make it parse that data too, and not only the first 2 fields?


text:
Q: Java :- How to save in Microsoft Excel 2010 when read through csv I am able to read the csv file in Microsoft excel, but when I try to save it, it gets saved as text as it's in tab delimited form and the changes made are lost.
WebUtils.download(response, datafetcher, form.getString("reportName") + ".xls",
                "application/vnd.excel", hdr, "\t");

A: If I'm reading this right, you are relying on the fact that Excel will go ahead and load a CSV file that is called something.XLS, but when it's saved again it will maintain the CSV format and therefore lose all the formatting applied. As DwB says, Excel should warn about this with a fairly clear message unless that's been disabled.
I don't think there's a lot you can do here, other than some client education or rewriting your report to actually export a genuine XLS or XLSX file.


text:
Q: Extracting Strings Containing Spaces I am trying to remove rows from a data frame in R that contain specific phrases in one of the columns. So far I have been successful using the following code to remove rows containing the word "date":
newdata <- mydata %>%
filter(!grepl(".*date.*", column_name))

However, this code does not work when I try to select multiple words that contain spaces in between. How could I extract rows containing "unknown year" as well as "date"?

A: newdata <- mydata %>%
filter(!grepl(".*(date|unknown\\s+year).*", column_name))


text:
Q: PromiseKit 6.0 passing catched errors to caller According to migration guide PromiseKit 6.x changed his policy about catch blocks. In PMK 4 catch returned the promise it was attached to. Now catch is a chain- terminator. I understand why these changes were made but...
In my codebase (connected with PK4) I take some advantages from that catch returns promise.
func loginAndSync(withServerAddress address: String, port: String) -> Promise<()> {
    synchronizationService.stopAllRunningSingleSynchronizations()

    return
        authorizationService.save(serverAddress: address, andPort: port)
            .then {
                self.synchronizationService.startSingleFullSynchronization()
            }
            .then {
                self.authorizationService.markAsServerSynced()
            }
            .catch { error in
                log.error(error)
                _ = self.authorizationService.markAsServerUnsynced()
            }
}

In this function I make some logic which is in some cases failable. In case of error catch block should make some logic but I want to also send to loginAndSync function`s caller a result of this promise (fulfill or reject). Above function can be called for example by ViewController and in ViewController I want to show for example Error or Success Dialog.
This is a reason where I need a two catches for one Promise-chain. One for authorizationService and one for UI.
Is there any workaround in PromiseKit6 to achieve this?
Edit
I found two solutions (workarounds). I have created two answers to separate them. Future readers can decide which one is better or provide new one.

A: I found (IMO) better workaround. PromiseKit6 introduces very handy method tap. I have tried use it to resolve my problem.
func loginAndSync(withServerAddress address: String, port: String) -> Promise<()> {
    synchronizationService.stopAllRunningSingleSynchronizations()

    return authorizationService.save(serverAddress: address, andPort: port)
        .then {
            self.synchronizationService.startSingleFullSynchronization()
        }
        .then {
            self.authorizationService.markAsServerSynced()
        }
        .tap { result in
            switch result {
            case .rejected(let error):
                log.error(error)
                _ = self.authorizationService.markAsServerUnsynced()
            default: break
            }
        }
        .done {
            self.coordinatorDelegate?.handleLoginServerSuccess()
        }
}

For doc:

tap feeds you the current Result for the chain, so is called if the chain is succeeding or if it is failing

So I can provide custom error handling for current state of Promise whit terminating the chain. Promise can be send to sender where I can do another tap or terminate chain by catch.

A: I have wrapped my Promise chain in another Promise:
func loginAndSync(withServerAddress address: String, port: String) -> Promise<()> {
    synchronizationService.stopAllRunningSingleSynchronizations()

    return Promise { seal in
        authorizationService.save(serverAddress: address, andPort: port)
            .then {
                self.synchronizationService.startSingleFullSynchronization()
            }
            .then {
                self.authorizationService.markAsServerSynced()
            }
            .done {
                self.coordinatorDelegate?.handleLoginServerSuccess()
                seal.fulfill(())
            }
            .catch {
                log.error($0)
                _ = self.authorizationService.markAsServerUnsynced()
                seal.reject($0)
            }
    }
}

It should work but I don't know is it a good approach.


text:
Q: Uploading file using Spring REST API I have my controller like this, i am using POSTMAN REST client for upload pdf file. setting content-type: multipart/form-data;boundary=randomBoundaryNotInAnyOfParts
It is creating the file but not writing anything in it. Am i missing something here?
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest request) {

InputStream is = null;
OutputStream out = null;
try {

is = request.getInputStream();
byte[] b = new byte[1024];
out = new FileOutputStream(new File("C:\\tmp\\upload.txt"));
out.write(b);
} catch (IOException e) {
e.printStackTrace();
} finally{

try{
if(out != null){
out.close();
}
if(is != null){
is.close();
}
}catch(IOException io){
io.printStackTrace();
}

}
return null;
}

Thanks,
Vinay

A: Your byte[] is empty hence it is writing nothing in the file. Get content of the request into the byte[] and then write it into file.
Or you can use BufferedWriter also it is more fast.
Thanks,
Brijesh


text:
Q: Why must I declare template above each function in a template? I'm writing a template, and I'm a bit new to doing that.  I've noticed that every tutorial I run into declares the template above each function that is implemented.  I'm curious if this is for a reason, if there is a way around it, and how it is useful.
Example: Within some file (we will call it template.h):
template <class T> class MyClass
{
public:
    MyClass(T parameter);
    T getParameter() const;
    void setParameter();
    void doSomethingUseless() const;
private:
    T mParameter;
}

template<class T>
MyClass<T>::MyClass(T parameter):mParameter{parameter}
    {}

template<class T>
T MyClass<T>::getParameter() const
    {
        return mParameter;
    }

template<class T>
void MyClass<T>::setParameter(T parameter)
    {
        mParameter = parameter;
    }
template<class T>
void MyClass<T>::doSomethingUseless() const
    {
        for (int i = 0; i < 10000; i++)
    }

*

*Why must every function be templated if it has nothing to do with the
template type? (for example, the doSomethingUseless method)

*Why are both the template<class T> and the MyClass<T> required above each function for this to compile?

*Am I approaching this incorrectly/Is there an easier way to do this?

Anyways, thanks for looking.  As a note, I did not compile the example above, I generalized a different template class that I wrote (without a bunch of busy functions in there)  If there are mistakes, I apologize.

A: The member functions of a template class are themselves also templates.  Because of this, they need to be defined with any required template parameters (in your case T).  If you did not do this, you might write a function like:
void MyClass::memberFunc(T var) {}

What is T in this case?  There's no T defined within this scope.
So what do people do?  Many code bases will simply define their functions inline with the class.  However others insist on separating them, like you have done.  The unfortunate reality is that it's simply a requirement of the language.

A: Member functions of a templated class require template so they can specify the class' template, even if the function itself isn't templated.  This is because the class isn't class MyClass, but template<typename T> class MyClass<T>, but the functions don't know that by default.  Because of this, the compiler needs to know what the class' template parameters are so it can associate the function with the actual class, allowing it to do things such as make the correct version of the member function's this pointer, or allow the function to use the class' template parameter list.
This is necessary because templates aren't raw code, they're blueprints for code, which the compiler uses to make the actual code whenever it needs to instantiate or otherwise use them.
template<typename T> class MyClass {};

// ...

MyClass<int>  mci; // Compiler creates class "MyClass_int".
MyClass<bool> mcb; // Compiler creates class "MyClass_bool".

Due to this, the member functions also need to be templated, so that the compiler will know to use them as code blueprints, too.
void MyClass::myFunc() {}
// Compiler thinks this explicitly belongs to class "MyClass".
// Can't be used with MyClass_int or MyClass_bool.

template<typename T>
void MyClass<T>::myFunc() {}
// Compiler knows this belongs to class template "MyClass<T>".
// Can be turned into MyClass_int::myFunc() or MyClass_bool::myFunc().

Normally, the template parameter list is defined for the entirety of the class' scope, which allows member functions defined within the class to use the template without explicitly specifying it.
template<typename T>
class MyClass {
  public:
    // Every function in here is implicitly "template<typename T>".

    void myInternalFunc(T t) {}
};

If the functions are defined outside the class, however, then they no longer have access to the implicit template parameter list, and need to specify it manually.
template<typename T>
void MyClass<T>::myExternalFunc(T t) {}

Note that this template parameter list is not the function's, but the class'.  This means that if the function is also templated, it requires a separate template parameter list, which, in all honesty, looks kinda silly.
template<typename T>
class MyClass {
    template<typename U>
    void myTemplatedFunc(U u);
}

template<typename T>
template<typename U>
void MyClass<T>::myTemplatedFunc(U u) {}
// Class is:     template<typename T> MyClass<T>.
// Function is:  template<typename U> myTemplatedFunc(U u).

In short: That's not the function's template parameter list, it's the class' template parameter list, used so that the compiler can match the function to the class, and so that the function can act in relation to the class' template parameters (such as having a template parameter as the return type, or taking one as a parameter type).  It's necessary when the function's definition isn't contained within the class' scope, because the function can't inherently see the class' template parameter list outside of the class' scope.

A: You might (and perhaps should) have a non-template base class that has all the non-template-type-dependent data and methods. That way, not only your declarations will be shorter (and, possibly for some compilers, even the code is shorter), you can have references of the base type and call the non-template-type-dependent functions: MyClass<int> a(42); const MyBase& b = a; b.doSomethingUseless();.


text:
Q: Awk/Gsub alternative for special characters and string extraction I have a file containing many lines such as below:

  - dep[(0:0)(0:0)]ref[(3:0)(0:0)]srch[?] - XX:The quick brown fox jumped over the lazy    - - user

  - dep[(0:0)(0:0)]ref[(3:0)(0:0)]srch[?] - YY:Jack and Jill went up the hill    - - user

  - dep[(0:0)(0:0)]ref[(3:0)(0:0)]srch[?] - ZZ: Mary had a little lamb    - - user

I wish to extract the following strings and discard the everything else.
XX: The quick brown fox jumped over the lazy
YY: Jack and Jill went up the hill
ZZ: Mary had a little lamb

So far I've tried using the following awk command but it appears to be limited as the XX needs to be replaced for YY and ZZ.
awk '{gsub(/^.*XX:/,"XX:"); gsub(/[<\a>].*$/,"[].");print}'

Is there an alternative anyone can suggest using any other standard Linux tool?
Thanks.

A: If your Input_file is same as shown example then following may help you in same too.
awk -F"\">|" 'NF{print $4}'  Input_file

Explanation: Making "> and  as a field separator(obviously to get what OP needs :) ). NF will make sure we should skip empty lines. Now when we set field separator as these 2, we could see 4th field will be the one which OP requires, here is how we could see all the field's value and we could pick 4th column which OP needs to get.
awk -F"\">|" '{for(i=1;i<=NF;i++){print i,$i}}'  Input_file
1
<img src="img/tt_potato-30x30.png" alt="ew_inactive
2  <img src="img/in-event-40x40.png" alt="event
3  - dep[(0:0)(0:0)]ref[(3:0)(0:0)]srch[?] - <a href "tcc_1111.html
4 XX:The quick brown fox jumped over the lazy
5   -<img src= "img/config-40x40.png" alt="config
6 <img src="img/validate-40x50.png"  alt="validate
7  - user
1
<img src="img/tt_potato-30x30.png" alt="ew_inactive
2  <img src="img/in-event-40x40.png" alt="event
3  - dep[(0:0)(0:0)]ref[(3:0)(0:0)]srch[?] - <a href "tcc_1111.html
4 YY:Jack and Jill went up the hill
5   -<img src= "img/config-40x40.png" alt="config
6 <img src="img/validate-40x50.png"  alt="validate
7  - user
1
<img src="img/tt_potato-30x30.png" alt="ew_inactive
2  <img src="img/in-event-40x40.png" alt="event
3  - dep[(0:0)(0:0)]ref[(3:0)(0:0)]srch[?] - <a href "tcc_1111.html
4 ZZ: Mary had a little lamb
5   -<img src= "img/config-40x40.png" alt="config
6 ((XX|YY|ZZ):[^<]*)}'

A: ^.XX means any character followed by XX at the start of a line - it will not match XX mid-line. [<\a>] means any of the characters <, \, a, or > - it will not match the string <\a>. Find a regexp tutorial...
Your question isn't clear but maybe this is what you're trying to do?
$ awk '{sub(/<\/a>.*/,""); sub(/.*>/,"")} NF' file
XX:The quick brown fox jumped over the lazy
YY:Jack and Jill went up the hill
ZZ: Mary had a little lamb

or with GNU awk for the 3rd arg to match() to print whatever's between ... (assuming one per line):
$ awk 'match($0,/.*]*>(.*)<\/a>.*/,a){print a[1]}' file
XX:The quick brown fox jumped over the lazy
YY:Jack and Jill went up the hill
ZZ: Mary had a little lamb

which in any sed would be:
$ sed -n 's/.*]*>\(.*\)<\/a>.*/\1/p' file
XX:The quick brown fox jumped over the lazy
YY:Jack and Jill went up the hill
ZZ: Mary had a little lamb


text:
Q: Trying to open programs with bat file but always comes back invalid I am a streamer and I need a few programs to stream. It's annoying to open all of them so I tried putting them in a batch file. I looked up the process and followed it,but every time I run the batch file it comes back invalid.
This is what my batch file looks like:
@echo off
cd C:\Program Files "(x86)\obs-studio\bin\64bit"
start obs64.exe

@echo off
cd "C:\Program Files\HexChat"
start hexchat.exe

@echo off
cd "C:\Program Files (x86)\Nightbot"
start nightbot.exe

exit

Cmd gives me an error saying it cannot find the file. When I put this into cmd by itself it opens the program.
Also is there a way to add applications from chrome to the file?

A: Open a command prompt window and run from within this window start /? which outputs the help for this command and explaining all options.
Following batch file most likely works:
@echo off
start "" "%ProgramFiles(x86)%\obs-studio\bin\64bit\obs64.exe"
start "" "%ProgramFiles%\HexChat\hexchat.exe"
start "" "%ProgramFiles(x86)%\Nightbot\nightbot.exe"

This batch file starts the three applications with current directory on execution of the batch file being also the current directory for the 3 started applications.
But the following batch file should be used if it is really necessary that each application is started with the application's directory as current directory:
@echo off
start "" /D"%ProgramFiles(x86)%\obs-studio\bin\64bit" obs64.exe
start "" /D"%ProgramFiles%\HexChat" hexchat.exe
start "" /D"%ProgramFiles(x86)%\Nightbot" nightbot.exe

With parameter /D and path of application's folder the Start In directory is set first like when using command CD. So for example hexchat.exe is started with current directory being C:\Program Files\HexChat for this application.
The two double quotes after command START are necessary as this command interprets first double quoted string as title for the process. By using "" an empty title string is explicitly specified resulting in rest of command line being correct interpreted as expected. I suppose those three applications are all GUI applications and not console applications and therefore a real title string being useful on running a console application in an new command process for the console window is not really necessary.
%ProgramFiles% references the predefined environment variable ProgramFiles containing path to standard program files folder for 64-bit applications on 64-bit Windows when batch file is started with 64-bit cmd.exe as default on 64-bit Windows and is replaced by Windows command interpreter before execution of the command line on your Windows computer by C:\Program Files.
%ProgramFiles(x86)% references the predefined environment variable ProgramFiles(x86) containing always path to standard program files folder for 32-bit applications on 64-bit Windows and is replaced by Windows command interpreter before execution of the command line on your Windows computer by C:\Program Files (x86).
It is of course also possible to use the real paths in your computer instead of the environment variable references if this batch file is never shared with other people.
Extra hint:
Run in a command prompt window the command you want to use with /? as parameter to get displayed the help for this command. Other sources for help on commands and predefined environment variables displayed all on running in a command prompt window set are:

*

*SS64.com - A-Z index of the Windows CMD command line

*Microsoft's command-line reference

*Windows Environment Variables and WOW64 Implementation Details


text:
Q: How do I write a countifs function across multiple sheets that pulls from filtered data? I am attempting to write a countifs function that populates data for my successful projects column. The data will be pulled from a separate page titled kickstarterscrape_06-02-201 with a filtered column.
Successful Projects Analysis
The filtered column of the other sheet is titled status within column G, I would only like to pull data for successful projects.
Filtered Data and Column I will be pulling data from
The current function that I have is..
=COUNTIFS('kickstarterscrape_06-02-201'!G:G="successful",Summary!B6)
However it returns an error. How do I write this correctly?

A: =COUNTIFS('kickstarterscrape_06-02-201'!G:G,"successful",Summary!B6,"criteria2")

try this, you shouldnt have to put an = just a comma separating the criteria and the range. however you have a criteria range1 and a criteria1 then a criteria range2 but you dont have a second criteria
if you were trying to place the count number in cell B6 on the sheet named summary, place this in that cell:
=COUNTIFS('kickstarterscrape_06-02-201'!G:G,"Art")

so if column G in sheet kickstarterscrape_06-02-201 has weather or not it was a success or not and say column B in the same sheet had the category,
=COUNTIFS('kickstarterscrape_06-02-201'!G:G,"successful",kickstarterscrape_06-02-201'!D:D,"Art")

would show (in the cell that the formula is placed) the number of rows that contain art in column D and successful in column G


text:
Q: The Underscore (_) in a Visual Basic If Statement using AndAlso I apologize if this is documented somewhere, I could not find the answer using an underscore in this specific manner (an If Not, AndAlso statement).
Here is what I don't understand
If Not variable Is Nothing _
    AndAlso Not Results.Tables.Count = 0 _
    AndAlso Not Results.Tables(0).Rows.Count = 0 Then

If I take away the Underscores in this code, VB2017 automatically puts a Then at the end of the first line of code and I get 2 Syntax Errors for AndAlso on both lines they are used.  Can someone explain why this is?  I read on StackOverflow that the Compiler doesn't care about the underscore, and I've also read MSDN's AndAlso documentation and I'm a little confused.
Thank you for your help.

A:
I read on StackOverflow that the Compiler doesn't care about the underscore

That's not quite true. Implicit line continuations are a fairly recent addition to the Visual Basic language1. They cover many, but not all, scenarios where the _ line continuation character used to be needed.
Here's the complete list from linked documentation:

*

*After a comma (,).

*After an open parenthesis (() or before a closing parenthesis ()).

*After an open curly brace ({) or before a closing curly brace (}).

*After an open embedded expression (<%=) or before the close of an embedded expression (%>) within an XML literal.

*After the concatenation operator (&). For example:

*After assignment operators (=, &=, :=, +=, -=, *=, /=, \=, ^=, <<=, >>=).

*After binary operators (+, -, /, *, Mod, <>, <, >, <=, >=, ^, >>, <<, And, AndAlso2, Or, OrElse, Like, Xor) within an expression.

*After the Is and IsNot operators.

*After a member qualifier character (.) and before the member name.

This shows we can safely add lines after AndAlso rather than before:
If Not variable Is Nothing AndAlso
   Not Results.Tables.Count = 0 AndAlso
   Not Results.Tables(0).Rows.Count = 0 Then

I also suggest rewriting as follows, because VB.Net does odd things with Not, using it as a bitwise rather than logical operator3:
If variable IsNot Nothing AndAlso
   Results.Tables.Count > 0 AndAlso
   Results.Tables(0).Rows.Count > 0 Then

1. Okay, 2010, but I still find a lot of VB developers who don't know about them, or know about them but never check the rules and either avoid them or let the compiler tell them when to add one.
2. Emphasis mine.
3. Plus, I just find it easier to read without the negations.

A:
"if I make it all one line of code I still get a Syntax Error"

This compiles fine:
If Not variable Is Nothing AndAlso Not Results.Tables.Count = 0 AndAlso Not Results.Tables(0).Rows.Count = 0 Then Exit Sub

This also compiles fine:
If Not variable Is Nothing _
        AndAlso Not Results.Tables.Count = 0 _
        AndAlso Not Results.Tables(0).Rows.Count = 0 Then Exit Sub

What won't work is this:
If Not variable Is Nothing
        AndAlso Not Results.Tables.Count = 0
        AndAlso Not Results.Tables(0).Rows.Count = 0 Then Exit Sub

Without the _ underscore it expects the If statement to be fully formed on the same line.
As Joel points out, the implicit line continuations require the AndAlso before the line break.  See his better answer.
What's good to know however is that the underscores are not necessary when using Linq in newer versions of the compiler:
Dim interesting = From r As DataRow In Results.Tables(0).AsEnumerable()
                  Let fieldId = r.Field(Of Integer)("id")
                  Where fieldId <> 0
                  Order By fieldId
                  Select r

A: It means "line continues on next line".
You can also write it as:
If variable IsNoT Nothing AndAlso
   Results.Tables.Count > 0 AndAlso
   Results.Tables(0).Rows.Count > 0 Then
       'something
End If

A: The conditions in the If statement must be on one line as a VB standard. because some conditions might be too long to be readable on one line, the underscore is used as an escape character that indicates that the line is not finished.
If you write
 If Not variable Is Nothing
AndAlso Not Results.Tables.Count = 0
AndAlso Not Results.Tables(0).Rows.Count = 0 Then

Visual stdio will only consider the first line as part of the If statement Making the result:
 If Not variable Is Nothing Then
 AndAlso Not Results.Tables.Count = 0
 AndAlso Not Results.Tables(0).Rows.Count = 0 Then

You will need to put all conditions on one line or use the underscore.
This is the standard in VB.


text:
Q: Datagrid textblock not aligned on left border This is probably a very stupid problem, which is also probably why I can't find an answer to it.
I have a datagrid in which I add messages every once in a while during a lengthy operation, and for some reason the textblocks appear slightly a bit on the right of the left border of the datagrid, even though there is no margin on the textblock and no padding on the datagrid :

Here is my XAML :
<DataGrid x:Name="dgrdMessages" HorizontalAlignment="Left" Margin="21,212,0,0" VerticalAlignment="Top" Height="202" Width="690">
                    <DataGrid.Columns>
                        <DataGridTemplateColumn Header="Message" Width="*">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding Message}" Width="Auto" HorizontalAlignment="Left" VerticalAlignment="Top">
                                        <TextBlock.Style>
                                            <Style>
                                                <Style.Triggers>
                                                    <DataTrigger Binding="{Binding IsError}" Value="true">
                                                        <Setter Property="TextElement.Foreground" Value="Red"/>
                                                    </DataTrigger>
                                                </Style.Triggers>
                                            </Style>
                                        </TextBlock.Style>
                                    </TextBlock>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                </DataGrid>

Any ideas ?

A: From your screenshot it does not seems the TextBlock are "slightly on the right" (they touch the left border).
Do you want to get rid of the "row selector", the small gray button on the left?
If so set HeadersVisibility="Column" in XAML.

A:  <DataGridTemplateColumn.CellStyle>
     <Style TargetType="DataGridCell">
         <Setter Property="HorizontalContentAlignment" Value="Left"/>
     </Style>
 </DataGridTemplateColumn.CellStyle>


text:
Q: Opening up two sockets in java from different instances of an application to the same source This could just be me being stupid, but I'm opening up two different applications on my computer that connect to the same port of a server running on the computer. Now, it's fine with one application connected, but once the other one is launched it starts throwing a bunch of exceptions about java.io.StreamCorruptedException: invalid type code: AC.. Is this because I'm trying to have the 1 server + 2 clients running on the same machine?
Edit: Code:
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),12352);
SocketThread sthread = new SocketThread(socket);
...
sthread.start();

Inside the socket thread:
 this.ois = new ObjectInputStream(socket.getInputStream()); <-- ois is a variable for the ObjectInputStream
 ...
 Packet packet = (Packet) ois.readObject(); <-- Error appears on this line.

Edit #2: Second - server code:
while(true)
{
        Socket player = server.accept();
        System.out.println(player.getRemoteSocketAddress().toString() + " connected.");
        startSocket(player);
}

public static void startSocket(Socket player) throws IOException
{
    new SocketThread(player).start();
}

Now, there is no errors on the server.

A: No, any number of clients should be able to connect to a single server.
One of my implementation has code looks a bit like this. And I'm able to connect any number of clients to this server from local as well as remote machines.
ServerSocket soc = new ServerSocket(port);

while (true) {
  try {
    if (StopService) {
      soc.close();
      break;
    }

    Socket s = soc.accept();
    new Thread(new ConnectionHandler(s)).start();
  } catch (SocketTimeoutException ex) {
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}

Just make sure that after accepting connection you have it sent to a separate thread for handling so that your server socket thread can accept() the next connection if its waiting.
Those errors do sound a bit weird. If you already have multiple threads going, maybe when you accept multiple connections both threads try to unintentionally modify something in a shared object or maybe one thread somehow gets access to the other thread's socket and manipulates it in unexpected way.
If you could shed some light on your code responsible for creation of sockets what the bit where the error actually occurs, a better answer can be given.
EDIT:
Sorry my rep does not permit to add comments yet.
How about the Server code which sends the data to client.


text:
Q: Dimensions of image and kernel of a $n \times n$ matrix Let $K$ be a field, $V$ a vector space over $K$ of a finite dimension $n=dim_K(V)$.
Let $f : V \rightarrow V$ be a  $K$-linear map and $\mathfrak{B}$ an ordered basis of $V$ with
$$M_{f, \mathfrak{B}, \mathfrak{B}} =
 \begin{pmatrix}
  0 & 1 & 1 & 1 & \cdots &1 \\
  0 & 0 & 1 & 1 &\cdots&1 \\
  0 & 0 & 0 & 1 & \cdots &1 \\
  \vdots  & \vdots  & \vdots & \ddots & \ddots & \vdots  \\
  &&&&&1\\
  0 & 0 & 0 & 0 & \cdots & 0
 \end{pmatrix}$$
Side questions: Does this matrix have a name? Does the basis with the columns as vectors have a name?
I need to calculate the dimensions of the image and the kernel of $f$, I know how to do it with a completely given matrix and basis, but without it I have problems. Any hints welcome.

A: Hint:
The rank of a matrix is the number of non-zero rows after the matrix has been written as an upper triangular matrix by row reduction. This one is already in upper triangular form.
For the dimension of the kernel, use the rank-nullity theorem.

A: We can row-reduce the matrix to
$$\begin{pmatrix}0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & & \vdots \\&&&\ddots&\\ \vdots & & & \ddots& 1 \\ 0 &\cdots & & & 0\end{pmatrix}$$
and in this form it is clear that the rank is $n-1$. Hence,
$$\dim\operatorname{im} f=n-1,$$
and by the rank-nullity theorem,
$$\dim\ker f=n-(n-1)=1.$$


text:
Q: Jenkins appears to be running multiple Jasmine tests I have a Jenkins system running a whole bunch of tests in different sub projects.
The tests are standard karma/jasmine tests, there's around 1100 of them.
When run locally everything is fine, however when I run on Jenkins - it's a bit of a slow box, things get a bit confused:
02 09 2022 10:56:56.958:INFO [Chrome Headless 88.0.4324.150 (Linux x86_64)]: Connected on socket bo3DxF9BnavPH6nwAAAD with id 94495247
02 09 2022 10:56:57.126:INFO [Chrome Headless 88.0.4324.150 (Linux x86_64)]: Connected on socket LdcMV2pzqr9wLn-hAAAF with id 55577246

My karma.conf is as follows:
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-jasmine-seed-reporter'),
      require('karma-coverage'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
      captureConsole: false // switch this flag to true if console log is required during Karma Runner
    },
    coverageReporter: {
      dir: require('path').join(__dirname, '../../coverage/project'),
      subdir: 'report',
      check: {
        global: {
          statements: 80,
          lines: 80,
          branches: 80,
          functions: 80
        }
      },
      reporters: [
        { type: 'json' },
        { type: 'lcovonly' },
        { type: 'text-summary' },
      ],
      includeAllSources: true
    },
    reporters: ['progress', 'kjhtml', 'jasmine-seed'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    singleRun: true,
    restartOnFileChange: false,
    captureTimeout: 240000,
    browserSocketTimeout: 240000,
    browserNoActivityTimeout: 240000,
    browserDisconnectTimeout: 240000,
    customLaunchers: {
      ChromeHeadless: {
        base: 'Chrome',
        flags: [
          '--headless',
          '--disable-gpu',
          '--no-sandbox',
          '--remote-debugging-port=9222']
      }
    }
  });
};

The problem gets more confused 1/2 way through when both browsers report on what they are doing:
[1A[2K[1A[2KChrome Headless 88.0.4324.150 (Linux x86_64): Executed 40 of 71 SUCCESS (0 secs / 0.232 secs)
Chrome Headless 88.0.4324.150 (Linux x86_64): Executed 0 of 71 SUCCESS (0 secs / 0 secs)

Has anyone had this problem and if so what was the solution. As I said the tests are very basic jasmine ones, so it shouldn't kick off a whole bunch of browsers.
SO help appreciated as ever.


text:
Q: obtain ViewGroup inside Fragment.onCreate() method there's a way to abtain ViewGroup inside the Fragment.onCreate() method or i can obtain just inside onCreateView ?
i would like to initialize some component before onCreateView method, so i need viewgroup to get the view

A: To get the root view of a fragment you can call getView()
  /**
     * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
     * if provided.
     *
     * @return The fragment's root view, or null if it has no layout.
     */
    public View getView() {
        return mView;
    }

But this will return null until onCreateView was finished. (as Niek indicated)
You can see in FragmentManger source that mView is set through the usage of onCreateView:
f.mView = f.onCreateView(f.getLayoutInflater(f.mSavedFragmentState),
                container, f.mSavedFragmentState);

Can you elaborate why do you want to intialize something before oncreateview?


text:
Q: portlet 2.0 (jsr286) development with spring We are discussing whether it's a good idea to switch from plain portlet development on a liferay installation to spring webmvc portlet based development.
We're starting the development of some portlets soon, so now is the time. But the problem I see is that we'd like to use some of the portlet 2.0 features, which won't work with versions older than spring 3.0. (Right?)
Has anyone insight, if it's worth the waiting? (When is 3.0 scheduled anyway?)
Is the current milestone stable enough?
Our first real release will be in the last quarter of the year, so the springsource guys have some time left to get a final out of the door... ;-)
Any ideas?
UPDATE
So, Spring 3 has been released and it supports all JSR286 features we need. (I think it's a pretty complete support for the JSR286 features)
The only drawback I am seeing is the documentation which is not up to speed in regard to the annotations.

A: We use Spring Portlet MVC 2.5 on Liferay and we have excellent results. Most of JSR-286 functionality(like events) can be reached be extending DispatcherPortlet class.
There is still a lot of bugs open for upcoming 3.0 release, so I would be rather conservative and stay with stable&mature version 2

A: The spring framework has an excellent track record of code quality. In the past their M releases were of high quality, so I would not be afraid to use it.

A: Juergen Hoeller gave Jul 2008 as the estimated release date for Spring 3.0:
http://www.springify.com/archives/15
I think they're late.  8)
Matt Raible lamented the fact in Oct 2008, almost six months ago:
http://raibledesigns.com/rd/entry/the_colorado_software_summit_and
I wonder if the new professional versus open source model has affected availability.
They also have the Spring DM, Spring Blaze, and Spring Integration work going on now.
Given their past history of quality releases, I'd bet that they're resisting the urge to release early in order to make certain the code is up to their standards.

A: I am just getting to know Portlet MVC with Spring 3.0 M4 and came across a modified PetPortlet sample making use of Spring3 (JSR-286) features and annotations. While it is Mavenized and probably not directly deployable on Liferay, it still provides good examples.
Please comment should you happen to come across any others.


text:
Q: Use custom button as RideRequestButton Uber I'am using uber api for my app and specific ride request widget. I want to use my own custom button in place of Uber's RideRequestButton.
This is the static code for ride request button.
private RideRequestButton blackButton;

blackButton = (RideRequestButton) findViewById(R.id.uber_button_black);
blackButton.setRequestBehavior(new RideRequestActivityBehavior(this,WIDGET_REQUEST_CODE));

Is it possible to apply the function on my own button.?

A: The customization options for the simple button is currently a color scheme, you can choose a white theme or a black theme. See the documentation for that here: https://github.com/uber/rides-android-sdk#ride-request-button
However, in the background, the button simply opens up a deeplink. If you would like you can just use that deeplink and create your own custom button on top of that. Please check out the documentation for the "requestride" method in the "RequestDeeplinkBehavior" class: https://github.com/uber/rides-android-sdk/blob/master/rides-android/src/main/java/com/uber/sdk/android/rides/RequestDeeplinkBehavior.java

A: In the case where we have our own button but still we need to use Uber sdk, hope this might be of help. For details, refer docs here
Build the session configuration using the keys from the dashboard.
SessionConfiguration sessionConfig = new SessionConfiguration.Builder()
                .setClientId(CLIENT_ID)
                .setServerToken(SERVER_TOKEN)
                .setRedirectUri(REDIRECT_URI)
                .setClientSecret(CLIENT_SECRET)
                .build();

Then set the ride parameters along with desired pickup and dropoff locations.
RideParameters rideParameters = new RideParameters.Builder()
                .setPickupLocation(Double.parseDouble(lat), Double.parseDouble(lng), "Your location", "Current Address")
                .setDropoffLocation(Double.parseDouble(mEvent.getLatitude()), Double.parseDouble(mEvent.getLongitude()), mEvent.getName(), mEvent.getCity())
                .build();

Build the deeplink with the session configuration and ride parameters from above.
mDeepLink = new RideRequestDeeplink.Builder(getActivity())
                .setSessionConfiguration(sessionConfig)
                .setFallback(Deeplink.Fallback.APP_INSTALL)
                .setRideParameters(rideParameters)
                .build();

Finally get the uri from the deeplink and pass it as an intent.
startActivity(new Intent(Intent.ACTION_VIEW, mDeepLink.getUri()));

It will always open the app and If it's is not installed, redirect manually to play store.


text:
Q: Difference between OpenAM AND ADFS I want to know the difference between OpenAM AND ADFS. Could the application tested with openAM will also successfully work with ADFS. I need to know this to put this as I do not have access to ADFS, and I can install opensource OpenAM and simualte SSO flows with it. Or should I test my code against ADFS directly. I could decide on this If I know differences in both.

A: In terms of how they handle the federation protocols e.g. WS-Fed and SAML, there is no difference. They both respond to protocol commands. They are both STS.
As to compatibility for applications, it depends on how they are written. ADFS applications would typically use something like WIF which is a .NET C# library, not appropriate for Java.
Also they have different functionality is terms of "add-ons".
Neither ADFS or OpenAM is "free" AFAIK.
Have a look at IdentityServer3 which is open-source.


text:
Q: onDestroy never called I have updated the latest Android Studio and created a new Blank Project. I added the following code to the MainActivity.java file, but onDestroy() is never called. Is there any way to get destroy event?
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.edevshop.destroy">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

A: just check it out and modify your onDestroy() method as below:
@Override
protected void onDestroy() {
    Log.d("TAG", "Yay.. onDestroy called!");
    super.onDestroy();
}

Now... Run App > Open LOGCAT > close App (By pressing BACK button)
You'll see a LOG.


text:
Q: delete functionality not working properly select all checkboxes I passed an array of employee Id via ajax call in my spring controller.
function deleteEntries() {

                var empList = $('input[type=checkbox]:checked').map(function (_, el) {
                    return $(el).val();
                }).get();

                if (empList.length !== 0) {
                    var r = confirm("Are you sure want to remove multiple entries? \nWarning: This process cannot be undone");
                    if (r === true) {

                        $.ajax({
                            type: 'Post',
                            url: baseUrl + 'delete_all',
                            data: {
                                empList: empList

                            },
                            success: function (successMsg) {
                                location.reload();
                            },
                            fail: function (data) {
                                unblockMyScreen();
                                alert('Failed to retrieve data');
                            }
                        });

                    }
                } else
                {
                    alert("Choose atleast single record to delete.");
                }
            }.

Now in UI, I have check boxes, also I provide the functionality to delete by selecting all at once and delete.
Now When I select all and press delete button then only single record is going to delete.However, It is working fine without select all
Here is the delete code
  @RequestMapping(value = "/delete_all", method = RequestMethod.POST)
    @ResponseBody
    public boolean deleteMultipleRecord(@RequestParam(value = "empList[]", required = false) String[] empListToBeRemoved, HttpServletRequest request) {
//        String[] empListToBeRemoved = request.getParameterValues("empList");
        Employee emp = new Employee();
        for (int i = 0; i <= empListToBeRemoved.length; i++) {
            if (!empListToBeRemoved[i].equals("0")) {
                emp.setEmpIdEnc(empListToBeRemoved[i]);
                try {
                    List<OrgStructureTagging> list = orgStructureTaggingDAO.findEmpByProperty("EMP_ID", emp.getEmpId());
                    for (OrgStructureTagging structureTagging : list) {
                        System.out.println("all ids of employees" + structureTagging.getEmployee().getName());
                        orgStructureTaggingDAO.delete(structureTagging);
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("Error Occured While updating the field");
                    return false;
                }
            }
        }
        return false;
    }

THIS IS HOW MY JSP CODE LOOKS LIKE:

Select All  <input type="checkbox" id="ckbCheckAll" value="0">

 <input type="checkbox" class="checkBoxClass" value="${tl.employee.empIdEnc}">

What I found, a default value of root checkbox  Select All  <input type="checkbox" id="ckbCheckAll" value="0"> is also passed via array, so I set its default value as "0", so i can easily skip the root checkbox value, but still it become problematic. kindly suggest me the best solution.

A: Only one record is getting deleted since your method is returning early. To fix this issue, create a boolean variable for returning the method control instead of returning  true/false also decrement 1 from length to avoid ArrayIndexOutOfBoundsException. Here is the code snippet that might help you
@RequestMapping(value = "/delete_all", method = RequestMethod.POST)
@ResponseBody
public boolean deleteMultipleRecord(@RequestParam(value = "empList[]", required = false) String[] empListToBeRemoved, HttpServletRequest request) {
    Employee emp = new Employee();
    for (int i = 0; i <= empListToBeRemoved.length-1; i++) {
        boolean result = false;
        if (!empListToBeRemoved[i].equals("0")) {
            emp.setEmpIdEnc(empListToBeRemoved[i]);
            try {
                List<OrgStructureTagging> list = orgStructureTaggingDAO.findEmpByProperty("EMP_ID", emp.getEmpId());
                for (OrgStructureTagging structureTagging : list) {
                    System.out.println("all ids of employees" + structureTagging.getEmployee().getName());
                    orgStructureTaggingDAO.delete(structureTagging);
                }
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("Error Occured While updating the field");
                result = false;
            }
        }
    }
    return result;
}


text:
Q: Doctrine try to re-add existing entity when added to new entity collection I'm trying to configure Doctrine for my project and I am running into some problems when adding an existing entity to a collection(many-to-many relationship).
Here's the first entity:
/**
 * @Entity
 * @Table(name="formations")
 */
class Formation
{

    /**
     * @var string
     * @Id
     * @GeneratedValue(strategy="NONE")
     * @Column(type="string")
     */
    private $id;

.....(others attributes)

    /**
     * @var Collection
     * @ManyToMany(targetEntity="Fsi\Uec\Domaine\Organisme\Organisme",cascade={"persist"})
     * @JoinTable(name="formation_organization",
     *      joinColumns={@JoinColumn(name="formation_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="organization_id", referencedColumnName="id")}
     *      )
     */
    private $organismes;

.....
    public function addOrganisme(Organisme $organisme)
    {
        if(!$this->hasOrganisme($organisme))
            $this->organismes->add($organisme);
    }

    private function hasOrganisme(Organisme $organisme): bool
    {
        return $this->organismes->contains($organisme);
    }

The second entity :
/**
 * @Entity
 * @Table(name="organizations")
 */
class Organisme
{
    /**
     * @var string
     * @Id
     * @GeneratedValue(strategy="NONE")
     * @Column(type="string")
     */
    private $id;

    /**
     * @var string
     * @Column(name="name", type="string", length=255)
     */
    private $nom;

    /**
     * @var bool
     * @Column(name="active", type="boolean")
     */
    private $actif;

Add the entity to collection and saving ($em is doctrine entity manager)
$formation = new Formation(....);

$organisme = $em->getRepository(Organisme::class)->find($id)
$formation->addOrganisme($organisme);

$em->persist($formation);
$em->flush();

On flush, I get the following error : Integrity constraint violation: 1062 Duplicate entry 'xxxx' for key 'PRIMARY'
It feels to me like Doctrine is trying to re-add the 'Organisme' entity when it already exists.
Some help with this would be appreciated !
Thanks.

A: Try modifying your method  addOrganisme to this :
public function addOrganisme(Organisme $organisme)
{
    if(!$this->organismes->contains($organisme))
        $this->organismes->add($organisme);
}

To be sure that you check if "organismes" has the organisme or not.


text:
Q: How to get rows that fully cover a given time range? I'm building a web application that has a javascript chart in it. The idea is to select a time range, get the relevant data (temperatures) from the DB, deliver it to the page and display it in the chart.
The data's datetime does not come in regular intervals, so from one row to the next, the time difference can be a second as well as some minutes.
I can easily do all of that, but I ran into an issue: currently, when I want to get data for, let's say, 08:00 to 10:00, I can do this by selecting rows where the datetime field is >= 08:00 and datetime field <= 10:00, pseudo-speaking. That is ok, but that gives me gaps on the beginning and end for almost every query, because the last resp. first value most probably is not equal to the boundary.
I need the data within the given time range as well as one value before the range and one value after the range, so that I can show a continuous line from the range's start to end.
I could, of course, simply do three queries: 1. get data within the range limits, 2. get first value before the range, 3. get first value after the range. This works, but I wonder if there is a better/more elegant/more performant way of doing it? Is there maybe some fancy SQL function that I haven't heard of? I'm using Entity Framework 6 as ORM.

A: Subqueries can provide the boundary values for your reporting window, making it possible to obtain all the rows you want in a single SELECT:
SELECT captureTime, temperature FROM temperatures
WHERE captureTime >= (
    SELECT MAX( captureTime ) FROM temperatures
    WHERE captureTime <= '2015-01-01 08:00:00'
) AND captureTime <= (
    SELECT MIN( captureTime ) FROM temperatures
    WHERE captureTime >= '2015-01-01 10:00:00'
)
ORDER BY captureTime


text:
Q: How to round 0.0 to 0.00 in java? I have used the following function
float val=0.0;
DecimalFormat toTheFormat = new DecimalFormat("#.##");
float value=Float.valueOf(toTheFormat.format(val));

But its not suitable for all conditions like "0.0" still "0.0". Its not scale up to "0.00".

A: try
DecimalFormat toTheFormat = new DecimalFormat("#.00");

A: Use
DecimalFormat toTheFormat = new DecimalFormat("0.00");

to round to 2 significant digits

A: Your approach is mistaken. Rounding is a numeric operation that takes a number x and returns another number y which approximates x and has the property that the decimal expansion has only so many digits. Example:
0.123 --> 0.12

But 0.0 and 0.00 are the exact same numbers, there is no point in rounding. What you (maybe) want is to format a number in a certain way on output. For this, see the other answers.

A: If I use DecimalFormat toTheFormat = new DecimalFormat("#.00");
am getting output as .00 not 0.00
so this would be the correct code
DecimalFormat toTheFormat = new DecimalFormat("#0.00");


text:
Q: Access SignalR connection context in authorization attribute handler code I can't get the SignalR connection context when using the Authorize attribute on a hub method.
I'm able to access the HttpContext from my custom Authorization attribute on my Hub:
[Authorize("MyAuthorizationPolicy")]
public class ChatHub : Hub

In my AuthorizationHandler I can inject IHttpContextAccessor to get to the HttpRequest, which gives me access to the token (which is in the header).
But because method invocation doesn't use the HttpRequest, I need to get to the SignalR request context, when I apply an Authorization attribute to my method:
[Authorize("MyAuthorizationPolicy")]
public async Task Join(Guid roomGuid)

Obviously, my instance of IHttpContextAccessor gives me a null HttpContext. How can I inject a 'SignalRConnectionContextAccessor'? :)
(https://github.com/aspnet/Docs/issues/11331)

A: Per discussion here, SignalR is decoupled with HTTP so you may not want to access HTTP context in SignalR contexts.
I do, however, have a not elegant solution for this. SignalR hub Context has a property Features of type IFeatureCollection, which is a dict. Do a LINQ on it:
var contextFeature = hub.Context.Features.SingleOrDefault(f => f.Key == typeof(IHttpContextFeature)).Value as IHttpContextFeature;
var httpContext = contextFeature?.HttpContext;

Remind to check null for httpContext.
I don't recommend this solution though. You should pass your authorization info in User as claims, which is accessible in hub's Context.


text:
Q: How to change "Next" & "Previous" link icon in Ajaxtoolkit's CalendarExtender? I created a web application with a calendar extender using vs2008. In viewing the calendar i wanted to change the images of the next and previous button inside the header of the calendar. is there anyway that i can do this? Thanks.

A: Try this. I have tested over the VS2010 and it worked.
This css code will modify the underlying class for the previous and next month images of the CalendarExtender
    .ajax__calendar_prev
    {
        background-image: url(Images/anyImage.png) !important;
    }

    .ajax__calendar_next
    {
        background-image: url(Images/anyImage.png) !important;
    }


text:
Q: Return Image From Web Url without Webview I need to make a preview of a website , I should pass the url (e.g http://www.google.com) and then  want to return an Image that I will use on ImageView to make the preview. I already did this using the webview object , following this GIT https://gist.github.com/jewelsea/5632958, but I don't know how to get an Image from webUrl without using the WebView object.
any suggestion is welcome

A: you can load the image in ImageView with volley. see this page for more information:
http://code.tutsplus.com/tutorials/an-introduction-to-volley--cms-23800


text:
Q: Call to undefined method stdClass::restore() on restoring soft delete I'm trying to restore softdeleted data but I just keep getting this error
Call to undefined method stdClass::restore()
My routes look like this
    Route::resource('/dvd', 'DvdController');
    Route:get('dvd/{id}/restore', 'DvdController@restore');

And this is my controller
    public function restore($id)
{
    //Dvd::withTrashed()->where('id','=',Input::get('id'))->restore();
    //Dvd::find($id)->restore();
    $dvds = DB::table('dvds')->where('id', $id)->first();
    $dvds->restore($id);
    $view = redirect('dvd')->with('message', 'Data berhasil di-restore');
    return $view;
}

I call the method from a button
    id . '/restore') }}">Restore

I don't know what i'm getting wrong, i'm a very newbie on PHP and laravel, please include the right code.
Thank you

A: You are using DB facade, so you get an StdClass instance as a result, not an Eloquent model and restore() is a method on Eloquent class.
You need to change:
$dvds = DB::table('dvds')->where('id', $id)->first();

To something like:
$dvds = Dvd::withTrashed()->where('id', $id)->first();

And then it should work fine.


text:
Q: Loss of admin privileges when Java program calls C# program to write to %ProgramData% The scenario:

*

*I have a Java based installer.

*The Java based installer calls a C# program, whose job is to create a shortcut.

*The shortcut location depends on if the installer is running as administrator or as a regular user. When running as admin, I'm trying to create a shortcut to "%ALLUSERSPROFILE%\Desktop", else I write to "%USERPROFILE%\Desktop".

My impression is that the issue seems to be a loss of administrative privilege when my Java program calls my C# shortcut maker program.
Notes:

*

*I run my Java based installer as administrator (right click, run as administrator).

*I'm able to verify the installer is running with administrator privileged because I can read registry keys that require administrative privilege.

*I'm calling my C# program via 'Process process = Runtime.getRuntime().exec(command);'

*When running the command manually through an administrative command prompt, the command works fine. (When outputting to "%ALLUSERSPROFILE%\Desktop")

*When running the the same command manually, from a normal command prompt, I get System.UnauthorizedAccessException. (Which is to be expected). The program crashes in a similar was that it does when run from the installer.

The Exception:

Unhandled Exception: System.UnauthorizedAccessException: Access is
  denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))    at
  IWshRuntimeLibrary.IWshShortcut.Save()

Any thoughts on what I'm missing? The installer needs to be flexible to run as both a normal user and as an administrator. How can I ensure this behavior?
Update 1
I attached a debugger to the C# program at runtime. It is throwing a:
DirectoryNoFoundException was unhandled
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)

I added "mkdir" commands before my shortcutmaker commands. The mkdir commands, just ensure that the directories exist before trying to write to them.
Rebuilt the installer, ran it and when trying to mkdir "%ALLUSERSPROFILE%\Desktop", java throws an exception of
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
java.io.IOException: Cannot run program "mkdir": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)

At this point, it looks like my process isn't getting admin access
        Process process = Runtime.getRuntime().exec(command);

I'm going to see if I can find anything else.
Update 2
The following gave me some info that I tried: Enterprise Logging not translating environment variables in XML Trace Listener fileName specification
It suggested that %ALLUSERSPROFILE% was not getting translated.
Instead of %ALLUSERSPROFILE%, I got the environment variable values via:
    String allUsersProfile = System.getenv("ALLUSERSPROFILE");
    String userProfile = System.getenv("USERPROFILE");

I was then able to supply the actual values to the C# program. But I'm still having issues.
From a admin console I can navigate to "c:\ProgramData\Start Menu", but if I run "explorer" with administrative priviledges, I can navigate to "c:\ProgramData" but not see anything past that... Through some looking, I found out that "c:\ProgramData\Start Menu" is a protected operating system file. So I turned on the setting to see it. So now I can see it, but not go into it.
Using system internals, I elevated an explorer.exe to "system" access and still can't go into the folder (System internal elevation reference: http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system/)
I right clicked on the folder and checked out the security tab. It looks like even my "System" user has limited access. I find this a bit baffling, that I can run the command from an admin command prompt that will write the shortcut to the desktop, but going through this other process I cannot... I also find the access to be a bit inconsistent.


text:
Q: StateListAnimator not working on checkbox I am following the article given here
I am trying to create a "like" button animation and need help since my animator does not seem to be doing anything
I have created the required animator file, created the stateListDrawable file and set it as the background to the CheckBox
The animator file uses a set of objectAnimator  tags which animate the scaleX, scaleY and translationZ properties.
This is my layout file "activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="@android:color/white"
android:layout_height="match_parent"
tools:context=".MainActivity">

<CheckBox
    android:id="@+id/checkbox"
    android:button="@null"
    android:checked="false"
    android:background="@drawable/like_icon"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:stateListAnimator="@animator/scale2"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

This is the stateListDrawable "like_icon.xml"
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_thumb_up_red_24dp"
android:state_checked="true" />

<item android:drawable="@drawable/ic_thumb_up_black_24dp" />
</selector>

This is my animator named "scale.xml". It is placed correctly in the "res/animator/" folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleX"
    android:valueTo="1.525"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleY"
    android:valueTo="1.525"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="translationZ"
    android:valueTo="4dp"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleX"
    android:valueTo="1.0"
    android:startOffset="@android:integer/config_longAnimTime"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="scaleY"
    android:startOffset="@android:integer/config_longAnimTime"
    android:valueTo="1.0"
    android:valueType="floatType" />

<objectAnimator
    android:duration="@android:integer/config_longAnimTime"
    android:propertyName="translationZ"
    android:startOffset="@android:integer/config_longAnimTime"
    android:valueTo="0dp"
    android:valueType="floatType" />

</set>

A: You need to set the checked states. Try the below code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <set>
            <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleX"
                android:valueTo="1.525"
                android:valueType="floatType" />

            <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleY"
                android:valueTo="1.525"
                android:valueType="floatType" />

            <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="translationZ"
                android:valueTo="4dp"
                android:valueType="floatType" />

            <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleX"
                android:startOffset="@android:integer/config_shortAnimTime"
                android:valueTo="1.0"
                android:valueType="floatType" />

            <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="scaleY"
                android:startOffset="@android:integer/config_shortAnimTime"
                android:valueTo="1.0"
                android:valueType="floatType" />

            <objectAnimator
                android:duration="@android:integer/config_shortAnimTime"
                android:propertyName="translationZ"
                android:startOffset="@android:integer/config_shortAnimTime"
                android:valueTo="0dp"
                android:valueType="floatType" />
        </set>
    </item>
</selector>


text:
Q: Why are .grd files used? (Mining and construction industries) I'm researching the .grd file format and its not clear to me why they are used, especially regarding the mining and construction industries. I understand they demonstrate changes in elevation or other geographic attributes in a binary format.
What analytical operations are .grd files used for in the mining and construction industry?

A: .grd files are sometimes used for geoid model files. A geoid model contains offsets between a geopotential surface and the ellipsoid model of the Earth. GNSS (GPS, GLONASS, Beidou, etc.) natively return heights above the ellipsoid surface. These are not always useful as they do not reflect which direction water will flow 'downhill'.
The geopotential surface of a geoid model is approximately equal to mean sea level as IF there was no topography. I've seen it described as there are tunnels connecting the oceans and allowing the water to freely flow.
Anyway, people often prefer elevations, heights above the geoid or another gravity-related surface as many vertical coordinate reference systems are like NAVD88 (USA), NAP (Netherlands), etc.

A: There are a few different grid file formats, using .grd as extension.
see qgis, Saga GIS, grdpaste, FiniteMap, etc..
It could be also an Adobe Photoshop Gradient file.
see the following tutorials for saga gis, for why this industries use grids
noise, hydrology and morphometry/slope, etc..

A: Having worked as geophysicist in the mining industry myself at the former Rio Tinto office in Newbury UK, I can answer your question. The .grd grids are binary grids for storing gridded magnetic and gravity observations. They are used to map the distribution of iron and dense rocks, and as such to find new mineral deposits.
The .grd data format in this case are geosoft grids.


text:
Q: c++ how should the makefile look Suppose I have these following c++ files, how should I write a basic makefile for them (using g++)?
a.cpp a.h, b.cpp b.h, c.cpp c.h, main.h
When b.h includes a.h, c.h includes b.h and main.h includes c.h?
thanks a lot

A: so you can write.
EXE := exe
CC := g++
CPP_FILES := a.cpp b.cpp c.cpp
HPP_FILES := a.h b.h c.h main.h

$(EXE) : $(CPP_FILES) $(HPP_FILES)
      $(CC) -o $@ $(CPP_FILES)
.PHONY : clean
clean:
      rm -rf $(EXE) *.o

A: How to compile a file? Say you have test.cpp and test.h now, to compile and link it:
g++ -c test.c
g++ -o test test.o

Easiest Makefile:
test: test.o                #means test depends on test.o
        g++ -o test test.o
test.o: test.cpp test.h     #means test.o depends on test.cpp and test.h
        g++ -c test.cpp
                            #if you want clean? add below line too.
clean:
    rm test test.o

If your app depends on multiple files, then
test: test1.o test2.o test3.o #means your app depends on test1.o test2.o and test3.o
        g++ -o test test1.o test2.o test3.o
test1.o: test1.cpp test1.h
        g++ -c test1.cpp
test2.o: test2.cpp test2.h
        g++ -c test2.cpp
...


text:
Q: Is there a theoretical characterisation/closed form of the Lorenz-63 attractor? For my research I'm learning about the Lorenz-63 system, and I have a relatively simple question that I can't find a straightforward answer to: are there any theoretical results about the shape of the Lorenz attractor? I know that the Lorenz system was proven to have a strange attractor by Warwick Tucker, but all of the results I'm looking at fail to give me a characterisation of that attractor itself.
If what I am asking for is too strong, are there any theoretically sound approximations of the Lorenz attractor? As in, it has this approximate shape with this specific radius, et cetera.
I know these things could be easily verified via a simple time-stepping simulation. However, my research is about creating numerical models, and I am interested in the question of whether my model could be improved with a priori knowledge of the system in question.


text:
Q: Project build error: Non-parseable POM C:\Users\Admin\.m2\repository\org\springframework\boot\spring-boot-dependencies\1.3.3.RELEASE\ My pom.xml is this:
https://hastebin.com/liyetukeze.xml
How it looks like under Eclipse neon.3


text:
Q: Perform GROUP BY in Tableau enter image description hereI am working with NYC 311 data. I want to calculate the efficiency of each agency as follows:
Efficiency = No of days (Closed Date - Created Date)/ number of requests handled by the agency.
closed date = the date issue was closed
created date = date when the request was received
Each record is a service request handled by a particular agency. Each record contains created date, closed date, agency name, unique key and many other attributes.
The challenge here is to compute the number of requests handled by the agency. Each record is identified by a unique key. I have already created a visualization(bar graph) which shows the number of records in each agency.
My idea is to display the efficiency as a line chart color-coded according to the agency. I have already generated a new measure in tableau which is called Processing time (using Date diff function) which gives me the number of days betweee\n closed date and created date for every record. I want to group the service requests according to agency, add the processing time column values for a particular group and then divide the aggregated processing time (for every group) by the number of requests handled by this group. Finally, I want to visualize this efficiency(avg no of days taken by each agency to complete a request) as a line chart or something different. I have just started learning tableau.
Any assistance is greatly appreciated
Thanks!
enter image description here

A: Assuming that you have a dataset like this:

If you want to have a dual chart (bar for number of records and line for the average processing time) you have just to use use the dual axis option clicking on the second measure.
I think that Avg od Date Diff field is mor than fine for your purpouse.
Am I right?
In your case, if I understand what you want, you should just replicate this scenario:

Which, by the way, is the same of getting this table:


text:
Q: RAILS 6 - how to use EasyAutocomplete I try the last hours to integrate EasyAutocomplete into RAILS 6. But not so easy.
What I did :
Install Javascript Package with yarn:
# yarn add easy-autocomplete

Add this in the file app/javascript/packs/application.js
import "easy-autocomplete"

Add this in the file app/assets/stylesheets/application.css
*= require easy-autocomplete
*= require easy-autocomplete.themes

Then start the Rails Server and refresh the Web Page.
Then try to use it. Go into the developer console and type :
var options = {
data: ["otto", "hans", "paula"]
};

$("#task_name_search_field").easyAutocomplete(options);

task_name_search_field was previously defined as id :
<input type="search" class="form-control" id="task_name_search_field">

I got this message:
TypeError: $(...).EasyAutocomplete is not a function
Any idea ?

A: I had the same problem. Turbolinks does not give access to the script, the code needs to be run after it is loaded, something like this:
document.addEventListener("turbolinks:load", function() {
  var options = {
   data: ["otto", "hans", "paula"]
  };

  $("#task_name_search_field").easyAutocomplete(options);
});

In order for the autocomplete to work, you need to add a script file to the application.js like this:
require("packs/youfile")

If it helps you, here is an example of my code:
document.addEventListener("turbolinks:load", function() {
 $input = $("[data-behavior='autocomplete']")

 var options = {
  getValue: "full_name",
  url: function(phrase) {
  return "/search.json?q=" + phrase;
 },
categories: [
  {
    listLocation: "cameras",
    header: "Cameras",
  }
],
list: {
  onChooseEvent: function() {
    var url = $input.getSelectedItemData().url
    $input.val("")
    Turbolinks.visit(url)
  }
 }
}
$input.easyAutocomplete(options)});

A: I suppose you wouldn't have included jquery in your application.js. You need to do explicitly as it doesn't get included automatically with rails 6 app.

A: I ran into a similar issue. I'm a n00b at Webpacker, but by default it doesn't seem to compile in the same order in which plugins are included.
To get around the issue I did this workaround which just wraps the plugin code in an anonymous jQuery function, like so:
(function($) {

//Eac plugin code

})(jQuery);

https://github.com/pawelczak/EasyAutocomplete/issues/200#issuecomment-212277620
Maybe there is a way in the configs to force compilation in the correct order. This looks promising https://stackoverflow.com/a/43005332/148390

A: Add script-loader to package.json then add
import 'script-loader!jquery/dist/jquery.min'

in app/javascripts/application.js
Check in your browser that $().jquery yields a proper result.


text:
Q: How to make the content scroll in a webview? Have an html which has some content seems cannot be scrollable after loaded into android webview.
The same html if directly tested with browser it seems scrolling fine.  Does anyone have same issue?
==============
Update:
For the scrolling issue, it turns out that in the code there is a listener disabled the the MotionEvent.ACTION_MOVE.
val listener = object : OnTouchListener {
        override fun onTouch(v: View, event: MotionEvent): Boolean {
            return event.action == MotionEvent.ACTION_MOVE
        }
    }

    webview.setOnTouchListener(listener)

Now only issue is why the iframe does not display the content?

There are two html files,  test-scroll.html  and test-scroll-content.html (has a table as content)
test-scroll.html:

 table in this page

                Firstname
                Lastname
                Age

                Jill
                Smith
                50

                Eve
                Jackson
                94

                John
                Doe
                80

                zbr
                Ford
                50

                Elis
                Liu
                94

                Pter
                Hans
                80

 table in iframe srcdoc

        <iframe scrolling="no"
                srcdoc="

                Firstname
                Lastname
                Age

                Jill
                Smith
                50

                Eve
                Jackson
                94

                John
                Doe
                80

                zbr
                Ford
                50

                Elis
                Liu
                94

                Pter
                Hans
                80

">

 table in iframe src

image in div

image in iframe

which tested a couple cases:

*

*a table in a div, div has height: 80px and overflow: scroll

*the same table put in iframe as its srcdoc

*in an iframe load in the conetnt src="test-scroll-content.html"

*an  has src points to a local image

*the same image file but load into a iframe's src

when directly loads the test-scroll.html into browser file:///Users/linma9/Documents/test-scroll.html, seems all cases in browser the content can scroll.
(it is easier to see the scroll after loaded in the browser then do "inspect" with chrome develop tool).

With android project and put the same files under the asset folder.
and do either
webview.loadUrl("file:///android_asset/test-scroll.html")

or put the test-scroll.html content as string inside a function fun getTestScrollHtmlStr() : String{} and
do:
webview.loadDataWithBaseURL("file:///android_asset/",
                getTestScrollHtmlStr(),
                "text/html", "utf-8",null)

when run on android device,  seems both way they can not scroll the content
(and another issue it cannot shows the content loaded with iframe src= ???)

Does anyone know how to make the content scrollable when loading the them into android webview (either in iframe or not)?
test-scroll-content.html:

 directly put in div

                Firstname
                Lastname
                Age

                Jill
                Smith
                50

                Eve
                Jackson
                94

                John
                Doe
                80

                zbr
                Ford
                50

                Elis
                Liu
                94

                Pter
                Hans
                80


text:
Q: Relationship between tables with dates I would like to know what kind of relationship I should be making between a dates table and other tables with date fields.
I understand the creation of relationships and tables for normalization purposes. I would just like to better understand relationships where dates are concerned for integrity and querying purposes.
I have a table tblLog with dates in more than one field (example: AuditStart and AuditEnd). I have another table tblDays that is just dates.
Would I create a relationship between the date field in tblDays and both fields in tblLog?
Or would it be better to create a tblDays1 and tblDays2 in the relationships and join AuditStart to tblDays1 and AuditEnd to tblDays2?


text:
Q: Immersing spaces in $\mathbb{R}^{n+1}$, Stiefel-Whitney classes Where can I find references to proofs/can anyone supply me a quick proof of the following facts?

*

*If the $n$-dimensional manifold $M$ can be immersed in $\mathbb{R}^{n+1}$, then each $w_i(M)$ is equal to the $i$-fold cup product $w_1(M)^i$.

*If $\mathbb{RP}^n$ can be immersed in $\mathbb{R}^{n+1}$, then $n$ must be of the form $2^r - 1$ or $2^r - 2$.

A: Read Milnor Stasheff: Characteristic classes.
For the first question:
The total normal Stiefel Whitney class of $M$ is $1-w_1(M)$, hence the inverse is
$W(M) = 1 + w_1(M) + w_1(M)^2 +... .$
For the second Question one uses that the tandent bundle $\tau$ of $RP^n$ satisfies the equality $\tau \oplus \epsilon$ is isomorphic to $n+1$ times $\gamma$, the tautological bundle. Hence $w_i(RP^n)$ the binomial coefficient choose $i$ from $n+1$ Put
 the two together you get the answer to the second question


text:
Q: Using getlementbyclass name or getlementbytag to scrape data from html content Here I have taken source code snipper from webpage : http://www.yelp.com/biz/franchino-san-francisco?start=80.
I want to scrape date, review, rate for each block on the page.
@: http://ideone.com/fork/Yfw2re
I am not much familiar with DOM element, I appreciate if someone can correct this
Here is the code :
<?php

// your code goes here
$html = <<< EOF

        <meta itemprop="ratingValue" content="5.0">

        <meta itemprop="datePublished" content="2013-10-28">
    10/28/2013

The reason I started a yelp account, was to write a review for Franchinos. This is my favorite restaurant in the city of San Francisco, and especially, North Beach.

Where do I start... I take every friend, family member and acquaintance to Franchinos in every opportunity I can. I am a Italy-nut and have been over three times - the mood + atmosphere is almost identical. It is a 100% family-run restaurant and you can taste the expertise and 'home-cooking'.

Each time, I get a large bottle of wine (One time - they ran out of the wine I had ordered - and instead gave me a larger, more expensive bottle - same price), a wonderful pasta dish (Alfredo, carbonara.. etc.) and a Caesar salad.

Need I say more? Buenisimo. I look forward to the next time.. and the times after that again and again.

è perfetto!

    Was this review …?

EOF;

$dom = new DOMDocument();
@$dom->loadHTML($html);
$classname = 'review-content'
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$tmp_dom = new DOMDocument();
foreach($nodes as $result) {

  //getting rate value from '<meta itemprop="ratingValue" content="5.0">'
  //getting  date from        <meta itemprop="datePublished" content="2013-10-28">     10/28/2013
  //getting review from  '
The reason I started a yelp account, was to write a review for Franchinos. This is my favorite restaurant in the city of San Francisco, and especially, North Beach.

Where do I start... I take every friend, family member and acquaintance to Franchinos in every opportunity I can. I am a Italy-nut and have been over three times - the mood + atmosphere is almost identical. It is a 100% family-run restaurant and you can taste the expertise and 'home-cooking'.

Each time, I get a large bottle of wine (One time - they ran out of the wine I had ordered - and instead gave me a larger, more expensive bottle - same price), a wonderful pasta dish (Alfredo, carbonara.. etc.) and a Caesar salad.

Need I say more? Buenisimo. I look forward to the next time.. and the times after that again and again.

è perfetto!
 '

}

A: you can loop through the class values or tag names like this :
$classname = 'rating-qualifier';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$results = $xpath->query("//*[@class='" . $classname . "']");

if ($results->length > 0) {
    echo $review = $results->item(0)->nodeValue;
}

$classname = 'review_comment ieSucks';
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$results = $xpath->query("//*[@class='" . $classname . "']");

if ($results->length > 0) {
    echo $review = $results->item(0)->nodeValue;
}

$meta = $dom->documentElement->getElementsByTagName("meta");
echo $meta->item(0)->getAttribute('content');

you can obviously loop the rating part to get all the ratings on the page using a simple for loop.
demo here : https://eval.in/143036


text:
Q: Failing Travis CI tests when using secret keys in rails I am using environment variables in secrets.yml for production environment in my rails app. I am sending http post request with api key and password. I can pass my local tests in test environment by using the password. But my password can't be exposed, so how do I pass travis ci tests on github?

A: You can encrypt your secrets.yml and push encrypted file to the repository.
travis encrypt-file secrets.yml

which will give you secrets.yml.enc add it to repository. Remember not to push secrets.yml.
You need to decrypt that file in before_script
before_script: openssl aes-256-cbc -K $encrypted_0a6446eb3ae3_key -iv $encrypted_0a6446eb3ae3_key -in secrets.yml.enc -out secrets.yml -d

You can directly add above command to travis.yml using --add option:
travis encrypt-file secrets.yml --add

Refer this documentation for more details - Encrypting Files in Travis


text:
Q: Apache password-protected folder disappears --> Problem with mod_auth_basic and mod_authn_file [SOLVED]
My problem was:
So I've tried to password-protect the directory "www.example.com/bla" on my apache server using mod_auth_basic and mod_authn_file.
in my httpd.conf I added:

<Location "/bla">
AuthType Basic
AuthName "private area"
AuthBasicProvider file
AuthUserFile /home/passwords/password-file
Require valid-user
</Location
As soon as I restarted the apache, I can't see the folder bla on example.com (= on the parent-folder, where it is located). It's not deleted though, I just can't see it on my page. The password protection also works perfectly fine when I access bla directly via example.com/bla.
So somehow my server seems to hide all the directories that are password protected. How can I change that?
Thanks for your help!
Emilja
Edit: I think this is just the normal behaviour of this directive.


text:
Q: Submit button helper with I18n.t I want to write a helper for a submit button, that takes in account the action (create or update) to get the right translation. Here they are :
fr:
  submit:
    create:
      user: "Créer mon compte"
      product: "Déposer l'objet"
      session: "Se connecter"
    update:
      user: "Mettre à jour mon compte"
      product: "Modifier l'objet"

I tried this :
def submit_button(model)
  if model == nil
    I18n.t('submit.create.%{model}')
  else
    I18n.t('submit.update.%{model}')
  end
end

But it didn't worked and rspec send me that :
Capybara::ElementNotFound: Unable to find button ...

I know that's a syntactical problem, but I don't find how to make this work...

A: You don't need a helper for that, you can achieve it with plain rails. The only thing you need is to properly order your I18n YAML
fr:
  helpers:
    submit:
      # This will be the default ones, will take effect if no other
      # are specifically defined for the models.
      create: "Créer %{model}"
      update: "Modifier %{model}"

      # Those will however take effect for all the other models below
      # for which we define a specific label.
      user:
        create: "Créer mon compte"
        update: "Mettre à jour mon compte"
      product:
        create: "Déposer l'objet"
        update: "Modifier l'objet"
      session:
        create: "Se connecter"

After that, you only need to define your submit button like this:
<%= f.submit class: 'any class you want to apply' %>

Rails will take the label you need for the button.
You can see some more info about it here

A: def submit_button(model)
  if model == nil
    I18n.t("submit.create.#{model}")
  else
    I18n.t("submit.update.#{model}")
  end
end

The %{} is used in en.yml file when you send a local variable from helper or view.

A: You need the name of the model not the model object itself.
Try the following:
def submit_button(model)
  model_name = model.class.name.underscore
  if model.new_record?
    I18n.t("submit.create.#{model_name}")
  else
    I18n.t("submit.update.#{model_name}")
  end
end

model must not be nil in a form.


text:
Q: Iniciar função e executar função novamente ao clicar no botão Quando a página carrega totalmente ele inicia uma função, gostaria que ao clicar em um botão essa mesma função inicializasse novamente passando um texto como Query String. Tenho o código:
$(document).ready(function() {

    function initMapplic(title){
        var mapplic = $('#mapplic').mapplic({
            source: '<?php echo base_url();?>assets/plugins/mapplic2/server.php?title='+title,    // Using mall.json file as map data
            sidebar: false,          // Enable sidebar
            developer:true,
            minimap: false,          // Enable minimap
            markers: true,         // Disable markers
            fillcolor: true,       // Disable default fill color
            fullscreen: true,       // Enable fullscreen
            maxscale: 3             // Setting maxscale to 3
        });
    }

    initMapplic('');

    $("#searchfilters").on('click',function(){

        initMapplic('apertou');

    });

});

Ele inicia normalmente, mas quando clico no botão ele parece que não atualiza passando o texto "apertou" como eu gostaria.

A:

$(document).ready(function() {
    initMapplic("");
});

function initMapplic (title) {
  alert(title);
  var mapplic = $('#mapplic').mapplic({
    source: 'assets/plugins/mapplic2/server.php?title='+title,    // Using mall.json file as map data
    sidebar: false,          // Enable sidebar
    developer:true,
    minimap: false,          // Enable minimap
    markers: true,         // Disable markers
    fillcolor: true,       // Disable default fill color
    fullscreen: true,       // Enable fullscreen
    maxscale: 3             // Setting maxscale to 3
  });
}
Veja se é mais ou menos isso que você precisa.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" onclick="initMapplic('apertou');" value="Enviar" />

A: Retire a função initMapplic do escopo do carregamento da página:
function initMapplic(title) {
    // ...
}

$(document).ready(function() {
    initMapplic('');

    $("#searchfilters").on('click', function() {
        initMapplic('apertou');
    });
});


text:
Q: Open GL : Changing Brightness and Contrast of the Image I have one module to implement in which I have to change the Brightness and Contrast of the Image for IPhone.
After ref some samples like GLImageProcessing , seems need to go with Open GL (In this sample, we can able to do one activity at a time either brightness or contrast), As I am new to this Open GL and not able to work out with this.
Kindly provide me some threads or ref regarding same ,it will be helpful to move in right direction.
thanks,
Sagar

A: Try google: glPixelTransferf and GL_RED_SCALE
Here's some ref: http://pyopengl.sourceforge.net/documentation/manual/glPixelTransfer.3G.html


text:
Q: TaskScheduler is blocking the sending of emails through R (RDCOMClient package) I have a script that is scheduled to run multiple times on a daily basis and is automated through TaskScheduler. Inside this script is a chunk of code to send an email when the process is completed.
When I run the script manually (without using TaskScheduler) the email gets eventually sent, through this code that is at the bottom of the script:
OutApp <- COMCreate("Outlook.Application")
    ## create an email
    outMail = OutApp$CreateItem(0)
    ## configure  email parameter
    outMail[["To"]] = paste ("xxx@xxx.com",
                             "xxx@xxx.com",
                             sep = ";", collapse = NULL)
    outMail[["subject"]] = "Some text"
    outMail[["body"]] = "Some text"
    ## send it
    outMail$Send()

But when exactly the same script runs through TS, I got this error in the log:

Error in COMCreate(guid, existing = FALSE) :
Failed to create COM object: Server execution failed
Calls: COMCreate -> getCOMInstance -> COMCreate
Execution halted

It looks like TS is blocking the send - any workaround?

A: Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
As a workaround, you may consider using a low-level API (Extended MAPI) on which Outlook is based on either. Or just use any third-party wrappers around this API such as Redemption.