text:
Q: Update a UDF where I know in advance the cells that will possibly change the result, but that are not direct parameters I have a UDF that calculates the carry-over of growth over a year. That is for instance, at the second quarter of the year, the yearly growth rate if the growth in the third and fourth quarters is null. In this case, I would need the growth or the fourt quarters of the previous year and the two first quarters of the current year.
This is not very hard to compute or to program. To be easily accessible, the people to whom it is destined have largely favoured that only the last observed point should be an input of the function. Other input is the number of quarters of observed data I have.  In this case it would be CarryOver(C16,2)
With this way of doing, if another past value changes, it does not update my UDF. I can force that by using Application.Volatile but first it does not seem to work if the value used is based on a formula that refers to another sheet.
And more fundamentally, I can calculate in advance which cells will be used with the two inputs (cell of the last data, number of quarters I have, so in this case : C11:C16) so there might be a way to tell Excel to calculate this UDF each time one of the values in the implied cells change, which would be better that the volatile option. Is that doable ?
EDIT : the core of my UDF would be :
Public Function CarryOver(DerniereDonneeDure As Range, AcquisAuMoment_T_plus_X As Integer)

Dim Trim As Double
Trim = 100
        Ligne = DerniereDonneeDure.Row - AcquisAuMoment_T_plus_X + 1
        Colonne = DerniereDonneeDure.Column
        For i = -4 To -1
            Trim = Trim * (1 + Cells(Ligne + i, Colonne).Value)
            Ecoule = Ecoule + Trim
        Next
        For j = 0 To AcquisAuMoment_T_plus_X - 1
            Trim = Trim * (1 + Cells(Ligne + j, Colonne).Value)
            Encours = Encours + Trim
        Next
        For j = AcquisAuMoment_T_plus_X To 3
            Encours = Encours + Trim
        Next
    Acquis = Encours / Ecoule - 1

End Function


text:
Q: Why do I have to put the project name when importing tasks when using Django with Celery? I just installed and configured Celery with RabbitMQ for a Django project and I was having an issue running tasks when I imported them like so:
from someapp.tasks import SomeTask

It worked when I added the project name:
from myproject.someapp.tasks import SomeTask

I tried adding this into the settings.py file but it doesn't change anything:
CELERY_IMPORTS = ("myproject.someapp.tasks",)

I'm fine with leaving the project name on the import line since it works but I'd like to know if there's a way around it or why it has to be that way.

A: It's probably because you have
INSTALLED_APPS = ("myproject.someapp", )

Instead you should add the directory containing the apps on the Python path (the project in
this case), and simply do
INSTALLED_APPS = ("someapp", )

IMHO this makes more sense for an "app" anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the simplest way to create python flask swagger I have written python program with some flask rest logic, and I want to know what is the easiest way to create flask swagger from it? I saw many tutorials with different packages but in my opinion they include too much manual work. Is there a package which does in 1 or 2 steps?

A: I don't think there are any fully automated approaches that you can just apply after-the-fact.
I suspect that for Flask the best you can do is something like Flask-RESTPlus. But there are, as you say, others.
Side note: I have myself switched from using Flask to using FastAPI instead, partly because it has OpenAPI specification (a.k.a Swagger) support built in, but it has some other nifty features too.


text:
Q: Inserting posts into a UICollectionView grid? Need some guidance on how to approach this. I'm not sure if I'm completely over complicating it or if it is a mess.
I've got a UICollectionView that I want to always have 9 cells and I'm wanting users to be able to insert posts by tapping on a cell..so if they press on cell 8, they make their post, and it shows up there in the 8th cell with potentially 8 other empty cells around it.
I'm posting/pulling these posts from firebase...so I was thinking the flow needed to look something like:
1) Make an empty array of 9 empty [Posts] so that the cells appear and are clickable.
2) On the firebase observer .. if there are say 3 posts able to be returned, it inserts them into the post array / replaces 3 empty posts.
3) I want the posts to show up sort of randomly throughout the grid, so I figured I'd shuffle the array before reloading the data?
4) I don't really care if the posts back from firebase are in the same spot as they were placed by the user, but I want when a user puts a post for it to stay in the same spot as they placed it, so I figured I'd save a variable to firebase like "position : 8" and I'd say something like "If your user uid = the uid of the post, grab the position number and insert that post at that index of the array.
Is this flow way off base or is there a better way to accomplish this? I haven't seen much about inserting items into certain positions into a table view/collection view.
Edit:
func fillWithBlanks() {
        for i in 0  ..< 9 {

            let blankPost = Post(timestamp: 99999999999999999, picURL: nil, postKey: "") // 100% need a better timestamp there, just filler for now.

            postsArray.append(blankPost)

        }
    }

and then
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").queryStartingAtValue(cutoff).observeEventType(.ChildAdded, withBlock: { (snapshot:FIRDataSnapshot) in

    let time = snapshot.value!["timestamp"] as? Int
    let text = snapshot.value!["text"] as? String
    let picURL = snapshot.value!["imageURL"] as? String
    let key = snapshot.key

    let post = Post(timestamp: time!, picURL: picURL!, postKey: key)

    self.postsArray[self.selectedPostIndex] = post

    self.collectionView.reloadData()

})

So basically on viewDidLoad I'm calling fillWithBlanks(), and then when I select a cell I set the selectedPostIndex to the index clicked on, create a post, and insert it in where I selected.
This works and I tested it by printing out the cell's timestamp when I press on it, and sure enough when I make a post the timestamp is appropraite to the post and not the 99999999.
My massive issue I'm having are the pictures. When I load up I get 9 cells that are empty but when I make a post it sets the picture I set for the post to all 9 cells, and then if I make 2 posts, I get a very Simon-says'ie flashing in all of my cells between the first picture, second picture, and the blank background from the blank cell.
When I make a post I'm saving a download url to firebase and then I have a caching system that downloads the posts or grabs them in. It all worked before trying to implement the blank posts.
Any ideas what would be causing that? I don't understand why appending a new post would do anything to the blank posts I'm making when the app loads up. I'm assuming I'm having some misunderstanding with classes and my Post array/ Post objects aren't what they need to be.

Edit 2:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let post = postsArray[indexPath.row]

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MainCell", forIndexPath: indexPath) as! PostCell

    if let imageURL = post.picURL {

        cell.cellImage.loadImageUsingNSCache(imageURL)

    }

    return cell

}

and the .loadimagesUsingNSCache comes from :
extension UIImageView {

func loadImageUsingNSCache(urlString: String){

    if let cachedImage = imageCache.objectForKey(urlString) as? UIImage {
        self.image = cachedImage
        return
    }
        let url = NSURL(string: urlString)
        NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) in

            if error != nil {
                print(error)
                return
            }
            dispatch_async(dispatch_get_main_queue(), {

                if let downloadedImage = UIImage(data: data!) {

                    imageCache.setObject(downloadedImage, forKey: urlString)

                    self.image = UIImage(data: data!)
                }

            })

        }).resume()
    }

A: About the problem with the images, remember collection view cells are reusable items, so you need to tell what's the content of every item inside every time you call collectionView(cellForItemAtIndexPath).
That means you need to provide a value for cell.cellImage every time, even if post.picURL is nil. In that case you can say cell.cellImage = nil or show a default empty picture.


text:
Q: AWS Connect API - Creating contact flow I am trying to create a contact flow in my connect instance and keep getting the following issue when trying to use the aws cli.
An error occurred (InvalidRequestException) when calling the CreateContactFlow operation: Invalid request

Here is the command im trying to run
aws connect create-contact-flow --instance-id 1d27d5a7-9101-4314-9bad-ad6b0df45d02 --type CONTACT_FLOW --name uki_dtc_test --content "{`"Version`":`"2019-10-30`",`"StartAction`":`"a2243fda-4f0d-4519-9cc7-c4b56f67a8c0`",`"Metadata`":{`"entryPointPosition`":{`"x`":20,`"y`":20},`"snapToGrid`":false,`"ActionMetadata`":{`"daa98067-59f9-4a7b-b628-df4fab712f4e`":{`"position`":{`"x`":802,`"y`":5},`"useDynamic`":false,`"ContactFlow`":{`"id`":`"arn:aws:connect:us-east-1:553243264439:instance/1d27d5a7-9101-4314-9bad-ad6b0df45d02/contact-flow/c5a6ed55-bacb-4a50-a45b-6167cf15449f`",`"text`":`"UKIAfterCallSurveyMainMenu`"}},`"d264e0c2-b926-4032-a105-184d7f2cc74b`":{`"position`":{`"x`":581,`"y`":22},`"useDynamic`":false},`"192e2e35-b42a-423b-8aff-90ff20ee2e52`":{`"position`":{`"x`":1029,`"y`":50}},`"a2243fda-4f0d-4519-9cc7-c4b56f67a8c0`":{`"position`":{`"x`":235,`"y`":34},`"useDynamic`":false,`"queue`":{`"id`":`"arn:aws:connect:us-east-1:553243264439:instance/1d27d5a7-9101-4314-9bad-ad6b0df45d02/queue/e46b202b-585e-4468-b406-bb319da83a1f`",`"text`":`"TestSurvey`"}},`"840faec3-893c-4e60-9ab5-460ef5a6e611`":{`"position`":{`"x`":466,`"y`":311}}}},`"Actions`":[{`"Identifier`":`"daa98067-59f9-4a7b-b628-df4fab712f4e`",`"Parameters`":{`"ContactFlowId`":`"arn:aws:connect:us-east-1:553243264439:instance/1d27d5a7-9101-4314-9bad-ad6b0df45d02/contact-flow/c5a6ed55-bacb-4a50-a45b-6167cf15449f`"},`"Transitions`":{`"NextAction`":`"192e2e35-b42a-423b-8aff-90ff20ee2e52`",`"Errors`":[{`"NextAction`":`"192e2e35-b42a-423b-8aff-90ff20ee2e52`",`"ErrorType`":`"NoMatchingError`"}],`"Conditions`":[]},`"Type`":`"TransferToFlow`"},{`"Identifier`":`"d264e0c2-b926-4032-a105-184d7f2cc74b`",`"Transitions`":{`"NextAction`":`"daa98067-59f9-4a7b-b628-df4fab712f4e`",`"Errors`":[{`"NextAction`":`"daa98067-59f9-4a7b-b628-df4fab712f4e`",`"ErrorType`":`"NoMatchingError`"},{`"NextAction`":`"daa98067-59f9-4a7b-b628-df4fab712f4e`",`"ErrorType`":`"QueueAtCapacity`"}],`"Conditions`":[]},`"Type`":`"TransferContactToQueue`"},{`"Identifier`":`"192e2e35-b42a-423b-8aff-90ff20ee2e52`",`"Type`":`"DisconnectParticipant`",`"Parameters`":{},`"Transitions`":{}},{`"Identifier`":`"a2243fda-4f0d-4519-9cc7-c4b56f67a8c0`",`"Parameters`":{`"QueueId`":`"arn:aws:connect:us-east-1:553243264439:instance/1d27d5a7-9101-4314-9bad-ad6b0df45d02/queue/e46b202b-585e-4468-b406-bb319da83a1f`"},`"Transitions`":{`"NextAction`":`"840faec3-893c-4e60-9ab5-460ef5a6e611`",`"Errors`":[{`"NextAction`":`"192e2e35-b42a-423b-8aff-90ff20ee2e52`",`"ErrorType`":`"NoMatchingError`"}],`"Conditions`":[]},`"Type`":`"UpdateContactTargetQueue`"},{`"Identifier`":`"840faec3-893c-4e60-9ab5-460ef5a6e611`",`"Parameters`":{`"FlowLoggingBehavior`":`"Enabled`"},`"Transitions`":{`"NextAction`":`"d264e0c2-b926-4032-a105-184d7f2cc74b`",`"Errors`":[],`"Conditions`":[]},`"Type`":`"UpdateFlowLoggingBehavior`"}]}"

A: Try escaping the double quotes within the json string.


text:
Q: Scala Spark setting schema duplicates columns I have an issue when specifying the schema of my dataframe. Without setting the schema, printschema() produces:
root
 |-- Store: string (nullable = true)
 |-- Date: string (nullable = true)
 |-- IsHoliday: string (nullable = true)
 |-- Dept: string (nullable = true)
 |-- Weekly_Sales: string (nullable = true)
 |-- Temperature: string (nullable = true)
 |-- Fuel_Price: string (nullable = true)
 |-- MarkDown1: string (nullable = true)
 |-- MarkDown2: string (nullable = true)
 |-- MarkDown3: string (nullable = true)
 |-- MarkDown4: string (nullable = true)
 |-- MarkDown5: string (nullable = true)
 |-- CPI: string (nullable = true)
 |-- Unemployment: string (nullable = true)

However, when i specify the schema with .schema(schema)
val dfr = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").schema(schema)

My printschema() produces:
root
 |-- Store: integer (nullable = true)
 |-- Date: date (nullable = true)
 |-- IsHoliday: boolean (nullable = true)
 |-- Dept: integer (nullable = true)
 |-- Weekly_Sales: integer (nullable = true)
 |-- Temperature: double (nullable = true)
 |-- Fuel_Price: double (nullable = true)
 |-- MarkDown1: double (nullable = true)
 |-- MarkDown2: double (nullable = true)
 |-- MarkDown3: double (nullable = true)
 |-- MarkDown4: double (nullable = true)
 |-- MarkDown5: double (nullable = true)
 |-- CPI: double (nullable = true)
 |-- Unemployment: double (nullable = true)
 |-- Dept: integer (nullable = true)
 |-- Weekly_Sales: integer (nullable = true)
 |-- Temperature: double (nullable = true)
 |-- Fuel_Price: double (nullable = true)
 |-- MarkDown1: double (nullable = true)
 |-- MarkDown2: double (nullable = true)
 |-- MarkDown3: double (nullable = true)
 |-- MarkDown4: double (nullable = true)
 |-- MarkDown5: double (nullable = true)
 |-- CPI: double (nullable = true)
 |-- Unemployment: double (nullable = true)

The dataframe itself has all these duplicate columns, and i'm not sure why.
My code:
// Make cutom schema
val schema = StructType(Array(
       StructField("Store", IntegerType, true),
       StructField("Date", DateType, true),
       StructField("IsHoliday", BooleanType, true),
       StructField("Dept", IntegerType, true),
       StructField("Weekly_Sales", IntegerType, true),
       StructField("Temperature", DoubleType, true),
       StructField("Fuel_Price", DoubleType, true),
       StructField("MarkDown1", DoubleType, true),
       StructField("MarkDown2", DoubleType, true),
       StructField("MarkDown3", DoubleType, true),
       StructField("MarkDown4", DoubleType, true),
       StructField("MarkDown5", DoubleType, true),
       StructField("CPI", DoubleType, true),
       StructField("Unemployment", DoubleType, true)))

val dfr = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").schema(schema)
val train_df = dfr.load("/FileStore/tables/train.csv")
val features_df = dfr.load("/FileStore/tables/features.csv")

// Combine the train and features
val data = train_df.join(features_df, Seq("Store", "Date", "IsHoliday"), "left")
data.show(5)
data.printSchema()

A: It's working as expected. Your train_df, features_df have the same columns  as schema (14 columns) after your load().
After your join condition , Seq("Store", "Date", "IsHoliday") takes thes 3 columns from the both DFs(total 3+3 =6 columns) and join it and gives one set of columns names(3 columns). But rest of columns will be from both train_df(rest 11 columns), features_df(rest 11 columns).
Hence you printSchema showing 25 columns(3 + 11 + 11).


text:
Q: Keep a check whether a value if selected from dropdown list using PHP I need to keep a check on whether a value is selected by the user from the dropdown box other than the default value which is at null position. If selected (any value other than default ) then I want to set a variable say $varSet = 1 and if not $varSet = 0, so depending on the $varSet value, I try to trigger the appropiate functions from my PHP script.
Is it possible to achieve this using only PHP and HTML without any Javascript(client side)? Or is there any other possibilty to get this logic going?

A: Let's assume that you have form with method="POST" and action="script.php". Form would have select tag (I assume that is what you call dropdown list):
<select name="dropdown">
  <option value="">Default value (key thing is leaving value="")</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

And script.php would read value of dropdown list and check if default value is checked:
if($_POST['dropdown'] != '') {
  //do something
} else {
  //user leaved default value for dropdown, tell him that:
  echo "Please select valid value from dropdown list";
}

A: Here is the simple easy solution to check either dropdown value is selected already if yes then show the selected with selected='selected' else nothing....
<select class="form-control" name="currency_selling" required >
         <option value="">Select Currency</option>
         <option value="pkr" <?=$selected_currency == 'pkr' ? ' selected="selected"' : '';?> >PKR</option>
      <option value="dollar"  <?=$selected_currency == 'dollar' ? ' selected="selected"' : '';?> >USD</option>
      <option value="pounds"  <?=$selected_currency == 'pounds' ? ' selected="selected"' : '';?> >POUNDS</option>
      <option value="dirham"  <?=$selected_currency == 'dirham' ? ' selected="selected"' : '';?> >DRHM</option>
      </select>


text:
Q: Xpages dojo listTextBox vertical stack? How do I stack items in a djListTextBox field to line up vertically instead of horizontally? They don't even break cleanly between values when it comes to the boundaries of the cell or panel .
I saw a solution HERE, but this solution claims that values displayed in djextListTextBox are surrounded by span and a tags, and therefore I can put some css on it (e.g. "verticalStack"), but the html I get is this without any span tags around each item:
<input type="text" dojoType="extlib.dijit.ListTextBox" msep="^^"
class="verticalStack" id="view:_id1:_id2:OneUIMainAreaCallback:NAICSCodes"
name="view:_id1:_id2:OneUIMainAreaCallback:NCodes" value="Oilseed^^Apple
Orchards^^Synthetic Dye">

A: This solution works for OneUI themes on 9.0.1:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
    xmlns:xp="http://www.ibm.com/xsp/core"
    xmlns:xe="http://www.ibm.com/xsp/coreex">
    <xp:this.beforePageLoad><![CDATA[#{javascript:
        sessionScope.test = ["aaa", "bbb", "ccc"]
    }]]></xp:this.beforePageLoad>
    <xp:this.resources>
        <xp:styleSheet
            href="/yourCssFile.css"></xp:styleSheet>
    </xp:this.resources>
    <xe:djextListTextBox
        id="djextListTextBox1"
        value="#{sessionScope.test}">
    </xe:djextListTextBox>
</xp:view>

with CSS file
.lotusInlineList span {
    display: block;
    margin-left: 0px !important;
}

.lotusInlineList a span {
    display: inline;
}


text:
Q: Kubernetes: How to get disk / cpu metrics of a node Without using Heapster is there any way to collect like CPU or Disk metrics about a node within a Kubernetes cluster?
How does Heapster even collect those metrics in the first place?

A: Kubernetes monitoring is detailed in the documentation here, but that mostly covers tools using heapster.
Node-specific information is exposed through the cAdvisor UI which can be accessed on port 4194 (see the commands below to access this through the proxy API).
Heapster queries the kubelet for stats served at <kubelet address>:10255/stats/ (other endpoints can be found in the code here).
Try this:
$ kubectl proxy &
Starting to serve on 127.0.0.1:8001
$ NODE=$(kubectl get nodes -o=jsonpath="{.items[0].metadata.name}")
$ curl -X "POST" -d '{"containerName":"/","subcontainers":true,"num_stats":1}' localhost:8001/api/v1/proxy/nodes/${NODE}:10255/stats/container
...

Note that these endpoints are not documented as they are intended for internal use (and debugging), and may change in the future (we eventually want to offer a more stable versioned endpoint).
Update:
As of Kubernetes version 1.2, the Kubelet exports a "summary" API that aggregates stats from all Pods:
$ kubectl proxy &
Starting to serve on 127.0.0.1:8001
$ NODE=$(kubectl get nodes -o=jsonpath="{.items[0].metadata.name}")
$ curl localhost:8001/api/v1/proxy/nodes/${NODE}:10255/stats/summary
...

A: I would recommend using heapster to collect metrics. It's pretty straight forward. However, in order to access those metrics, you need to add "type: NodePort" in hepaster.yml file. I modified the original heapster files and you can found them here. See my readme file how to access metrics. More metrics are available here.
Metrics can be accessed via a web browser by accessing http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/cpu/usage_rate. The Same result can be seen by executing following command.
$ curl -L http://heapster-pod-ip:heapster-service-port/api/v1/model/metrics/cpu/usage_rate


text:
Q: Is there a way to specify the encoding of a PowerShell script Is there a way to mark the encoding of a PowerShell script within the script (much like Perl's use utf8)?
When googling about that, I only find recommendations that change the default encoding globally or for the session which is not what I want or need because I have a script that contains utf-8 strings and I want to make sure that they're treated or understood as such.
If this is not possible, I'd like to specify the encoding of the script at the time when I execute it.


text:
Q: Хранение данных полученных с сайта Есть порядка 15-20 json файлов. Через Retrofit получаю эти данные в коллекции и вывожу в RecyclerView в различных фрагментах и активити. У меня такой вопрос. Как лучше организовать хранение и отображение этих данных?
Вот я получил парсингом json данные и загнал их в коллекции (получаю данные сразу не со всех 15-20 json файлов, а какого-нибудь одного в зависимости от того какое активити или фрагмент открывается). Как дальше лучше организовать вывод и хранение?
Или можно каждый раз при открытии актвиити/фрагмента получать данные из json? Прошу заметить я не прошу писать какой-то код, а лишь спрашиваю про процесс организации хранения и вывода данных

A: Как правило делают так, получаете данные с сервера, сохраняете в БД и от туда достаете и показываете в ресайклере. Такой подход обеспечит "кеширование", то есть при старте приложения выводите данные из БД, а не идете на сервак за ними, тем самым пользователь намного раньше увидит инфу. Параллельно (в другом потоке) идете на сервак и проверяете актуальность данных, если надо, снова пишите в БД и показываете в списке.


text:
Q: Why URL re-writing is not working when I do not use slash at the end? I have a simple ingress configuration file-
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /link2/link3/
  name: tut-ingress
  namespace: default
spec:
  rules:
    - host: tutorial.com
      http:
        paths:
          - path: /link1/
            pathType: Prefix
            backend:
              service:
                name: nginx-ingress-tut-service
                port:
                  number: 8080

in which requests coming to /link1 or /link1/ are rewritten to
/link2/link3/.
When I access it using http://tutorial.com/link1/
I am shown the correct result but when I access it using
http://tutorial.com/link1, I get a 404 not found.

The nginx-ingress-tut-service has the following endpoints-

*

*/

*/link1

*/link2/link3
I am a beginner in the web domain, any help will be appreciated.
When I change it to-
- path: /link1

it starts working fine, but can anybody tell why is it not working with /link1/.
Helpful resources -
https://kubernetes.io/docs/concepts/services-networking/ingress/#examples
https://kubernetes.github.io/ingress-nginx/examples/rewrite/
Edit- Please also explain what happens when you write a full HTTP link in
nginx.ingress.kubernetes.io/rewrite-target

A: The answer is posted in the comment:

Well, /link1/ is not a prefix of /link1 because a prefix must be the same length or longer than the target string

If you have
- path: /link1/

the string to match will have to have a / character at the end of the path. Everything works correctly. In this situation if you try to access by the link http://tutorial.com/link1 you will get 404 error, because ingress was expecting  http://tutorial.com/link1/.
For more you can see examples of rewrite rule and documentation about path types:

Each path in an Ingress is required to have a corresponding path type. Paths that do not include an explicit  pathType  will fail validation. There are three supported path types:

*

*ImplementationSpecific: With this path type, matching is up to the IngressClass. Implementations can treat this as a separate  pathType  or treat it identically to  Prefix  or  Exact  path types.

*Exact: Matches the URL path exactly and with case sensitivity.

*Prefix: Matches based on a URL path prefix split by  /. Matching is case sensitive and done on a path element by element basis. A path element refers to the list of labels in the path split by the  /  separator. A request is a match for path  p  if every  p  is an element-wise prefix of  p  of the request path.

EDIT:
Based on documentation this should work, but it looks like there is a fresh problem with nginx ingress. The problem is still unresolved. You can use workaround posted in this topic or try to change your you similar to this:
- path: /link1(/|$)


text:
Q: Unable to convert .mp3 to .m4a using ffmpeg I am fully aware the legal constraints in using libfaac but this is just for my testing purpose.
I have compiled ffmpeg with faac enabled. So when I tried to convert an .mp3 to a .m4a here is the error that I am getting. Please provide a resolution to this problem. I tried it on two different sources of .mp3, still I am getting the same error.
[user@ip-10-161-13-26 ~]$ ffmpeg  -i Kalimba.mp3 -c:a libfaac Kalimba.m4a
ffmpeg version 0.11.1 Copyright (c) 2000-2012 the FFmpeg developers
  built on May  4 2013 09:33:27 with gcc 4.4.6 20120305 (Red Hat 4.4.6-4)
  configuration: --enable-libfaac --enable-nonfree --disable-yasm
  libavutil      51. 54.100 / 51. 54.100
  libavcodec     54. 23.100 / 54. 23.100
  libavformat    54.  6.100 / 54.  6.100
  libavdevice    54.  0.100 / 54.  0.100
  libavfilter     2. 77.100 /  2. 77.100
  libswscale      2.  1.100 /  2.  1.100
  libswresample   0. 15.100 /  0. 15.100
[mp3 @ 0x2464680] Header missing
[mp3 @ 0x2463100] max_analyze_duration 5000000 reached at 5015510
[mp3 @ 0x2463100] Estimating duration from bitrate, this may be inaccurate
Input #0, mp3, from 'Kalimba.mp3':
  Metadata:
    publisher       : Ninja Tune
    track           : 1
    album           : Ninja Tuna
    artist          : Mr. Scruff
    album_artist    : Mr. Scruff
    title           : Kalimba
    genre           : Electronic
    composer        : A. Carthy and A. Kingslow
    date            : 2008
  Duration: 00:05:50.60, start: 0.000000, bitrate: 191 kb/s
    Stream #0:0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s
    Stream #0:1: Video: mjpeg, yuvj420p, 512x512, 90k tbr, 90k tbn, 90k tbc
    Metadata:
      title           : thumbnail
      comment         : Cover (front)
Output #0, ipod, to 'Kalimba.m4a':
  Metadata:
    publisher       : Ninja Tune
    track           : 1
    album           : Ninja Tuna
    artist          : Mr. Scruff
    album_artist    : Mr. Scruff
    title           : Kalimba
    genre           : Electronic
    composer        : A. Carthy and A. Kingslow
    date            : 2008
    Stream #0:0: Video: none, q=2-31, 128 kb/s, 90k tbn
    Metadata:
      title           : thumbnail
      comment         : Cover (front)
    Stream #0:1: Audio: none, 0 channels, 128 kb/s
Stream mapping:
  Stream #0:1 -> #0:0 (mjpeg -> ?)
  Stream #0:0 -> #0:1 (mp3 -> libfaac)
Encoder (codec none) not found for output stream #0:0

MP3 file is at http://db.tt/HtpEBpFU
Also while using Faac independently I get this weird error for any file.
Freeware Advanced Audio Coder
FAAC 1.28

Couldn't open input file sample.mp3

A: The problem is that your input contains album artwork, which ffmpeg parses as video.
Stream #0:0: Audio: mp3, 44100 Hz, stereo, s16, 192 kb/s
Stream #0:1: Video: mjpeg, yuvj420p, 512x512, 90k tbr, 90k tbn, 90k tbc

It tries to convert the video, but doesn't find a valid output codec for the MPEG-4 format (M4A is just another name). This is because you compiled ffmpeg without libx264, which ffmpeg needs in that case, as it doesn't have a native H.264 encoder.
Anyway, you need to prevent it from trying to convert the artwork/video. Add -vn to the options:
ffmpeg  -i Kalimba.mp3 -c:a aac -vn Kalimba.m4a

Some tips:

*

*FAAC is not supported by ffmpeg anymore. Use the built-in AAC encoder instead.

*Encoding to .aac works because the output format cannot contain video, so ffmpeg won't try to convert the video/artwork stream in the first place.


text:
Q: On Click of an item in a recycler adapter in a fragment, display a custom popup I have a recycler view adapter inside a fragment.
On click of the items in the adapter, I want to display a custom popup.
Following is the code for the same
In onBindViewHolder:
holder.profileImageView.setOnLongClickListener(view -> {

            PopupWindow optionPopUp;

            View rootView = ((Activity)context).getWindow().getDecorView().findViewById(R.id.board_info_id);
            LinearLayout v = rootView.findViewById(R.id.owner_options_popup);

            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View layout = layoutInflater.inflate(R.layout.owner_options_for_admin_or_user_popup, v);

            int[] location = new int[2];

            view.getLocationOnScreen(location);

            //Initialize the Point with x, and y positions
            Point point = new Point();
            point.x = location[0];
            point.y = location[1];

            // Displaying the popup at the specified location, + offsets.

            optionPopUp = new PopupWindow(context);
            optionPopUp.setContentView(layout);
            optionPopUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
            optionPopUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            optionPopUp.setFocusable(true);

            //Clear the default translucent background
            optionPopUp.setBackgroundDrawable(new BitmapDrawable());

            // Displaying the popup at the specified location, + offsets.
            optionPopUp.showAtLocation(layout, Gravity.NO_GRAVITY, point.x , point.y );

            return true;
        });

On the line
View rootView = ((Activity)context).getWindow().getDecorView().findViewById(R.id.board_info_id);

I am getting the following error
cannot be cast to android.app.Activity
Can anyone point out what is wrong in what I'm doing?


text:
Q: why Error:(2) No resource identifier found for attribute 'shortcutShortLabel' in package 'android' when creating shourtcut in Android7? When I create a shortcut refer to the developer.android.com,
the code I wrote is below
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
    android:enabled="true"
    android:icon="@drawable/share"
    android:shortcutId="search"
    android:shortcutShortLabel="@string/recommend_us"
    android:shortcutLongLabel="@string/recommend_to_friend"
    android:shortcutDisabledMessage="@string/bind_unbound">
    <intent
        android:action="android.intent.action.VIEW"
        android:targetPackage="com.example.myapplication"
        android:targetClass="com.yidian.news.ui.search.SearchChannelActivity" />
</shortcut>
<!-- Specify more shortcuts here. -->

A simple one. But when I build the project, here comes out error message says
Error:(2) No resource identifier found for attribute 'shortcutId' in package 'android'
Error:(2) No resource identifier found for attribute 'shortcutShortLabel' in package 'android'
Error:(2) No resource identifier found for attribute 'shortcutLongLabel' in package 'android'
Error:(2) No resource identifier found for attribute 'shortcutDisabledMessage' in package 'android'
why is that
have upgrade all Android SDK & tools

A: Shortcuts require Android 7.1 . ie, API level 25


text:
Q: Determine from JWT generated by Keycloak if a user is authorized to access specific resource Keycloak docs on OpenID Connect states that

The access token is digitally signed by the realm and contains access
information (like user role mappings) that the application can use to
determine what resources the user is allowed to access on the
application.

Is it possible to determine from the access token returned by Keycloak after authentication what resources a user is allowed to access?
Following the keycloak quickstart's instructions on Obtaining an OAuth2 Access Token, i get the following JWT (with not relevant fields ommitted) :
{
  "aud": "app-authz-springboot",
  "sub": "9c6c4a66-bb14-420f-a8af-3b2771266b38",
  "typ": "Bearer",
  "azp": "app-authz-springboot",
  "realm_access": {
    "roles": [
      "user"
    ]
  },
  "resource_access": {},
  "preferred_username": "alice"
}

There's an empty field

resource_access

Is there any way to fill it with the resources a user has access to? What's the specification of this field? Couldn't find it in JWT RFC or OpenID Connect Spec
I attempted another way that worked:

*

*Obtaining the access token using password credentials flow

*Exchanging the obtained token for rpt with slight
modification adding response_mode argument:
curl -v -X POST \
  http://localhost:8180/auth/realms/spring-boot-quickstart/protocol/openid-connect/token \
  -H "Authorization: Bearer "$access_token \
  --data "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket" \
  --data "audience=app-authz-rest-springboot" \
  --data "permission=Default Resource"
  --data "response_mode=decision"

However this solution requires dispatching 2 requests to Keycloak to determine if a user is allowed a specific resource.

A: Your usage scenario is not clear. The standard mechanism to control access to specific resources is roles and you do get them as a part of the token. So if you configure access to your endpoints using appropriate roles model and assign required roles to the corresponging users, it will control the access. Actually this is the way access to the /api/premium URL is managed in the SpringBoot example that you referencing in your question (compare access by alice vs jdoe).
From your question as it is now, it is not clear why such approach doesn't work for you and why you want something else.


text:
Q: Padrão de projeto ou práticas recomendadas para lidar com arquivos em disco virtual Existe padrão ou práticas recomendadas para lidar com envio, armazenamento, publicação de arquivos e controle de acesso?
Exemplo de ambiente:
Tenho um sistema que precisará que possui cadastro de Atendimentos e Notícias e em ambos preciso permitir inserção de anexos e depois liberá-los para download ou visualização no browser conforme possível (pdf, txt, em alguns casos arquivos do office).
Também terei uma área para publicação direta, onde os arquivos serão submetidos para um diretório "virtual" selecionado pelo usuário, determinados grupos de usuários terão acesso à esses diretórios e arquivos, outros não.
Também serão disponibilizados para download e/ou visualização em browser quando possível.
Existem padrões ou práticas recomendadas para lidar com esse tipo de necessidade?
Um detalhe importante é que não será feito o controle de acesso por usuário de um domínio. Serão usuários do sistema somente.

A:
Algumas das práticas citadas abaixo são de outras perguntas do Stack Overflow, e algumas são minhas, por empirismo. Não há um guia de boas práticas da Microsoft. Essa resposta deve servir como um bom guia de boas práticas, o qual pretendo ir atualizando conforme novas questões devam ir aparecendo.

Existe padrão ou práticas recomendadas para lidar com envio, armazenamento, publicação de arquivos e controle de acesso?
Envio

*

*Faça seus Controllers manipularem todo e qualquer arquivo recebido;

*Procure usar sempre formulários e a decoração [HttpPost] nas Actions do seu Controller;

*Procure limitar tamanhos e tempos de envio;

Armazenamento

*

*Para envios de arquivos pelos usuários, evite diretórios em que possa ser feito o acesso direto por link, como o diretório Content, por exemplo. Use um diretório inacessível externamente;

*Se for separar por usuário, evite usar o nome do usuário para a nomenclatura dos diretórios;

*Ao receber um arquivo, mude seu nome antes de salvá-lo. Isso garante alguma segurança se alguém tentar explorar os problemas de segurança de sua aplicação usando o nome original do arquivo;

*Antes de salvar, se for um arquivo de imagem, procure redimensionar o arquivo. Se alguma coisa falhar neste redimensionamento, pode não ser exatamente uma imagem que o usuário enviou;

*Antes de salvar, verifique se o MIME Type do arquivo é de fato correspondente ao conteúdo dele;

Publicação

*

*Jamais deixe seus usuários acessarem diretamente seus arquivos no caso de um Download. Forneça ao usuário um link para uma Action que devolva um FileResult;

*Ainda sobre os links, não forneça um arquivo com um link facilmente dedutível, como por exemplo uma ID inteira (http://meusitemaroto/Arquivos/1) ou então o nome do arquivo (http://meusitemaroto/Arquivos/MinhaImagem1, http://meusitemaroto/Arquivos/MinhaImagem2). Gere uma string aleatória que funcione como token ou use Guids;

Controle de Acesso

*

*Seguindo a linha anterior, faça sua Action verificar o acesso através de Attributes. Pode ser o bom e velho [Authorize] ou um atributo de autorização implementado por você. Há diversas questões aqui no SOpt em que ensino a fazer isso;

*Evite permitir downloads se o usuário não estiver autenticado. Se isso não for possível, valide cada download usando tokens de autorização e contadores de download, ou até mesmo expirando o arquivo depois de um tempo.


text:
Q: Function similar to group_by when groups are not mutually exlcusive I would like to create a function in R, similar to dplyr's group_by function, that when combined with summarise can give summary statistics for a dataset where group membership is not mutually exclusive. I.e., observations can belong to multiple groups. One way to think about it might be to consider tags; observations may belong to one or more tags which might overlap.
For example, take R's esoph dataset (https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/esoph.html) documenting a case-control study of esophageal cancer. Suppose I'm interested in the number and proportion of cancer cases overall and per 'tag', where the tags are: 65+ years old; 80+ gm/day alcohol; 20+ gm/day tobacco; and a 'high risk' group where the previous 3 criteria are met.
Let's transform the dataset to long format (one participant per row) and then add these tags (logical columns) to the dataset:
library('dplyr')
data(esoph)
esophlong = bind_rows(esoph %>% .[rep(seq_len(nrow(.)), .$ncases), 1:3] %>% mutate(case=1),
                      esoph %>% .[rep(seq_len(nrow(.)), .$ncontrols), 1:3] %>% mutate(case=0)
            ) %>%
            mutate(highage=(agegp %in% c('65-74','75+')),
                   highalc=(alcgp %in% c('80-119','120+')),
                   hightob=(tobgp %in% c('20-29','30+')),
                   highrisk=(highage & highalc & hightob)
            )

My usual approach is to create a dataset where each observation is duplicated for every tag it belongs to, and then summarise this dataset:
esophdup = bind_rows(esophlong %>% filter(highage) %>% mutate(tag='age>=65'),
                     esophlong %>% filter(highalc) %>% mutate(tag='alc>=80'),
                     esophlong %>% filter(hightob) %>% mutate(tag='tob>=20'),
                     esophlong %>% filter(highrisk) %>% mutate(tag='high risk'),
                     esophlong %>% filter() %>% mutate(tag='all')
           ) %>%
           mutate(tag=factor(tag, levels = unique(.$tag)))

summary = esophdup %>%
          group_by(tag) %>%
          summarise(n=n(), ncases=sum(case), case.rate=mean(case))

This approach is inefficient for large datasets or for a large number of tags and I will often run out of memory to store it.
An alternative is to summarise each tag separately and then bind these summary datasets afterwards, as follows:
summary.age = esophlong %>%
              filter(highage) %>%
              summarise(n=n(), ncases=sum(case), case.rate=mean(case)) %>%
              mutate(tag='age>=65')

summary.alc = esophlong %>%
              filter(highalc) %>%
              summarise(n=n(), ncases=sum(case), case.rate=mean(case)) %>%
              mutate(tag='alc>=80')

summary.tob = esophlong %>%
              filter(hightob) %>%
              summarise(n=n(), ncases=sum(case), case.rate=mean(case)) %>%
              mutate(tag='tob>=20')

summary.highrisk = esophlong %>%
              filter(highrisk) %>%
              summarise(n=n(), ncases=sum(case), case.rate=mean(case)) %>%
              mutate(tag='high risk')

summary.all = esophlong %>%
              summarise(n=n(), ncases=sum(case), case.rate=mean(case)) %>%
              mutate(tag='all')

summary=bind_rows(summary.age,summary.alc,summary.tob,summary.highrisk,summary.all)

This approach is time-consuming and tedious when I have a large number of tags or I want to reuse the tags often for different summary measures throughout a project.
The function I have in mind, say group_by_tags(data, key, ...), which includes an argument to specify the name of the grouping column, should work something like this:
summary = esophlong %>%
          group_by_tags(key='tags',
                        'age>=65'=highage,
                        'alc>=80'=highalc,
                        'tob>=20'=hightob,
                        'high risk'=highrisk,
                        'all ages'=1
          ) %>%
          summarise(n=n(), ncases=sum(case), case.rate=mean(case))

with the summary dataset looking like this:
> summary
       tags     n ncases case.rate
1   age>=65   273     68 0.2490842
2   alc>=80   301     96 0.3189369
3   tob>=20   278     64 0.2302158
4 high risk    11      5 0.4545455
5       all  1175    200 0.1702128

Even better, it could take variables of type "factor" as well as "logical" so that it could summarise, say, each age group individually, the 65+ year olds, and everybody:
summaryage = esophlong %>%
          group_by_tags(key='Age.group',
                        agegp,
                        '65+'=(agegp %in% c('65-74','75+')),
                        'all'=1
          ) %>%
          summarise(n=n(), ncases=sum(case), case.rate=mean(case))

>summaryage
  Age.group     n ncases case.rate
1     25-34   117      1 0.0085470
2     35-44   208      9 0.0432692
3     45-54   259     46 0.1776062
4     55-64   318     76 0.2389937
5     65-74   216     55 0.2546296
6       75+    57     13 0.2280702
7       65+   273     68 0.2490842
8       all  1175    200 0.1702128

Perhaps it's not possible with ... and instead you might need to pass a vector/list of column names for the tags.
Any ideas?
EDIT: to be clear, the solution should take tag/group definitions and the required summary statistics as arguments, rather than being built into the function itself. Either as a two-step data %>% group_by_tags(tags) %>% summarise_tags(stats) or a one-step data %>% summary_tags(tags,stats) process.

A: This is a variation on @eddi's answer. I am taking the definitions of highage et al as part of the function's job:
library(data.table)
custom_summary = function(DT, tags, stats){
    setDT(DT)
    rows = stack(lapply(tags[-1], function(x) DT[eval(x), which=TRUE]))
    DT[rows$values, eval(stats), by=.(tag = rows$ind)]
}

And some example usage:
data(esoph)
library(dplyr)
esophlong = bind_rows(esoph %>% .[rep(seq_len(nrow(.)), .$ncases), 1:3] %>% mutate(case=1),
                      esoph %>% .[rep(seq_len(nrow(.)), .$ncontrols), 1:3] %>% mutate(case=0)
            )

custom_summary(
    DT = esophlong,
    tags = quote(list(
        'age>=65'   = agegp %in% c('65-74','75+'),
        'alc>=80'   = alcgp %in% c('80-119','120+'),
        'tob>=20'   = tobgp %in% c('20-29','30+'),
        'high risk' = eval(substitute(`age>=65` & `alc>=80` & `tob>=20`, as.list(tags))),
        'all ages'  = TRUE
    )),
    stats = quote(list(
        n           = .N,
        n_cases     = sum(case),
        case.rate   = mean(case)
    ))
)

         tag    n n_cases case.rate
1:   age>=65  273      68 0.2490842
2:   alc>=80  301      96 0.3189369
3:   tob>=20  278      64 0.2302158
4: high risk   11       5 0.4545455
5:  all ages 1175     200 0.1702128

The technique of using eval inside DT[...] is explained in the data.table FAQ.

A: Not a completely functional answer, more "WIP" or start for discourse. This should ultimately go in a repo and either an additional package or a PR for dplyr.
One way is to mimic the attributes' structure from a "normally" grouped variable:
library(dplyr)
esoph %>% group_by(agegp, alcgp) %>% attributes %>% str
# List of 9
#  $ names             : chr [1:5] "agegp" "alcgp" "tobgp" "ncases" ...
#  $ row.names         : int [1:88] 1 2 3 4 5 6 7 8 9 10 ...
#  $ class             : chr [1:4] "grouped_df" "tbl_df" "tbl" "data.frame"
#  $ vars              :List of 2
#   ..$ : symbol agegp
#   ..$ : symbol alcgp
#  $ drop              : logi TRUE
#  $ indices           :List of 24
#   ..$ : int [1:4] 0 1 2 3
#   ..$ : int [1:4] 4 5 6 7
#   ..$ : int [1:3] 8 9 10
#   ...........
#  $ group_sizes       : int [1:24] 4 4 3 4 4 4 4 3 4 4 ...
#  $ biggest_group_size: int 4
#  $ labels            :'data.frame':   24 obs. of  2 variables:
#   ..$ agegp: Ord.factor w/ 6 levels "25-34"<"35-44"<..: 1 1 1 1 2 2 2 2 3 3 ...
#   ..$ alcgp: Ord.factor w/ 4 levels "0-39g/day"<"40-79"<..: 1 2 3 4 1 2 3 4 1 2 ...
#   ..- attr(*, "vars")=List of 2
#   .. ..$ : symbol agegp
#   .. ..$ : symbol alcgp
#   ..- attr(*, "drop")= logi TRUE

We can reproduce this artificially to see if/how it might work:
esoph2 <- esoph
syms <- list(as.symbol("agegp65"), as.symbol("alcgp80"))
attr(esoph2, "vars") <- syms
attr(esoph2, "drop") <- TRUE
# 'agegp' and 'aclgp' are ordered factors, for simplicity here just using ints
# `group_by` indices are 0-based
indices <- list(
  which(as.integer(esoph2$agegp) >= 5) - 1,
  which(as.integer(esoph2$alcgp) >= 3) - 1
)
attr(esoph2, "indices") <- indices
attr(esoph2, "group_sizes") <- lengths(indices)
attr(esoph2, "biggest_group_size") <- max(lengths(indices))
df <- data.frame(agegp65 = "agegp >= 65", alcgp80 = "alcgp >= 80", stringsAsFactors = FALSE)
attr(df, "vars") <- syms
attr(esoph2, "labels") <- df
class(esoph2) <- c("grouped_df", "tbl_df", "tbl", "data.frame")

Which "looks" like a normal grouped data.frame:
str(esoph2)
# Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame':   88 obs. of  5 variables:
#  $ agegp    : Ord.factor w/ 6 levels "25-34"<"35-44"<..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ alcgp    : Ord.factor w/ 4 levels "0-39g/day"<"40-79"<..: 1 1 1 1 2 2 2 2 3 3 ...
#  $ tobgp    : Ord.factor w/ 4 levels "0-9g/day"<"10-19"<..: 1 2 3 4 1 2 3 4 1 2 ...
#  $ ncases   : num  0 0 0 0 0 0 0 0 0 0 ...
#  $ ncontrols: num  40 10 6 5 27 7 4 7 2 1 ...
#  - attr(*, "vars")=List of 2
#   ..$ : symbol agegp65
#   ..$ : symbol alcgp80
#  - attr(*, "drop")= logi TRUE
#  - attr(*, "indices")=List of 2
#   ..$ : num  62 63 64 65 66 67 68 69 70 71 ...
#   ..$ : num  8 9 10 11 12 13 14 23 24 25 ...
#  - attr(*, "group_sizes")= int  26 42
#  - attr(*, "biggest_group_size")= int 42
#  - attr(*, "labels")='data.frame':    1 obs. of  2 variables:
#   ..$ agegp65: chr "agegp >= 65"
#   ..$ alcgp80: chr "alcgp >= 80"
#   ..- attr(*, "vars")=List of 2
#   .. ..$ : symbol agegp65
#   .. ..$ : symbol alcgp80
esoph2
# Source: local data frame [88 x 5]
# Groups: agegp65, alcgp80 [2]
#    agegp     alcgp    tobgp ncases ncontrols
#    <ord>     <ord>    <ord>  <dbl>     <dbl>
# 1  25-34 0-39g/day 0-9g/day      0        40
# 2  25-34 0-39g/day    10-19      0        10
# 3  25-34 0-39g/day    20-29      0         6
# 4  25-34 0-39g/day      30+      0         5
# 5  25-34     40-79 0-9g/day      0        27
# 6  25-34     40-79    10-19      0         7
# 7  25-34     40-79    20-29      0         4
# 8  25-34     40-79      30+      0         7
# 9  25-34    80-119 0-9g/day      0         2
# 10 25-34    80-119    10-19      0         1
# # ... with 78 more rows

Unfortunately:
esoph2 %>% summarize(n = n())
# Error: corrupt 'grouped_df', contains 88 rows, and 68 rows in groups

Ergo my comment that summarize assumes full coverage; you'd have to modify dplyr_summarise_impl (in C++), perhaps making a third option to summarise_grouped and summarise_not_grouped.

A: library(data.table)
setDT(esophlong)

special.summary = function(dt, vars) {
  rbindlist(lapply(seq_along(vars), function(i) {
      var = vars[[i]]
      if (is.logical(dt[, eval(var)])) {
        dt[eval(var) == TRUE, .(.N, sum(case), mean(case))][, tag := names(vars)[i]][
           , .SD, by = tag] # last step is a lazy version of setcolorder
      } else {
        dt[, .(.N, sum(case), mean(case)), by = .(tag = eval(var))]
      }
    }))
}

special.summary(esophlong, list('age>=65'=quote(highage),
                                'alc>=80'=quote(highalc),
                                'tob>=20'=quote(hightob),
                                'high risk'=quote(highrisk),
                                'all'=quote(TRUE)))

#         tag    N  V2        V3
#1:   age>=65  273  68 0.2490842
#2:   alc>=80  301  96 0.3189369
#3:   tob>=20  278  64 0.2302158
#4: high risk   11   5 0.4545455
#5:       all 1175 200 0.1702128

special.summary(esophlong, list(quote(agegp),
                                '65+'=quote(agegp %in% c('65-74','75+')),
                                'all'=quote(TRUE)))

#     tag    N  V2          V3
#1: 25-34  117   1 0.008547009
#2: 35-44  208   9 0.043269231
#3: 45-54  259  46 0.177606178
#4: 55-64  318  76 0.238993711
#5: 65-74  216  55 0.254629630
#6:   75+   57  13 0.228070175
#7:   65+  273  68 0.249084249
#8:   all 1175 200 0.170212766

This can be made more customizable of course, and that's left as an exercise to the reader.

A: In the absence of any knowledge of tidyverse internals, I avoided trying to create group_by()-type function whose output should be passed to summarise() and instead made a single function that combines both (similar to other answers but, I hope, more user-friendly and generalisable).
Since group_by() %>% summarise() returns the joint summary information for each nested combination of grouping variables, I chose the name summarise_marginal() since it will return the marginal summary information for each grouping variable independently.
Solution that doesn't work with grouped_df objects
First, a solution that doesn't work with grouped_df classes, but is extended below:
summarise_marginal0 <- function(.tbl, .vars, ..., .removeF=FALSE){

  dots <- quos(...)

  .tbl %>%
    transmute(!!! .vars) %>%
    map_dfr(
      ~ summarise(group_by(.tbl, 'value'=., add = TRUE), !!! dots) %>%  # piping .tbl %>% group_by() %>% summarise() evaluates in the wrong order for some reason
      filter_at(vars('value'), all_vars(!(.==FALSE & .removeF))) %>%  # to remove rows where a logical group is FALSE.
      mutate_at(vars('value'), as.character)  # standardises 'value' column in case map_dfr tries to convert logical to factor
      , .id='group'
    )
}

mtcars %>%
  summarise_marginal0(
    vars(cyl, am),
    meanmpg = mean(mpg),
    meanwt = mean(wt)
  )

#> # A tibble: 5 x 4
#>   group value  meanmpg   meanwt
#>   <chr> <chr>    <dbl>    <dbl>
#> 1   cyl     4 26.66364 2.285727
#> 2   cyl     6 19.74286 3.117143
#> 3   cyl     8 15.10000 3.999214
#> 4    am     0 17.14737 3.768895
#> 5    am     1 24.39231 2.411000

Capturing groups with vars() (like with summarise_at() or mutate_at()) neatly separates the groups from the summary functions, and allows new groups to be created on-the-fly:
mtcars %>%
  summarise_marginal0(
    vars(cyl, hp_lt100 = hp<100),
    meanmpg = mean(mpg),
    meanwt = mean(wt)
  )

#> # A tibble: 5 x 4
#>      group value  meanmpg   meanwt
#>      <chr> <chr>    <dbl>    <dbl>
#> 1      cyl     4 26.66364 2.285727
#> 2      cyl     6 19.74286 3.117143
#> 3      cyl     8 15.10000 3.999214
#> 4 hp_lt100 FALSE 17.45217 3.569652
#> 5 hp_lt100  TRUE 26.83333 2.316667

We can use the .removeF argument to remove FALSE logical values. Useful if you want to summarise certain rows but not their compliment:
mtcars %>%
  summarise_marginal0(
    vars(cyl==6, hp_lt100 = hp<100, hp_lt200 = hp<200),
    meanmpg = mean(mpg),
    meanwt = mean(wt),
    .removeF = TRUE
  )

#> # A tibble: 3 x 4
#>      group value  meanmpg   meanwt
#>      <chr> <chr>    <dbl>    <dbl>
#> 1 cyl == 6  TRUE 19.74286 3.117143
#> 2 hp_lt100  TRUE 26.83333 2.316667
#> 3 hp_lt200  TRUE 21.96000 2.911320

Notice the how even without explicitly naming the cyl == 6 group we still get a useful name for it.
Solution that does work with grouped_df objects
summarise_marginal0() can be extended to work with grouped_df objects returned by group_by():
summarise_marginal <- function(.tbl, .vars, ...){

  dots <- quos(...)

  .tbl %>%
    nest() %>%
    mutate(
      summarised = map(data, ~summarise_marginal0(., .vars, !!! dots))
    ) %>%
    unnest(summarised) %>%
    purrrlyr::slice_rows(group_vars(.tbl))
}

mtcars %>%
  group_by(am) %>%
  summarise_marginal(
    vars(cyl, hp_lt100 = hp<100),
    meanmpg = mean(mpg),
    meanwt = mean(wt)
  )

#> # A tibble: 10 x 5
#> # Groups:   am [2]
#>       am    group value  meanmpg   meanwt
#>    <dbl>    <chr> <chr>    <dbl>    <dbl>
#>  1     1      cyl     4 28.07500 2.042250
#>  2     1      cyl     6 20.56667 2.755000
#>  3     1      cyl     8 15.40000 3.370000
#>  4     1 hp_lt100 FALSE 20.61429 2.756857
#>  5     1 hp_lt100  TRUE 28.80000 2.007500
#>  6     0      cyl     4 22.90000 2.935000
#>  7     0      cyl     6 19.12500 3.388750
#>  8     0      cyl     8 15.05000 4.104083
#>  9     0 hp_lt100 FALSE 16.06875 3.925250
#> 10     0 hp_lt100  TRUE 22.90000 2.935000

In fact, summarise_marginal() will work for both grouped and ungrouped data.frames so this function alone is suitable.
This is a useful solution, but given that group_by() has uses beyond summarise(), for example with nest() or do(), I think the idea of a group_by_marginal() (or group_by_tag() or whatever name is best) is worth pursuing.
Some remaining issues:

*

*The function needs to convert integer, factor and logical columns to character so their values all sit nicely in the same values column. This is a slight violation of tidy data principles, though is no different to how gather() behaves.

*Assuming a group_by_marginal() function is possible, it's output cannot be passed to mutate() without resolving the ambiguity of where to place the values from each group. From the example above, which value of meanmpg should be given to a row with cyl==4 and am==0? Both 26.66364 (from cyl==4) and 17.14737 (from am==0) are relevant. (Note there is no ambiguity for group_by() %>% mutate() since it will return the joint summary function for cyl==4 & am==0). Three possible options for group_by_marginal() %>% mutate():

*

*It should be forbidden.

*It should create multiple columns, eg, meanmpg_cyl and meanmpg_am.

*It should replicate rows for each group.

*Speed. I'm certain my implementation of this concept is inefficient and could be improved.

Finally, to demonstrate on the original example problem:
bind_rows(
  esoph %>% .[rep(seq_len(nrow(.)), .$ncases), 1:3] %>% mutate(case=1),
  esoph %>% .[rep(seq_len(nrow(.)), .$ncontrols), 1:3] %>% mutate(case=0)
) %>%
summarise_marginal(
  vars(highage = agegp %in% c('65-74','75+'),
       highalc = alcgp %in% c('80-119','120+'),
       hightob = tobgp %in% c('20-29','30+'),
       highrisk = highage & highalc & hightob,
       all = 1),
  n=length(agegp),
  ncases=sum(case),
  case.rate=mean(case),
  .removeF=TRUE
)

#> # A tibble: 5 x 5
#>      group value     n ncases case.rate
#>      <chr> <chr> <int>  <dbl>     <dbl>
#> 1  highage  TRUE   273     68 0.2490842
#> 2  highalc  TRUE   301     96 0.3189369
#> 3  hightob  TRUE   278     64 0.2302158
#> 4 highrisk  TRUE    11      5 0.4545455
#> 5      all     1  1175    200 0.1702128

A: Here's a (mostly) dplyr version:
Given the columns the OP created, the tags could be:
tags = list('age>=65'="highage",
            'alc>=80'="highalc",
            'tob>=20'="hightob",
            'high risk'="highrisk",
            'all'=TRUE)

But better to create the filtering expressions from the original data as @Frank did:
tags1 = list(
  'age>=65'   = ~agegp %in% c('65-74','75+'),
  'alc>=80'   = ~alcgp %in% c('80-119','120+'),
  'tob>=20'   = ~tobgp %in% c('20-29','30+'),
  'high risk' = ~agegp %in% c('65-74','75+') & alcgp %in% c('80-119','120+') & tobgp %in% c('20-29','30+'),
  'all ages'  = TRUE
)

Then create a function that uses lapply to run the dplyr summary on each row of tags1:
my_summary = function(dat, groups) {
  bind_rows(lapply(1:length(groups), function(i) {
    dat %>% filter_(groups[[i]]) %>%
      summarise(tag=names(groups)[i],
                n=n(),
                ncases=sum(case),
                case.rate=mean(case))
  }))
}

my_summary(esophlong, tags1)

        tag    n ncases case.rate
1   age>=65  273     68 0.2490842
2   alc>=80  301     96 0.3189369
3   tob>=20  278     64 0.2302158
4 high risk   11      5 0.4545455
5       all 1175    200 0.1702128

I was hoping to create a simpler way to generate the filtering expressions, but I'm still a bit mystified about how to create complex expressions to use in standard-evaluation versions of dplyr functions.
For example, I'd be interested in how to use an approach something like the one below. The filt function is intended to create the filtering expression, but the returned expression needs to be unquoted and have a ~ in front of it for filter_ to interpret it properly. Or maybe there's some gyration with interp that's required. Anyway, I'd be interested in how to make this work (or suggestions for a better way) and also how to create a filter with multiple conditions (as in the 'high risk' filter) by combining the individual filters:
# Create a filtering expression
filt = function(var, cutoff) {
  paste("as.numeric(gsub('([0-9]{1,3})[-+].*','\\1',", var, ")) >= ", cutoff)
}

# Run the summary function with three different filters plus "all"
my_summary(esophlong, c(mapply(filt, c("agegp","alcgp","tobgp"), c(65,80,20)), 'all'=TRUE))


text:
Q: MySQL: Why I get no results for a specific query on fulltext index? I have some trouble with a MySQL table and a fulltext index. My table structure looks similar to this:
CREATE TABLE example_index (
    id int(11) NOT NULL auto_increment,
    title tinytext,
    content text,
    FULLTEXT INDEX title (title),
    FULLTEXT INDEX titlecontent (title,content),
    PRIMARY KEY (id)
)ENGINE=MyISAM;

As you can see I have created a fulltext index for the fields title and title and content in combination. Furthermore I have stored some data into this table like this:
id | title      | content
1  | Teamwork   | Example data
2  | CSV-Export | Testdata

If I try to get some data from this table via a match against query then I got one result for the following query:
SELECT *
FROM example_index
WHERE MATCH (title) AGAINST('csv' IN BOOLEAN MODE);

BUT no results for this query:
SELECT *
FROM example_index
WHERE MATCH (title) AGAINST('Team' IN BOOLEAN MODE);

Can someone tell me, why I got no results here?

A: MySQL fulltext indexes index words. This is a very important limitation. You do not have the word team in your data, but you do have the word csv because - is considered a word delimiter.
If you are looking for words starting with team then you can still use the fulltext index using the * operator within the string to be searched:
SELECT *
FROM example_index
WHERE MATCH (title) AGAINST('Team*' IN BOOLEAN MODE);

If you would like to get records that contain the substring team anywhere within the indexed field, then MySQL fulltext index and fulltext search cannot help you. In this case you either need to revert to the good old title like '%team%' or you need to use a different fulltext search provider that can use MySQL.

A: Full text search looks for words in the text not partial words.  Because your text contains "Teamwork", it does not contain team.  This is a limitation of many full text implementations.
If your data is not too big, you can use like:
SELECT *
FROM example_index
WHERE title LIKE '%Team%';

If you are just looking for titles that start with "Team", you can do:
SELECT *
FROM example_index
WHERE title LIKE 'Team%';

The advantage of this approach is that it will take advantage of a regular index on example_index(title).
I notice that MySQL now has an n-gram parser.  This parser is designed for non-English (primarily east Asian) languages.  However,  it might work on English as well.  You might be able to try this to do what you want.


text:
Q: constructor missing error although a constructor is implemented I have got this constructor undefined error from the following code:
package arrayClassObject;

public class Constructor {
    public class Student{
        String name;
        public Student() {

        }
        public Student(String name) {
            this.name = name;
        }
        void setName(String name) { // setter
            this.name = name;
        }
        public String getName() { // getter
            return name;
        }

        }
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("Jack");
        System.out.println(s.getName());
    }

}

can anyone explain me why I got such errors? I believe I have done the construction definition in the class Student
    The constructor Constructor.Student() is undefined

    at arrayClassObject.Constructor.main(Constructor.java:18)

A: When you have a non-static inner class, you can only make an instance when an instance of the enclosing class exists.  So without changing your class structures above, you would need to do the following:
Constructor c = new Constructor(); // instance of the enclosing class
Student s = c.new Student();       // special syntax
s.setName("Jack");
System.out.println(s.getName());

A: You defined Student as a nested inner class of the enclosing class Constructor.
Since Student is non-static it can only exist with an associated instance of Constructor.
See Nested Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects) for more information about nested classes.
There are multiple ways to get around this problem.

*

*Make Student static. That way you don't need an instance of Constructor to create a Student.

*Keep Student a non-static inner class. Then you first need to construct an instance of Constructor for the Student to be associated with. (new Constructor().new Student())

*Move Student to its own file. There's probably no need to have Student as an inner class. So just make it a regular class.


text:
Q: How to end a hardhat node so that the associated PID is freed? After I run a node for example:
npx hardhat node
I want to end the node and free the port so I can run another node something like:
npx hardhat node --fork <mainnet_link>
Currently, I do ctrl+z and the use lsof -i :8545 to get the PID of the port and then do kill -9 PID to free up the port otherwise I get a EADDRINUSE error.
Is there anyway to kill the port from the node instead of doing ctrl+z?


text:
Q: Laravel, how to call or append(join) another model with condition in existing model condition I am stuck with search functionality from two different tables (VenueHall and Venue). The data is coming in the search1 parameter. I am able to search the data from one table (VenueHall) but I am not able to map with another table (Venue) using the existing object from the first table ($VenueHall`).
$VenueHall = VenueHall::orderBy('created_at', 'DESC');
$VenueHall = $VenueHall->with('venue');
$VenueHall = $VenueHall->with('venueType');
$VenueHall = $VenueHall->with('venue.area');

if (Input::has('query') && $searchQuery = Input::get('query'))
{
    $perecentilify = '%'. $searchQuery .'%';

    $VenueHall = $VenueHall->where(function($query) use ($perecentilify, $searchQuery) {
        $query->where('name', 'LIKE', $perecentilify)
            ->orWhere('code', 'LIKE', $perecentilify);
            //->orWhere('from venue table');
        });
    }

    $data = array(
        'venueHall' => $VenueHall->paginate(2)
    );

    return View::make('venues/venues', array('data' => $data));

I am not able to map the //->orWhere('from venue table') clause which comes from the Venue table. Please help me out get the data from the two tables based on the search value in the search box.

A: Often I find joins to be the easiest solution in such cases:
$VenueHall = VenueHall
    ::join('Venue', 'Venue.id', '=', 'VenueHall.venue_id')
    ->where('VenueHall.name', 'LIKE', $perecentilify)
    ->orWhere('VenueHall.code', 'LIKE', $perecentilify)
    ->orWhere('Venue.name', 'LIKE', $perecentilify)
    ->orderBy('created_at', 'DESC')
    ->with(['venue', 'venueType', 'venue.area'])
    ->paginate(2)
;


text:
Q: problem in trasform UTM sirgas 2000 coordinates to Lat Long myProj= Proj('+proj=utm +zone=23 +south +units=m +ellps=WGS84', preserve_units=False)

NameError                                 Traceback (most recent call last)
 in
----> 1 myProj= Proj('+proj=utm +zone=23 +south +units=m +ellps=WGS84', preserve_units=False)
NameError: name 'Proj' is not defined


text:
Q: what is difference between .submit() vs :submit? Someone tell me the difference between .submit() vs :submit. When & where to use with a simple example please.
Thanks

A: *

*.submit() is a function that submits a form.

*:submit is a selector to find submit buttons

A: .submit() is a method. That means you need to call it when you want to trigger a form submission
$("#form").submit()

:submit is a selector helper to find specifically buttons that submits
$("button:submit")

You can find very valuable examples on the jquery doc pages linked in my answer.

A: .submit() is a function, used to submit a form. :submit is a selector, used to identify <input type="submit"> elements.
Example:
<form id="myForm">
    <input type="submit" id="mySubmitButton" value="Click me!">
</form>

$('#myForm').submit(); // submits the form
$(':submit'); // selects the submit button

A: The :submit pseudo-class will match <input> elements with a type of submit. The .submit() method is completely different; depending on what you pass it, it will either submit a form or add an event listener to one.
Here's a quick example:
$(':submit'); // will return all <input type="submit">
$('form:submit'); // shouldn't ever return anything
$('form').submit(); // submits all forms
$('form').submit(function(e) {
    e.preventDefault();
}); // disallows any forms to be submitted

For more information, see the jQuery API documentation on .submit().

A: $("html_element").X().Y().Z() - function: do something with the selected html_element
eaxample - in this case do something= modify the css property:
$("li").css({"color":"orange"});

$("html_element:X") - selector: filter somehow the selected html_element
eaxample - in this case all "li" elements was reduced to only the first one
$("li:nth-child(1)").css({"color":"red"});


text:
Q: How can I prevent Excel from formating Numbers that I import via Java? I´m trying to get this number: "16.233549.1008" into an Excel sheet without changing the format of the cell. But always when I import this number, Excel just writes: "162.335.491.008".
My simple code: println("16.233549.1008");
Can anybody help me with this issue?

A: i guess you want to create a csv-file
for that case, i suggest to create the particular content as 'String'-Function that makes the csv-file look like this:
A;B;C;D;="16.233549.1008";E;F;G


text:
Q: Telling a Separate Window to Scroll I need to be able to programmatically scroll a window up and down given only a point on a screen. I've managed to retrieve a handle using Windows API, but I am unable to get it to scroll up or down.
Assume the following code:
//retrieves the correct window.
IntPtr      hWnd = Win32.WindowFromPoint(new Point(xPos, yPos));

Win32.Rect  rect = default(Win32.Rect);

//retrieves a rectangle with the desired windows dimensions
Win32.GetWindowRect(hWnd, ref rect);

//Insert scroll code here...

A: to scroll a window you need to send it a windows message by calling SendMessage with the appropriate parameters - for full details regarding scrolling and associated messages etc. see MSDN.
UPDATE - as per comments:
Another option might be to call ScrollWindowEx on the hWnd - as per comments calling ScrollwindowEx should NOT be used since it would create an inconsistency between the displayed state and the internal state of the respective window!

A: Have you tried using SendMessage() function with WM_VSCROLL and WM_HSCROLL messages?
Also check SetScrollInfo (pInvoked version here). Even this post may be helpful to you.


text:
Q: JRE not found by eclipse I am having issues starting up my java neon, and it keeps saying saying "A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run eclipse. no java virtual machine was found after searching the following locations C:/Program Files/Java/jre1.8.0_45/bin" but i installed the jre1.8.0_131, as i dont know how to either downgrade mine or update eclipse's. I feel so silly for not even knowing how to do this but thanks for any help you guys have!

A: It's better if you uninstall current java version and install newest jdk from here. This jdk also contains jre inside.
After installation in Eclipse go to Preferences -> Java -> Installed JREs and point to your jdk installation folder, for example C:\Java\jdk1.8.0_131. After that it should be fine.

A: This is not a version problem, but a problem with where it is installed.  You need to do more than install the JDE or JDK.  You have to put it in a special location depending on your OS.
Here is a good step by step for installing JDK on MAC, Windows and Linux:
https://www3.ntu.edu.sg/home/ehchua/programming/howto/JDK_Howto.html
You might also need to look at what you gave eclipse access to in the setup stage.  There is a chance you didn't give it the option to look in the place it needs to.
I would reccommend you try to compile and run java from a text file and use the command prompt before an IDE.  If you can compile and run a test prompt then you know its in the right spot and the problem lies with eclipse location/locator.
To run from a text file.  Just open a text file, save it as something.java then type some code and navigate to the file, type javac name of file.java and then if that works  type java name of file  If this all works fine then it is a problem with eclipse.  If not you have a problem with where it is installed.

A: Your JAVA_HOME and or JRE_HOME variables are probably pointing to a wrong installation.
Update those environmental variables and you should be good.

A: Please edit the eclipse.ini which is located in the eclipse folder and specifiy the vm you want to use.
simply add two lines at the beginning of the file (set path to directory of your java installation)
-vm
C:/Program Files/Java/jdk1.8.0_121/bin/javaw.exe

the other way is to check and update the environment variables JAVA_HOME and/or JRE_HOME.


text:
Q: function non static in class calling hello i whave an function which it take the number after the (.) and after "Vl" in string
so i want call this function on the code but they tell me this error
non-static method Ajuster(String) cannot be referenced from a static context

this the code
public class Test {
     public Integer Ajuster(String data) {
        Integer vlan=0;

        if (data.indexOf("Vl") >= 0) {
            int pos = data.indexOf("Vl") + 2;
            String vl = data.substring(pos, data.length());
            vlan=Integer.parseInt(vl.trim());
        } else {
            int pos = data.lastIndexOf(".") + 1;
            String vl = data.substring(pos, data.length());
            try {
               vlan=Integer.parseInt(vl.trim());

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return vlan;
    }

    public static void main(String[] args) {

       Connection conn = null;
       try {
          conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
          String sql = "SELECT * FROM router;";
          Telnet_Interface telnet = new Telnet_Interface();
          Telnet_Ressources telnet_R = new Telnet_Ressources();
          Telnet_Interface telnet1 = new Telnet_Interface();
          Telnet_Interface telnet2 = new Telnet_Interface();
          PreparedStatement prest = conn.prepareStatement(sql);
          ResultSet res=prest.executeQuery();
          while(res.next()){
             telnet1.Config(res.getString(1), "noc", "nocwana", res.getString(1));
             telnet2.Config(res.getString(2), "noc", "nocwana", res.getString(2));
          }
          ArrayList myData=telnet.getMyData();
          ArrayList myData1=telnet1.getMyData();
          ArrayList myData2=telnet2.getMyData();

          for(int i=0;i<myData1.size();i++)
          {
             String data1=myData1.get(i).toString();
             Integer vl1=Ajuster(data1);
             System.out.print(vl1);
          }
       }

}

so the problem it's about the line: Integer vl1=Ajuster(data1);
Thank you

A: You cant call a non-staic without any object reference.
Either make the method static like  (depends if it dont involve any instance varialbe)
 public static Integer Ajuster(String data)

or invoke with a object of class Test like
Test obj = new Test();
obj.Ajuster("data");

or better this http://docs.oracle.com/javase/tutorial/
PS: Method starting with capital name looks really weird

A: main is static. It means that it is not related to a instance of the Test class, but to the class itself.
Ajuster (please follow Java coding guidelines, it should be ajuster) is not static, so it is related to an instance of Test. So, to use it you must use it from a created instance (like this)
Test test = new Test();
test.ajuster();

or make it static (try not to overuse static methods)

A: It seems you're calling the method public Integer Ajuster(String data) that is non-static from the main that's, in fact, static. In order to call that method Ajuster you must instantiate an object of the class Test.
I suppose you know how to do this, but however you must write this down Test test = new Test().

A: You cannot call a non-static method with out creating an object. If it's a non-static context, however current object (this) will be there. If from static method you have to create an object and call the method on that object.
Static methods are all same for every object. In that case, we cannot know on what object are we applying the method or accessing a variable, that's why there is restriction.
Alternatively, you can make the method as static. But that depends. You should know when to use static methods and when not to use. It's a design issue.
Read:
To know the difference between static and non-static method
When should a method be static
How to call a non static method from main
So, create an object and call the method:
                   Test newTest = new Test();
                   newTest.ajuster();

A: You have to understand that non-static context cannot be referred in static context
public int test = 0;

public static void main(String[] args) {
  test += 4; //this wont compile
}

Non-static context however can include both non-static and static contexts.
Try something like this.
public class Test {

public int test = 0;

  public static void main(String[] args) {
    new Test();
  }
  public Test() {
    test += 4; //this will compile
  }
}

If you cannot understand this, try to search and learn about Constructor


text:
Q: How to delete version control log(history) from IntelliJ I copied an existing Spring(java) project and started using this copy.
But, I found that Version Control Git history of the previous project exists in my project.
I tried to delete previous commit history, but I couldn't find how to.
Briefly, what I want to know is how to delete version control log(history) from IntelliJ.

A: Delete .git folder from your project.


text:
Q: Formik losing selected values after button click I have a form with some inputs of type "select". One of them works like: The user selects one service and click on "Add" button to add to a list of services, but after this click, the previously selected values (cliente, funcionario) are getting empty.
<Formik
  enableReinitialize
  validationSchema={formSchema}
  onSubmit={(values, { resetForm }) => {
    entry
      ? props.setSubmit(values, entry.id)
      : props.setSubmit(values, resetForm);
  }}
  initialValues={defaultValues}
>
  {({
    handleSubmit,
    handleChange,
    values,
    errors,
    touched,
    setFieldValue,
  }) => (
    <Modal
      show={modalForm}
      onHide={handleClose}
      backdrop="static"
      size="lg"
    >
      <Modal.Header closeButton>
        <Modal.Title>Preencha o formulário</Modal.Title>
      </Modal.Header>
      <Form onSubmit={handleSubmit}>
        <Modal.Body>
          <Combobox
            label="Cliente"
            name="cliente"
            onChange={handleChange}
            value={values.cliente}
            errors={errors.cliente}
            options={customers}
          />
          <Combobox
            label="Funcionário"
            name="funcionario"
            errors={errors.funcionario}
            onChange={async e => {
              handleChange(e);
              setFieldValue(
                'comissao',
                await loadComission(e.target.value)
              );
            }}
            value={values.funcionario}
            options={employees}
          />
          <hr />
          <CustomCombo
            className="cbwbuton"
            label="Serviço"
            name="servico"
            onChange={handleChange}
            value={values.servico}
            options={services}
          >
            <Button
              variant="outline-primary"
              onClick={() => {
                console.log(values.funcionario);
                addServ(values.servico);
              }}
            >
              <i className="fa fa-plus-circle" />
            </Button>
          </CustomCombo>

AddServ function:
  const addServ = async id => {
if (id !== '') {
  try {
    const newServ = await api.get(`/service/${id}`);
    await setServicosRealizados([...servicosRealizados, newServ.data]);
  } catch (error) {
    console.log(error);
  }
}

};
On screen the values "cliente" and "funcionario" still selected, but these values is empty on output json when I submit. Could someone help me with this issue?


text:
Q: Ellipsoid and its projections I need to plot a figure combining of a three-dimensional ellipsoid and its projections on the sides of a box. I have no idea about it. I need to have something like

in Mathematica. Thanks.

A: pp3d = ParametricPlot3D[{2 Cos[u] Sin[v], Sin[u] Sin[v], Cos[v]},
  {v, 0, π}, {u, 0, 2 π},
  BoundaryStyle -> Directive[Thick, Blue],
  MeshFunctions -> {# &, #2 &, #3 &}, Mesh -> {{0}, {0}, {0}},
  MeshStyle -> (Directive[Thick, #] & /@ {Red, Blue, Green}),
  PlotStyle -> Opacity[.3],
  PlotRange -> {{-4, 4}, {-3, 3}, {-3, 3}}, Axes -> True,
  AxesOrigin -> {0, 0, 0}, Ticks -> False]

Post-process to project the lines to three walls:
Normal[pp3d] /. Line[x_, ___] :>
{Line[x], Line /@ (x /.
     {{{a_, b_, c_} :> {-4, b, c}},
      {{a_, b_, c_} :> {a, 3, c}},
      {{a_, b_, c_} :> {a, b, -3}}})}

A: First, you needs in coordinates of ellipsoid surface points:
a = 1; b = 0.5; c = 0.5;
cp = ContourPlot3D[
  x^2/a^2 + y^2/b^2 + z^2/c^2 == 1,
  {x, -1.1, 1.1}, {y, -1.1, 1.1}, {z, -1.1, 1.1}][[1,1]];

Further, just make the projections:
cp2d = cp[[All, {1, 2}]];
cm = SortBy[MeshCoordinates[ConvexHullMesh[cp2d]],
   ArcTan[#[[1]], #[[2]]] &];
cm3dz = Insert[#, 1.1, 3] & /@ cm;
cp2d = cp[[All, {1, 3}]];
cm = SortBy[MeshCoordinates[ConvexHullMesh[cp2d]],
   ArcTan[#[[1]], #[[2]]] &];
cm3dy = Insert[#, 1.1, 2] & /@ cm;
cp2d = cp[[All, {2, 3}]];
cm = SortBy[MeshCoordinates[ConvexHullMesh[cp2d]],
   ArcTan[#[[1]], #[[2]]] &];
cm3dx = Insert[#, 1.1, 1] & /@ cm;

Draw the solutions:
Show[cp,
Graphics3D[{EdgeForm[{Black, Thick}], Transparent,
Polygon@cm3d, Polygon@cm3dx, Polygon@cm3dy}]]


text:
Q: Get specific children with name into array I want to get all childrens and sub childrens of a parent gameObject by their names. Few children have a specific name and I am trying to get all them and store in an array. How do I achieve this?
    public GameObject[] Storage;

    void Start()
    {
        var childrenOfParent = this.GetComponentsInChildren<GameObject>();
        foreach (var child in childrenOfParent)
        {
            if (child.name == "NAME OF THE CHILD ")
            {
                Storage= child.gameObject; //Not working
            }
        }
    }

UPDATE: Taken into consideration, I am using List instead of array and this is how I have progressed so far. There is no addition to my list. Am I doing it right? It seems like it is not searching all the children (especially sub childrens of sub parents). How do I achieve this?
public List<GameObject> Storage= new List<GameObject>();

foreach (Transform child in transform)
         {
             if (child.name == "NAME OF THE CHILD")
             {
                 Storage.Add(child.gameObject);
             }
         }

A: You could use LINQ:
Storage = GetComponentsInChildren<GameObject>()
    .Where(x => x.name == "NAME OF THE CHILD") // Filter based on name
    .Select(x => x.gameObject) // Select child's GameObject
    .ToArray(); // Convert to array

A: If you don't know the quantity of child you'll store you can use the convenient List object insteed of an Array.
public List<GameObject> Storage = new List<GameObject>;

And then you add them like this :
Storage.Add(child.gameObject);

If you want to use an Array, you should first count how many children you'll have then create the array like this :
Storage = new GameObject[numberOfChild];

Then you can add GameObject to the array :
Storage[index] = child.gameObject;

But you have to know at wich index you want to save it. So everytime you add a child you must increment a int index variable for example : index++;.
Note that in you case you'll get only child of your parent, you'll have to make a recursive method to get child of child and so one.
Advice
If all theses childs already exist on editor time you should save their reference on editor time and not on runtime. You could just drag and drop them into inspector array or list. If you have too many to make it by hand you can make an method to do it for you on the OnValidate method for example and it will be executed on editor time everytime the object has a change.
Answer to edited post
Here's an example how get children of children recursively :
public class GetChildren : MonoBehaviour
{
    public List<GameObject> Storage = new List<GameObject>();

    public void Start()
    {
        string name = "NAME";

        Storage = new List<GameObject>();
        Storage.AddRange(GetAllChildrenRecursive(transform, name));
    }

    public List<GameObject> GetAllChildrenRecursive(Transform container, string name)
    {
        List<GameObject> childFound = new List<GameObject>();

        for (int i = 0; i < container.childCount; i++)
        {
            var child = container.GetChild(i);

            if(child.name == name)
            {
                childFound.Add(child.gameObject);
            }
            childFound.AddRange(GetAllChildrenRecursive(child, name));
        }
        return childFound;
    }
}


text:
Q: Rails app fails to load as soon as i installed capistrano i am trying to deploy my rails application for the first time on vexxhost. i am using github as my Source code management and capistrano.
here is my deploy file
require 'bundler/capistrano'
require 'capistrano'
require 'bundler'
require 'capistrano-vexxhost'

# Account Settings

ssh_options[:forward_agent] = true
set :scm_command, "/home/user/opt/bin/git"
set :local_scm_command,"git"
set :user, "xxxxxxxx"
set :password, "xxxxxxxxx"
set :domain, "domain.com"
set :mount_path,"/home/xxxxxxxx/xxxxxxx"
set :application,"app name"
set :scm, :git
set :deploy_via, :copy
set :repository, "git@github.com:xxxxx/xxxxxxx.git"
default_run_options[:pty] = true

As soon as i installed gem 'capistrano' gem 'capistrano-vexxhost' i got the following error when trying to load my application locally on my laptop (it was working before installing capistrano).
 C:/Ruby193/lib/ruby/gems/1.9.1/gems/capistrano-2.14.1/lib/capistrano/configuration/loading.rb:18:in `instance': Please require this file from within a Capistrano recipe (LoadError)
  from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.2.3/lib/bundler/capistrano.rb:7:in `<top (required)>'
    from C:/Users/mummy/LagoAds/config/application.rb:6:in `require'
    from C:/Users/mummy/LagoAds/config/application.rb:6:in `<top (required)>'
    from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.6/lib/rails/commands.rb:53:in `require'
    from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.6/lib/rails/commands.rb:53:in `block in <top (required)>'
    from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.6/lib/rails/commands.rb:50:in `tap'
    from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-3.2.6/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

NOTE But as i soon as i comment the Bundler.require line from the following code in the application.rb file, it successfully runs but doesn't recognize the gems
 if defined?(Bundler)
 # If you precompile assets before deploying to production, use this line
 Bundler.require(*Rails.groups(:assets => %w(development test)))
 # If you want your assets lazily compiled in production, use this line
 # Bundler.require(:default, :assets, Rails.env)
 end

UPDATE
when i enter the following code " rake --trace " it also gives me the following error
 rake aborted!
 please require the file from withen a capistrano recipe

PLEASE I NEED HELP WITH THIS PROBLEM

A: if you put capistrano* gems into the Gemfile you need to disable automatic requiring:
gem 'capistrano-vexxhost', :require => false


text:
Q: SQL Services Wont Start After Removing TLS I need to remove TLS 1.0 from one of my SQL servers. When I do so and then reboot the server the SQL services dont start automatically. When I attempt to start them I get an error that it cant be done.
Once I renable TLS 1.0 the SQL services start again after a reboot.
Im running SQL 2012 Developer edition. Version is 11.0.2100.60
Im using IIS crypto to remove TLS.
I keep TLS1.1 and 1.2 on there
Has anyone got a suggestion of what I can do to have the SQL services start when I remove TLS 1.0
Thanks

A: You have to patch the sql server instance to a newer version to be able to use TLS 1.2
Take a look at TLS 1.2 support for Microsoft SQL Server
Either patch at least to SP2 CU10 (preferably a higher CU)
 or SP3 CU1.
When patching to SP3 CU1
You would still be 9 CU updates behind, the latest CU for SP3 at the time of writing is SP3 CU10.
So when going this route I would go for SP3 CU10 but preferably choose for SP4

Note: TLS 1.2 support is also available in 2012 SP4.

When patching to SP4 (preferred)
In short, simply patching to SP4 would be the preferred option, you have to remember that there is a hotfix out for this Service Pack.
More questions and answers on disabling tls 1.0 and the sql server service not being able to start
here and here


text:
Q: Установить обложку для записи в WordPress Здравствуйте. Каким образом в WordPress можно установить, скажем так, обложку для каждой записи? Чтобы на выводи записи было сначала изображение, а потом текст записи.
Буду благодарен за полезную информацию.

A: В редактировании записи, в правом нижнем углу "задать миниатюру". Позволяет добавить изображение к любой записи и выводить в нужных местах.

A: Для загрузки изображений используйте миниатюры записи. Если при создании записи вы не находите поля для загрузки миниатюры, включите её поддержку, добавив следующий код в файл темы functions.php:
if (function_exists('add_theme_support')) {
    add_theme_support('post-thumbnails', array('post','page'));
}

Далее в цикле вывода постов используйте функцию the_post_thumbnail() для вывода миниатюры

A: Для вывода миниатюр в теме оформления WordPress используется специальная функция the_post_thumbnail().
<?php if (function_exists ('has_post_thumbnail') && has_post_thumbnail () ) {
    the_post_thumbnail ();
} ?>


text:
Q: Angular Issue - Cannot GET / I am running an ASP.NET Core app with Angular in visual studio 2017. Unfortunately whenever I run the project, it shows the following message in the browser:
Cannot GET /

So few hours of googling (Sample Link), I tried the following, adding in the tsconfig.json file:
"lib": [ "es5", "es6", "es2017", "dom" ]

In my case, that was earlier as follows:
"lib": [ "es2017" ]

Though the project was built successfully, it had few errors as follows:
Severity    Code    Description Project File    Line    Suppression State
Error   TS2583  (TS) Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.  ASP.NETCoreWithAngular  C:\Users\Amit's-PC\source\repos\ASP.NETCoreWithAngular\ASP.NETCoreWithAngular\ClientApp\node_modules\@angular\common\src\directives\ng_class.d.ts   48  Active

Severity    Code    Description Project File    Line    Suppression State
Error   TS2583  (TS) Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.  ASP.NETCoreWithAngular  C:\Users\Amit's-PC\source\repos\ASP.NETCoreWithAngular\ASP.NETCoreWithAngular\ClientApp\node_modules\@angular\core\src\change_detection\differs\default_keyvalue_differ.d.ts    24  Active

Severity    Code    Description Project File    Line    Suppression State
Error   TS2585  (TS) 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.  ASP.NETCoreWithAngular  C:\Users\Amit's-PC\source\repos\ASP.NETCoreWithAngular\ASP.NETCoreWithAngular\ClientApp\node_modules\rxjs\Observable.d.ts   58  Active

Anything that I missed here? Any idea would be highly appreciated.

A: From the error messages you are getting it seems most likely your default configuration for JavaScript is es5 or any other below es2015. Meaning you are trying to use es2015 features and your compiler is now allowing you to. Check your IDE configs and make sure your JavaScript config is set to at least es2015

A: Based on your error, I would think that you have a routing issue in the MVC part of your app.  You should endure that your default route is configured correctly.
The following article gives some useful guidance here.
https://knightcodes.com/angular2/2017/01/05/angular-2-routes-with-asp-net-mvc.html


text:
Q: Windows 10 can not be woken up from the keyboard if it sleeps for a while? I installed a windows 10 desktop recently which goes to sleep after a while if not used. The user reported that he left the computer there for a while and when he got back, simply pressing a key on the USB keyboard did not wake the computer up. He needed to press the power button.
I tested sleep when I was there it worked properly, I was able to wake the computer by pressing any key on the keyboard. ((I made it to sleep and woke it up right after that.)
Why is it that after a longer sleep the user could only wake the computer up with the power button, instead pressing a key on the keyboard?

A: The problem might arise from the power plan options that allow
Hybrid Sleep
to pass into hibernate after a certain time.
Check for it this way:

*

*Open Power Options from the Start menu

*On your power plan, click Change plan settings

*In Edit Plan Settings, click Change advanced power settings

*In Advanced settings, open the branch of Sleep

*Either set "Allow hybrid sleep" to Never, or set "Hibernate after"
to a longer time

*Click OK

*Reboot might be required

A: It might be possible that after first being on sleep, somehow the electric supply got cut(any reason) and hence it would only start by the power key.
Or the PC went into hibernation...it stays at sleep for some time but then goes into hibernation....so longer sleep induces hibernation.


text:
Q: Need to Deactivate the On-Click function if hovering on other link I am working on a DropDown menu and i added hovering effect for the Dropdown items but what i am strugging is when i am click on a link then the dropdown menu opens  but when i am hovering then that click function is still activate.
Please see the attached image for more clarity & let me know if you require more details :

HTML CODE :

.dropdown:hover .dropdown-menu {
 display: block;
}

JS CODE :

$(function() {
  $('.navbar-nav li a').filter(function() {
   return this.href == location.href
  }).parent().addClass('active').siblings().removeClass('active');
  $('.navbar-nav li a').click(
    function() {
     $(this).parent().addClass('active').siblings().removeClass(
       'active');
    })
 });

A: HTML
<div id="myDIV">
<button class="btn">1</button>
<button class="btn active">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
</div>

CSS: Design your own
Try this pure JavaScript code
        // Get the container element
        var btnContainer = document.getElementById("myDIV");

        // Get all buttons with class="btn" inside the container
        var btns = btnContainer.getElementsByClassName("btn");

        // Loop through the buttons and add the active class to the current/clicked button
    for (var i = 0; i < btns.length; i++) {
     btns[i].addEventListener("click", function() {
     var current = document.getElementsByClassName("active");
     current[0].className = current[0].className.replace(" active", "");
        this.className += " active";
    });
    }