text:
Q: List Phoenix API I would like to have an endpoint /api/api_endpoints/ that list all the public api endpoints. Similar to mix phx.routes, but I only want to list things like
...
GET /api/users
PUT /api/users/name
...

Things like that. I looked in the documentation but did not see anything for listing routes.

A: There is nothing built in, but for something as simple as you want you could always roll your own. All the routes are stored inside your router as a list of Phoenix.Router.Route stucts. For example in a project called Residential:
iex(1)> ResidentialWeb.Router.__routes__
[%Phoenix.Router.Route{assigns: %{}, helper: "page", host: nil, kind: :match,
opts: :index, path: "/", pipe_through: [:browser],
plug: ResidentialWeb.PageController, private: %{}, verb: :get},
%Phoenix.Router.Route{assigns: %{}, helper: "user", host: nil, kind: :match,
opts: :index, path: "/users", pipe_through: [:browser],
plug: ResidentialWeb.UserController, private: %{}, verb: :get},
%Phoenix.Router.Route{assigns: %{}, helper: "user", host: nil, kind: :match,
opts: :edit, path: "/users/:id/edit", pipe_through: [:browser],
plug: ResidentialWeb.UserController, private: %{}, verb: :get},

You can map over them and extract the verb and path and show them as you please.
This is pretty much how mix phx.routes works, if you take a look at the implementation


text:
Q: Projected Conjugate Gradient or BFGS for bound constrained optimization We know how projected gradient descent works for bound constrained optimization (https://neos-guide.org/content/gradient-projection-methods). It is basically steepest descent with an additional requirement of projecting the point back to the feasible region at each step. I have a nonlinear objective function subject to bound constraints on each variable.
Can we tailor conjugate gradient or BFGS using projections to solve the problem. So instead of steepest descent, each step will do CG or BFGS step, and if the new point goes beyond feasible region, we project it back to original region using projection like the one suggested in referred link. I know BFGS-B exists but I can't find any general theory for CG based approaches. Do we have a generalized theory or convergence results for all gradient/Hessian based approaches added with projection for bound constrained optimization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to print an object as JSON to console in Angular2? I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})

When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?

A: To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);

This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table

Example:

A: you may use below,
  JSON.stringify({ data: arr}, null, 4);

this will nicely format your data with indentation.

A: first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);

A: Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>

A: you can print any object
console.log(this.anyObject);

when you write
console.log('any object' + this.anyObject);

this will print
any object [object Object]

A: You could log each element of the array separately
arr.forEach(function(e){console.log(e)});

Since your array has just one element, this is the same as logging {'title':name}


text:
Q: Reading line from a file adding additional line This is the contents of my file ITEM.dat is
DB1:TEST1:Y
DB2:TEST2:N
Code is
MYFILE='/tmp/ITEM.dat'
M_ITMES=['TEST1']
for ITEM in ITMES:
if ITEM in open(MYFILE):
    if not line.startswith('#'):
        ITEM_YN=(line.split(':'))[2]
        print(ITEM_YN)

The print command results in additional blank line after Y
Y

This does not occur when I use
ITEM_YN=(line.split(':'))[1]

A: line includes the new line character as does the final item in line.split(':'). Since you likely want to use that item for other things, trim the newline before the split:
ITEM_YN = line.strip().split(':')[2]

Notice, I also got rid of those extra unneeded parens.


text:
Q: HttpServletRequest for jsf i have a jsp site where i get an attribute using request.getAttribute.
i'm looking for a way to get that attribute in jsf (running in the same tomcat). this is what i found on the internet:
HttpServletRequest requestObj = (HttpServletRequest)
FacesContext.getCurrentInstance().getExternalContext().getRequest();
    String value =  (String) requestObj.getAttribute("property");

but the result (value) stays null.
what could possible reasons be that it works in the first case but not in the second?

A:
what could possible reasons be that it works in the first case but not in the second?

If the attribute is not there anymore, then it simply concerns a completely different request. Probably you have sent a redirect, or the webbrowser has sent a new request, etc. The real answer to your problem is hard to give since you didn't elaborate anything about the functional requirement in your question. You just posted some code snippet and said "why doesn't this work?".
At any way, the request attributes live as long as the request/response itself and they are not retained in subsequent requests. For that you'd rather like to store it as a session attribute instead, or to pass as a request parameter in case of a redirect. Or, when you're already on JSF 2.0, storing it as a property of a view scoped bean should also do for the case the bean is to be accessed from the same view subsequently.
To learn more about the lifecycle of the HTTP servlet request/response, I'd suggest to get yourself through this answer.

Unrelated to the concrete problem: whenever you need to haul the raw Servlet API from under the JSF covers, then you should really take a break and think twice if you're really doing things the right way (read: without the need to fall back to the raw javax.servlet API). Shouldn't it better be a fullworthy JSF managed bean, for example?
At any way, request attributes are also accessible by ExternalContext#getRequestMap().
Map<String, Object> requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
String value = (String) requestMap.get("property");

No need to utilize the raw Servlet API.


text:
Q: Convert RBG char array to RGB int value in Java I have a char[] rbg containing :

*

*rgb[0] : red value

*rgb[1] : green value

*rgb[2] : blue value

I want to use the method BufferedImage::setRGB(x, y, int rgb)
How can I proceed to convert the char array to the int value ?
Note : I use Java
Edit : I'm looking for the fastest solution
Thanks

A: int value = ((255 & 0xFF) << 24) | //alpha
            (((int)rgb[0] & 0xFF) << 16) | //red
            (((int)rgb[1] & 0xFF) << 8)  | //green
            (((int)rgb[2] & 0xFF) << 0); //blue

A: import java.awt.Color;

Color color = new Color(rgb[0],rgb[1],rgb[2]);
int rgb = color.getRGB();

ref : http://download.oracle.com/javase/1.5.0/docs/api/java/awt/Color.html#getRGB%28%29

A: int rgb2 = rgb[0] << 16 | rgb[1] << 8 | rgb[2];

Maybe you will have to reverse the order of indices.

A: BufferedImage buffImg = new BufferedImage(176, 144, BufferedImage.TYPE_INT_RGB);

            /*Setting RGB values to BufferedImage*/
            int[] raw = new int[rgbCameraData.length * 4 / 3];
            for (int i = 0; i < rgbCameraData.length / 3; i++) {
                raw[i] = 0xFF000000
                        | ((rgbCameraData[3 * i + 0] & 0xFF) << 16)
                        | ((rgbCameraData[3 * i + 1] & 0xFF) << 8)
                        | ((rgbCameraData[3 * i + 2] & 0xFF));
            }
            buffImg.setRGB(0, 0, 176, 144, raw, 0, 176);
            System.out.println("BufferedImage  :" + img);


text:
Q: Make selected polygon different color without covering everything? Working in ArcGIS Desktop 9.3
I'm selecting polygons by attributes and trying to have the selection show up as a light yellow. I set the selection color to the light yellow and it's the 'lowest/last' layer but it covers all of the other layers. Is there a way to change it?

A: As @Baltok alluded to, you are trying to have the Selection on a particular layer be treated in the same way as other layers are, with respect to drawing order.  I think that by default, and design, ArcGIS makes the Selection override the symbology of anything that is underneath it, as a means of making it easy to find the selection.
Since you are selecting by Attributes, and it is likely you don't want to create another layer from these particular features, you want to Create a Layer from Selected Features.
Example:

That gives you a result of:

This may then be symbolized the same as any other layer in the Table of Contents, including the ability to set the Transparency to allow other features to show through underneath.
Please be aware that there are times when this selection layer may be invalidated.  I think these circumstances can arise when changes are made to the original layer, for instance adding or deleting features.  The Selection Layer is based on an index of the FID's in the layer, so if something causes them to change, it may corrupt the child layer.
A way to avoid this problem, which is perfect for you since you are performing an Attribute Selection anyway, is to instead create a copy of your original layer, and use your Attribute Selection as a Definition Query on this copy to limit the layer to only your desired features.

Hope these give you some options to work with.  The second one is more complicated, but is definitely more robust than the first since it is based directly off the attributes, as opposed to an internal index managed by ArcGIS.

A: If you right-click on the layer in the table of contents, select 'Properties', and then select the 'Display' tab you can set the transparency of your layer.

A: *

*in table of contents click selection tab ( below the table of content) .

*unselect other layers


text:
Q: Absolute position for android I'm trying to create a screen that looks like the attached picture. The styling code I used works only for iOS but doesn't work for Android.
The sample code with preview can be found here: https://snack.expo.io/@tushark/absolute-android
Please check for both iOS and android.
Here is the layout I want to create.

A: I've create a new Expo project from a sample code you give here: https://snack.expo.io/S1yDf4Q47
On the AbsoluteView Component add another View to handle the display screen:
<View style={styles.container}>
  <View style={{borderColor:'transparent'}}> // add borderColor, or the screen looks weird on android (i don't know why)
    {View of card, row, title and content styles}
  </View>
  <OrangeButton
      label="CONFIRM"
      onPress={() => console.log('Pressed')}
      styleButton={styles.loginBtn}
  />
</View>

and the Button Component I change the Bottom: -20 to top: width / 3,
and the layout look's like :
Android :

iOS:

A: I would recommend leaving the orange button outside of the card container and using an absolute position with device height to position it, you can also do the same for the card container to give the button the same position relevant to the card container on any device.
ex.
top: Dimensions.get('window').height/8


text:
Q: listview setonitemclicklistener with arrayadapter When try tu add method setOnItemClikListener show me this error: setOnItemClikListener (ItemClikListener) in AdapterView cannot be applied to ().
My code is:
List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
    mForecastAdapter = new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);

    ListView listViewForecast = (ListView) rootView.findViewById(R.id.listview_forecast);
    listViewForecast.setAdapter(mForecastAdapter);
    listViewForecast.setOnItemClickListener();

A: Try the following :
List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));

    mForecastAdapter = new ArrayAdapter<String>
            (getActivity(),android.R.layout.simple_list_item1,weekForecast);

    ListView listViewForecast = (ListView) rootView.findViewById(R.id.listview_forecast);
    listViewForecast.setAdapter(mForecastAdapter);

    listViewForecast.setOnItemClickListener(new OnItemClickListener() {
              public void onItemClick(AdapterView<?> parent, View view,
                      int position, long id) {
                       //Do your thing here

                  }
                });


text:
Q: How can I find out a users name and role in MVC? Is there some way that I can find a user and user's role in MVC ? Also can a user in .Net have more than one role at once?

A: Use
string username = Page.User.Identity.Name;
string[] roles =Roles.GetRolesForUser(username);

Hope It Helps. Good Luck.

A: Standard ASP.NET way:
  public ActionResult Test()
  {
    if (User.IsInRole("role name"))
    {
      //do something
    }
    return View();
  }

And yes, a user can be in more than one role.

A: You will find the User & its role (Identity & Principle) object in HttpContext object as follows
HttpContext.User
HttpContext.User.Identity

You will have to overrider onauthorize method on basecontroller something like this
public class HomeController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            //filterContext.HttpContext.User.Identity
            base.OnAuthorization(filterContext);
        }
}


text:
Q: how to make bullets appear incrementally r presentation How does one make an R presentation display bullets incrementally. By "R presentation" I mean Rstudio's .rpres -I know this can be done in ioslides, beamer, slidify, etc. but I cannot find any documentation about how this is implemented in .rpres. Is this possible without css? Thanks.

A: Through random trial and error:
Title
========================================================
author: Name
date: 10/10/10
autosize: true
incremental: true


text:
Q: error mounting "/PATH/nginx/nginx.conf" to rootfs at "/etc/nginx/conf.d/default.conf": mount /PATH/nginx/nginx.conf:/etc/nginx -- DOCKER Error Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/PATH/nginx/nginx.conf" to rootfs at "/etc/nginx/conf.d/default.conf": mount /PATH/nginx/nginx.conf:/etc/nginx/conf.d/default.conf (via /proc/self/fd/14), flags: 0x5001: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type
//docker-compose.yaml CODE
server:
image: 'nginx:1.15-alpine'
ports:
- '8000:80'
volumes:
- ./:/var/www/html
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- php
- mysql
//dockerfiles/nginx.dockerfile CODE
FROM nginx:1.15-alpine
WORKDIR /etc/nginx/conf.d
COPY nginx/nginx.conf .
RUN mv nginx.conf default.conf
WORKDIR /var/www/html
COPY  . .
//nginx/nginx.conf CODE
server {
listen 80;your text
index index.php index.html;
server_name localhost;
root /var/www/html/public;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ .php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass php:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}


text:
Q: jax-rs only authentication no authorization I have a JAX-RS web service deployed on IBM WebSphere and I want to secure this WS when it receives the requests (delegated from other server).
So I use the basic auth and set the username and password on BasicAuthSecurityHandler object and delegate the request to other server.
Now when the other server receives the request I use Federated repository in WAS under Global security and do the authentication.
If I comment out the auth-constraint in the deployment descriptor, the authentication is not taking place.
I want to do only authentication and no authorization.
I tried using @PermitAll annotation on the Jax-WS method but the authorization is also happening before the Jax-WS method is executed.
So is there any way I can skip the authorization and still do the authentication?
I dont have any rules associated to my users, so I want to skip the authorization.
<security-constraint id="SecurityConstraint_1">
  <display-name>RESTSecurity</display-name>
    <web-resource-collection id="WebResourceCollection_1">
      <web-resource-name>DelegateReqComApp</web-resource-name>
      <description>
          Protection area for Rest resource /addresses
      </description>
      <url-pattern>/rest/*</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>

    <!-- Authorization Constraint commented out  -->
    <auth-constraint id="AuthConstraint_1">
        <description>
                Used to guard resources under this url-pattern
        </description>
        <role-name>iapawas012</role-name>
    </auth-constraint>
</security-constraint>

A: Create the auth-constraint and map iapawas012 role to the special subject ALL_AUTHENTICATED. It basically says that any user, which successfully authenticates is authorized to invoke your service.
You can do it either in the web admin console on the Enterprise Application > yourApplication > Security role to user/group mapping or via binding file ibm-application-bnd.xml in the EAR in META-INF folder:
<?xml version="1.0" encoding="UTF-8"?>
<application-bnd
    xmlns="http://websphere.ibm.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-application-bnd_1_2.xsd"
    version="1.2">

    <security-role name="iapawas012">
        <special-subject type="ALL_AUTHENTICATED_USERS" />
    </security-role>
</application-bnd>


text:
Q: Android Studio - Could not find com.parse.bolts:bolts-android:1.2.0 I am trying to incluide FaceBook Sdk 4.2 in my app. When I import this module , it´s all rigth, but when my app run the following occurs:
Error:A problem occurred configuring project ':Glam Main'.
> Could not resolve all dependencies for configuration ':Glam Main:_debugCompile'.
   > Could not find com.parse.bolts:bolts-android:1.2.0.
     Searched in the following locations:
         file:/C:/Users/JL9/AppData/Local/Android/sdk/extras/android/m2repository/com/parse/bolts/bolts-android/1.2.0/bolts-android-1.2.0.pom
         file:/C:/Users/JL9/AppData/Local/Android/sdk/extras/android/m2repository/com/parse/bolts/bolts-android/1.2.0/bolts-android-1.2.0.jar
         file:/C:/Users/JL9/AppData/Local/Android/sdk/extras/google/m2repository/com/parse/bolts/bolts-android/1.2.0/bolts-android-1.2.0.pom
         file:/C:/Users/JL9/AppData/Local/Android/sdk/extras/google/m2repository/com/parse/bolts/bolts-android/1.2.0/bolts-android-1.2.0.jar
     Required by:
         Glam Main:Glam Main:unspecified > com.facebook.android:facebook:4.2.0

gradle.Module.Glam Main:Glam Main:
apply plugin: 'com.android.application'

dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    compile project(':appcompat_v7_21')
    compile project(':appcompat_v7_21-cardview')
    compile project(':appcompat_v7_21-recyclerview')
    compile project(':httpmime-4.2.6')
    compile project(':facebook')
}

android {
    compileSdkVersion 21
    buildToolsVersion "20.0.0"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

In my module Facebook , I have added com.parse.bolts:bolts-android:1.2.0. this module Facebook has been imported correctly because i can work with their classes.
Here my gradle.Module.Facebook
apply plugin: 'com.android.library'

repositories {

    mavenCentral()
}

project.group = 'com.facebook.android'

dependencies {
    compile 'com.android.support:support-v4:[22,23)'
    compile 'com.parse.bolts:bolts-android:1.2.0'
}

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
    }

    lintOptions {
        abortOnError false
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

apply plugin: 'maven'
apply plugin: 'signing'

def isSnapshot = version.endsWith('-SNAPSHOT')
def ossrhUsername = hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
def ossrhPassword = hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""

task setVersion {
    // The version will be derived from source
    project.version = null
    def sdkVersionFile = file('src/com/facebook/FacebookSdkVersion.java')
    sdkVersionFile.eachLine{
        def matcher = (it =~ /(?:.*BUILD = \")(.*)(?:\".*)/)
        if (matcher.matches()) {
            project.version = matcher[0][1]
            return
        }
    }
    if (project.version.is('unspecified')) {
        throw new GradleScriptException('Version could not be found.', null)
    }
}

uploadArchives {
    repositories.mavenDeployer {
        beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

        repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
            authentication(userName: ossrhUsername, password: ossrhPassword)
        }

        snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
            authentication(userName: ossrhUsername, password: ossrhPassword)
        }

        pom.project {
            name 'Facebook-Android-SDK'
            artifactId = 'facebook-android-sdk'
            packaging 'aar'
            description 'Facebook Android SDK'
            url 'https://github.com/facebook/facebook-android-sdk'

            scm {
                connection 'scm:git@github.com:facebook/facebook-android-sdk.git'
                developerConnection 'scm:git@github.com:facebook/facebook-android-sdk.git'
                url 'https://github.com/facebook/facebook-android-sdk'
            }

            licenses {
                license {
                    name 'Facebook Platform License'
                    url 'https://github.com/facebook/facebook-android-sdk/blob/master/LICENSE.txt'
                    distribution 'repo'
                }
            }

            developers {
                developer {
                    id 'facebook'
                    name 'Facebook'
                }
            }
        }
    }
}

uploadArchives.dependsOn(setVersion)

signing {
    required { !isSnapshot && gradle.taskGraph.hasTask("uploadArchives") }
    sign configurations.archives
}

task androidJavadocs(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    // JDK 1.8 is more strict then 1.7. Have JDK 1.8 behave like 1.7 for javadoc generation
    if (org.gradle.internal.jvm.Jvm.current().getJavaVersion() == JavaVersion.VERSION_1_8) {
        options.addStringOption('Xdoclint:none', '-quiet')
    }
}

task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
    classifier = 'javadoc'
    from androidJavadocs.destinationDir
}

task androidSourcesJar(type: Jar) {
    classifier = 'sources'
    from android.sourceSets.main.java.sourceFiles
}

artifacts {
    archives androidSourcesJar
    archives androidJavadocsJar
}

afterEvaluate {
    androidJavadocs.classpath += project.android.libraryVariants.toList().first().javaCompile.classpath}

I have read the follow post Android Studio 0.8.1 - how to use Facebook SDK? but I getnt  resolve my problem. Thanks.
Update 1
I have modified gradle.Module.Glam Main:Glam Main. I added this sentences:
allprojects {
    repositories {
        jcenter()
    }
}

Now i have this error
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;

Error:Execution failed for task ':Glam Main:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_45\bin\java.exe'' finished with non-zero exit value 2

A: You can add the latest Facebook SDK via Gradle dependency:
compile 'com.facebook.android:facebook-android-sdk:4.2.0'

Take a look to my build.gradle file:
https://github.com/lalongooo/permutas-sep/blob/master/app/build.gradle


text:
Q: Different volume left and right headphone - Macbook Pro 2019 I am using bluetooth headphones and the volume is lower on the left side than the right side.
Is there a way to configure this permanently?
Left headphone have significantly lower volume than right one - Macbook Pro 2012
This questions does not provide a permanent solution, as when I change the volume using the volume the problem comes back.
I have this problem on a MacBook Pro 2019, OS Monterey 12.6.
Changing the balance in Settings->Sound: Balance and then adjusting the volume and the problem is still occurring as shown in images below:


text:
Q: cannot bind scroll event to an div which has been created from ajax sucess Here is my code - where I have created a new div using ajax. name of div is
$('#section_product_listing_Csearch_ss').html(html);

The code for ajax call is given below
$.ajax({
type: "POST",
url: "_ajax_files/product_listing_Csearch-ss_ajax.php,
dataType: "html",
success: function(html){ $('#section_product_listing_Csearch_ss').html(html);
} });

I cannot bind the scroll event to object
#section_product_listing_Csearch_ss

I have tried everything as described below by adding it inside ajax success; after the line of $('#section_product_listing_Csearch_ss').html(html);
1.) var newnode = $(html);  $newnode.find('#section_product_listing_Csearch_ss').scroll(function(){alert("hi");});

2.) $(window).on('scroll', '#section_product_listing_Csearch_ss',function(){
            alert("hi");});

3.) $("#section_product_listing_Csearch_ss").bind('scroll', function(){
            alert("hi"); });

4.) $(html).scroll(function(){ alert("hi");});

5.)$(html).bind('scroll', function(){ alert("scrolling");});

6.) $('#section_product_listing_Csearch_ss').append('

');

listenForScrollEvent($(".myDivx"));

function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})


text:
Q: setHours() is always sets the date-time with a delay of my Timezone Consider the date generator :
getStartAndEndDatesByWeeks = howManyWeeksFromNow => {

    let firstDay = new Date();
    let nextWeek = new Date(firstDay.getTime() + 7 * 24 * 60 * 60 * 1000);

    let first = nextWeek.getDate() - nextWeek.getDay(); // First day is the day of the month - the day of the week
    let last = first + 6; // last day is the first day + 6

    let firstday = new Date(nextWeek.setDate(first));
    firstday.setDate(firstday.getDate() + howManyWeeksFromNow * 7);

    let lastday = new Date(nextWeek.setDate(last));
    lastday.setDate(lastday.getDate() + howManyWeeksFromNow * 7);

    firstday.setHours(0, 0, 0, 1);
    lastday.setHours(23, 59, 59, 999);

    return {
      firstday,  // this one is mapped to LeadStartDate
      lastday    // this one is mapped to LeadEndDate
    };
  };

It creates the beginning and end of X weeks from now , starting from Sunday.
For example :
Beginning of next week 01/12/19  - 07/12/19

However when inserting those two fields into Mongo DB, there is a delay of two hours because of my timezone : (GMT+2)
Which also leads to a delay of 1 day in the dates (instead of 01/12/19  - 07/12/19  , it's 30/11/19 - 07/12/19)
Even though I set the hours here :
   firstday.setHours(0, 0, 0, 1);
   lastday.setHours(23, 59, 59, 999);

How can we fix the hours to start without UTC , but with local time :
from 00:01 for firstday / LeadStartDate , and 23:59 for lastday / LeadEndDate
Please notice : I need to store those dates as a date object , not a string.
Thanks


text:
Q: Spring boot for legacy Struts application I have come across couple of discussions here about Spring Boot setup for Struts application but did not get a valid yes or no.
I know we can migrate the struts to spring and then use it with Spring boot but considering the timelines and application complexity we need to just migrate from Legacy Websphere to Spring boot for the Struts application.
Can we integrate spring boot with a legacy Struts 1.x application ?
P.S:
So far I am able to start up tomcat for spring boot successfully for my war but I do get 404 on browser so need to understand what would be the flow after the request flow to Main class.


text:
Q: How to make a backup of a pharo image What is the recommended way to make a backup of a pharo 3.0 image on linux? I do not need anything too fancy, just a single backup.
I will be upgrading to pharo 4 soon; is there anything different I need to do on that version?
Thank you.

A: You just need to copy the .image and .changes files.  As long as they're kept together and have the same root name, you should be good to go.
Alternatively, if you choose "Save As.." from the world menu, you can create a backup copy of both files with a new name.  (Though that will change the name the currently running instance uses, so if you were just backing up, you'd want to exit immediately after doing that).

A: I prefer to backup code I use in github repos, this make the code way more modular for moving around images. Even in the case of moving from Pharo 3 to Pharo 4 or even Pharo 5. Of course you could achieve the same using StHub. To make things even easier you can make the code install with a single click via Configuration Browser.

A: in addition to the responses above - If your code is defined within your own packages then from the system browser you can File out and or commit in a repository - that way you will find it easier to import in your Pharo 4 image


text:
Q: Can not upload images with php using Jquery form Plugin I try to upload image/Multiple Images with PHP using Jquery form plugin
all data successfully insert to database but only images not work
this is my first usage to jquery.form.js plugin
this is my HTML code
<form method="POST" action="data/addtrip.php" class="form-horizontal form-groups-bordered">

                    Trip information

                        Trip Name

                            <input type="text" class="form-control input-lg" name="title" placeholder="Trip Name">

                        Category

                            <select class="form-control" id="category" name="category" required>
                                <option></option>
                                <?php foreach($categorys as $cat):?>
                                <option value="<?echo $cat['id'];?>"><?echo $cat['title'];?></option>
                                <?php endforeach;?>
                            </select>

                        Trip Price

                            <input type="text" class="form-control input-lg" name="price" placeholder="Trip Name">

                        Information

                            <textarea class="form-control autogrow" name="details" placeholder="Trip Details"></textarea>

                        Multiple files

                            <input type="file" class="form-control file2 inline btn btn-primary" name="images" multiple="multiple" data-label="  Browse Files">

                    <button type="submit" name="insert" class="btn btn-lg btn-info submit">Add trip</button>

</form>

and this is my Jquery
$(document).ready(function(){

    $(document).ready(function() {
        $('form').ajaxForm( function(data) {

            var thisform = $(this);

            if($.trim(data) == 'Please check all fields'){
                $('.alert').hide();
                $(thisform).before('
'+ data +'
');
                $('html, body').animate({scrollTop : 0},300);
            } else {
                $('.btn i').hide();
                $('form .btn').append('  ');

                setTimeout( function() {

                  $('.alert').hide();
                  $(thisform).before('
'+ data +'
');
                  $('html, body').animate({scrollTop : 0},300);

                }, 1500 );

                setTimeout(function() {
                      location.reload();

                }, 3000 );

            }

        });
    });

});

and this is my php code
if(isset($_POST)){
  $title    = $_POST['title'];
  $category = $_POST['category'];
  $details  = $_POST['details'];
  $price    = $_POST['price'];
  $date     = date('Y-m-d');

  // Execute database query
  $insert = insert_trip($title, $category, $details, $price, $date);

  if(!empty($_FILES['images']['name'])) {

      $lastid  = last_trip();
    foreach($_FILES['images']['tmp_name'] as $key => $tmp_name ){
        $file_name = $_FILES['images']['name'][$key];
        $file_tmp  =$_FILES['images']['tmp_name'][$key];
        $file_type =$_FILES['images']['type'][$key];

          $desired_dir="../../includes/trip_images/";
          if(is_dir($desired_dir)==false){
              mkdir("$desired_dir", 0700);      // Create directory if it does not exist
          }
          $image_name = rand().$file_name;
          move_uploaded_file($file_tmp,"../../includes/trip_images/".$image_name);
          insert_trip_images($lastid['id'], $image_name);
      }

  }

  if(!empty($insert)) {

    echo 'Your Trip is succesfully add !';

  } else {

    echo 'Please check all fields';

  }

}

A: Add the enctype="multipart/form-data" attribute to your form.


text:
Q: Java AES Decryption Exception: javax.crypto.BadPaddingException:     public static String encrypt(String strToEncrypt) {
        SecureRandom secureRandom = new SecureRandom();
        byte[] key = new byte[16];
        secureRandom.nextBytes(key);
        if (strToEncrypt != null) {
            try {
                IvParameterSpec ivspec = new IvParameterSpec(key);
                SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8), Constants.AES);
                Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
                cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
                return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
            } catch (Exception ex) {
                LOGGER.error(CommonUtil.exceptionErrorPrefixSuffix("Encryption Exception in DoEncryption::encrypt", ex));
            }
        }
        return null;
    }

    public static String decrypt(String id) throws UnsupportedEncodingException {
        String decryptedId = null;
        SecureRandom secureRandom = new SecureRandom();
        byte[] key = new byte[16];
        secureRandom.nextBytes(key);
        SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8),Constants.AES);
        byte[] decodedCiphertext = Base64.getDecoder().decode(id);
        try {
            IvParameterSpec ivspec = new IvParameterSpec(key);
            Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
            cipher.init(Cipher.DECRYPT_MODE, keySpec , ivspec);
            byte[] original = cipher.doFinal(decodedCiphertext);
            decryptedId = new String(original);
            return decryptedId;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

Encryption works fine. but while decryption it throws an exception.

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption. at cipher.doFinal(decodedCiphertext);

Thanks in advance.

A: Here the problem is you are generating the Key randomly in both the Encryption and decryption method. But since you are using AES algorithm(symmetric algorithm), you should keep the key same for both encryption and decryption.

A: You need to use the same Secret Key and the same Initialization Vector when decrypting as was used to encrypt. This code uses a different random IV to encrypt than to decrypt. Often the IV is something that can be calculated incrementally by both parties, or it is prepended to the encrypted message if it's random bytes like in this code.
You can reuse the Key over time, but you should not reuse both the Key and the IV for multiple messages. See For AES CBC encryption, whats the importance of the IV? and AES encryption how to transport IV for questions and answers about the Initialization Vector and more information on why not to use a fixed IV or reuse an IV, and so on.
Padding bytes are appended to a message (before encryption) to make its length a multiple of the cipher's block-size (see https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7 if interested).
When the byte array is decrypted using a different IV, the decrypted text will not be the same as the plaintext (at least in the first block). If the padding bytes are not the same after being decrypted (which could be the case for a short plaintext), they would not be recognizable and this would cause the BadPaddingException.
( There's another minor issue in this code: It converts the text into bytes to encrypt using the UTF-8 character encoding, but converts the decrypted bytes back into text using the platform default character encoding, which may not be UTF-8. Something like decryptedId = new String(original, "UTF-8"); in the decrypt method would be one possible fix. )


text:
Q: Methods calling other methods in the same class In class design, is it a bad habit if one method calls another method in the same class (For example, 3 methods call 1 method in the same class).
Thanks

A: Not at all, it's expected if you've designed your classes properly. You should have a small public interface, and if the implementation is complex, you'll probably end up calling many private methods in the same class.
In fact, not doing this can be an anti-pattern. If you're constantly calling methods of another class, it's called Feature Envy and you should probably combine classes. If you're putting all the implementation into one gargantuan function, that's just unmaintainable, and probably contains a lot of code duplication.
Breaking things out into other reusable methods is a good thing. Your case of 3 methods calling the same one is perfect code reuse. It would be very bad if the code of that one function was duplicated in each of the calling functions.

A: Methods are just functions and functions are abstractions useful for code reuse and design improvement. If three methods of one class need to do the same thing while running should they copy-paste the code for that or call a separate method?
Having some meaningful part of code separated into a method being called by other methods is just another example of code reuse which is good unless you really overdo it.

A: No. It appears that you have found a valid use to uphold DRY principles.

A: No. In fact it is good practice to do this. Or do you think that your three methods that do the calling should each duplicate the called code?

A: Not at all. Infact quite the opposite. Methods are there to accomplish specific tasks, and you should use them for precisely that.

A: Yes, if those methods are overridable, i.e. if the class and/or methods are not final. The reason being that subclasses that attempt to override behavior or to provide a layer of service cannot do so reliably because the layer can be entered multiple times.
Example (Scala pseudo code) where we assume that HashSet.addAll calls its own HashSet.add:
class MemCountingSet[T] extends HashSet[T] {
  private def sizeOf(t: T) = ...

  private var memCount = 0

  def add(t: T) = {
    memCount += sizeOf(t)
    super.add(t)
  }
  def addAll(coll: Collection[T]) = {
    memCount += coll.foreach(sizeOf)
    super.addAll(coll)
  }
}

When using addAll we now end up double-counting.


text:
Q: Problem wrapping .java to .exe using Launch4J but problem is likely version compliance I have a problem trying to wrap a java .jar as .exe and feel like I have checked out all there was on here which was remotely related. But I still couldn't get it to work. All the questions I found which seemed similar only concerned a part of my problem and also, the solution didn't work for me (such as this Convert .jar to .exe using launch4j or this The compiler compliance specified is 1.6 but a JRE 1.8 is used and many more).
The Problem
So, in my concrete case, I need to wrap a small program to a Windows .exe for an elderly person to use (I can't expect them to run a .jar file themselves). I'm trying to get everything to run on 1.0.8, so that's Java 8.
The errors I get are, on the one hand, that the resulting .exe doesn't work, throwing a class error (indicating that there's a problem with the compiler compliance) when trying to run it.
Later on, trying around, I also got a compiler compliance warning in Eclipse, so that's likely the problem.
Then I also get an error concerning module-info.java. Just deleting the contents of the file seems to help (in terms of Eclipse warnings) but the final result also doesn't work.
I saw that you need Java 9 to use module-info.java. What do I have to do with this? I couldn't find any helpful answers on here (or maybe I didn't understand them).
What I've tried
I have both the JDK and JRE installed (enviroment var set to JRE). I tried a clean and rebuild (like suggested in a question I can't find anymore) but it didn't do anything.
I am not so famililar with Java and usually use Linux, so Windows problems are not so familiar to me. I have found myself a Windows machine to compile my program from (because there seem to have been Java version problems when using Launch4J under Linux, trying to get an .exe.)
Edit: If one of you can help me solve my problem under Linux, that would be my favourite kind of solution. I currently use Linux Mint 20 but I also have Ubuntu installed on a machine I can access.
In the end, I think my Launch4J problem is actually a pre-existing problem of my .jar file stemming from the errors outlined above which I'll sum up again below:
I have been trying around for ages but I always get

*

*The warning: The compiler compliance specified is 1.8 but a JRE 14 is used

*The error: Syntax error on token "module", interface expected
I think that I should have fixed the compliance (both in Build Path and Compiler in the Properties) but it still doesn't work and it seems I've tried all there is. The environment variable is set and all. (There also isn't a javac.exe in my folder in case that makes a difference? Someone said to download it again but it doesn't help. Also, I've tried it on the customer's computer. They had a javac.exe and the whole thing still didn't work altough throwing different errors.)
Contents of module-info.java
Regarding the module, as the asker of this question ("Syntax error on token "module", interface expected") has nothing but
module NameOfMyThingy {
}

Maybe some of you can help - would appreciate it!
Thanks!

A: Rather than using launch4j, I recommend that you take a look at jpackage, which is available in JDK 14 and 15.  See Packaging Tool User's Guide.  Note that for Windows you will also need to download the WiX toolset.


text:
Q: Rxjs: Observable with takeUntil(timer) keeps emitting after the timer has ticked I have run into a very strange behavior of takeUntil(). I create an observable timer:
let finish = Observable.timer(3000);

Then I wait for some time and call
// 2500 ms later
someObservable.takeUntil(finish);

I would expect said observable to stop emitting after the timer "ticks", i.e. about 500ms after its creation. In reality it keeps emitting for 3000ms after its creation, way beyond the moment when the timer "ticks". This does not happen if I create the timer with a Date object containing absolute time value.
Is this by design? If yes, what is the explanation?
Here's complete code, runnable with node.js (it requires npm install rx):
let {Observable, Subject} = require("rx")
let start = new Date().getTime();
function timeMs() { return new Date().getTime() - start };

function log(name, value) {
    console.log(timeMs(), name, value);
}

Observable.prototype.log = function(name) {
    this.subscribe( v=>log(name,v),
                    err=>log(name, "ERROR "+err.message),
                    ()=>log(name, "DONE"));
    return this;
}

let finish = Observable.timer(3000).log("FINISH");
setTimeout( ()=>Observable.timer(0,500).takeUntil(finish).log("seq"), 2500);

This generates the following output:
2539 'seq' 0
3001 'FINISH' 0
3005 'FINISH' 'DONE'
3007 'seq' 1
3506 'seq' 2
4006 'seq' 3
4505 'seq' 4
5005 'seq' 5
5506 'seq' 6
5507 'seq' 'DONE'

If I create the timer using absolute time:
let finish = Observable.timer(new Date(Date.now()+3000)).log("FINISH");

Then it behaves as expected:
2533 'seq' 0
3000 'seq' 'DONE'
3005 'FINISH' 0
3005 'FINISH' 'DONE'

This behavior seems to be rather consistent in various situations.E.g. if you take an interval and create child sequences using mergeMap() or switchMap(), the result would be similar: child sequences keep emitting beyond the finish event.
Thoughts?

A: You are forgetting the first rule of cold Observables: Each subscription is a new stream.
Your log operator has a bug; it is subscribing once to the Observable (thus creating the first subscription) and then returning the original Observable, which get subscribed to again, implicitly, when you pass it to the takeUntil operator. Thus in reality you actually have two seq streams active, both of which are behaving correctly.
It works in the absolute case, because you are basically setting each stream to emit at a specific time, not a relative time to when the subscription occurs.
If you want to see it work I would suggest you change your implementation to:
let start = new Date().getTime();
function timeMs() { return new Date().getTime() - start };

function log(name, value) {
    console.log(timeMs(), name, value);
}

Observable.prototype.log = function(name) {
    // Use do instead of subscribe since this continues the chain
    // without directly subscribing.
    return this.do(
      v=>log(name,v),
      err=>log(name, "ERROR "+err.message),
      ()=>log(name, "DONE")
    );
}

let finish = Observable.timer(3000).log("FINISH");

setTimeout(()=>
  Observable.timer(0,500)
    .takeUntil(finish)
    .log("seq")
    .subscribe(),
2500);

A: For completeness, here's the code that actually does what I wanted. By using Observable.publish().connect() it creates a "hot" timer that starts ticking immediately, and keeps the same time for all subscribers. It also avoid unwanted subscriptions in the "log" method, as suggested by @paulpdaniels.
Warning: beware of the race condition. If the child sequence starts after the timer has ticked, it will never stop. To demonstrate, change timeout in the last line from 2500 to 3500.
let {Observable, Subject, Scheduler, Observer} = require("rx")
let start = new Date().getTime();
function timeMs() { return new Date().getTime() - start };

function log(name, value) {
    console.log(timeMs(), name, value);
}

var logObserver =  function(name) {
    return Observer.create(
      v=>log(name,v),
      err=>log(name, "ERROR "+err.message),
      ()=>log(name, "DONE"));
}

Observable.prototype.log = function(name) { return this.do(logObserver(name)); }

Observable.prototype.start = function() {
    var hot = this.publish(); hot.connect();
    return hot;
}

let finish = Observable.timer(3000).log("FINISH").start();

setTimeout(()=>
  Observable.timer(0,500)
    .takeUntil(finish)
    .log("seq")
    .subscribe(),
2500);

The output is
2549 'seq' 0
3002 'FINISH' 0
3006 'seq' 'DONE'
3011 'FINISH' 'DONE'


text:
Q: T-test on multiple dataframes and output into dataframe I have multiple pandas data frames that I perform the t-tests on.
All data frames consist of a specific column named count that I perform the t-tests on.
def retrieve_name(var):
   callers_local_vars = inspect.currentframe().f_back.f_globals.items()
   return [var_name for var_name, var_val in callers_local_vars if var_val is var][0]

list1,list2 = [a_apple, b_apple, c_apple, d_apple], [a_orange, b_orange, c_orange, d_orange]
for x in range(len(list1)):
    for y in range(len(list2)):
        print('---------')
        print(retrieve_name(list1[x]) + ' and ' +retrieve_name(list2[y]) )
        print(ttest_ind(list1[x]['count'], list2[y]['count']))

Currently the code above is giving me what I want as shown by the sample output below
---------
a_apple and a_orange
Ttest_indResult(statistic=0.17363567462699322, pvalue=0.8625959461018068)
---------
a_apple and b_orange
Ttest_indResult(statistic=-2.8910258868131904, pvalue=0.004956889487716552)
---------
a_apple and c_orange
Ttest_indResult(statistic=-1.2417412995214525, pvalue=0.21800606685014645)
---------
a_apple and d_orange
Ttest_indResult(statistic=-3.2827337601654727, pvalue=0.0015326335802097308)

I am expecting the output to be in a data frame. How can I accomplish this?
    group1      group2          statistics              pvalue
0   a_apple     a_orange    0.17363567462699322     0.8625959461018068
1   a_apple     b_orange    -2.8910258868131904     0.004956889487716552
2   a_apple     c_orange    -1.2417412995214525     0.21800606685014645
3   a_apple     d_orange    -3.2827337601654727     0.0015326335802097308

```

A: You can simply append the group names and the results of the T-tests to a list and convert this to a dataframe.
Expanding on your code try this:
...
results = []
for x in range(len(list1)):
    for y in range(len(list2)):

        name_list1 = retrieve_name(list1[x])
        name_list2 = retrieve_name(list2[y])
        ttest_result = ttest_ind(list1[x]['count'], list2[y]['count'])
        results.append([name_list1, name_list2, ttest_result[0], ttest_result[1]])

        print('---------')
        print(name_list1 + ' and ' name_list2)
        print(ttest_result)

df = pd.DataFrame(results, columns=["group1", "group2", "statistics", "pvalue"])
print(df.head())


text:
Q: Using the distance variable - Robotic lawn mower simulation project I am trying to simulate a robotic lawn mower (like this one) on Netlogo.
I would like it finds its way home to recharge itself when the battery is low.
However I cannot find a working solution as I got the error "DISTANCE expected
input to be an agent but got NOBODY instead." every time.
I just started studying with Netlogo and would be very happy if someone give me some help finding a solution.
Interface
Thanks !
breed [cars car]
cars-own [target]

breed [houses house]

to setup
  clear-all
  setup-patches
  setup-cars
  setup-house
  reset-ticks
end

to setup-patches
  ask patches [set pcolor green] ;;Setup grass patches
  ask patches with [ pycor >= -16  and pycor >= 16]
  [ set pcolor red ] ;; setup a red frame stopping the lawn mower
    ask patches with [ pycor <= -16  and pycor <= 16]
  [ set pcolor red ]
    ask patches with [ pxcor >= -16  and pxcor >= 16]
  [ set pcolor red ]
    ask patches with [ pxcor <= -16  and pxcor <= 16]
  [ set pcolor red ]
end

to setup-cars
create-cars 1 [
    setxy 8 8
    set target one-of houses
  ]

end

to setup-house
  set-default-shape houses "house"
  ask patch 7 8 [sprout-houses 1]
end

to place-walls ;; to choose obstacles with mouse clicks
  if mouse-down? [
    ask patch mouse-xcor mouse-ycor [ set pcolor red ]
    display
  ]
end

to go
  move-cars
  cut-grass
  check-death ;; Vérify % battery.
  tick
end

to move-cars
  ask cars
  [
    ifelse [pcolor] of patch-ahead 1 = red
      [ lt random-float 360 ]   ;; cant go on red as it is a wall
      [ fd 1 ]                  ;; otherwise go
    set energy energy - 1
]
  tick
end

to cut-grass
  ask cars [
    if pcolor = green [
      set pcolor gray
    ]
  ]
end

to check-death ;; check battery level
  ask cars [
    ifelse energy >= 150
    [set label "energy ok"]
    [if distance target = 0
      [ set target one-of houses
        face target ]
    ;; move towards target.  once the distance is less than 1,
    ;; use move-to to land exactly on the target.
    ifelse distance target < 1
      [ move-to target ]
      [ fd 1 ]
   ]
  ]
end

A: Looks like the issue is due to the fact that you setup-cars before you setup-houses- there is therefore no house for the new car to set as its target. You can change the order of the setup calls, or you can change if distance target = 0 to if target = nobody, or you can do something like the following, where the turtle will just choose the nearest house as its target when energy drops below 0:
to check-death
  ask cars [
    ifelse energy >= 150
    [ set label "Energy ok" ]
    [ set target min-one-of houses [distance myself]
      face target
      ifelse distance target < 1
      [ move-to target ]
      [ fd 1 ]
    ]
  ]
end

As a side note, if you plan on expanding the model to include more mowers you may want to make energy a turtle variable. If you plan on making the world bigger, you may also want to change your frame setup slightly to dynamically scale- something like:
to setup-patches
  ask patches [set pcolor green] ;;Setup grass patches
  ask patches with [
    pxcor = max-pxcor or
    pxcor = min-pxcor or
    pycor = max-pycor or
    pycor = min-pycor ] [
    set pcolor red
  ]
end


text:
Q: How to get Mashape key to work with Javascript API     var nRequest = new XMLHttpRequest();
var nutritionalAPIData;
var phrase = document.getElementById('foodSearchBar');
var link = 'https://nutritionix-api.p.mashape.com/v1_1/search/' + phrase + '?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat';
var mashapeKey = 'My key would be written here';
console.log(link);
JSON.stringify(link);
console.log('Button Works');
    nRequest.open('GET', link);
    nRequest.setRequestHeader('X-APP-KEY', mashapeKey);
    nRequest.setRequestHeader('Content-Type', 'application/json');
    nRequest.onload = function getInfo(){
        nutritionalAPIData = JSON.parse(nRequest.responseText);
        console.log(nutritionalAPIData);
        localStorage.setItem('foodInfo', nutritionalAPIData);
    }
    nRequest.send();

When I send the request, the console in google chrome states my key is missing. I've also attempted to write the key in the header directly (not as a variable), yet I get the same issue.


text:
Q: how to make PHP lists all Linux Users? I want to build a php based site that (automate) some commands on my Ubuntu Server
first thing I did was going to the file (sudoers) and add the user www-data so I can execute php commands with root privileges!
# running the web apps with root power!!!
www-data    ALL=(ALL) NOPASSWD: ALL

then my PHP code was
<?php
   $command = "cat /etc/passwd | cut -d\":\" -f1";
   echo 'running the command: '.$command."
";
   echo exec($command);
?>

it returns only one user (the last user) !!! how to make it return all users?
thank you

A: From the PHP manual on exec:

Return Values
The last line from the result of the
  command. If you need to execute a
  command and have all the data from the
  command passed directly back without
  any interference, use the passthru()
  function.
       To get the output of the executed command, be sure to set and use the
  output parameter.

So you have to do something similar to this:
<?php
   $output = array();
   $command = "cat /etc/passwd | cut -d\":\" -f1";
   echo 'running the command: '.$command."
";
   exec($command, &$output);
   echo implode("
\n", $output);
?>

A: As @benjamin explains, no need to be root or sudo, no need for SUID.
Just pure PHP. I used the field names from posix_getpwnam.
function getUsers() {
    $result = [];
    /** @see http://php.net/manual/en/function.posix-getpwnam.php */
    $keys = ['name', 'passwd', 'uid', 'gid', 'gecos', 'dir', 'shell'];
    $handle = fopen('/etc/passwd', 'r');
    if(!$handle){
        throw new \RuntimeException("failed to open /etc/passwd for reading! ".print_r(error_get_last(),true));
    }
    while ( ($values = fgetcsv($handle, 1000, ':')) !== false ) {
        $result[] = array_combine($keys, $values);
    }
    fclose($handle);
    return $result;
}

It returns an array containing all users, formatted like this:
[
  [
    'name' => 'root',
    'passwd' => 'x',
    'uid' => '0',
    'gid' => '0',
    'gecos' => 'root',
    'dir' => '/root',
    'shell' => '/bin/bash',
  ],
  [
    'name' => 'daemon',
    'passwd' => 'x',
    'uid' => '1',
    'gid' => '1',
    'gecos' => 'daemon',
    'dir' => '/usr/sbin',
    'shell' => '/usr/sbin/nologin',
  ],
  ...
]

A: Like Matt S said, that's an incredibly bad idea to allow www-data root access on your server. The slightest compromise through your web applications could allow anyone full control of your system.
A better idea would be to make separate scripts for specific accessions then use SUID permissions. This means, a specific user (in this case, www-data) can make small changes to the system through the execution of scripts. Still not a good idea, though. You may be able to work around it with suPHP but security is still a major concern.

A: /etc/passwd is readable by anyone, so you should be able to execute your command without having any special rights (unless PHP prevents it?).


text:
Q: WSO2 Proxy service doesn't return expected result when used in Postman client I have a proxy service which returns records from a database and sends the records to an endpoint. All this in a single Proxy service. It works fine when I use the Try this service in the WSO2 UI itself. But when I use the same URL in postman or any other Client, the result is a success but doesn't return any records nor posts these records to the endpoint.
Any idea what would I be doing wrong?
Thanks.


text:
Q: KSOAP 2 Android with HTTPS I am using KSOAP2 to manage SOAP in Android but it use https for the SOAP url and I am getting this error: javax.net.ssl.SSLException: Not trusted server certificate
A normal error because the certificate is untrusted, but anyone knows how to workaround with this error?
I can not manage the certificate because is from a other company and I don't have access to change it.
Thanks

A: I find the answer by myself

*

*on ServiceConnectionSE.java add this for accept untrusted certificate:
private TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

*then in the constructor add this to allow untrusted certificates and not verified hostnames:
    try {
       SSLContext sc = SSLContext.getInstance("TLS");
       sc.init(null, trustAllCerts, new java.security.SecureRandom());
       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
       e.getMessage();
    }
    connection = (HttpsURLConnection) new URL(url).openConnection();
    ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

A: Create a new class FakeX509TrustManager to handle the certificate problem,
    FakeX509TrustManager.allowAllSSL();
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

The new created class is as the following:
public class FakeX509TrustManager implements X509TrustManager {

    private static TrustManager[] trustManagers;
    private static final X509Certificate[] _AcceptedIssuers = new
X509Certificate[] {};

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String
authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String
authType) throws CertificateException {
    }

    public boolean isClientTrusted(X509Certificate[] chain) {
            return true;
    }

    public boolean isServerTrusted(X509Certificate[] chain) {
            return true;
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
            return _AcceptedIssuers;
    }

    public static void allowAllSSL() {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                            return true;
                    }

            });

            SSLContext context = null;
            if (trustManagers == null) {
                    trustManagers = new TrustManager[] { new FakeX509TrustManager() };
            }

            try {
                    context = SSLContext.getInstance("TLS");
                    context.init(null, trustManagers, new SecureRandom());
            } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
            } catch (KeyManagementException e) {
                    e.printStackTrace();
            }

       HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }

}

A: Checking again this problem, I've discovered a more clean solution for me. No KSOAP2 files modification needed.
In your project, link the ksoap2-android-assembly-3.0.0-jar, with no modifications.
Next, create a file named SSLConnection.java with this code:
package com.example.mypackage;

import android.util.Log;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SSLConection {

    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        javax.net.ssl.SSLContext context;

        if (trustManagers == null) {
            trustManagers = new TrustManager[]{new _FakeX509TrustManager()};
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
    }
}

And just call to SSLConection.allowAllSSL(); before calling a server method via KSOAP2. It's all, works for me. All SSL certificates are accepted and I can use KSOAP2 with https protocol.

A: I can't comment yet so i post my comments to rallat answer here. His solution works but it needs further explanations. To run ksoap2 with ssl:

*

*Put ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar in a project

*Download ksoap2 sources from https://github.com/mosabua/ksoap2-android/tree/ (ksoap2 repository)

*Copy HttpTransportSE.java, ServiceConnectionSE.java (I also needed to copy Transport.java, ServiceConnection.java and HeaderProperty.java). Delete imports from those files and make sure that they use your files (not imports from ksoap2.jar)

*Use rallat answer ( I copy-pasted it):

*

*ServiceConnectionSE.java add this for accept untrusted certificate:
private TrustManager[] trustAllCerts = new TrustManager[] {
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

*then use this constructors to
allow untrusted certificates and not
verified hostnames:
public ServiceConnectionSE(String url) throws IOException {
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.getMessage();
    }
    connection = (HttpsURLConnection) new URL(url).openConnection();
    ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());
}

*Second contructor
public ServiceConnectionSE(Proxy proxy, String url) throws IOException {
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
     } catch (Exception e) {
        e.getMessage();
     }
     connection = (HttpsURLConnection) new URL(url).openConnection();
    ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);
}

*In your code just use:
HttpTransportSE aht = new HttpTransportSE(URL);
aht.call(SOAP_ACTION, envelope);

Other things as in tutorials


text:
Q: How to solve this semi gaussian definite complex integral? How can I solve this definite complex integral :
$L=\int_{-\infty}^{\infty} e^{-{\lambda r^2}-jr \zeta_1+j\zeta_2}dr$
where :
$\lambda , \zeta_1, \zeta_2$ are real and constant values and $\,j =\sqrt{-1} \,$.

A: We use the noation $j=i$.
Use that $\int_{-\infty}^{\infty}e^{-ax^2+bx+c}dx=\sqrt{\pi\over a}e^{{b^2\over 4a}+c}$  to get the answer $\sqrt{\pi\over \lambda}e^{{-{\xi_1}^2\over 4\lambda}+i\xi_2}$

A: You need to complete the square in the $r$. That is, write
$$
-\lambda r^2 - ir\zeta_1 + i\zeta_2 = -\lambda\Bigl(r+\frac{i\zeta_1}{2\lambda}\Bigr)^2+i\zeta_2-\frac{\zeta_1^2}{4\lambda}
$$
We can now write your integral as
$$
\exp\Bigl[i\zeta_2-\frac{\zeta_1^2}{4\lambda}\Bigr]\int_{-\infty}^{\infty}\exp\biggl[-\lambda\Bigl(r+\frac{i\zeta_1}{2\lambda}\Bigr)^2\biggr]dr
$$
Let $u = r+\frac{i\zeta_1}{2\lambda}$. Then $dr = du$ so we have
$$
\exp\Bigl[i\zeta_2-\frac{\zeta_1^2}{4\lambda}\Bigr]\int_{-\infty}^{\infty}e^{-\lambda u^2}du
$$
For $\lambda > 0$, the integral is $\sqrt{\frac{\pi}{\lambda}}$. Note the following integral
$$
\int_{-\infty}^{\infty}e^{-x^2}dx = \sqrt{\pi}\tag{1}
$$
The goal with integrals like yours is to manipulate into the form of equation $(1)$.

A: Write
$$L = \int_{-\infty}^{\infty} e^{-\lambda r^2 - jr\zeta_1}e^{j\zeta_2}\,dr = e^{j\zeta_2}\int_{-\infty}^\infty e^{-\lambda\left(r + \frac{j\zeta}{2\lambda}\right)^2+\lambda\left(\frac{j\zeta_1}{2\lambda}\right)^2}\, dr = e^{j\zeta_2}e^{-\frac{\zeta_1^2}{4\lambda}}\int_{-\infty}^\infty e^{\lambda\left(r - \frac{j\zeta_1}{2\lambda}\right)^2}\, dr.$$
By contour shifting, the integral on the right is $\int_{-\infty}^\infty e^{-\lambda r^2}\, dr$. To justify this, consider the contour integral
$$\int_{\Gamma(R)} e^{-\lambda z^2}\, dz$$
where $\Gamma(R)$ is a rectangle parallel to the axes, with counterclockwise orientation, and with vertices at $-R$, $R$, $-R + j\zeta_1/(2\lambda)$, and $R + j\zeta_1/(2\lambda)$,. The integrals along the vertical edges are $O(e^{-\lambda R^2})$, which is negligible as $R \to \infty$. Further, since $e^{-\lambda z^2}$ is entire, $\int_{\Gamma(R)} e^{-\lambda z^2}\, dz = 0$ by Cauchy's integral theorem. Hence, the contour shifting is valid and
$$\int_{-\infty}^\infty e^{-\lambda\left(r - \frac{j\zeta_1}{2\lambda}\right)^2}\, dr = \int_{-\infty}^\infty e^{-\lambda r^2}\, dr = \sqrt{\frac{\pi}{\lambda}}.$$ So
$$L = e^{j\zeta_2 - \frac{\zeta_1^2}{4\lambda}} \sqrt{\frac{\pi}{\lambda}}.$$


text:
Q: Apache PDFBox Merge Error - java.io.IOException: Missing root object specification in trailer I am trying to merge two existing PDF documents that are InputStreams together using the PDFMergerUtility.mergeDocuments() method in PDFBox.  Here's my code; the entry method is pullDocumentsIntoSystem():
private boolean pullDocumentsIntoSystem(final String id, final String filePathAndName, final List<Letter> parsedLetters)
        throws IOException {

    final List<InputStream> pdfStreams = new ArrayList<InputStream>();
    final ByteArrayOutputStream mergedPdfOutputStream = new ByteArrayOutputStream();

            // make a call to retrieve each document
            for (final Letter letter : parsedLetters) {
                pdfStreams.add(this.getSpecificDocument(letter.getKey(), id));
            }

            // merge all the documents together
            this.mergePdfDocuments(pdfStreams, mergedPdfOutputStream);

            // write file to directory
            this.writeMergedPdfDocument(mergedPdfOutputStream, filePathAndName); //...more code below...

}

private InputStream getSpecificDocument(final String id, final String key) throws IOException {

    HttpURLConnection conn = null;
    InputStream pdfStream = null;

    try {
        final String url = this.getBaseURL() + "/letter/" + id + "/documents/" + key;

        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("X-Letter-Authentication", this.getAuthenticationHeader());
        conn.setRequestProperty("Accept", "application/pdf");
        conn.setRequestProperty("Content-Type", "application/pdf");
        conn.setDoOutput(true);

        pdfStream = connection.getInputStream();

    }
    finally {
        this.disconnect(connection);
    }

    return pdfStream;
}

    private void mergePdfDocuments(final List<InputStream> pdfStreams, final ByteArrayOutputStream mergedPdfOutputStream)
        throws IOException {

    final PDFMergerUtility merger = new PDFMergerUtility();

    merger.addSources(pdfStreams);

    merger.setDestinationStream(mergedPdfOutputStream);
    merger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());  // ERROR THROWN HERE
}

Here's the error I'm receiving on the line with the comment above:
Caused by: java.io.IOException: Missing root object specification in trailer.
at org.apache.pdfbox.pdfparser.COSParser.parseTrailerValuesDynamically(COSParser.java:2832) ~[pdfbox-2.0.11.jar:2.0.11]
at org.apache.pdfbox.pdfparser.PDFParser.initialParse(PDFParser.java:173) ~[pdfbox-2.0.11.jar:2.0.11]
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:220) ~[pdfbox-2.0.11.jar:2.0.11]
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1144) ~[pdfbox-2.0.11.jar:2.0.11]
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1060) ~[pdfbox-2.0.11.jar:2.0.11]
at org.apache.pdfbox.multipdf.PDFMergerUtility.legacyMergeDocuments(PDFMergerUtility.java:379) ~[pdfbox-2.0.11.jar:2.0.11]
at org.apache.pdfbox.multipdf.PDFMergerUtility.mergeDocuments(PDFMergerUtility.java:280) ~[pdfbox-2.0.11.jar:2.0.11]

I am using PDFBox 2.0.11.
My list of InputStreams are each coming from a separate HttpURLConnection.getInputStream() call in case that matters.  I have confirmed that there are indeed documents coming back from the calls being made in the HttpURLConnection.
UPDATE
On the advice of @Tilman Hausherr below, I tested the same functionality without using the InputStreams.  If I use PDFMergerUtility.addSource(File source) method instead the PDFMergerUtility.addSource(List<InputStream>) the merge works successfully.  So it seems as if something with my InputStreams isn't working correctly.
I appreciate any help and am happy to provide more information if needed.
Thanks for your time!

A: In the end this was really a silly mistake.  I was closing the HttpURLConnection too early.  If I remove the this.disconnect(connection) call at the end of the getSpecificDocument() method then everything works fine.
Well, hopefully this will help someone else.
Thanks for the leads @Фарид Азаев and @Tilman Hausherr!

A: probably problem in input stream try adding application/pdf mime type.


text:
Q: I can't get code analysis rule CA2202 fixed I have a function (see code snippet below).
I have Code Analysis enabled, and I get a CA2202 rule violation.
(edit: I added the close on the pdfStamper otherwise the PDF will be corrupted)

CA2202: Do not dispose objects multiple times
A method implementation contains code paths that could cause multiple calls to IDisposable.Dispose or a Dispose equivalent, such as a Close() method on some types, on the same object.

In the CA2202 MSDN page(here), the proposed fix doesn't work.
How can the code be rewritten without having to suppress this violation ?
private byte[] DoGenerateFinishedGamePdf(int gameSessionLogId)
{
   var finishedGameCertificatePdfFile = httpServerUtilityWrapper.MapPath(ConfigurationManager.AppSettings["FinishedGameCertificateFile"]);

   var pdfReader = new PdfReader(finishedGameCertificatePdfFile); // note that PdfReader is not IDisposeable

   using (MemoryStream memoryStream = new MemoryStream())
   using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
   {
      var fields = pdfStamper.AcroFields;
      fields.SetField("CityName", "It works!");

      pdfReader.Close();

      pdfStamper.FormFlattening = true;
      pdfStamper.FreeTextFlattening = true;
      pdfStamper.Close();

      return memoryStream.ToArray();
   }
}

A: Ah, everyone's favourite warning! In this instance MemoryStream.Dispose is idempotent (the current implementation does nothing) so it's not really a problem, however the 'fix' is as follows:
MemoryStream memoryStream = null;
try
{
  memoryStream = new MemoryStream();
  using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
  {
    memoryStream = null;

    var fields = pdfStamper.AcroFields;
    fields.SetField("CityName", "It works!");

    pdfReader.Close();

    pdfStamper.FormFlattening = true;
    pdfStamper.FreeTextFlattening = true;
    pdfStamper.Close();

    return memoryStream.ToArray();
  }
}
finally
{
  if (memoryStream != null) memoryStream.Dispose();
}

Since the PdfStamper 'owns' the MemoryStream it will dispose of it when PdfStamper.Dispose is called, so we only need to call Dispose on the MemoryStream if we do not Dispose of the PdfStamper, which can only happen if the construction of the PdfStamper fails.

A: This is happening because the PdfStamper is disposing the stream even though it shouldn't.  It didn't create it and doesn't own it, so it has no business disposing it.
Your code did create the stream and it does own it, so it's quite natural that it should dispose it.  If the PdfStamper weren't disposing the stream inappropriately, all would be fine with your nested usings.
Your first move should probably be to file a bug report/feature request that the PdfStamper disposition of the stream be removed or at least made avoidable.  Once you've done that, you can pretty safely suppress the CA2202 violation since double disposition of a MemoryStream will have no deleterious consequences.
BTW, PdfStamper.Dispose() call PdfStamper.Close() (at least in version 5.4.0), so you should be able to remove the PdfStamper.Close() call.


text:
Q: $\mathbb{A}^1$-homotopy classes of maps from and to $\mathbb{G}_m^n$ I am trying to understand relatively simple examples of calculations in $\mathbb{A}^1$-homotopy theory to build intuition.
For example, if $S$ is a scheme over a field $k$, what is the set $[\mathbb{G}_m, S]_{\mathbb{A}^1}$ of $\mathbb{A}^1$-homotopy classes of morphisms from $\mathbb{G}_m$ to $S$ over $k$? $\mathbb{G}_m$ is the multiplicative group.
How does this generalize to $\mathbb{G}_m^n$, $n \in \mathbb{N}$? Also dually, what are $[S, \mathbb{G}_m^n]_{\mathbb{A}^1}$?


text:
Q: Getting different output when casting between int and int64 in Go; is it due to processor architecture? A small part of an application I'm using to test some expected behavior is giving different output, depending on what processor I run it on. Here's the relevant part of the code:
   for b := 0; b < intCounter; b++ {

            //int64Random = rand.Int63()
            int64Random = int64(rand.Int())

//CHECKING FOR SANITY
fmt.Println("int64Random is " + strconv.FormatInt(int64Random, 10))

            slcTestNums = append(slcTestNums, int64Random)
    }

When I run this on my Mac (amd64, darwin) I get output like:
int64Random is 2991558990735723489
int64Random is 7893058381743103687
int64Random is 7672635040537837613
int64Random is 1557718564618710869
int64Random is 2107352926413218802

When I run this on a Pi (arm, linux) I get output like:
int64Random is 1251459732
int64Random is 1316852782
int64Random is 971786136
int64Random is 1359359453
int64Random is 729066469

If on the Pi I change the int64Random to = rand.Int63() and recompile, I get output like:
int64Random is 7160249008355881289
int64Random is 7184347289772016444
int64Random is 9201664581141930074
int64Random is 917219239600463359
int64Random is 6015348270214295654

...which more closely matches what the Mac is getting. Is this because of something that is changed at runtime due to the processor architecture? Why is int64(rand.Int()) generating int64-ranged numbers instead of keeping an int-ranged number, but changing the type for the variable it's being stored in? Am I missing the Go documentation that mentions this behavior?

A: According to https://golang.org/doc/go1.1

The language allows the implementation to choose whether the int type
  and uint types are 32 or 64 bits. Previous Go implementations made int
  and uint 32 bits on all systems. Both the gc and gccgo implementations
  now make int and uint 64 bits on 64-bit platforms such as AMD64/x86-64

rand.Int() returns int. On amd64 it will be 64 bits, on ARM it will be 32 bits


text:
Q: Atomic compare and exchange in arm assembly I am trying to compile the arm inline assembly code for ARMV7 to compare and swap  atomically, basically i have copied the code from ARM linux kernel but somehow it doesnt compile. it gives the below error
Erro: thumb conditional instruction should be in IT block -- strexeq r5,r1,[r3]. below is the code
static inline int
dfp_atomic32_cmpset(volatile uint32_t *dst, uint32_t exp, uint32_t src)
{

        unsigned long oldval, res;

        smp_mb();

        do {
                __asm__ __volatile__("@ dfp_atomic32_cmpset\n"
                "ldrex  %1, [%3]\n"
                "mov    %0, #0\n"
                "teq    %1, %4\n"
                "strexeq %0, %5, [%3]\n"
                    : "=&r" (res), "=&r" (oldval), "+Qo" (*dst)
                    : "r" (dst), "Ir" (exp), "r" (src)
                    : "cc");
        } while (res);

        smp_mb();

        return oldval;
}

Any idea what that error means?

A: You need to add an IT EQ instruction; see Thumb2 porting at the Ubuntu wiki. You are copying ARM code and trying to use it in thumb2 mode. All ARM instructions are conditional and the IT EQ is a phantom in ARM mode (not needed). In Thumb2 mode, you have to notify the process which condition should be tested for the following instructions.
It is possible that gcc inlines do not apply to -mimplicit-it; especially as the compiler needs to guess the number of op-codes to make it's own code.  Ie, to calculate branch sizes, etc.


text:
Q: Can i access sessions in ExpressJS without the request object? I have an application that uses swig for templating, and sessions to store some client specific data.
I create my sessions inside a route like this:
exports.RenderIndex = function(req, res){
  if (req.body.filters) {
    var filters = req.body.filters;
    if (filters.date && filters.date.length > 0) {
      var d = moment(filters.date, "YYYY-MM-DD");
      var weekNumber = d.week();

      req.session.selectedDate = filters.date;
      req.session.selectedWeek = weekNumber;
    }
  }
};

Later on in my app i have a swig-filter needs to read and use my sessions, but i'm not quite sure how to access the sessions when i have no request object to take it from.
My swig-filter looks something like this:
swig.setFilter('getOpeninghourTable', function (input, idx) {
  var weeknumber = HERE_ID_LIKE_MY_SESSION_VALUE
  var data = calendar.json(input, weeknumber );
  return swig.renderFile(''template.html, calendarData);
});

IS it possible?

A: No, it's not possible.  Why would it be?  How would your code know what session to use?
Any request-specific code must be in a request handler (or called from it) so it has a reference to the request data.


text:
Q: PHP MySQL - Order Alpha and Numeric strings I have the following data:
GROUP 1 - FINANCE
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
GROUP 2 - OPS

When ORDERING the data in a MySQL question it, rightly, brings this data back in the above order.  However, is there anyway (without changing the data you can order it in Numeric order?  As follows
GROUP 1 - FINANCE
GROUP 2 - OPS
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR

Thanks!

A: Adding ORDER BY
 CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(column, ' ', 2), ' ', -1) AS UNSIGNED) clause should help.
Nesting SUBSTRING_INDEX functions with the right parameters makes it possible to split and extract the string parts. it this case the numeric part after the first string part in this case 'GROUP' will be extracted.
Query
SELECT
 records.data
FROM (

SELECT
 "GROUP 1 - FINANCE" AS data
UNION
SELECT
 "GROUP 10 - SALES" AS data
UNION
SELECT
 "GROUP 11 - MARKETING" AS data
UNION
SELECT
 "GROUP 12 - HR" AS data
UNION
SELECT
 "GROUP 2 - OPS" AS data
) AS records
ORDER BY
 CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(records.data, ' ', 2), ' ', -1) AS UNSIGNED)

see demo https://www.db-fiddle.com/f/sGqUeTKaDjihRA3Bg3Myca/0

A: Since MySQL 8.0 you can use REPLACE and REGEXP_SUBSTR to ORDER BY the column:
SELECT *
FROM table_name
ORDER BY CAST(TRIM(REPLACE(REGEXP_SUBSTR(column_name, '(GROUP )([0-9]+)'), 'GROUP', '')) AS UNSIGNED)


text:
Q: How to write if statement in JSON? I don't know json , I have for loop statement.I need only single data  , How can write if statement in JSON. Please help me,
function myFunction(response) {
        var arr = JSON.parse(response);
        var i;
        var out = "
";
       for(i = 0; i < arr.length; i++) {
            out += "
 " +
            arr[i].offerPercentage +
            "	" +
            arr[i].offerName +
            "
";
        }enter code here
        out += "
";
        document.getElementById("id01").innerHTML = out;
    }

A: Edit:
Now that it's clear what you want, to loop over just a single item, you change the amount of times to iterate - currently it will iterate over the whole array, to only iterate over one change arr.length to 1 (or however many items you want to display):
function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var out = "
";

    for(i = 0; i < 1; i++) {
        out += "
 " +
        arr[0].offerPercentage +
        "	" +
        arr[0].offerName +
        "
";
    }

    out += "
";
    document.getElementById("id01").innerHTML = out;
}

or you could simply reference the first result directly and bypass the loop which would make more sense:
function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var out = "
";

    // Only append if `arr` has at least one result.
    if (typeof arr[0] !== 'undefined') {
        out += "
 " +
        arr[0].offerPercentage +
        "	" +
        arr[0].offerName +
        "
";
    }

    out += "
";
    document.getElementById("id01").innerHTML = out;
}

Old Answer:
Objects in Javascript don't have a .length property.
To loop over an object, use the for...in syntax:
for (var offer in arr) {
    // `offer.offerPercentage` and `offer.offerName` will be available here.
}

If what's being returned is actually an array, your issue isn't your syntax, it's the fact that you are using arr[0] in each loop rather than arr[i].


text:
Q: Spring REST reuse nested requstmapping We have a REST API, for some comments. Currently, the most interesting URIs are:
GET /products/1/comments             // get all comments of product 1
GET /products/1/comments/5           // get the 5th comment of product 1
GET /products/1/comments/5/user      // get the user of the 5th comment
GET /products/1/comments/latest      // get the latest comment of product 1
GET /products/1/comments/latest/user // get the user of the latest comment

in addition, you can directly access comments
GET /comments/987                    // get the comment with id 987
GET /comments/987/user               // get the user of comment with id 987

so, we have two @RestController:
@RestController
@RequestMapping("/products/{productId}")
public class ProductsCommentsResource {

    @GetMapping(value = "/comments")
    public ResponseEntity<?> getComments(@PathVariable Long productId){
       // get all products...
    }

    @GetMapping(value = "/comments/{commentNr}")
    public ResponseEntity<?> getComment(@PathVariable Long productId, @PathVaraible Long commentNr){
       // get comment with number commentNr of product productId
    }

    @GetMapping(value = "/comments/{commentNr}/user")
    public ResponseEntity<?> getCommentUser(@PathVariable Long productId, @PathVaraible Long commentNr){
       // get the user of comment with commentNr of productId
    }

    @GetMapping(value = "/comments/latest")
    public ResponseEntity<?> getLatestComment(@PathVariable Long productId){
       // get latest commentNr and call getComment(productId, commentNr)
    }

    @GetMapping(value = "/comments/latest/user")
    public ResponseEntity<?> getLatestCommentUser(@PathVariable Long productId){
       // get latest commentNr and call getCommentUser(productId, commentNr)
    }
}

@RestController
@RequestMapping("/comments")
public class CommentsResource {
    @GetMapping(value = "/{commentId}")
    public ResponseEntity<?> getComment(@PathVaraible Long commentId){
       // get comment id commentId
    }

    @GetMapping(value = "/{commentId}/user")
    public ResponseEntity<?> getCommentUser(@PathVaraible Long commendId){
       // get the user of comment with id commentId
    }
}

The latest is therefore only a replacement-keyword for "get the last commentNr and call the corresponding method with this commentId"
This is just an excerpt and in addition to the user, a comment has about 30 sub-and sub-sub-resources (including methods POST, DELETE etc.).
Therefore, we have more or less everything three times.
So, obviously, we need to improve this, to remove duplicate code etc.
The idea is to "encapsulate" the comments-resources and make it reusable by using the @RequestMapping annotated at the class.
We thought about a mechnism like:

*

*the /products/1/comments/latest/user is called

*the call is intercepted and the "latest" of product 1 is resolved to the commentId

*the call will be redirect to ```/comments/{commendId}/user

Thus, we would need to have something that redirects
 - /products/1/comments/latest[what ever] to /comments/{commentId}[what ever]
 - /products/1/comments/5[what ever] also to /comments/{commentId}[what ever]
and /comments/{commentId} would be the only the implementation.
However, we did not find anything suitable in the spring docs...

A: You could add additional URL path prefix in your controller's @RequestMapping.
@RequestMapping(value = { "/products/{productId}", "/" })

This means that you can remove CommentsResource controller and you'll be able to access the same resource at:
/products/1/comments/5

and at
/comments/5

For instance, here:
 @GetMapping(value = "/comments/{commentNr}")
    public ResponseEntity<?> getComment(@PathVariable Long productId, @PathVaraible Long commentNr){
       // get comment with number commentNr of product productId
    }

The obvious issue would be a productId path variable. If you're using Java 8, that can be solved fairly easy by using Optional:
@GetMapping(value = "/comments/{commentNr}")
public ResponseEntity<?> getComment(@PathVariable Optional<Long> productId, @PathVaraible Long commentNr){
    // get comment with number commentNr of product productId
    // Check whether productId exists
}


text:
Q: Not able to send http Request with authorization header in my Azure function when deployed in Server I have used HttpClient and I'm setting Authorization headers to it, when I run my Timer Trigger and HTTP trigger functions locally Everything is working fine and able to get the expected response,
But, when I deployed the same in the production environment It is throwing 401 Unauthorized error in the response. I'm able to see the Authorization headers in HttpRequest Object through my logs, but the same is not reaching the destination end point.
Thank you.
I've tried Default headers, and reused the HttpClient

HttpClient client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes(configObj.loginId + ":" + configObj.password);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

 client.BaseAddress = new Uri(configObj.Url);

Then I'm passing the client object as parameter to some methods and using client as mentioned below
public static async Task<string> methodName(string VariableName, HttpClient client)
{
 HttpResponseMessage response = await client.GetAsync($"/reports/{VariableValue}");
 string content = await response.Content.ReadAsStringAsync();
    if (response.IsSuccessStatusCode)
    {
       playing with the Data
    }
}

I even Tried assigning all the values to HttpRequestmessage and send it through http client, even that didn't help me in the production.

A: Thankyou Asiful-Nobel. Posting your suggestion as an answer so that it will be helpful for other community members who face similar kind of issues.
Below is the command which will help you in getting the authorization for function in production.
https://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?code=<API_KEY>

For complete information check the link.


text:
Q: How to find the type of a variable in Chapel It seems I come across the answer, then I lose it.  I'm at the "lost" stage.  If I have an object in Chapel, what is the equivalent of Python's
>>> thing = 'i am a thing'
>>> type(thing)
<type 'str'>

I have seen that writeln(A.type) and writeln(type(A)) both throw errors of the form
'writeln(type _array(DefaultSparseArr(real(64),2,int(64),DefaultSparseDom(2,int(64),_domain(DefaultRectangularDom(2,int(64),false))))))'
$CHPL_HOME/modules/standard/IO.chpl:3992: note: candidates are: channel.writeln(out error: syserr) [233811]
$CHPL_HOME/modules/standard/IO.chpl:3998: note:                 channel.writeln() [233840]
$CHPL_HOME/modules/standard/IO.chpl:4006: note:                 channel.writeln(const args ...?k, out error: syserr) [233876]
$CHPL_HOME/modules/standard/IO.chpl:4012: note:                 channel.writeln(const args ...?k) [233916]
$CHPL_HOME/modules/standard/IO.chpl:4020: note:                 channel.writeln(const args ...?k, style: iostyle) [233954]
$CHPL_HOME/modules/standard/IO.chpl:4047: note:                 channel.writeln(const args ...?k, style: iostyle, out error: syserr) [233998]
$CHPL_HOME/modules/standard/IO.chpl:4267: note:                 writeln(const args ...?n) [235140]
$CHPL_HOME/modules/standard/IO.chpl:4273: note:                 writeln() [235158]

A: var x = 1;
writeln(x.type:string);


text:
Q: Creating a Docker volume at a specific location Can I tell Docker to create a volume at a specific location on the host machine?
The host machine has some storage restrictions and I'd like the volume to be stored in /data instead of /var/lib/docker/vfs/dir/.
This isn't even mentioned in the documentation so I suspect I misunderstood something.

A: Do you want to use a  different directory than the default /var/lib/docker as Docker runtime? You can do this by starting docker daemon with -g option and path to the  directory of your choice. From the man page:
-g, --graph=""
     Path to use as the root of the Docker runtime. Default is /var/lib/docker.

A: When firing up your container with "docker run":
 docker run -v /data/some_directory:/mount/location/in/your/container your_docker_image

You cannot do this in the same way via Dockerfile because of portability.


text:
Q: What are the different ways to install a software on Ubuntu? I am  a beginner trying to understand how installation of software works in Ubuntu.
I have installed a lot of softwares on my system but everytime I want to install something I will just google and follow without really understanding how it works.The different ways I have done installation

*

*sudo apt-get install

*Download .deb and use dpkg

*Install from Ubuntu software center

*Synpatic package

*Add link to sources.list

*Using PPA

Why are there so many ways to install a software?. what is the difference? How does these different ways of installing it works?
Any help or links would be appreciated.

A: I'll step you through each method.

*

*apt-get uses the Debian PPA system to install software. It is what goes on in the background when you install software from the software center.

*dpkg is even further in the background. It is what Ubuntu uses to actually install software, as opposed to simply managing it. You should not use this method if you can help it, since higher-level methods, such as apt-get, are superior in utility.

*Installing from the Software Center is the highest-level method of package installation. It is not designed for advanced users, who tend to prefer apt-get. However, it makes the Ubuntu ecosystem more accessible for the general user.

*Synaptic package manager is like a GUI alternative to apt-get. For apt-get, you need to know the name of a package. Synaptic instead lists packages that your computer knows of, and allows you to install those by clicking on them. It is more advanced than the Software Center and still has the same usage of apt-get.

*Adding links to sources.list is a way to add a PPA that may require a key. This is the method for installing some proprietary apps like Google Chrome. Doing this does not actually install the app, you still need to update your sources, then perform apt-get install or use Synaptic afterwards. Like Sparhawk said, these can also be used for official repositories, whereas PPAs cannot.

*PPAs are needed to update software. They are generally what is used to install as well. They are also the main reason apt-get is superior to dpkg for the installation process. apt-get can provide you with updates and dpkg cannot. As Sparhawk said, it is important to note that PPA stands for Personal Package Archive. These are not official repositories, which instead belong in sources.list.

A: It may seem that there are many ways to install softwares in Ubuntu(or GNU/Linux), but behind the hood, there is only one thing that all applications do:  copy different files in appropriate locations and make the system aware## that a new software has been added
##sometimes you may install softwares manually in directories like $HOME or using a .bin file , in such cases system is not aware of the installation)
apt-get and dpkg are command line tools(backends) which you can use to install software.They can be comparatively difficult than software center but provide more functionality.
Ubuntu software center and synaptic package manager are GUI tools(frontends) which use the command line tools to install software. they are comparatively easy to use but provide less functionality.
sources.list is the file where your ppa are stored. ppa are kind of links that apt-get uses to find softwares, install them and update them.
Note that you may also install software by manually copying necessary files to appropriate locations.

A: Dillmo's answer covers all the methods that you mentioned, but I can think of two more that are more manual methods of installation.
You might need to manually download the binary and run it from your computer directly. For example, I had to do this with the academic citation software Jabref, as the official repositories had a year-old beta at one stage.
The other method is actually building from source yourself (i.e. with build, make, install). I did this recently for the KDE widget "STDIN plasmoid", which was otherwise unavailable. There is also an excellent utility called checkinstall that creates fake packages for these manually builds, allowing easier uninstallation.

In answer to your question, "why are there so many ways to install a software?", there are two main reasons. As Dillmo states, some are backends to others. This is because people prefer the ease of different frontends and GUIs.
The other reason, primarily relating to my examples above, is availability. Some developers don't package specifically for Ubuntu, and that's why you have to manually install.