text:
Q: more than one build in queue for specific job in jenkins I have a job which I trigger with parameters from another job using wget. each time I give the job different parameter - which svn revision to run with.
I don't want to allow concurrent runs of the same job, but I want to allow more than one pending build in the queue for the job.
From what I have tried it didn't work, I see in the queue only one build of the job pending, no matter how many builds I trigger.
Is it possible with any plugin?

A: I needed to do the same, and discovered the Random String Parameter Plugin. This adds a random string to each build as a parameter, which is enough to make each build unique and for Jenkins to queue them independently rather than coalesce them.

A: Jenkins doesn't place a build in the queue if it already contains one with the same param values.
To trick it, you could add an additional, unused param, and set it to a random value when calling wget.


text:
Q: Unable to delete mongoose collection within Cucumber-JS Step I'm using Cucumber-JS to write some BDD features and Mongoose to reset a database for each scenario.
I'm setting up a background task, generating the step for it and changing the callback.pending() to callback() which passes.
Feature: x
  Background: Clear person collection
    Given that I have an empty person collection
...

and my step code:
...
this.Given(/^that I have an empty person collection$/, function (callback) {
    callback();
});
...

I add a require statement to my mongoose schema and then wrap the callback in this:
var Product = require("../models/product);
...
this.Given(/^that I have an empty person collection$/, function (callback) {
    Product.remove(function(err){
        callback();
    });
});
...

this is the product.js file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProductSchema = new Schema({
    name: String,
    price: String,
    description: String
});

module.exports = mongoose.model('Product', ProductSchema);

And when I run cucumber-js is just terminates.
When I go back and remove the remove function, it runs fine again.
I've even tried running it like this:
...
this.Given(/^that I have an empty person collection$/, function (callback) {
    Product.remove().exec(callback);
});
...

Any ideas what is causing this behaviour?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get a generic list from a datatable with the lowest overhead? I'm looking for best practices here. Sorry. I know it's subjective, but there are a lot of smart people here, so there ought to be some "very good" ways of doing this.
I have a custom object called Employee. That object has seven properties like name, phone, email, and so on. There is also a table in my SQL database called tblEmployees with seven columns labeled somewhat similarly. My goal is to "convert" the results from a query to a generic list of Employee objects. What is the best way to do this (lowest overhead, quickest)?
What I am doing currently is something that I've seen proposed all over the web. I don't like it because I feel like it slows down my page loads. Generic lists make me faster at what I do, but I don't feel good about making my customers pay the price.
Here's what I'm doing:
List<Employee> list = new List<Employee>();
DataSet ds = Employee.searchEmployees("Byron");
foreach (DataRow dr in ds.Tables[0].Rows)
{
   list.Add(new Employee(dr));
}

I have a constructor that takes a DataRow (as shown) which handles the 'property = dr["column"]' stuff.
Looking forward to your thoughts.

A: Which part of the process do you feel is slow?  Your methodology doesn't have any glaring performance bottlenecks as far as I can see.

A: I would suggest using an OR Mapper like Linq2SQL or entity framework

A: The reason for building a list is to pass between functions on the server side.
What is the advantage of passing the list as opposed to passing a DataSet reference or even a DataTable?
Those thoughts aside, what you are currently doing is standard procedure for building a list.  How do you think you could speed it up?  By not instancing the Employee object?  You would then have to do without the Employee object which would probably mess with your entity modeling.

A: Briefly looking at the code, and not seeing how it is used, I would return a IEnumerator instead of a list.  You can then use the yield return statement and you won't be looping through the list twice (one to populate and one to display).
so...
protected IEnumerable<Employee> GetEmployees ()
{
   List<Employee> list = new List<Employee>();
   DataSet ds = Employee.searchEmployees("Byron");

   foreach (DataRow dr in ds.Tables[0].Rows)
   {
       yield return new Employee(dr);
   }
}

A: What you are doing now is something that needs to be done one way or another at some point, and you can't really do it significantly faster than the way you have described. But you can reduce the number of times you have to do it at all by caching your data.
Store the list of customers in the cache. Populate it on application start for example. When something changes a customer record you update the cache and save the record to the database. Any reads by any user will go to the cache, not the database.
This approach will usually be an order of magnitude faster than any approach that hits the database.


text:
Q: How to call native iOS function from Flutter using the Pigeon package? I am trying to integrate some native code in my project. For that, I am using the new Pigeon package: https://pub.dev/packages/pigeon
On Android it works just fine but on iOS, whenever I try to call the method written in swift (on button press), it throws a PlatformException(channel-error, Unable to establish connection on channel., null, null)
I've setup the flutter starting project and then I am calling the native methods when the floatingActionButton is pressed. When the native method is executed, it returns a String saying "Hello from Android" on the android side and "Hello from Xcode" on iOS.
main.dart file:
import 'package:flutter/material.dart';
import 'package:platforms/pigeon.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          Api api = Api();
          final searchReply = await api.search(SearchRequest());
          print(searchReply.result);
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

MainActivity.java file:
package com.example.platforms;
import android.os.Bundle;
import io.flutter.embedding.android.FlutterActivity;

public class MainActivity extends FlutterActivity {
    private class Api implements Pigeon.Api {

        @Override
        public Pigeon.SearchReply search(Pigeon.SearchRequest arg) {
            Pigeon.SearchReply searchReply = new Pigeon.SearchReply();
            searchReply.setResult("Hello from Android!");
            return searchReply;
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Pigeon.Api.setup(getFlutterEngine().getDartExecutor().getBinaryMessenger(), new Api());
    }

}

AppDelegate.swift file:
import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate, Api {
    var engine: FlutterEngine = {
        let result = FlutterEngine.init()
        // This could be `run` earlier in the app to avoid the overhead of doing it the first time the
        // engine is needed.
        result.run()
        return result
      }()

    func search(_ input: SearchRequest, error: AutoreleasingUnsafeMutablePointer<FlutterError?>) -> SearchReply? {

        let reply = SearchReply()

        reply.result = "Hello from Xcode!!!!"
        return reply
    }

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    GeneratedPluginRegistrant.register(with: self)
    ApiSetup(engine.binaryMessenger, self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Result of onPressed on Android:

Result of onPressed on iOS:

What's also worth noting is that when I call the code in onPressed in the didChangedDependencies function, the code in swift does run, and the result does show up, but the same exception is then thrown again. Which means that the channel does get created, I am just using it wrong.
When this is added to main.dart
@override
  void didChangeDependencies() async {
    Api api = Api();
    final searchReply = await api.search(SearchRequest());
    print(searchReply.result);
    super.didChangeDependencies();
  }

It prints the result from swift and then throws the same error.

A: I think the BinaryMessenger is getting set incorrectly.
I tried this and it worked:
In the didFinishLaunchingWithOptions method get the rootViewController and cast it as FlutterBinaryMessenger:
let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController
// get binaryMessenger
let binaryMessenger = rootViewController as! FlutterBinaryMessenger

// set binaryMessenger
ApiSetup(binaryMessenger, self)

The complete method becomes like this:
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self);

    let rootViewController : FlutterViewController = window?.rootViewController as! FlutterViewController

    // get binaryMessenger
    let binaryMessenger = rootViewController as! FlutterBinaryMessenger

    // set binaryMessenger
    ApiSetup(binaryMessenger, self)

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }


text:
Q: Fastest way to output very large data to stdout in Java I want to print a lot of data to Stdout in the fastest possible way. One way is that I use a StringBuilder and keep appending the output to it and then print the stringbuffer. But sometimes this fails when the data to be printed is more than the maximum allowable size and gives Memory Limited Exceeded error. (for example in online judges). Is there some other better and faster way to print data?

A: You may try this:
try {
  BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
  //.....
  log.flush();
}

Although writing to a file directly will be more efficient


text:
Q: Rewriting matrix equation into terms of $t$ I have a matrix equation in the form of:
$$
\begin{equation}
\begin{bmatrix}
0       & y_{1} & \cdots                                   & y_{k} \\
y_{1}   &       &                                          &         \\
\vdots  &       & A + t(B + C) + t^2 D                     &         \\
y_{k}   &       &                                          &
\end{bmatrix}
\begin{bmatrix}
\Delta \mu \\
\Delta \alpha_{1} \\
\cdots \\
\Delta \alpha_{k}
\end{bmatrix}
=
-
\begin{bmatrix}
0 \\
(t(B + C) + t^2 D)\boldsymbol{\alpha}
\end{bmatrix}
\end{equation}
$$
where $\Delta \mu$ is a scalar, $\boldsymbol{\alpha}$ and $\Delta \boldsymbol{\alpha}$ are vectors of size $k$, and matrices
$A, B, C, D$ are of size $k\times k$.
I am looking to convert this into something of the following form:
$$
\begin{equation}
\begin{bmatrix}
\Delta \mu \\
\Delta \alpha_{1} \\
\cdots \\
\Delta \alpha_{k}
\end{bmatrix}
=
G
\begin{bmatrix}
1 \\
t \\
t^2
\end{bmatrix}
\end{equation}
$$
I have gone as far as converting the right side of the equation to
$$
-
\begin{equation}
\begin{bmatrix}
0 & 0 \\
(B + C)\boldsymbol{\alpha} & D\boldsymbol{\alpha}
\end{bmatrix}
\begin{bmatrix}
t \\ t^2
\end{bmatrix}
\end{equation}
$$
but I haven't gotten much further with the left side. I especially have trouble getting all terms containing $t$ to the right side, while keeping $\Delta \boldsymbol{\alpha}$ on the left side. Is my problem even possible to solve?


text:
Q: Concatenate JSONArrays I am using JSONArray under the org.json Package.
My first JSONArray is like:

[["249404","VPR249404"],["249403","VPR249403"],["249391","M249391"]]

and Second

[["249386","M249386"],["249385","M249385(I)"],["249384","I249384"]]

So I'd like to append new JSONArray to my first JSONArray.
I am working on Java and Android. I have heard about google-gson library, but I don't know whether it can help me or not but I don't want any other dependency in my Android Application.

A: I would try something like this:
private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
        throws JSONException {
    JSONArray result = new JSONArray();
    for (int i = 0; i < arr1.length(); i++) {
        result.put(arr1.get(i));
    }
    for (int i = 0; i < arr2.length(); i++) {
        result.put(arr2.get(i));
    }
    return result;
}

I don't have a compiler right now to test, but you can give it a try and see if it works (or, at least, it gives you an idea of how to do it).
EDIT
This version could concat multiple arrays (concatArray(arr1, arr2, arr3)):
private JSONArray concatArray(JSONArray... arrs)
        throws JSONException {
    JSONArray result = new JSONArray();
    for (JSONArray arr : arrs) {
        for (int i = 0; i < arr.length(); i++) {
            result.put(arr.get(i));
        }
    }
    return result;
}

A: Use ...
jarray1.addAll(jarray2);

A: try this:
private JSONArray concatArray(@NotNull JSONArray jsArr1, @NotNull JSONArray jsArr2) {
    List<Object> list = jsArr1.toList();
    list.addAll(jsArr2.toList());
    return new JSONArray(list);
}


text:
Q: Trying to use fetch with hooks on a react native project. Error => Invariant Violation: Objects are not valid as a React Child how are you?
I am a newbie trying my best here to develop a simple app where I must use an API to fetch some data about one country.
I am currently trying to figure out how to do this in react native with the use of hooks and the fetch method.
The API I am using: https://restcountries.eu/
Here's the sample code:
import React, {useState, useEffect} from 'react';
import { Text, StyleSheet, View, ActivityIndicator,FlatList } from 'react-native';

const MainInfoScreen = () => {

  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState({});

  useEffect(() => {
    fetch('https://restcountries.eu/rest/v2/callingcode/82')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  });

  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text>{item}</Text>
          )}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({});

export default MainInfoScreen;

And here's the error:
Invariant Violation: Objects are not valid as a React child (found: object with keys {name, topLevelDomain, alpha2Code, alpha3Code, callingCodes, capital, altSpellings, region, subregion, population, latlng, demonym, area, gini, timezones, borders, nativeName, numericCode, currencies, languages, translations, flag, regionalBlocs, cioc}). If you meant to render a collection of children, use an array instead.

To be honest the whole point isn't even trying to list the data in a FlatList, I only wanted to fetch some specific data and place them in variables for using in my application as a means to show i can fetch this from an API.
The ListItem component is only being used as I have tried following another tutorial that worked perfectly with one API, but not the one im using for some reason.
I believe the main reason is that i need to map this data as I believe I may be working with an Array, but again, im not too sure.

A: The warning message is giving you a clue. You can't render an object as a React child. But you can use JSON.stringify() to visualize the object, this way you can figure out what and how you want to render the information contained in that object.
The example below is written in plain React (Stackoverflow cannot render native code). But the functionality is the same.
 would be the equivalent of <View>.

function App() {

  const [ data, setData ] = React.useState(null)

  React.useEffect(() => {
    fetch('https://restcountries.eu/rest/v2/callingcode/82')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
  }, [])

  return (

      {JSON.stringify(data)}

  )
}

ReactDOM.render(<App />, document.getElementById('root'))

So, in your code you would write:
<View>
  <Text>{JSON.stringify(data)}</Text>
</View>


text:
Q: Predictive models to predict sales with r I would like to find a good model to predict which client will buy my product in 2018. I would like to have opinions on which method can fit my data to predict which client will the product A in 2018.
I have the following data:
client buyproductin17 buyproductin16 buyproductin15 all_day  day_cnt product
 22         1               0              1           34      5       2
 23         0               1              1           56      11      2
 24         1               1              1           122     45      3

client = client ID
buyproduct17 = if the client buy the product A in 2017 or not
buyproduct16 = if the client buy the product A in 2016 or not
buyproduct15 = if the client buy the product A in 2015 or not
all_day = total number of day the client spent with all my product
day_cnt = total number of day the client spent with product A
product = total number of product A the client has
My first thought are a logistic regression model or a random forest. But which dependant variable can I use ? buyproductin17 ?
Thanks a lot
Dany


text:
Q: How generate play application with default SBT layout How to create new play application template with default sbt layout?
I can set disablePlugins(PlayLayoutPlugin) in build.sbt on exiting app, but I want generate template from scratch

A: I finally created a Giter8 template specifically for this.
You can do:
sbt new muya/play-sbt-scala-seed.g8

https://github.com/muya/play-sbt-scala-seed.g8

A: Assuming that you are using Activator, you can use the play-sbt-layout-seed template to create an application using the default SBT layout. In order to do that, just run the following command:
activator new your-project-name play-sbt-layout-seed

A: u need to download play zip package as set path in environment variables and from command prompt execute play new YourApplication
https://www.playframework.com/documentation/2.0/NewApplication


text:
Q: Can anyone suggest a faster method for creaing this array? I am creating this array for my shader and this step is very slow as it constitutes a nested for loop. Currently this methos takes approx 1 sec to create this. Can anyone suggest any faster method for creating this array.
import numpy as np

elems = []
b = 23503
a = 24

for i in range(0, a - 1):
    for j in range(0, b - 1):
        elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
        elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

elems = np.array(elems, dtype=np.int32)

A: First I would recognise that there is a lot of repeated computation. The base term involving the iterator variables here is i*b+j, so let's have NumPy create an array that contains those values in the order they should appear:
ib_j = (np.arange(a-1)[:, None]*b + np.arange(b-1)).flatten()

Next we compute the six different columns from this base, stack them horizontally, and flatten:
def create_shader_array(a, b):
    ib_j = (np.arange(a-1)[:, None]*b + np.arange(b-1)).flatten()
    return np.column_stack((ib_j, ib_j+1, ib_j+b, ib_j+b, ib_j+b+1, ib_j+1)).flatten()

Validation:
>>> all(create_shader_array(a, b) == AKS(a, b)) # AKS is your original implementation
True

Timing:
>>> %timeit AKS(24, 23503)
1.02 s ± 8.25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
>>> %timeit create_shader_array(24, 23503)
28.8 ms ± 364 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: You can use meshgrid to cover the i and j iterations and then to an outer add to get the inner shading. Using ravel in the end to get a 1D array.
inner = np.array([0, 1, b, b, b+1, 1], dtype="int32")
j, i = np.meshgrid(np.arange(b-1), np.arange(a-1))
elems = np.add.outer((j+b*i), inner).ravel()

or with a one-liner:
elems = ([0, 1, b, b, b+1, 1]+np.arange(b-1)[:, None]+b*np.arange(a-1)[:,None, None]).ravel()

Finishes in <6ms on my computer
In [9]: %timeit ([0, 1, b, b, b+1, 1]+np.arange(b-1)[:,None]+b*np.arange(a-1)[:
   ...: ,None, None]).ravel()
5.23 ms ± 112 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [10]: %timeit create_shader_array(a, b)
29.8 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


text:
Q: Spinner dropdown item out of screen How to prevent spinner dropdown item beyond the screen? PS scrollable not function.
spinner dropdown item beyond screen users are not able to select more item from spinner.
Found out increase spinner height can solve the problem, but it makes design worse.

<ScrollView>
        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@color/white">
        <Spinner
            android:id="@+id/bank"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="@dimen/normal_text"
            android:textColor="@color/black"
            android:padding="10dp"
            android:forceHasOverlappingRendering="false"
            android:scrollbars="vertical" />
    </LinearLayout>
</ScrollView>

A: You don't need to use a ScrollView. It will automatically scroll if necessary.
Use something like this only:
<Spinner
    android:id="@+id/planets_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

If you follow it exactly like this in this example it will scroll just fine: https://developer.android.com/guide/topics/ui/controls/spinner.html
Basially, take out your ScrollView and LinearLayout. You don't need them.


text:
Q: Add/import javascript library into JSF+Maven project I'm using a javascript library to develop a interface with 3D graphics in a JSF project with Maven and I was wondering if there is a way to add/import this js library into my project without having to move/copy all the js files into the webapp/resources directory. I already tried to do it with the tags  and  within the  tag of the pom.xml file but it didn't work.
The error is produced by this line:
<h:outputScript name="Three.js" />

It says the resource is not found.
Thanks in advance.
EDIT: I'm using JFS 2.1

A: Maven is a tool for among others managing java dependencies, and building your application. It is used to produce a java application. As you understand, JavaScript runs on the client side in a web application, while java runs on the server side. But sometimes Maven can import JS resources as an integral part of a java library. PrimeFaces is one example.
As to the resource management within a JSF application, including JS scripts, you've basically got two ways:

*

*Import external scripts with a plain HTML <script> element. This way you don't need to do any imports and just reference an external to JSF script.

*Import internal scripts with a <h:outputScript>. This way, resources and in particular your scripts, will be imported from within a web application, most possibly, but not necessarily, from within your resources folder. Otherwise, you can access scripts from maven imported artifacts, like PrimeFaces, that include JS resources as well. In this case you need to specify library attribute of <h:outputScript>.

To my knowledge, no java library ships with Three.js included, so your best bet is to either reference an external script, or import it within your JSF project. But if I'm wrong - just go ahead and incude that library via Maven to be able to reference it in your views.


text:
Q: Resize whole app depending on device resolution I've already searched a lot for how to handle different screen sizes. But one thing I couldn't find out:
Is there a possibility just to scale the whole app, instead of the contents? Like you just zoom in the whole app. The iPad does it with iPhone apps, so I think it should be kinda possible.
And - of course - is this possible for iOS and Android Apps?


text:
Q: How to Install Ubuntu 12.04 With Win7 Dual-Boot I had been using Ubuntu for a little while now and I must say very nice a few hardware compatibility issues but that's not why I am here. I have recently uninstalled Ubuntu because I did not feel safe having both OS able to access data from The Same Drive I would like to install Ubuntu on one partition so that its data is kept with that OS on its own partition separate from windows. How can I do this from windows 7 ? I am using a Live CD for installation of Ubuntu. If I am unclear please do say so :)
EDIT: HDD status at the moment is Windows C:\ And System E:\ Both partitions I believe used for my Win 7. HDD is 500gb in total.

A: Not trying to be rude but it is very generic question and if you Google this you will probably find many links with step by step instructions. Try this for example.


text:
Q: Python Spyne custom output parameters I need an output like this in Spyne:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <getActiveServicesResponse xmlns="http://mci.tajmi.ir/">
            <getActiveServicesReturn>12345:2030:hafez poem:hafez </getActiveServicesReturn>
            <getActiveServicesReturn>12346:2031:شعر طنز:tanz </getActiveServicesReturn>
            <getActiveServicesReturn>bardari123:203861:سرویس بارداري :bar
</getActiveServicesReturn>
        </getActiveServicesResponse>
    </soapenv:Body>
</soapenv:Envelope>

What I can generate is
<?xml version='1.0' encoding='UTF-8'?>
<soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="http://mci.tajmi.ir/">
    <soap11env:Body>
        <tns:getActiveServicesResponse>
            <tns:getActiveServicesReturn>
                <tns:string>12345:2030:hafez poem:hafez</tns:string>
                <tns:string>12346:2031:شعر طنز:tanz </tns:string>
                ....
            </tns:getActiveServicesReturn>
        </tns:getActiveServicesResponse>
    </soap11env:Body>
</soap11env:Envelope>

How can I customize the output? I tried complex methods without success.

A: have a look at my code at https://github.com/timi-ro/simulator. you can find how to make it. Also read it:
Spyne - how to duplicate one elements of wsdl file created by spyne?


text:
Q: setActionButton accepts just first pendingIntent When building CustomTabsIntent using builder and setting setActionButton:
new CustomTabsIntent.Builder(getSession())
            .setActionButton(getShareIcon(),
                             "Share text",
                             getShareIntent(),
                             true)
            .build()

Crude implementation of getShareIntent:
@NonNull
private PendingIntent getShareIntent() {
    Intent shareIntent = new Intent(mContext, ShareBroadcastReceiver.class);
    shareIntent.putExtra("extra", someValue);
    return PendingIntent.getBroadcast(mContext, 0, shareIntent, 0);
}

I espect to get the extra's content in my Broadcast receiver. It works but when I rebuild it with different "someValue" I receive the initaial someValue.
Custom Tabs seem to only send the initial intent and ignore the updated intents until the Custom Tab Service is restarted.
The behaviour is not documented. Is it a bug?

A: Here is the problem
@NonNull
private PendingIntent getShareIntent() {
   Intent shareIntent = new Intent(mContext, ShareBroadcastReceiver.class);
   shareIntent.putExtra("extra", someValue);
   return PendingIntent.getBroadcast(mContext, 0, shareIntent, 0);
}

2nd Parameter is the requestCode which should be different for different broadcast
Replace
PendingIntent.getBroadcast(mContext, 0, shareIntent, 0);

with
PendingIntent.getBroadCast(mContext, requestCode , shareIntent, 0}

Generate a different requestCode each time


text:
Q: Need to align four lines of display-style math
I want write this in LaTeX. especially  with the brace on the right-hand side, and the = signs aligned horizontally. so I used align..  This is how it looks like in the output:

I am so desperate right now. every single time, latex doesn't seem to work right and this digitalizing takes more time than it already takes. Here is my code and my packages:
\documentclass[a4paper,10pt]{scrartcl} %Wissenschaftliche längere Arbeit, wie {report} aber als KOMA-Script-Klasse, was erweiterte Funktionen bietet
\usepackage[T1]{fontenc} %führt bei der Kodierung Umlaute zu einem Zeichen zusammen
\usepackage{listings}
\usepackage[utf8]{inputenc} %Zur direkten Eingabe von Umlauten ohne Befehle wie \"a
\usepackage[ngerman]{babel} %Lädt Trennmuster nach neuer deutscher Rechtschreibung
\usepackage{graphicx} %Einbindung von Grafikdateien
\usepackage{amsmath} %Erweiterer Mathemodus
\usepackage{amssymb} %-"-
\usepackage{textcomp} % für µ etc. in Textumgebung
\usepackage{scrpage2} %Zur Einrichtung von Kopf- und Fußzeile
\usepackage{helvet} %Arial
\usepackage{wrapfig} %Für Textunmflossene Grafiken
\usepackage{siunitx} %Eingeben von SI-Einheiten in Textumgebungen
%\usepackage[locale=DE]{siunitx} %Stellt deutsche Ausgabe von SI-Einheiten für Textumgebung ein
\usepackage{hyperref} %Zum anzeigen von HTML-Links
%\usepackage{subfig} %Um mehrere Grafiken via {subfigure} in ein eine {figure}-Umgebung zu tun
\usepackage{caption}
      \usepackage{subcaption}
\usepackage{tikz}%für koordinatensystem zeichnen
\usepackage{mathtools, amssymb}
\usepackage{cancel}%fürs durchstreichen im mathemodus
\begin{document}

\begin{align*}
    g_1: \; \vec{r}(t) &= \vec{r}_1 + t\vec{a}\\
    g_2: \; \vec{r}(s) &= \vec{r}_2 + s\vec{v}\\
    \left \vec{a} \times \vec{b} &\neq 0\\\langle \vec{a} \; \vec{b} \; \overrightarrow{P_1P_2} \rangle &\neq 0 \right\} \Rightarrow (\textrm{windschief})
\end{align*}

\end{document}

I also tested it with an array, but it didn't work, the equation signs weren't among themselves..

A: I suggest you use an rcases environment, provided by the mathtools package, for lines 3 and 4. A separate comment: use \colon, not :, in rows 1 and 2.

\documentclass[a4paper,10pt]{scrartcl}
\usepackage{scrpage2}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage{listings}
\usepackage{graphicx}
\usepackage{mathtools, amssymb}
\usepackage{textcomp}
\usepackage{helvet}
\usepackage{wrapfig}
\usepackage{siunitx}
\usepackage{caption,subcaption}
\usepackage{tikz}
\usepackage{cancel}
\usepackage{hyperref} % load this package last
\begin{document}

\begin{align*}
  &\begin{aligned}
    g_1\colon \vec{r}(t) &= \vec{r}_1 + t\vec{a}\\
    g_2\colon \vec{r}(s) &= \vec{r}_2 + s\vec{v}
   \end{aligned} \\
  &\begin{rcases}
     \vec{a} \times \vec{b} \neq 0\\
     \big\langle \vec{a\mathstrut}\,\vec{b\mathstrut}\,
          \overrightarrow{P_1P_2} \big\rangle \neq 0
   \end{rcases}\Rightarrow (\text{windschief})
\end{align*}
\end{document}

Addendum: If the material to the right of the curly brace on lines 3 and 4 should be typeset flush-right (also known as ragged-left), I suggest you employ an array environment instead of the rcases environment.

% preamble exactly the same as above
\begin{align*}
  &\begin{aligned}
    g_1\colon \vec{r}(t) &= \vec{r}_1 + t\vec{a}\\
    g_2\colon \vec{r}(s) &= \vec{r}_2 + s\vec{v}
   \end{aligned} \\
  &\renewcommand\arraystretch{1.3}
   \kern-2\nulldelimiterspace % adjust spacing at left-hand edge
   \left.\begin{array}{@{}>{\displaystyle}r@{}}
     \vec{a} \times \vec{b} \neq 0\\
     \big\langle \vec{a\mathstrut}\,\vec{b\mathstrut}\,
          \overrightarrow{P_1P_2} \big\rangle \neq 0
   \end{array}\right\}
   \Rightarrow (\text{windschief})
\end{align*}

A: I suggest two other alignment possibilities.  Also, you might be interested by the \vvcommand, from the esvect package, which has nicer arrow tips, in my opinion (7 variants!), and manages indices with \vv*. I used it in the second code:
\documentclass[a4paper,10pt, ngerman]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{textcomp, helvet, old-arrows}
\usepackage[b]{esvect}
\usepackage{babel}
\usepackage{scrpage2}
\usepackage{listings}
\usepackage{graphicx}
\usepackage{mathtools, amssymb}
\usepackage{wrapfig}
\usepackage{siunitx}
\usepackage{caption,subcaption}
\usepackage{tikz}
\usepackage{cancel}
\usepackage{hyperref} % load this package last (exception: cleveref)

\begin{document}

\begin{align*}
    g_1\colon \vec{r}(t) &= \vec{r}_1 + t\vec{a} \\
    g_2\colon \vec{r}(s) &= \vec{r}_2 + s\vec{v} \\
  \begin{rcases}
     \begin{aligned}\vec{a} \times \vec{b} & \neq 0\\
     \big\langle \vec{a\mathstrut}\,\vec{b\mathstrut}\,
            \overrightarrow{P_1P_2} \big\rangle & \neq 0
\end{aligned}
   \end{rcases} & \Rightarrow (\text{windschief})
\end{align*}

\begin{gather*}
  \begin{aligned}
    g_1\colon \vv{r}(t) &= \vv*{r}{\!1} + t\vv{a}\\
    g_2\colon \vv{r}(s) &= \vv*{r}{\!2} + s\vv{v}
   \end{aligned} \\
  \begin{rcases}
     \begin{aligned}\vv{a} \times \vv{b} & \neq 0\\
     \bigl\langle \vv{a\vphantom{b}}\,\vv{b}\,
          \vv*{P_1P\,}{\mkern-5mu 2} \bigr\rangle & \neq 0
\end{aligned}
   \end{rcases}\Rightarrow (\text{windschief})
\end{gather*}

\end{document}


text:
Q: Unable to create binding using current selection and specified binding type I'm currently using Microsoft Office Professional in version 16.0.4266.1001, and it has Word JavaScript API 1.1.
My function addFromSelectionAsync stopped working but I'm sure it worked recently. The result.status is Failed. Here is my code:

And here are error message I get:

Error: Unable to create binding using current selection and specified binding type.

I'm sure Office.BindingType.Text is correct because I'm selecting text in the document


text:
Q: How to run TestNG multiple TestClass using ANT? I am testing my web project using TestNG. In my project, I have 3 test classes with set of @Test methods, say

*

*ClassA

*ClassB

*ClassC

I want to execute all these Test class (they are my TestCases) in sequence. How should i write my testng.xml and build.xml to achieve this ?

A: If u wanna make this Class A, B, C running in a sequence ..
I would suggest u create a ClassD(), then u control the calling sequence of ClassA.method(), ClassB.method(), ClassC.method() inside the ClassD().
@Test shall reside in your ClassD
Your Build.XML shall be configure to
<suite name="xxx" parallel="none">
  <test name="xxx" preserve-order="true">
    <classes>
       <class name="package.ClassD"/>
    </classes>
  </test>
</suite>

A:
//TestNG can use priorities as which order to handle the methods.
import blah; import testng_Annotations;
@BeforeTest
BeforeTestMethod()
@Test (priority=1)
ClassA.method()
@Test (priority=2)
ClassB.method()
@Test(priority=3)
ClassC.method()
@AfterTest
EndTestMethod()

Ensure your testng.xml calls this new java file.


text:
Q: Syntax for wfs-t request I am in need of the correct syntax for performing transaction on WFS layer using OpenLayers. I have gone through many examples on the OpenLayers site and other examples, but can't figure out how to use the necessary and optional options like geometryname, schema etc

A: Try with this example. I am using same codes for my layers and they are working fine. But   be specific in giving SRID.


text:
Q: how to automatically open Shadowbox on window/page load Me using Shadowbox and its working fine.
But I dont like to open it after clicking on image (href), need to open it automatocally on pageload.
What can I change to do it?
Here is HTML

                    Image -1
                    Image -2
                    Image -3
                    Image -4
                    Image -5

And here JavaScript
window.onload = function () {
             loadShadowbox();
         };

function loadShadowbox() {
Shadowbox.init({
            showOverlay: false
        });

        window.Shadowbox.setDimensionsOld = window.Shadowbox.setDimensions;
        window.Shadowbox.setDimensions = function (height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect) {
            var S = window.Shadowbox;
            window.Shadowbox.setDimensionsOld(height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect);
            window.Shadowbox.dimensions.top = 340;
            window.Shadowbox.dimensions.left = 430;
            return window.Shadowbox.dimensions;
        }

A: You atually initialize a Shadowbox on window load, but not opening it. Once done, you end the function loadShadowbox, Instead open the Shadowbox towards the end.
EDIT:
I have modified the code. I actually missed a closed brace.
function loadShadowbox() {
    Shadowbox.init({
        showOverlay: false
    });

    window.Shadowbox.setDimensionsOld = window.Shadowbox.setDimensions;
    window.Shadowbox.setDimensions = function (height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect) {
        var S = window.Shadowbox;
        window.Shadowbox.setDimensionsOld(height, width, maxHeight, maxWidth, topBottom, leftRight, padding, preserveAspect);
        window.Shadowbox.dimensions.top = 340;
        window.Shadowbox.dimensions.left = 430;
        return window.Shadowbox.dimensions;
    }

window.Shadowbox.open();    //Add this line
}  //This is where your `function loadShadowbox()` ends.


text:
Q: Laravel Passport, multiple connexions via password client I am having troubles understanding how could I implement multiple connexions for same user via password client with Laravel Passport:
I have a mobile app, that needs to communicate with a Laravel based API. My users, at first launch of the app, will have to enter their login and password to get an access_token.
So I think that I need to put my password client secret in the code of my mobile app to be able to request tokens. But what if, my user has an iPhone and an iPad and he wants to login from both.
I'm asking because every time I make a request to POST /oauth/token, from the same password_client, every access_token of a certain user requested with my password_client gets revoked.
That would mean that, every time my user would use his iPad, he would be disconnected from his iPhone because the token wouldn't be valid anymore?
Am I missing something?

A: I believe that Passport changed the way it was dealing with the Access Token creation and the method @issueToken in AccessTokenController does no longer revoke old tokens (check Multiple Access Token).
I think that this change was introduced before @jesús-lozano-m answer and therefore there is no longer the need to customize controller.
However, if you want to revoke old tokens, now you can do that by setting a listener to the Passport Event AccessTokenCreated.
app/Providers/eventServiceProvider.php:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {
    protected $listen = [
        'Laravel\Passport\Events\AccessTokenCreated' => [
            'App\Listeners\RevokeOldTokens'
        ]
    ];
    public function boot() {
        parent::boot();
    }
}

app/Listeners/RevokeOldTokens.php:
<?php

namespace App\Listeners;

use Laravel\Passport\Events\AccessTokenCreated;
use Laravel\Passport\Client;
use Carbon\Carbon;

class RevokeOldTokens {
    public function __construct() {
        //
    }
    public function handle(AccessTokenCreated $event) {
        $client = Client::find($event->clientId);
        // delete this client tokens created before one day ago:
        $client->tokens()
                  ->where('user_id', $event->userId)
                  ->where('created_at', '<', Carbon::now()->subDay())
                  ->delete();
    }
}

A: You can write your own Controller and Routes...
Passport has a defined "Laravel\Passport\Http\Controllers\AccessTokenController" and there is a method called "issueToken()".
If you see the method below it calls the function "revokeOtherAccessTokens()", and this deletes or revoke all "access_tokens" using the "Laravel\Passport\TokenRepository"
So what you can do is to write your own controller and prevent to call "revokeOtherAccessTokens()"
The fact that you must keep in mind is that the access tokens will never be pruned or revoked at least that the refresh token became issued or manually delete them.
Refresh tokens and access tokens are revoked when refresh token is issued, because the "League\OAuth2\Server\Grant\RefreshTokenGrant" in method "respondToAccessTokenRequest()", it already revoke old "access_token" and "refresh_token", so we don't have to worry about revoke or delete them in this case.
...
// Expire old tokens
$this->accessTokenRepository->revokeAccessToken($oldRefreshToken['access_token_id']);
$this->refreshTokenRepository->revokeRefreshToken($oldRefreshToken['refresh_token_id']);
...

Here is an sample implementation, hope it helps:

routes:
Route::post('oauth/access_token', 'Auth\OAuth2Controller@issueToken');

customized controller:
<?php

namespace App\Http\Controllers\Auth;

use Laravel\Passport\Http\Controllers\HandlesOAuthErrors;

use Zend\Diactoros\Response as Psr7Response;
use Psr\Http\Message\ServerRequestInterface;
use League\OAuth2\Server\AuthorizationServer;

use App\Http\Controllers\Controller;

class OAuth2Controller extends Controller
{
    use HandlesOAuthErrors;

    /**
     * The authorization server.
     *
     * @var AuthorizationServer
     */
    protected $server;

    /**
     * Create a new controller instance.
     *
     * @param  AuthorizationServer  $server
     * @return void
     */
    public function __construct(AuthorizationServer $server)
    {
        $this->server = $server;
    }

    /**
     * Authorize a client to access the user's account.
     *
     * @param  ServerRequestInterface  $request
     * @return Response
     */
    public function issueToken(ServerRequestInterface $request)
    {
        return $this->withErrorHandling(function () use ($request) {
            return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
        });
    }
}

A: I wirte below mention code in my app/Providers/AuthServiceProvider and its working. It won't removke old token and allow me login from multiple devicess
use Dusterio\LumenPassport\LumenPassport;

public function boot()
{
        $this->setPassportConfiguration();
}

private function setPassportConfiguration(): void
{
        LumenPassport::allowMultipleTokens();
}


text:
Q: Troubleshoot docker Exit on 137 when "OOMKilled": false What I did

*

*Started services on an AlmaLinux server with docker-compose up

*Noticed output of docker-compose logs wasn't changing for a while

*Check docker-compose ps
$ docker-compose ps
              Name                            Command                State     Ports
------------------------------------------------------------------------------------
mysupercoolsystem_api_1           python -m mysupercoolsyste ...   Exit 137
mysupercoolsystem_dev_1           sh -c jupyter lab --ip=0.0 ...   Exit 137
mysupercoolsystem_loader_1        /bin/sh -c python -m mysup ...   Exit 137
mysupercoolsystem_predictor_1     /bin/sh -c python -m mysup ...   Exit 137
mysupercoolsystem_trainer_1       /bin/sh -c python -m mysup ...   Exit 137

$ docker ps -a  # just to confirm
72708f3450   hub.nic.dk/nicecompany/mysupercoolsystem   "/bin/sh -c 'python …"   2 days ago    Exited (137) 2 days ago              mysupercoolsystem_trainer_1
3e286cabb0   jupyter/scipy-notebook:33add21fab64        "sh -c 'jupyter lab …"   2 days ago    Exited (137) 2 days ago              mysupercoolsystem_dev_1
246b87f0ac   hub.nic.dk/nicecompany/mysupercoolsystem   "/bin/sh -c 'python …"   2 days ago    Exited (137) 2 days ago              mysupercoolsystem_predictor_1
7d3297092c   hub.nic.dk/nicecompany/mysupercoolsystem   "python -m mysuperc …"   2 days ago    Exited (137) 2 days ago              mysupercoolsystem_api_1
2a07851f9c   hub.nic.dk/nicecompany/mysupercoolsystem   "/bin/sh -c 'python …"   2 days ago    Exited (137) 2 days ago              mysupercoolsystem_loader_1

*Research whether containers were stopped because of out-of-memory

*

*Checked virtual host: The docker containers run on a single virtual (vcenter-managed) host. The host is allocated 20GB of RAM and vcenter monitor shows RAM usage peaks at ca. 8GB and not more.

*Follow-up: Talked to sysadmin: Servers were not restarted or explicitly asked to terminate any processes.

*docker info | grep Memory returns Total Memory: 19.37GiB

*checked each container with docker inspect <container_id> gives the same "State", apart from the field "FinishedAt" which varies with ±0.05 seconds.

"State": {
  "Status": "exited",
  "Running": false,
  "Paused": false,
  "Restarting": false,
  "OOMKilled": false,
  "Dead": false,
  "Pid": 0,
  "ExitCode": 137,
  "Error": "",
  "StartedAt": "2021-11-13T10:33:04.785566471Z",
  "FinishedAt": "2021-11-13T10:33:57.1xxxxZ"

*Re-examined my docker-compose.yml.

$ cat docker-compose.yml
version: "3"
services:
  dev:
    image: jupyter/scipy-notebook:33add21fab64
    environment:
      - COMPONENT=develop
    volumes:
      - /opt/mysupercoolsystem:/home/jovyan/work
      - /media:/media
    ports:
      - "3333:3333"
    entrypoint: sh -c "jupyter lab --ip=0.0.0.0 --port=3333 --no-browser --allow-root"

  loader:
    image: hub.nic.com/nicecompany/mysupercoolsystem
    working_dir: "/app"
    volumes:
      - /media:/media

  trainer:
    image: hub.nic.dk/nicecompany/mysupercoolsystem
    environment:
      - COMPONENT=train
    working_dir: "/app"
    volumes:
      - models:/models

  predictor:
    image: hub.nic.dk/nicecompany/mysupercoolsystem
    environment:
      - COMPONENT=pred
    working_dir: "/app"
    volumes:
      - models:/models

  api:
    image: hub.nic.dk/nicecompany/mysupercoolsystem
    environment:
      - COMPONENT=api
    working_dir: "/app"
    ports:
      - "69:69"
    entrypoint: python -m mysupercoolsystem.web_api

volumes:
  models:

*Examine Dockerfile. Note: Services that do not have an explicit entrypoint in docker-compose.yml inherit the entrypoint from the Dockerfile.

$ cat mysupercoolsystem/Dockerfile
FROM python:3.8
WORKDIR /app
COPY ./requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app
RUN pip install .
ENTRYPOINT python -m mysupercoolsystem

*Checked similair issue (this issue had --abort-on-container-exit-flag as the culprit. I am not using any flags).

How to proceed

*

*Why are the services exiting?

*What can I do to troubleshoot the error?

*Are there other logs I should be checking?

*If I add restart: unless-stopped on each service, is there any way to examine docker service exits apart from my own logging via docker logs?

A: You can use https://pythonspeed.com/fil/ to debug out-of-memory errors in Python (see https://pythonspeed.com/articles/crash-out-of-memory/).


text:
Q: How to pass array value with an XMLHttpRequest i need to send array parameter or value using XMLHttpRequest
Something like this
$(document).on('click','.save_edit_class',function(){

var crit_name_text = $('#crit_name_text').val();
var crit_desc = $('#crit_desc_text').val();
var sub_crit_arr = [];
$('.sub_crit_text').each(function(k , v){
    sub_crit_arr[k] = $(v).val();

});

var http = new XMLHttpRequest();
var url = "xml_remove_criteria.php";
var params =  "crit_name_text="+crit_name_text+"&crit_desc="+crit_desc+"&sub_crit_arr[]="+sub_crit_arr+"";

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function(){//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200){
        alert(http.responseText);
    }
}
http.send(null);

});

How can i send  the sub_crit_arr(the array) variable to my xml page as array? I'm trying to send using that, but i got an error invalid argument supplied foreach.
This is my xml page..
<?php
session_start();
include("../global.php");
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo '<response>';
    if(isset($_GET['crit_name_text'])){
       $criteria_name = $_GET['crit_name_text'];
       echo $criteria_name;//testing

        if(isset($_GET['crit_desc'])){
            $crit_desc = $_GET['crit_desc'];
            echo $crit_desc;//testing
        }

    if(isset($_GET['sub_crit_arr'])){
        $sub_crit_arr = $_GET['sub_crit_arr'];
        $sub_crit_arrs = array();
        $count = 0;
        foreach ($sub_crit_arr as $value) {
            $sub_crit_arr[$count] = $value;
            echo $sub_crit_arr[$count]." - value<br/>";//testing
            $count++;
        }
    }

   }
   echo '</response>';

?>


text:
Q: Flexbox with fixed width elements I have a pyramid shape of images contained in a Flexbox. It works as expected as long as the width of the images is fixed. If I resize the screen (or change it to a smaller resolution), since it's a Flexbox, the base items (lower row) will have less space and will be shrinked.
I would ideally like to have a dynamic base size for base items (the smaller the screen is, the smaller the items will be), but the items sizes on the rows above should be indexed on the lower row and have the same size.
Here is an example of what I want to achieve: https://codepen.io/Mantequilla_/pen/WNrWBWW
Once the browser is resized (or the resolution too low), the pyramid is malformed (e.g. the upper an item is, the bigger it will be which is unwanted).
Not sure, what I want to achieve is doable in CSS only but I'm open to any suggestions.
Example code for reference:

.row {
  margin: 0 auto;
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
}

.item {
  display: inline-block;
}

img {
  width: 50%;
}

A: You can try using a view width.

A: If the number of row is known or you have a maximum value you can try like below:

:root {
  --r:5; /* number of row */
}
body {
  margin:0;
  text-align:center;
}
.container {
  display:inline-flex;
  flex-direction:column;
}
.row {
  padding:0;
  margin:0 auto;
  display: flex;
  list-style:none;
}
img {
  width: 50%;
}

.row:not(:last-child) {
  width:0;
}

/* you can easily generate the below using SASS/LESS*/
.row:nth-last-child(2) {min-width:calc(100% * (var(--r) - 1)/var(--r));}
.row:nth-last-child(3) {min-width:calc(100% * (var(--r) - 2)/var(--r));}
.row:nth-last-child(4) {min-width:calc(100% * (var(--r) - 3)/var(--r));}
.row:nth-last-child(5) {min-width:calc(100% * (var(--r) - 4)/var(--r));}
.row:nth-last-child(6) {min-width:calc(100% * (var(--r) - 5)/var(--r));}
.row:nth-last-child(7) {min-width:calc(100% * (var(--r) - 6)/var(--r));}
.row:nth-last-child(8) {min-width:calc(100% * (var(--r) - 7)/var(--r));}
.row:nth-last-child(9) {min-width:calc(100% * (var(--r) - 8)/var(--r));}
/*.row:nth-last-child(N) {min-width:calc(100% * (var(--r) - (N-1))/var(--r));}*/

With more rows:

:root {
  --r:7; /* number of row */
}
body {
  margin:0;
  text-align:center;
}
.container {
  display:inline-flex;
  flex-direction:column;
}
.row {
  padding:0;
  margin:0 auto;
  display: flex;
  list-style:none;
}
img {
  width: 50%;
}

.row:not(:last-child) {
  width:0;
}

/* you can easily generate the below using SASS/LESS*/
.row:nth-last-child(2) {min-width:calc(100% * (var(--r) - 1)/var(--r));}
.row:nth-last-child(3) {min-width:calc(100% * (var(--r) - 2)/var(--r));}
.row:nth-last-child(4) {min-width:calc(100% * (var(--r) - 3)/var(--r));}
.row:nth-last-child(5) {min-width:calc(100% * (var(--r) - 4)/var(--r));}
.row:nth-last-child(6) {min-width:calc(100% * (var(--r) - 5)/var(--r));}
.row:nth-last-child(7) {min-width:calc(100% * (var(--r) - 6)/var(--r));}
.row:nth-last-child(8) {min-width:calc(100% * (var(--r) - 7)/var(--r));}
.row:nth-last-child(9) {min-width:calc(100% * (var(--r) - 8)/var(--r));}
/*.row:nth-last-child(N) {min-width:calc(100% * (var(--r) - (N-1))/var(--r));}*/


text:
Q: File permissions denied when unzipped with java application, manually works fine So I have two applications.

*

*1) Launcher application to download client application versions
(v2, v3, v3, etc).

*

*2) A client that the end user uses.

The workflow is basically to open the launcher, and select a client version to run.
ProcessBuilder processBuilder = new ProcessBuilder(revision.getPath() + "/" + AutoUpdate.OSX_EXE);
AutoUpdate.process = processBuilder.inheritIO().start();

The client uses jxBrowser and requires binaries it needs to download/extract. However when I download the .zip and unzip and set file permissions for the executable and run it from within the launcher, it doesn't work.
But when I download the version .zip and unzip it myself and run it without the launcher, it works just fine?
This is a java application compiled into native using excelsiorjet.
This is the error I'm getting:
    Caused by: com.teamdev.jxbrowser.chromium.internal.ChromiumExtractorException: Failed to extract Chromium binaries into /var/folders/kb/f884blms2g56m8xscqnsg9jh0000gn/T/jxbrowser-chromium-60.0.3112.113.6.16
    at com.teamdev.jxbrowser.chromium.internal.ChromiumExtractor.extractChromiumBinariesIfNecessary(Unknown Source)
    at com.teamdev.jxbrowser.chromium.internal.ipc.IPC.<init>(Unknown Source)
    at com.teamdev.jxbrowser.chromium.internal.ipc.IPC.create(Unknown Source)
    at com.teamdev.jxbrowser.chromium.internal.ipc.IPC$a.<clinit>(Unknown Source)
    ... 4 more
Caused by: java.lang.RuntimeException: java.io.IOException: Cannot run program "/var/folders/kb/f884blms2g56m8xscqnsg9jh0000gn/T/jxbrowser-chromium-60.0.3112.113.6.16/7zr-mac": error=13, Permission denied
    at com.teamdev.jxbrowser.chromium.internal.XZExtractor.extract(Unknown Source)
    at com.teamdev.jxbrowser.chromium.internal.b.run(Unknown Source)
    at java.security.AccessController.<unknown>(Unknown Source)
    ... 8 more
Caused by: java.io.IOException: Cannot run program "/var/folders/kb/f884blms2g56m8xscqnsg9jh0000gn/T/jxbrowser-chromium-60.0.3112.113.6.16/7zr-mac": error=13, Permission denied
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at com.teamdev.jxbrowser.chromium.internal.xz.XZ.decompress(Unknown Source)
    ... 11 more
Caused by: java.io.IOException: error=13, Permission denied
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)

Here's my code changing the permissions:
    if(AutoUpdate.OS.equalsIgnoreCase("OSX")){
        File exe = new File(localPath + AutoUpdate.OSX_EXE);
        exe.setReadable(true);
        exe.setExecutable(true);
        exe.setWritable(true);
        File folder = new File(localPath + "rt");
        folder.setReadable(true);
        folder.setExecutable(true);
        folder.setWritable(true);
    }
    else{
        File exe = new File(localPath + AutoUpdate.WINDOWS_EXE);
        exe.setReadable(true);
        exe.setExecutable(true);
        exe.setWritable(true);
        File folder = new File(localPath + "rt");
        folder.setReadable(true);
        folder.setExecutable(true);
        folder.setWritable(true);
    }

A: I got the same issue at the MAC machine through the Build. If I run it through STS/Eclipse it works fine. I used the following:

*

*JRE - jre1.8.0_232_windows (OpenJDK Server VM
Corretto-8.232.09.1) and Corretto-8.232.09.2 at MAC,

*JxBrowser version 7.3,

*MAC 10.14 (Mojave)
I have resolved the issue by giving executable permission to the \lib folder (where my jxBrowser files placed). \bin folders permission code is already there. You can refer to the following code.
if(OSDetector.isMacOSX()) {
    String binPath = new File(new File(lJreVersion, "bin").toString()).getAbsolutePath();
    String libPath = new File(new File(lJreVersion, "lib").toString()).getAbsolutePath();
    logger.info("getSpecifiedJavaExecutable() => " + binPath);
    setExecutable(binPath);
    setExecutable(libPath);
        }

private void setExecutable(String path){
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();
    for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isFile()) {
        System.out.println("File " + listOfFiles[i].getName());
        listOfFiles[i].setExecutable(true);
    } else if (listOfFiles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
    }
}


text:
Q: Passport desrerialization in NodeJs I am working on Login system in Nodejs with Passport,everything is working well but when i hit login it take me to the route i specified in the successRedirect but with an error message
and the error message is the below function .
function deserialized(e, u) {
      pass(i + 1, e, u);
    }

in the console I also get the same message.
handling the request
module.exports.Login=function(req,res,next){
   passport.authenticate('local',{
       successRedirect:'/Dashboard',
       failureRedirect:'/Login',
       failureFlash:true
   })(req,res,next)

   }

passport.js file
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const bodyparser = require('body-parser')
const conn = require('../Model/db');
const flash=require('express-flash')

module.exports = function(passport) {

passport.use(new LocalStrategy({usernameField:'Email'},function(Email,password,done){
 var select=`SELECT * FROM user WHERE email='${Email}'`;
 conn.query(select,(err,user)=>{
     if(err) throw err;
     if(user.length == 0 )
     {

         done(null,false,{message:'incorrect Login Information'})

     }
     else{
         bcrypt.compare(password,user[0].Password,(err,resdb)=>{
             if(err) throw err;
             if(resdb==true){

                 done(null,user,{message:'Successfully loged in'})
             }
             else{

                 done(null,false,{message:'incorrect Login Information'})

           }
         })

     }

 })

}))

passport.serializeUser((user,done)=>{
 done(null,user[0].id)
})

passport.deserializeUser(function(id,err){
 if(err) throw err;
   var select=`SELECT * FROM user WHERE id='${id}'`;
conn.query(select,(err,user)=>{
   done(err,user)
})
})

}

A: Try using this to handle the request:

app.post('/Login', passport.authenticate('local', { successRedirect: 'Dashboard', failureRedirect: '/Login', failureFlash:

And then you can use this to see if user is logged in:
function loggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    next()
  } else {
    res.render('Login.ejs')
  }
}

So:

app.get('/', loggedIn, (req, res) => {
  res.render('Dashboard.ejs', { email: req.user.email })
})


text:
Q: How do you use the font shorthand if your font has a space in it? For instance
@import url('https://fonts.googleapis.com/css?family=Open+Sans');

div {
    font:12px black "Open Sans";
}

Isn't accepted by chrome, using single quotes or no quotes doesn't help either. How do you use the font without writing an extra line for font-family?

A: Actually, the black is what makes that line of CSS invalid. font: 12px "Open Sans"; should work perfectly (and does when I try on Chrome). If you're trying to set font color, do it with the color: black; property.

A: Actually, Chrome doesn't recognise black, not 'Open Sans'. Use the weight measurement instead:

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800');

div {
  font: 800 12px 'Open Sans';
}
<div>
  Some lipsum text right here.
</div>

black is not a recognised value for font:

The font CSS property is either a shorthand property for setting
  font-style, font-variant, font-weight, font-size, line-height and
  font-family, or a way to set the element's font to a system font,
  using specific keywords.

If you wish to set the font colour, you must use color:
div {
  color: #000; /*or color: black;*/
  font: 800 12px 'Open Sans';
}


text:
Q: Core Data Entity Relationship like Array inside Entity? So I am making a todo like app. Now I have made the app I want to add a functionality where each task can have subtasks like:
Task: Book Report
Sub Tasks:
     - Get Information
     - Summarise and Print information
     - Stick information to paper
To clarify I kind of want the core data entity to function as if it were an array.
Now I tried attempting this myself and I did it but what happened was that the when I would add a task and delete the task, the subtasks would still be there.
I am really confused on how I need to setup my entity. Any help is appreciated!
Thanks!

A: You need to create a to-many relationship to another entity and a reciprocal "Inverse" relationship in the child entity.
Check this out:
http://timroadley.com/2012/02/19/core-data-basics-part-4-relationships/
Inverse relationships must be created in the model editor:


text:
Q: Cannot import module after install I have installed a python application with the command python setup.py install from the project folder, but when I execute it from my bash I get the error:

ImportError No module named 'skipgram'

This module is imported directly from the __main__.py file.
The project source is https://github.com/phanein/deepwalk. You can see that in the deepwalk folder there is the file __main__.py, and from there, it imports the Skipgram library.
I am a newbie in python programming, maybe this is a problem concerning some path variable?
PS. My actual setup is: Python 3.5 on anaconda3 on Linux Mint 18.

A: I agree with @erotemic, it seems that line 16 in main.py should be changed to:
from deepwalk.skipgram import Skipgram

you can see a discrepancy in the imports when you note that
graph.py and walks.py are in the same folder as skipgram.py, yet graph and walks are imported like this:
from deepwalk import graph
from deepwalk import walks as serialized_walks


text:
Q: C# DbConnection cast to SqlConnection I found this piece of code in one application
Database database = DatabaseFactory.CreateDatabase("connection string");
DbConnection connection = database.CreateConnection();
connection.Open();
SqlConnection sqlConnection = (SqlConnection)connection;

Is it safe, SqlConnection derieve from DbConnection. Database comes from Microsoft.Practices.EnterpriseLibrary.Data. According to documentation CreteDatabase returns DbConnection.

A: It depends on the databases you are using in your application. From the code you wrote it looks like that only SQL Server is used. If it is so, then you can cast DbConnection to SqlConnection safely. In fact DbConnection is a base class for any other database connection. In your case it is SqlConnection (which is used to work with SQL Server database), also there are different databases like Oracle, Mysql, etc and their providers usually have own classes for connections. So if your app uses another databases or may use in the future it is unsafe to have such cast.

A: No it is not safe, casting is never safe and it may blow anytime while your application is running. While SqlConnection derives indeed from DbConnection you are not guaranteed that database.CreateConnection() will return a SqlConnection as this could be parametrized in the configuration file. Also why do you need to cast to SqlConnection? It is always better to work with classes that are higher in the hierarchy to avoid coupling your code with a specific implementation which will make your code impossible to test in isolation.
While the EnterpriseLibrary does a decently good job in keeping things abstract you are killing everything with this cast. Also you should make sure that disposable resources are always disposed properly. How about this instead:
Database database = DatabaseFactory.CreateDatabase("connection string");
using (var conn = database.CreateConnection())
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT id FROM foo";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            // TODO: work with the results here
        }
    }
}

This way your code is less fragile to database changes in the config file. Well of course you still have this SQL hardcoded and there are ORMs that will take care of this situation. They will also allow you to focus on the real domain of your application instead of wasting time in writing SQL queries and casting from one database provider to another. But for a simple application this is OK.

A: It should be safe as long as you never change the connection string to connect to anything other than a SQL Server Database. If that's ever a possibility, then you should add a little more logic to make things safe:
Database database = DatabaseFactory.CreateDatabase("conn string");

using(DbConnection conn = database.CreateConnection())
{
    if(conn is SqlConnection)
    {
        var sqlConn = conn as SqlConnection;
    }
}

A: You can always do a check and convert it to SqlConnection with C# pattern matching (C# 7.0+)
Database database = DatabaseFactory.CreateDatabase("conn string");

using(DbConnection connection = database.CreateConnection())
{
    if(connection is SqlConnection sqlConnection)
    {
        // do something with sqlConnection
    }
    else
    {
       throw new InvalidOperationException("Connection is not to a SQL Database");
    }
}


text:
Q: Gitlab: how to pause job and resume based on codebuild input? Looking for a way to pause gitlab job and resume based on AWS lambda input.
Due to restrictive permissions in my organization, below is my current CI workflow:

In diagram above, on push event lambda triggers gitlab job through webhook. the gitlab job only gets latest code, zip files and copy to certain s3 bucket. AFTER gitlab job is finished, same lambda then triggers codebuild build which does gets latest zip file from s3 bucket, creates UI chunk files and artifacts are pushed to a different s3 bucket.
### gitlab-ci.yml ###
variables:
  environment: <aws-account-number>

stages:
  - get-latest-code

get-latest-code:
  stage: get-latest-code
  script:
    - zip -r project.zip $(pwd)/*
    - export PATH=$PATH:/tmp/project/.local/bin
    - pip install awscli
    - aws s3 cp $(pwd)/project.zip s3://project-input-bucket-dev
  rules:
  - if: ('$CI_PIPELINE_SOURCE == "merge_request_event"' || '$CI_PIPELINE_SOURCE == "push"')

### lambda code ###
def runner_lambda_handler(event, context):

    cb = boto3.client( 'codebuild' )

    builds_dir = os.environ.get('BUILDS_DIR', '/tmp/project/builds')
    logger.debug("STARTING GIT LAB RUNNER")
    gitlab_runner_cmd = f"gitlab-runner --debug run-single -u https://git.company.com/ -t {token} " \
                        f"--builds-dir {builds_dir} --max-builds 1 " \
                        f"--wait-timeout 900 --executor shell"
    s3_libraries_loader.subprocess_cmd(gitlab_runner_cmd)

    cb.start_build(projectName='PROJECT-Deploy-dev')

    return {
        "statusCode": 200,
        "body": "Gitlab build success."
    }

#### Codebuild Stack ####
codebuild.Project(self, f"Project-{env_name}",
                        project_name=f"Project-{env_name}",
                        role=codebuild_role,
                        environment_variables={
                            "INPUT_S3_ARTIFACTS_BUCKET": {
                                "value": input_bucket.bucket_name
                            },
                            "INPUT_S3_ARTIFACTS_OBJECT": {
                                "value": "project.zip"
                            },
                            "OUTPUT_S3_ARTIFACTS_BUCKET": {
                                "value": output_bucket.bucket_name
                            },
                            "PROJECT_NAME": {
                                "value": f"Project-{env_name}"
                            }
                        },
                        cache=codebuild.Cache.bucket(input_bucket),
                        environment=codebuild.BuildEnvironment(
                            build_image=codebuild.LinuxBuildImage.STANDARD_5_0
                        ),
                        vpc=vpc,
                        security_groups=[codebuild_sg],
                        artifacts=codebuild.Artifacts.s3(
                            bucket=output_bucket,
                            include_build_id=False,
                            package_zip=False,
                            encryption=False
                        ),
                        build_spec=codebuild.BuildSpec.from_object({
                            "version": "0.2",
                            "cache": {
                                "paths": ['/root/.m2/**/*', '/root/.npm/**/*', 'build/**/*', '*/project/node_modules/**/*']
                            },
                            "phases": {
                                "install": {
                                    "runtime-versions": {
                                        "nodejs": "14.x"
                                    },
                                    "commands": [
                                        "aws s3 cp --quiet s3://$INPUT_S3_ARTIFACTS_BUCKET/$INPUT_S3_ARTIFACTS_OBJECT .",
                                        "unzip $INPUT_S3_ARTIFACTS_OBJECT",
                                        "cd project",
                                        "export SASS_BINARY_DIR=$(pwd)",
                                        "npm cache verify",
                                        "npm install",
                                    ]
                                },
                                "build": {
                                    "commands": [
                                        "npm run build"
                                    ]
                                },
                                "post_build": {
                                    "commands": [
                                        "echo Clearing s3 bucket folder",
                                        "aws s3 rm --recursive s3://$OUTPUT_S3_ARTIFACTS_BUCKET/$PROJECT_NAME"
                                    ]
                                }
                            },
                            "artifacts": {
                                "files": [
                                    "**/*.html",
                                    "**/*.js",
                                    "**/*.css",
                                    "**/*.ico",
                                    "**/*.woff",
                                    "**/*.woff2",
                                    "**/*.svg",
                                    "**/*.png"
                                ],
                                "discard-paths": "yes",
                                "base-directory": "$(pwd)/dist/proj"
                            }
                        })
        )

What's needed:
Currently there is a disconnect between gitlab job and codebuild job. I'm looking to find a way to PAUSE gitlab job after all steps are executed. later on codebuild job successful completion I can resume the same gitlab job and mark as done
thanks in advance

A: you need to change gitlab's webhook update part and there by curl you can check the status of other parts.
if their status are not finished pause git push to pushing event

A: You'll need to implement your own logic to wait for the codebuild job you finish, you may use batch-get-builds you check the status.
Check out this, you can have something similar in you gitlab job waiting for the codebuild job to finish

A: You can create a manual job in your pipeline to serve as a pause. Code build can call the GitLab API to run the manual job, allowing the pipeline to continue. That would probably be the most resource-efficient way to handle this scenario.
However you won't be able to resume the same job with this method.
There is no mechanism to 'pause' a job, but you can implement a polling mechanism as suggested in another answer if you really need to keep things in the same job for some reason. However, you will end up consuming more minutes (if using GitLab.com shared runners) or system resources than needed. You may also want to consider your job timeouts if the process takes a long time.


text:
Q: Links in Excel to pages with session_start() and X-Sendfile I have an Excel file with a link in it.  This link points to a remote page http://www.example.com/test.php whose code consists of:
<?php
session_start();

// Irrelevant stuff here which requires sessions
// but which can be removed without affecting whether
// the bug is triggered

header("X-Sendfile: /path/to/pdf/file.pdf");
header("Content-Type: application/pdf");

When this link is clicked in, e.g., LibreOffice, the PDF file opens properly.  However, when it's clicked in Excel (I've tried both 2007 and 2010), I receive the error message "Unable to open http://www.example.com/test.php. Cannot open the specified file."
If I remove the session_start() line, then the PDF file opens.
How can I modify my PHP code so this error isn't triggered anymore?  Or just...what's going on?  Or...help?


text:
Q: Getting all names in an enum as a String[] What's the easiest and/or shortest way possible to get the names of enum elements as an array of Strings?
What I mean by this is that if, for example, I had the following enum:
public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;

    public static String[] names() {
        // ...
    }
}

the names() method would return the array { "NEW", "RUNNABLE", "BLOCKED", "WAITING", "TIMED_WAITING", "TERMINATED" }.

A: Create a String[] array for the names and call the static values() method which returns all the enum values, then iterate over the values and populate the names array.
public static String[] names() {
    State[] states = values();
    String[] names = new String[states.length];

    for (int i = 0; i < states.length; i++) {
        names[i] = states[i].name();
    }

    return names;
}

A: I would write it like this
public static String[] names() {

    java.util.LinkedList<String> list = new LinkedList<String>();
    for (State s : State.values()) {
        list.add(s.name());
    }

    return list.toArray(new String[list.size()]);
}

A: Another ways :
First one
Arrays.asList(FieldType.values())
            .stream()
            .map(f -> f.toString())
            .toArray(String[]::new);

Other way
Stream.of(FieldType.values()).map(f -> f.toString()).toArray(String[]::new);

A: Something like this would do:
public static String[] names() {
  String[] names = new String[values().length];
  int index = 0;

  for (State state : values()) {
    names[index++] = state.name();
  }

  return names;
}

The documentation recommends using toString() instead of name() in most cases, but you have explicitly asked for the name here.

A: Got the simple solution
Arrays.stream(State.values()).map(Enum::name).collect(Collectors.toList())

A: If you can use Java 8, this works nicely (alternative to Yura's suggestion, more efficient):
public static String[] names() {
    return Stream.of(State.values()).map(State::name).toArray(String[]::new);
}

A: i'd do it this way (but i'd probably make names an unmodifiable set instead of an array):
import java.util.Arrays;
enum State {
    NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED;
    public static final String[] names=new String[values().length];
    static {
        State[] values=values();
        for(int i=0;i<values.length;i++)
            names[i]=values[i].name();
    }
}
public class So13783295 {
    public static void main(String[] args) {
        System.out.println(Arrays.asList(State.names));
    }
}

A: My solution, with manipulation of strings (not the fastest, but is compact):
public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;

    public static String[] names() {
        String valuesStr = Arrays.toString(State.values());
        return valuesStr.substring(1, valuesStr.length()-1).replace(" ", "").split(",");
    }
}

A: the ordinary way (pun intended):
String[] myStringArray=new String[EMyEnum.values().length];
for(EMyEnum e:EMyEnum.values())myStringArray[e.ordinal()]=e.toString();

A: Here`s an elegant solution using Apache Commons Lang 3:
EnumUtils.getEnumList(State.class)

Although it returns a List, you can convert the list easily with list.toArray()

A: Here's one-liner for any enum class:
public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}

Pre Java 8 is still a one-liner, albeit less elegant:
public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
}

That you would call like this:
String[] names = getNames(State.class); // any other enum class will work

If you just want something simple for a hard-coded enum class:
public static String[] names() {
    return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");
}

A: With java 8:
Arrays.stream(MyEnum.values()).map(Enum::name)
                    .collect(Collectors.toList()).toArray();

A: I have the same need and use a generic method (inside an ArrayUtils class):
public static <T> String[] toStringArray(T[] array) {
    String[] result=new String[array.length];
    for(int i=0; i<array.length; i++){
        result[i]=array[i].toString();
    }
    return result;
}

And just define a STATIC inside the enum...
public static final String[] NAMES = ArrayUtils.toStringArray(values());

Java enums really miss a names() and get(index) methods, they are really helpful.

A: org.apache.commons.lang3.EnumUtils.getEnumMap(State.class).keySet()

A: I did a bit test on @Bohemian's solution. The performance is better when using naive loop instead.
public static <T extends Enum<?>> String[] getEnumNames(Class<T> inEnumClass){
    T [] values = inEnumClass.getEnumConstants();
    int len = values.length;
    String[] names = new String[len];
    for(int i=0;i<values.length;i++){
        names[i] = values[i].name();
    }
    return names;
}

//Bohemian's solution
public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}

A: Very similar to the accepted answer, but since I learnt about EnumSet, I can't help but use it everywhere. So for a tiny bit more succinct (Java8) answer:
public static String[] getNames(Class<? extends Enum<?>> e) {
  return EnumSet.allOf(e).stream().map(Enum::name).toArray(String[]::new);
}

A: You can get Enum String value by "Enum::name"
public static String[] names() {
    return Arrays.stream(State.values()).map(Enum::name).toArray(String[]::new);
}

This implementation does not require additional "function" and "field". Just add this function to get the result you want.

A: Basing off from Bohemian's answer for Kotlin:
Use replace() instead of replaceAll().
Arrays.toString(MyEnum.values()).replace(Regex("^.|.$"), "").split(", ").toTypedArray()

Side note: Convert to .toTypedArray() for use in AlertDialog's setSingleChoiceItems, for example.

A: If you want the shortest you can try
public static String[] names() {
    String test = Arrays.toString(values());
    return text.substring(1, text.length()-1).split(", ");
}

A: Just a thought: maybe you don't need to create a method to return the values of the enum as an array of strings.
Why do you need the array of strings? Maybe you only need to convert the values when you use them, if you ever need to do that.
Examples:
for (State value:values()) {
    System.out.println(value); // Just print it.
}

for (State value:values()) {
    String x = value.toString(); // Just iterate and do something with x.
}

// If you just need to print the values:
System.out.println(Arrays.toString(State.values()));

A: Try this:
public static String[] vratAtributy() {
    String[] atributy = new String[values().length];
    for(int index = 0; index < atributy.length; index++) {
        atributy[index] = values()[index].toString();
    }
    return atributy;
}

A: Another way to do it in Java 7 or earlier would be to use Guava:
public static String[] names() {
    return FluentIterable.from(values()).transform(Enum::name).toArray(String.class);
}

A: You can put enum values to list of strings and convert to array:
    List<String> stateList = new ArrayList<>();

            for (State state: State.values()) {
                stateList.add(state.toString());
            }

    String[] stateArray = new String[stateList.size()];
    stateArray = stateList.toArray(stateArray);

A: The easiest way:
Category[] category = Category.values();
for (int i = 0; i < cat.length; i++) {
     System.out.println(i  + " - " + category[i]);
}

Where Category is Enum name

A: enum CardType {
    CLUB, DIAMOND, HEART, SPADE;

}

public class Control {
    public static void main(String[] args) {

        String[] cardsArray = new String[CardType.values().length];
        int i = 0;

        for (CardType cardType : CardType.values()){
            cardsArray[i] = cardType.name();
            i++;
        }
        //to output the array
        for (int j = 0; j < CardType.values().length; j++){
            System.out.println(cardsArray[j]);
        }
    }
}

A: You don't need to use the Streams API or the Apache Commons library. Here is arguably the simplest and the fastest way to do this:
public static String[] names() {
    String[] names = new String[State.values().length];
    State[] values = State.values();
    for (int i = 0, valuesLength = values.length; i < valuesLength; i++) {
        names[i] = values[i].toString();
    }
    return names;
}


text:
Q: Gradle Milestone 5 shows error about a missing artifact *#*!*.* How can I resolved this error that I see in Gradle after upgrading to Milestone 5:

:nodes-all:war
:: problems summary ::
:::: ERRORS
    a required artifact is not listed by module descriptor: *#*!*.*

A: I had this problem because I was importing:
compile 'com.googlecode.linkedin-j:linkedin-j:1.0.416'

I should have been importing:
compile 'com.googlecode.linkedin-j:linkedin-j-core:1.0.416'

The difference here is that the first is a parent project not actually containing any jars of its own.  If I downgraded to M3 it didn't spit any warnings on to the screen, but the real fix was to point at the right jar in the Maven repository.

A: It's gone after upgrading to gradle  milestone 6 and after... not sure what caused it. I checked for empty dependencies as Ben suggested but that wasn't it. Anyways... problem some bug that just got fixed.


text:
Q: Why are all my snap directories empty even though I have apps installed there? If I browse to ~/snap all of the directories contained inside are empty. Also, if I ls -a in terminal I get,
intellij-idea-community/current $ sudo ls -la
total 8

But no files?

A: The snap folder under your home directory is not where snaps are installed. It's simply the confined path tree for where those apps are allowed to read/write user data from (barring any exceptions granted by the user).
The actual snaps are in a different system-wide location, and mounted on yet another location for use.

A: Snap files are in /var/lib/snapd/snap/


text:
Q: Updating tiles after creation JSTileMap I'm loading a TMX file of size 32x32 and I want to be able to control the size and images of the sprites generated from JSTileMap after creation.
I am able to change their size but I am unable to get what tile image it is to load the appropriate image.
If someone knows how to edit the code of JSTileMap so that it can load the 2x of my images that would work too.
The method that I am using to retrieve those tiles after creation
for var a = 0; a < Int(tileMap.mapSize.width); a++ {
for var b = 0; b < Int(tileMap.mapSize.height); b++ {
// here I can retrieve the tiles and alter their size but I am unable to differentiate what tile image it is so I can't load the correct image
}}


text:
Q: Port forwarding failure on a Zyxel VMG8324-B10A I'm trying to port forward a TeamSpeak 3 server, I've done this several times before with success. But now I have a new router and it doesn't seem like it wants to play nice. I confirmed that the server is in working order by connecting to it through the local IP Address in advance, for double checking. I can connect through the local IP address, but not the external IP address.
The router model is a Zyxel VMG8324-B10A
The ports are:

*

*9987 (UDP)

*10011 (TCP)

*30033 (TCP)

Note that the first port is the only one that truly matters for connecting to the server.
Local IP Address of the server computer is 192.168.1.39
This is what my attempt looks like (Image)
And I did confirm that VDSL is the active WAN Interface used for my internet connection. There's also IPTV-VDSL in use for Internet TV; other interfaces show no activity.
The one thing I myself notice that I find confusing is that I need to enter two IP addresses, in an older Zyxel router model I once had this wasn't the case—but I tried various combinations without success—I also tried disabling the firewall in the router, I still couldn't connect to the server. The server's firewall is correctly configured, it was working just fine in it's current state on a different router.
What am I doing wrong?
Update: I wasn't doing anything wrong, and the router was not broken either, I will be trying another router soon, and if I run into the same issue, it's an ISP issue.

A: I called my ISP, in this case the WAN IP field was ok to leave empty according to them. They grubbed around a bit and in the end said that the router I was using had to be faulty and we have to exchange it.
We're going to do that, I'll update this answer if it'll work with another router of the same model.
Update: I got a new router of the same model, the same problem occurred again, my ISP's customer support had no clue why. I will try again with another router, it may actually be an ISP issue.
Update2: It worked with another router, I believe this was an ISP issue however, I was living in a relatively remote town, I have no idea what may have caused this, but people living in a more central area with the same ISP and router were not running into this problem. If I recall correctly my friend who lived in the same area also switched to this ISP and experienced the same problems.

A: I had issues with this also but for me making one for each WAN Interface worked. So in total you will have 9 instead of 3. Just make 3 of the exact same rules but change the WAN Interface on each one. You should only have 3 WAN Interface options.

A: I have the vmg8324-b10a and port forwarding works just fine. Make sure you have a recent firmware, V7 or V8, available from https://www.tweak.nl/support/firmware.html
The WAN IP address should be blank as your IP has suggested, otherwise the rules appear fine.
You must be using VDSL for internet, rather than ADSL or Ethernet, as you have the rules configured on the VDSL interface.
The rules are active when the status light is yellow, as yours appear to be. A port will not appear open on the WAN unless there is a service, on your LAN, listening on that port. You can test if they are open by using netcat, or equivalent, to listen on each port and use a port scanner to scan your WAN interface, public, IP address.

A: The WAN ip should be your public facing IP address (see http://www.whatismyip.com)
There could be a few other things such as being behind a second router or CGN, but, try the above first and then we can move on to other issues...


text:
Q: Selecting an Item from a List based on Probabilities and Constraints I have a list of items, and I want to randomly choose one of them. It should be more likely to choose some of these items then others in the list, so each item could have set some kind of probability.
Moreover, some of these items, or better: their probabilities, depend on different constraints. For example, list item A should have a higher probability if variable X is > 1. Or list item B should have a probability of 0 (i.e. must not be chosen) if variable Z is true.
Now, I assume the simplest approach would be to define the probability for each item and store it in a ma, or two arrays, or something like that. But is that really the best approach, are there alternatives? How would I link those constraints to the random selection and probabilities?

A: Maybe represent your data as a Feature tree?
http://www.cs.bris.ac.uk/~flach/mlbook/materials/mlbook-beamer.pdf
See slide 26.

A: You can "weight" each item and total up the weights. Then generate a random number between 1 and the total of the weights. Then find the item that matches that random number. Here are the steps:
Step 1: Calculate the points (or weight) of each and then total up all of the points.
    Item RunningTotal
     A        5        -- 5 points
     B        6        -- 1 point
     C        6        -- 0 points
     D        8        -- 2 points
-------------------------------------
    TOTAL                 8 points

Step 2: Use your language's random number function to generate a random number between 1 and the total points.  Something like:
int match = Math.Random(1, 8); -- 8 is the total of the points.

Step 3: Find the item that matches the random number.
int runningTotal = 0;
int index;

for(index = 1; index < Items.Count(); index++)
{
    if(Items[index].Points == 0)
        continue;

    runningTotal += Items[index].Points;

    if(runningTotal >= match)
       break;
}

return Items[index];   // the winner


text:
Q: Are there any alternatives to the "echo" command? is there a command other than "echo" that can be used to display text to the terminal, in bash?
preferably one that can output to any point in the terminal.

A: Maybe tput is what you're looking for. For example you could create a little menu like so:
#!/bin/bash

# clear the screen
tput clear

# Move cursor to screen location X,Y (top left is 0,0)
tput cup 3 15

# Set a foreground colour using ANSI escape. Not sure this works on OSX
tput setaf 3

# Set reverse video mode
tput rev
echo "S U S H I  M E N U  I T E M S"
tput sgr0

tput cup 5 17
echo "Please select an option"
tput sgr0

tput cup 7 15
echo "1. Sushi Sashimi Combo"

tput cup 8 15
echo "2. Omakase"

tput cup 9 15
echo "3. Chirashi"

tput cup 10 15
echo "4. Eel and Avacado Roll"

# Set bold mode
tput bold
tput cup 12 15
read -p "Enter your choice [1-4] " choice

tput clear
tput sgr0
tput rc

echo "You chose $choice"


text:
Q: How can I play .SWF in a Java Application? Could anyone tell me how to play a SWF file inside a Java application or does anyone know of a free plugin to do this?

A: You can also look at JFlashPlayer. http://www.jpackages.com/jflashplayer/
I have only played around with it a little, but it does have a developer license fee.

A: Maybe you can try JSwiff . I never used it myself but it seems quite useful plus it is open source ;)


text:
Q: Perl: Uploading a file from a web page I am trying to upload a file from a web page without using:
my $query = CGI->new;
my $filename = $query->param("File");
my $upload_filehandle = $query->upload("File");

My form has several input fields and only one of them is a file name.  So when I parse the form I parse all of the input fields in one pass.  This means that I have the filename withough using my $filename = $query->param("File"); but, as far as I can tell, this means I can't use my $upload_filehandle = $query->upload("File"); to do the actual uploading.
Any advice is appreciated.
Regards.

A: How are you parsing the input fields?  More importantly why are you using CGI and reimplementing some of its functionality?
This should still work:
my %args              = how_you_are_parsing_the_url();
my $query             = CGI->new;               #this parses the url as well
my $upload_filehandle = $query->upload("File"); #assuming the input is named File


text:
Q: "Could not find transactional storage type" error with embedded RavenDB I was able to successfully run a simple test for RavenDB based on the code found at: http://ravendb.net/tutorials/hello-world
Next I tried to run it in an Embedded Manner, but I keep on getting the following error:
Message: Could not find transactional storage type: Raven.Storage.Esent.TransactionalStorage, Raven.Storage.Esent
StackTrace:    at Raven.Database.Config.InMemoryRavenConfiguration.CreateTransactionalStorage(Action notifyAboutWork) in c:\Builds\raven\Raven.Database\Config\InMemoryRavenConfiguration.cs:line 272
   at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration) in c:\Builds\raven\Raven.Database\DocumentDatabase.cs:line 109
   at Raven.Client.Client.EmbeddableDocumentStore.InitializeInternal() in c:\Builds\raven\Raven.Client.Embedded\EmbeddableDocumentStore.cs:line 130
   at Raven.Client.Document.DocumentStore.Initialize() in c:\Builds\raven\Raven.Client.Lightweight\Document\DocumentStore.cs:line 388
   at Tests.RavenEmbedded.RavenDB..ctor() in C:\Users\Pranav\Documents\Projects\Repositories-Clone\Common-clone\Tests\RavenDB.cs:line 114
   at Tests.TestRavenDB.Basics() in C:\Users\Pranav\Documents\Projects\Repositories-Clone\Common-clone\Tests\RavenDB.cs:line 170

Setup:
Target framework is .NET Framework 4
I added the following References to my project:

*

*\RavenDB-Build-309\EmbeddedClient\Raven.Client.Embedded.dll

*\RavenDB-Build-309\Client\Raven.Client.Lightweight.dll

*\RavenDB-Build-309\EmbeddedClient\Raven.Storage.Esent.dll

*\RavenDB-Build-309\EmbeddedClient\Raven.Storage.Managed.dll

The code is:

namespace Tests.RavenEmbedded
{
    using Raven.Client.Client;
    using Raven.Client.Document;
    using Raven.Storage.Esent;
    using Raven.Storage.Managed;
    using Tests.RavenData;

    class RavenDB
    {
        public RavenDB()
        {
            // EmbeddableDocumentStore store = new EmbeddableDocumentStore { DataDirectory = @"C:\Temp\RavenData" };
            //Raven.Storage.Esent.TransactionalStorage
            var store = new EmbeddableDocumentStore  { DataDirectory = @"C:\Temp\RavenData" };
            store.Initialize();

            #region Write Data
            using (var session = store.OpenSession())
            {
                var product = new Product
                {
                    Cost = 3.99m,
                    Name = "Milk",
                };
                session.Store(product);
                session.SaveChanges();

                session.Store(new Order
                {
                    Customer = "customers/ayende",
                    OrderLines =
                      {
                          new OrderLine
                          {
                              ProductId = product.Id,
                              Quantity = 3
                          },
                      }
                });
                session.SaveChanges();
            }
            #endregion

            #region Read Data
            using (var session = store.OpenSession())
            {
                var order = session.Load("orders/1");
                Debug.Print("Customer: {0}", order.Customer);
                foreach (var orderLine in order.OrderLines)
                {
                    Debug.Print("Product: {0} x {1}", orderLine.ProductId, orderLine.Quantity);
                }
                session.SaveChanges();
            }

            #endregion

        }
    }
}

namespace Tests
{
    public class TestRavenDB
    {
        public static void Basics()
        {
            try
            {
                //var db = new RavenClientServer.RavenDB();
                var db = new RavenEmbedded.RavenDB();
            }
            catch (Exception ex)
            {

                Debug.Print("Message: {0} ",ex.Message);
                Debug.Print("StackTrace: {0} ",ex.StackTrace);

            }
        }

    }
}

I have tried searching for this for a few days and tried a few different variations too.  I am not sure what's going on.

A: You need to add a reference to Raven.Storage.Esent.dll

A: Thanks to Ayende Rahien on groups.google.com/group/ravendb/topics.
The solution was to add "Raven.Storage.Esent" reference to the main project.  It's an issue with Visual Studio and indirect references.
Thanks @Derek for suggesting that I post there.
-- Pranav


text:
Q: How to truncate end of SKU in Magento on frontend? What I'm seeking to do is display the SKU of a product on the frontend of my Magento cart, which is working accurately with this code:
<?php echo $this->htmlEscape($_product->getSku()) ?>

However, what I need to do in addition to this is truncate the last character returned when the SKU is loaded on the front end.  How can I achieve this with PHP, what code can I use to accomplish this, and how would I insert it into this string to truncate the last character from the output?
Thanks for any help in advance! :]

A: To truncate the last character in a string call substr with -1 for the second parameter.
 <?php echo $this->htmlEscape(substr($_product->getSku(), 0, -1)) ?>