text:
Q: How do i resolve the error Type 'CommunityEventsApp' does not conform to protocol 'App' I've been stuck trying to debug this for a while so i thought i would ask for some advice as i've got to the point where i've really confused myself. I'm trying to get data from a local api that i've created and use mapkit to display the events i get from my api on the map.
In my apps entry point i have this error "Type CommunityEventsApp does not conform to protocol 'App', it appears on the same line as struct CommunityEventsApp: App. I've trying adding an initialiser above my body in this file as this is what the error suggested as the fix however this didn't resolve the error. I have no other errors in my app. This is the code:
struct CommunityEventsApp: App {
    @StateObject var viewModel: ContentViewModel
    var event: Event

    var body: some Scene {
        WindowGroup {
            TabView {
               //rest of the tab view code
            }
            .environmentObject(viewModel)
        }
    }
}

I'm trying to get data from a local api i've made here in my ContentViewModel:

    var eventsList: [Event]
    var primary: Event

    init() {
        self.eventsList = []
        self.primary = eventsList[0]
    }

    func getEvents() async throws {
        guard let url = URL(string: "http://localhost:5172/events") else {fatalError("Missing URL")}
        let urlRequest = URLRequest(url:url)
        let (data, response) = try await URLSession.shared.data(for: urlRequest)

        guard (response as? HTTPURLResponse)?.statusCode == 200 else { fatalError("Error while fetching data")}
        eventsList = try JSONDecoder().decode([Event].self, from:data)
        print("Async decodedEvent", eventsList)
    }

}

This is my Event struct
struct Event: Decodable, Identifiable {

    let id: String
    let title: String
    let date: String
    let time: String
    let location: String
    let latitude: Double
    let longitude: Double
    let price: Double
    let description: String
    let link: String?
    let imageUrl: String

    init(id: String,
         title: String,
         date: String,
         time: String,
         location: String,
         latitude: Double,
         longitude: Double,
         price: Double,
         description: String,
         link: String,
         imageUrl: String) {
        self.id = id
        self.title = title
        self.date = date
        self.time = time
        self.location = location
        self.latitude = latitude
        self.longitude = longitude
        self.price = price
        self.description = description
        self.link = link
        self.imageUrl = imageUrl
    }
}

I call getEvents inside the onAppear in the ContentView:
    let event: Event
    let viewModel: ContentViewModel

    var body: some View {
         // UI formatting here
                .onAppear {
                    Task {
                        do {
                            try await viewModel.getEvents()
                        } catch {
                            print("Error", error)
                        }
                    }
                }
            }
            .navigationTitle("Event Information")
        }
    }
}

MapView where i use my api data to display events on the map:
    @EnvironmentObject var events: ContentViewModel
    @State var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: 53.483959, longitude: -2.244644),
        span: MKCoordinateSpan(latitudeDelta: 0.2, longitudeDelta: 0.2)
    )

    var body: some View {
        Map(coordinateRegion: $region,
            annotationItems: events.eventsList) {
            event in
            MapAnnotation(coordinate: CLLocationCoordinate2D(latitude: event.latitude, longitude: event.longitude)) {
                NavigationLink(destination: ContentView(event: event, viewModel: ContentViewModel())) {
                    Image(systemName: "pin.fill")
                        .onHover { hover in
                            print(event.title)
                        }
                }
            }
        }
            .navigationTitle("Events Near You")
    }
}

I don't have anyone else that i can ask for help so any help or information would be greatly appreciated! I'm still a beginner with Swift development and don't really feel comfortable with it yet. I'm using xcode version 13 and swift version 5

A: Your properties need default values.
The App struct is the entry point in your application. So every property needs to be properly initialized.
Especially your @StateObject var.


text:
Q: DB2 SQL Query Filtering rows based on multiple fields I need to write a query based on the following conditions:
Within one table, the following condition must be met:
table name:  DLS_RBM_RBI
columns within the table

*

*RBM_3_CD must be blank

*If RBM_3_CD is blank, then RBM_2_CD must be 1

*If RBM_3_CD is blank and RBM_2_CD is blank, then RBM_1_CD must be 1

How would these conditions be coded in a SQL statement?  In an IF within a where clause or case in a select?
I tried using a where clause with these conditions.
 AND (D.RBM_3_CD = '')
        OR (D.RBM_3_CD = '' AND D.RBM_2_CD = '1')
        OR (D.RBM_3_CD = '' AND RBM_2_CD = '' AND RBM_1_CD = '1')

A: The first statement
AND (D.RBM_3_CD = ' ')
negates the need for the second and third.  There's no way for the first statement to false while the second or third are true.
try this instead
where D.RBM_3_CD = ' '
   and ( (D.RBM_3_CD = '' AND D.RBM_2_CD = '1')
        or (D.RBM_3_CD = '' AND RBM_2_CD = '' AND RBM_1_CD = '1')
       )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set the maximum number of choices made by pickerInput() Im trying to limit the max number of choices made by pickerInput() to two in shiny app but I cannot make it work.
library(shiny)
library(shinydashboard)
library(plotly)
library(shinyWidgets)
header <- dashboardHeader()

sidebar <- dashboardSidebar(

  fluidRow(column(12,
                  pickerInput(
                    inputId = "iss",
                    label = "Issue",
                    choices = colnames(mtcars),
                    multiple = T,
                    options =  list("max-options-group" = 2)
                  )
  ))

)

body <- dashboardBody(fluidPage(

  )

)

ui <- dashboardPage(title = 'Search', header, sidebar, body)

server <- function(input, output, session) {

}
shinyApp(ui = ui, server = server)

A: Try this
columns <- as.list(names(mtcars))
type <- as.list(1:ncol(mtcars))
header <- dashboardHeader()

sidebar <- dashboardSidebar(

  fluidRow(column(12,
                  pickerInput(
                    inputId = "iss",
                    label = "Issue",
                    choices = list(Columns = columns,
                                   Type = type),
                    selected = list(columns[[1]],type[[1]]),
                    multiple = T,
                    inline=TRUE,
                    options =  list("max-options-group" = 1, `style` = "btn-info")
                  )
  ))

)

body <- dashboardBody(fluidPage())

ui <- dashboardPage(title = 'Search', header, sidebar, body)

server <- function(input, output, session) {}
shinyApp(ui = ui, server = server)

A: The problem is that you are using "max-options-group" but you are not using any groups in your choices. You must use "max-options" = 2 in the options argument of pickerInput().
For completeness, this is the modified version of your code. We cannot pick more than 2 options with it:
library(shiny)
library(shinydashboard)
library(plotly)
library(shinyWidgets)
header <- dashboardHeader()

sidebar <- dashboardSidebar(

  fluidRow(column(12,
                  pickerInput(
                    inputId = "iss",
                    label = "Issue",
                    choices = colnames(mtcars),
                    multiple = T,
                    options =  list("max-options" = 2)
                  )
  ))

)

body <- dashboardBody(fluidPage(

)

)

ui <- dashboardPage(title = 'Search', header, sidebar, body)

server <- function(input, output, session) {

}
shinyApp(ui = ui, server = server)


text:
Q: SQL Developer Get Current Script Path I'm looking for a way to be able to select the path of a script inside the script.
For example, I create a script called test.sql. If I save this to C:\test\test.sql then running the select statement in the script would return C:\test\

A: There's no way for server to know the client-side executed file path.
You have to code your way around this using your set of client-side tools.


text:
Q: typeahead suggestions list not decreasing I'm trying to implant twitter typeahead.js
https://github.com/corejavascript/typeahead.js
But the suggestion list doesn't decrease....
HTML code :

    <form action="" method="POST">

            <input type="text" id="my_search" name="search" autocomplete="off" placeholder="Enter Country Code"/>
            <input type="submit">

    </form>

Javascript Code
$(document).ready(function($) {
  var cities_suggestions = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("DESIGNATION"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: "villes2.json",
      transform: function(data) {
        var newData = [];
        data.forEach(function(item) {
          newData.push(item.DESIGNATION);
        });
        console.log(newData);
        return newData;
      }
    }
  });

  cities_suggestions.initialize();

  $("#my_search").typeahead(
    {
      hint: true,
      minLength: 1,
      highlight: true
    },
    {
      name: "cities",
      source: cities_suggestions, // suggestion engine is passed as the source
      limit: 10
    }
  );
});

My Json file looks like that :
[
  {
    "CODE_INSEE": 1344,
    "DESIGNATION": "1000 SAINT-DENIS-LES-BOURG"
  },
  {
    "CODE_INSEE": 1053,
    "DESIGNATION": "1000 BOURG-EN-BRESSE"
  },
  {
    "CODE_INSEE": 1225,
    "DESIGNATION": "1090 LURCY"
  },
  {
    "CODE_INSEE": 1165,
    "DESIGNATION": "1090 FRANCHELEINS"
  },
  {
    "CODE_INSEE": 1263,
    "DESIGNATION": "1090 MONTMERLE-SUR-SAONE"
  },
  {
    "CODE_INSEE": 1169,
    "DESIGNATION": "1090 GENOUILLEUX"
  }
]

I still have the ten first suggestions of the json file and anything else
The console.log(NewData) is ok

A: I've found
$(document).ready(function($) {
var cities_suggestions = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('text'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: 'villes2.json',
    remote: {
        url: 'villes2/queries/%QUERY.json',
        wildcard: '%QUERY'
  },
});
cities_suggestions.initialize();
// init Typeahead
$('#my_search').typeahead(
{
    hint: true,
    minLength: 1,
    highlight: true
},
{
    name: 'cities',
    display: 'text',
    source: cities_suggestions,   // suggestion engine is passed as the source
    limit: 10,
});
// then fill hidden input for get the value :-)
$('#my_search').bind('typeahead:select', function(ev, suggestion) {
    $('#my_search_value').val(suggestion.value)
});

});


text:
Q: load data from text with pandas with a two characters as separator I'm trying to load data with pandas from a txt table.
The column separator was defined as "|@" as you can see in the example:
LINEA DE NEGOCIO|@NOMBRE CLIENTE|@NUMERO CLIENTE|@NUMERO DE CONTRATO|@TIPO DE SEGURO
The system does not allow to use "|@" as separator.
Could you help me with this loading?
Thanks in advance.
I share the code:
df = pd.read_table('D:/Art_492/Encabezado.txt', sep='|@', index_col=0).astype(str)

A: The | represents OR operator in regular expression, you need to escape it using \ so updating your regex string to \|@ and setting engine='python' you can get your desired result.
pd.read_table(data,sep='\|@',engine='python',index_col=0).astype(str)


text:
Q: Django Redis sorl.Thumbnails thumbnail in my django project.
It require a key value database, my project have redis.
I configured solr.thumbnails with redis:
THUMBNAIL_DEBUG = True
THUMBNAIL_FORMAT = 'PNG'
THUMBNAIL_KVSTORE = 'sorl.thumbnail.kvstores.redis_kvstore.KVStore'
THUMBNAIL_REDIS_HOST = 'localhost'
THUMBNAIL_REDIS_PORT = 6379

Later I activated sorl.thubnails. I copied an static image in my static folder and I put this image in a template with sorl.thumbnails code:
{% load thumbnail %}
{% thumbnail "myimage.png" "100x110" crop="center" as im %}

{% endthumbnail %}

It create an image with the correct dimensions in a /cache folder at the root of my project. This image have the correct new dimensions.
cache/c8/1a/c81a5dc6e63107dd2614b2b89d04d4c5.png

Redis console MONITOR, have a line with the request
1380142932.884816 [0 127.0.0.1:38838] "GET" "sorl-thumbnail||image||789cd5e7c339366b2b99f45d1daf3101"

In the html the image tag is correct:

But image cannot show, django console says:
GET /cache/c8/1a/c81a5dc6e63107dd2614b2b89d04d4c5.png HTTP/1.1" 404 1728
Helpme please, what's wrong?

A: Looks like MEDIA_URL is missing.
try doing src="{{MEDIA_URL}}{{ im.url }}"


text:
Q: Dict recursion without for or while loop I'm fairly new to python, and I am already challenged by what many of you might find like a piece of cake. The output must be:
The Monkey-child could not fall asleep, so the mother told him a story, he was once a Tiger-child
  The Tiger-child could not fall asleep, so the mother told him a story, he was once a Human-child
    The Human-child could not fall asleep, so the mother told him a story, he was once a Panther-child
      The Panther-child could not fall asleep, so the mother told him a story, he was once a Snake-child
      The Snake-child has tired and fell asleep
     The Panther-child has tired and fell asleep
    The Human-child has tired and fell asleep
   The Tiger-child has tired and fell asleep
  The Monkey-child has tired and fell asleep

The code to modify is following (for and while loops are not allowed):
 import sys

 StorySequence = {
     "Monkey": "Tiger",
     "Tiger": "Human",
     "Panther": "Snake",
     "Snake": "",
     "Human": "Panther"
 }

 def writePaddingForDepth(depth):
     for i in range(0, depth):
         sys.stdout.write('  ')
         sys.stdout.flush()

 def endStory(thread, depth):
     writePaddingForDepth(depth)
     print ("The " + thread + "-child has tired and fell asleep.")
     return True

 def startStory(thread, depth):
    if (len(StorySequence[thread]) == 0):
        return endStory(thread, depth)

 writePaddingForDepth(depth)

 print ("The " + thread + "-child could not fall asleep, "
        "so the mother told him a story, he was once "
        + StorySequence[thread] + "-child")

 ## Code here

 startStory("Monkey", 0)

I tried to handle this like if it was array in C, but obviously it isn't, to all my little knowledge it is a dict type, which is something totally new for me. I would like to know how to implement recursion without for or while loops in this example.

A: Instead of doing
for i in range(0, depth):
 sys.stdout.write('  ')

to print twice the number of spaces as depth, you could just do
sys.stdout.write('  ' * depth)

You could do something like
def fn(who, depth):
  if(who in StorySequence):
    if(StorySequence[who]!=''):
      print ("\t" * depth + "The " + who + "-child could not fall asleep, "
          "so the mother told him a story, he was once "
          + StorySequence[who] + "-child")
      fn(StorySequence[who], depth+1)
    print ("\t" * depth + "The " + who + "-child has tired and fell asleep.")

fn("Monkey", 0)

A recursive function must have an exit condition to prevent it from being an infinite recursion.
Here, the recursion is done only as long as there's a valid key in the dictionary and the value is not an empty string.
who in StorySequence is used to check whether a key having the contents of who exists inside the dictionary StorySequence.


text:
Q: How to select mutiple values from excel single cell I have excel cell having multiple rows of data with image url.
Now I want to select all images having 1500 value. So basically I want to select row starting with http and ending 1500.jpg.
Please not that in my single cell values are also other than 1500.jpg.Sample data is given below
colorImages': { 'initial': [{"hiRes":"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UL1500_.jpg","variant":"MAIN","lowRes":null},{"hiRes":"https://images-na.ssl-images-amazon.com/images/I/716mECZ9JDL._UL1500_.jpg","thumb":"https://images-na.ssl-images-amazon.com/images/I/313QD20m4WL._SR38,50_.jpg","large""thumb":"https://images-na.ssl-images-amazon.com/images/I/313QD20m4WL._SR38,50_.jpg","large":"https://images-na.ssl-images-amazon.com/images/I/313QD20m4WL.jpg","main":{"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY445_.jpg":[445,117],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY500_.jpg":[500,132],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY550_.jpg":[550,145],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY606_.jpg":[606,160],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY679_.jpg":[679,179],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY741_.jpg":[741,195],"https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._UY879_.jpg":[879,231]},

A: Assuming data is in Column A starting from Cell A2 and all the URLs ending with 1500.jpg needs to be displayed in adjacent columns i.e. same row Column B, Column C, Column D,.... then following might help.
Sub Demo()
    Dim ws As Worksheet
    Dim lastRow As Long, colIndex As Long
    Dim rng As Range, cel
    Dim X As Long, DotCount As Long
    Dim Pat As String, EndPat As String, Parts() As String

    Set ws = ThisWorkbook.Worksheets("Sheet3")  'change Sheet3 to your data sheet
    With ws
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row        'get last row with data in Column A
        For Each cel In .Range(.Cells(2, 1), .Cells(lastRow, 1))    'loop through A2 to last cell with data in Column A
            colIndex = 1

            Pat = "*[!&-;?-[_a-z~=!" & Chr$(1) & "]."
            EndPat = "[!&-;?-[_a-z~=!" & Chr$(1) & "]*"
            Parts = Split(cel.Value, """")      'split cell value into an array
            For X = 0 To UBound(Parts)
              If Parts(X) Like "*?.?*" Then
                DotCount = Len(Parts(X)) - Len(Replace(Parts(X), ".", ""))
                If """" & Replace(Parts(X), "]", Chr$(1)) & """" Like Application.Rept(Pat, DotCount) & EndPat Then
                    Parts(X) = ""
                ElseIf Right(Parts(X), 8) <> "1500.jpg" Then
                    Parts(X) = ""
                Else
                    cel.Offset(0, colIndex) = Parts(X)  'display URL
                    colIndex = colIndex + 1
                End If
              Else
                Parts(X) = ""
              End If
            Next X
        Next cel
    End With
End Sub

Derived this solution using Function URLs from here.

A: This is done easily via VBA, but am not expert in that. So I have done some thing for you,just follow the instruction , still it is apply to get only single search entry i.e. means in a cell its find only one 1500.jpg entry.
To get second entry in the same cell you need some effort via change or get substring from the G1 Cell string and repeat the step as explained again.

*

*In A1 Cell, put 1500.jpg

*In B1 Cell, put your actual string as you have above

*In C1 cell, put formula "=SEARCH(A1,B1)", which find the search 1500 in string

*In D1 cell, put formula "=MID(B1,1,C1)", which extract the substring

*For E1 we need reverse the string via VBA code - Add Reversestr function (To add this function, see this link)

*In F1 cell, put formula "=SEARCH(CHAR(34),E1)", which search " in above reverse string

*In G1 cell, put formula "=MID(B1,C1-F1+1,C1)"

Finally you get the string in G1 Cell as "https://images-na.ssl-images-amazon.com/images/I/71GOT-L%2BOSL._1500.jpg"
For VBa formula, check this links
http://analystcave.com/excel-substring-vba-substring/


text:
Q: Im missing main class in NetBeans I accidentally deleted main class in NetBeans from Templates, know I cannot create any projects.
Does anyone know how to retrieve it?
I tried to reinstall NetBeans but it didn't work for me.
So please if anyone knows how to fix this I would appreciate  it very much.

A: Take a look here. Same problem resolved.
UPDATE
Ok.
Close NetBeans IDE, go to NetBeans userdir
, then to config/templates directory and delete Classes_hidden file.
When NetBeans IDE is started again templates for Java are back.
From here duplicate post
p.s Net beans user dir is something like this
C:\Users\YOUR_USER\AppData\Roaming\NetBeans\8.2\config\Templates
I tried this and it worked.

A: Netbeans automatically updates your work when you clean and run. Just:

*

*open your project

*Go to project History / History

*Select a period that the project worked correctly before deleting the main class

*Right click and revert from History


text:
Q: Remove '@NA' from Matlab Table I have the following code to clean table data of error terms:
    errorTerms={'@NA', '#NA', 'ActiveX VT_ERROR: '};
inputData=readtable(inputFile,'TreatAsEmpty',errorTerms);

However '@NA' terms remain.
I can get rid of them in this way:
inputData.GICS1=strrep(inputData.GICS1,'@NA','NaN');

But this requires several independent loops as I have many tables of different sizes.
Is there a more elegant way to import this data as tables? Or clean it?
The data looks like this:

Id Avg GICS1
a 3.0 @NA
b 5.6 Consumer Staples
c 4.8 Materials
d 3.1 Health Care
e 1.6 Energy
f 9.3 @NA
g 8.5 Industrials
h 7.0 Consumer Discretionary

A: You can use varfun to go through your table columns and apply a regex to each column using regexrep and your errorTerms array:
inputData = readtable('test.xlsx');

errorTerms = {'@NA', '#NA', 'ActiveX VT_ERROR: '};
expression = sprintf('(%s)', strjoin(errorTerms, '|'));

% Explicit loop
varnames = inputData.Properties.VariableNames;
for ii = 1:length(varnames)
    try
        inputData.(varnames{ii}) = regexprep(inputData.(varnames{ii}), expression, 'NaN');
    catch err
        switch err.identifier
            case 'MATLAB:UndefinedFunction'
                % Do nothing, skip loop iteration
            otherwise
                rethrow(err)
        end
    end
end

% % Only works for string data
% varnames = inputData.Properties.VariableNames;
% inputData = varfun(@(x) regexprep(x, expression, 'NaN'), inputData);
% inputData.Properties.VariableNames = varnames; % Variable names overwritten by varfun, set them back

Edit: I have added a try/catch block to account for mixed data types in your columns. I will caveat that this is a fairly greedy implementation, a more robust method would be to compare the error message to make sure regexprep is what is causing the issue but I'm lazy.


text:
Q: Setting up Samba4 internal DNS forwarder to try multiple DNS servers Our network setup until recently was that we had a Samba4 server acting as a DNS server for a few internal names, and forwarding to our main router for everything else (i.e. stuff on the internet.)  Our main router, a Dlink DI-624, was happy to forward these requests to the appropriate DNS servers, which it would obtain from our modem.
Well, that worked great, without hiccups, until the DI-624 died.  Our new router does not have DNS forwarding, so for the moment I took the primary DNS server from our internet connection and put that in smb.conf on the dns forwarder = line where our D-Link's address used to be.
My main beef with this is if our ISP changes that primary DNS server, which they have been known to do a few times a year, we have internet downtime and general confusion until this is figured out, and even once it is, we have to restart Samba which interrupts our fileshare in the process (more downtime).  All this for something our old router just neatly took care of.
Unfortunately whether with spaces or commas dns forwarder in smb.conf doesn't seem to take more than one argument.  I don't want to run BIND if I don't have to, but if it's simple enough I wouldn't mind switching from Samba's built-in internal DNS if it helps with this issue.
Is there some way to have CentOS grab current DNS server settings from our router and update smb.conf with them?  Or at least let me list a bunch of DNS servers to try?  Or better yet handle things automagically like our D-Link used to?

A: Solution 1. get a cheap new router - it is higly unlikely your brand new $30 router won't have DNS forwarding function. Check the product specs before buying!
It's also strange your new router does not have DNS function - did you check manuals and configuration interface thoroughly?
Solution 2. use google's public dns forwarder. it's quite ok (namebench tests claims google's distributed dns system is 266% faster than using my local bind9 caching-only service) unless you're concerned about privacy (about the fact that google might or might not collect your queries)
and at last, if the OP considers isc bind is too much overhead then maybe a light resolver like dnsmasq or unbound might come to help

A: you can install a bind instance, set it to forward to whatever list you like in named.conf.options, and then point samba to it. you don't have to replace anything, just point samba to bind, and bind to whatever list of servers you like.
the only downside is that now your dns is inside your firewall, and you will likely have to open a hole for forwarded queries to respond through.


text:
Q: Change Error response in web API I'm using token based authentication in my Web Api Application.
In Login Request, If User enter wrong credentials, then it return a response error in this format.
In GrantResourceOwnerCredentials method
if (user == null)
    {
      context.SetError("The email or password is incorrect.");
      return;
    }

Which return response as
 {
      "error": "InvalidLogin",
      "error_description": "The email or password is incorrect."
    }

And in my application all the error response returned in this format
{
  "message": "Some Internal server error occurred."
}

So how can I change the error response of web api
to
    {
      "message": "The email or password is incorrect."
    }

A: EDITED : TRY THIS
string jsonString = "{\"message\": \"The email or password is incorrect.\"}";
context.SetError(new string(' ',jsonString.Length-12));
context.Response.StatusCode = 400;
context.Response.Write(jsonString);


text:
Q: ASP.NET cannnot access to windows temp folder? whenever I want to run my application from localhost
it generates the following wierd error
Server Error in '/' Application.
--------------------------------------------------------------------------------

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CVT1108: cannot open C:\Windows\TEMP\RESC1C1.tmp for writing

Source Error:

[No relevant source lines]

Source File:    Line: 0

Show Detailed Compiler Output:

....

CVTRES : fatal error CVT1108: cannot open C:\Windows\TEMP\RESC1C1.tmp for writing
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

error CS1583: 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\449ad1a6\abc33f1b\CSCC1C0.tmp' is not a valid Win32 resource file

A: for those who cant give FULL CONTROL to c:\windows\temp like me
[this is how i solved]
1- run cmd AS admin (keep it open ).
2- open task manager and  KİLL explorer.exe.
3- goto previously opened cmd. write explorer.exe  hit enter.
4- go to c:\windows  temp (right click)>properties ->security
5- now you will be able to change  \IIS_IUSRS to Full Control
note: some application may give error about elevated exploer.exe . it will be fixed after restart.
if you dont wanna restart;
[take explorer.exe out of Administrator mode]
1- goto previosly opened task manager.  kill explorer.exe
2- in task manager file-> start new process  write there explorer.exe
3- now the  explorer.exe is in normal mode.
https://serverfault.com/questions/694184/cannot-provide-permission-to-iis-iusrs-on-c-windows-temp/731681#731681

A: Here are the steps to fix it:
Go to C:\Windows
Right Click the Temp folder
Click on Properties
Go to Security
Give CREATOR OWNER group full control.


text:
Q: Python exchangelib - mark item as read I am trying to accomplish one task in my mailbox using Python's exchangelib module - how to move a certain email to a folder if it contains specific subject and has 'unread' status.
while True:
    print("Checking inbox...")
    for msg in acc.inbox.filter(subject="Kontrol fra EVT...", is_read=False):
        if "SOS" in msg.text_body:
            pass
        else:
            msg.is_read = True
            print("Moving to EVT folder...")
            msg.move(archive)
            time.sleep(0.5)
    time.sleep(5)

Everything appears to be working except for msg.is_read = True part. The message remains unread, despite being successfully moved to the required folder.
I believe I am missing something simple here. I tried googling and using official module's documentation but came up empty in this regard. Could find only one person with the same question as mine: Mark email as read with exchangelib
Thank you!

A: Found the answer myself while digging through modules' files. Apparently you have to "save" the item after flagging it.
In the end my code should look like this:
while True:
    print("Checking inbox...")
    for msg in acc.inbox.filter(subject="Kontrol fra EVT...", is_read=False):
        if "SOS" in msg.text_body:
            pass
        else:
            msg.is_read = True
            msg.save()
            print("Moving to EVT folder...")
            msg.move(archive)
            time.sleep(0.5)
    time.sleep(5)


text:
Q: stage Event.ENTER_FRAME vs. CREATION_COMPLETE I've got an AS3 project that I'm building in FlexBuilder.
In my main class's constructor, I've got this:
    stage.addEventListener(Event.ENTER_FRAME, stage_enterFrameHandler);

And then the event handler function:
    private var tempCounter:uint = 0;

    private function stage_enterFrameHandler(event:Event):void
    {
        stage.removeEventListener(Event.ENTER_FRAME, stage_enterFrameHandler);
        tempCounter += 1;
        trace(tempCounter);
    }

When I run in debug mode, tempCounter writes out once, as 1.  Why is this? I though the whole point of Event.ENTER_FRAME is that it keeps firing.
The documentation says:

If the playhead is not moving, or if there is only one frame, this event is dispatched continuously in conjunction with the frame rate. This event is dispatched simultaneously to all display objects listening for this event.

So why would I not see that counter incrementing about 30x a second (which is what I have the frame rate set to)?
EDIT NOTE:
OK, well, doh, I've figured it out. It's because I immediately remove the eventlistener. The ENTER_FRAME event does keep firing... The only reason the code is done this way (code I inherited) is, I suppose, that CREATION_COMPLETE isn't available if you aren't using the flex framework.

A: The answer is simple as soon as enter in your enter frame you are removing the listener so the next time the enter frame event occured there is no one to react to it.
remove the line
stage.removeEventListener(Event.ENTER_FRAME, stage_enterFrameHandler);


text:
Q: Trying to show buttons under every row in DataTable Bootstrap but can only display them under a specific column instead of whole row I am creating a system that manages event expenses.
In this system, one event can have multiple installments of a single payment. What I am trying to do is to show these installments whenever the user hovers its mouse over an event in the Table. (Each row represents one event)
These installments can vary from one to multiple, meaning all events won't have same number of installments.
So, what I did was basically this,

So, if you can see, basically green buttons represent paid installments and yellow warning buttons represent unpaid installments.
but problem is, they are being shown under a single column. I want these to be spread horizontally under that row, rather than being shown under a single column.
Here's a code that I am using to show this datatable, (only including the relevant code)

Events

jQuery code
$(document).ready(function(){
        function getEvents() {
            $.ajax ({
                url: "action.php",
                type: "POST",
                data: {action: "get_events"},
                success: function(response) {
                    $("#events_table").html(response);
                    table = $("table").DataTable({
                        pagingType: 'full_numbers',
                        filter: true,
                    });
                }
            })
        }

        getEvents();
    });

And this is the action.php file, this is where I am writing all the syntax for this table.
if (isset($_POST['action']) && $_POST['action'] == "get_events")
{
    $output = '';
    $data = $db->get_all_events();
    $output .= '

                  ID
                  Event Name
                  Date
                  Total Payment
                  Expenses
                  Profit
                  Actions

';
      $number = 1;
    foreach($data as $row)
    {
        $expense = $row['discount']+$row['photo']+$row['video'];
        $profit = $row['payment'] - $expense;
        $date = $row['day'].'-'.$row['month'].'-'.$row['year'];
        $output .= '

        '.$number.'
        '.$row['e_name'].'';

        $payments = $db->get_payments($row['c_id']);
        foreach ($payments as $payment)
        {
          if ($payment['p_status'] == 'pending')
          {
            $output .= '

                '.$payment['p_amount'].'
';
          }
          else
          {
            $output .= '

                '.$payment['p_amount'].'
';
          }
        }
        $output .='
        '.$date.'
        '.$row['payment'].'
        '.$expense.'
        '.$profit.'
        View
        Update
        Delete

';

        $number++;
    }
    $output .= '

';
    echo $output;
}

As you would notice, currently I have my buttons set under the "Event Name" field. I would like to have those buttons spread over the whole row. Any help would be really appreciated.
Also, can anyone tell how can I align the Show entries and the Search Bar on top of the table? Thank you.
Edit: I tried to use the colspan property by creating a new row in the table and put my buttons in it (as suggested in comments) but it did not work out for me. Instead, it showed some very undesirable results.
First of all, the buttons did separate from the "one" column, so that issue did get resolved but in this case, now all the similar buttons were in same column still. For example, Green buttons were stacked up upon each other while yellow buttons were separate but stacked up upon each other.
Plus, bigger problem was now the buttons would show only when I "hover" over the row under the "Events" Row. It has a created a very small White Line under each row to represent the buttons row and Buttons get displayed only when I hover over that white line while nothing shows up when I hover over the actual Event Row.

The new modified code of action.php is as follows,
if (isset($_POST['action']) && $_POST['action'] == "get_events")
{
    $output = '';
    $data = $db->get_all_events();
    $output .= '

                  ID
                  Event Name
                  Date
                  Total Payment
                  Expenses
                  Profit
                  Actions

';
      $number = 1;
    foreach($data as $row)
    {
        $expense = $row['discount']+$row['photo']+$row['video'];
        $profit = $row['payment'] - $expense;
        $date = $row['day'].'-'.$row['month'].'-'.$row['year'];
        $output .= '

        '.$number.'
        '.$row['e_name'].'';

        $output .='
        '.$date.'
        '.$row['payment'].'
        Rs. '.$expense.'
        Rs. '.$profit.'
        View
        Update
        Delete

';
        $payments = $db->get_payments($row['c_id']);
        $output .= '
';
        foreach ($payments as $payment)
        {
          if ($payment['p_status'] == 'pending')
          {

            $output .='    '.$payment['p_amount'].'
';
          }
          else
          {
            $output .='    '.$payment['p_amount'].'
';
          }
        }
        $output .='
';

        $number++;
    }
    $output .= '

';
    echo $output;
}

A: You can use the "child rows" feature of DataTables - see an example here.
The benefit of these child rows is that they span the entire width of the table but only contain one cell.
In your case, you need to make some adjustments:

*

*Make sure every child row is always displayed. As you can see in the above linked demo, they are all hidden by default.

*Hide the column which normally contains the "show/hide" button for each child row.
Here is some code showing my simple demo:

// this function controls what is displayed in each child row. It has access to all the parent row's data
function format ( rowData ) {
    // `rowData` is the data object (or array) for the row
    return 'Put whatever you want in here, for example: "' + rowData.name + '". It spans all the columns.';
}

$(document).ready(function() {

  var dataSet = [
    {
      "id": "123",
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },
    {
      "id": "456",
      "name": "Donna Snider",
      "position": "Customer Support",
      "salary": "$112,000",
      "start_date": "2011/01/25",
      "office": "New York",
      "extn": "4226"
    },
    {
      "id": "567",
      "name": "Cedric Kelly",
      "position": "Senior Javascript Developer",
      "salary": "$433,060",
      "start_date": "2012/03/29",
      "office": "Edinburgh",
      "extn": "6224"
    },
    {
      "id": "432",
      "name": "Airi Satou",
      "position": "Accountant",
      "salary": "$162,700",
      "start_date": "2008/11/28",
      "office": "Tokyo",
      "extn": "5407"
    },
    {
      "id": "987",
      "name": "Brielle Williamson",
      "position": "Integration Specialist",
      "salary": "$372,000",
      "start_date": "2012/12/02",
      "office": "New York",
      "extn": "4804"
    }
  ];

  var table = $('#example').DataTable( {
    data: dataSet,
    columns: [
      {
        "className": 'details-control',
        "orderable": false,
        "data": null,
        "visible": false, // do not show the open/close column
        "defaultContent": ''
      },
      { "data": "name" },
      { "data": "position" },
      { "data": "office" },
      { "data": "salary" }
    ],
    "order": [[1, 'asc']]
  } );

  // force each child row to be displayed:
  $("#example").DataTable().rows().every( function () {
    this.child( format(this.data()) ).show();
    $( this.node() ).addClass('shown');
  });

} );
<!doctype html>

  <meta charset="UTF-8">
  <title>Demo</title>

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

                Name
                Position
                Office
                Salary

                Name
                Position
                Office
                Salary

In the above example, look specifically at the format ( rowData ) function.
In my demo, that function simply assembles some very basic HTML, as a string. That HTML is displayed as the content of the child row.
In your case, you can build much more complex HTML, representing the horizontally-aligned row of buttons you want to display underneath each row.


text:
Q: MacOS LLDB | Thread 1: EXC_BAD_ACCESS (code=1 & 2, address=0x123456789) So to start, I am not too knowledageble in C++, I know very little from a class I took a while back. Almost everything I have so far is from this very generous and knowledgable community.
I have to use a wack piece of custom software for work on MacOS and it doesn't have any form autosave and it occasionally likes to crash. Though I regularly save, its annoying loosing any amount of work because it crashes.
What I am trying to do is use the save function address to save and repeat every 5 or so minutes. So far I have the process id, the runtime base memory address for the process, the offset of the save function address(I have subtracted the disassembler base address from the address I found with debugging and disassembling), and the arguments it requires. When I try to run the save function I get the lldb error Thread 1: EXC_BAD_ACCESS (code=1, address=0x10a106ecf) and sometimes it changes to Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf). I have found other questions about this error on this website, but it either doesn't apply to my situation, or due to my limited knowledge I just don't understand how to solve it for my case. If anyone could explain in detail what I am doing wrong in detail along with a solution, it would be much appreciated because I would like to get an understanding and learn.
The project is a Command Line Utility in Xcode. I'm not sure if it would need to be a .dylib and added into the process, but if it could be an external command line utility, that would be more optimal for me.
Here is the problem code:
mach_vm_address_t runtimeBase = 0; // Base process memory address. Set in the getProc() function
mach_vm_address_t funcBase = 0x973ECF; // Function Address from disassembling. (0x100973ECF - 0x100000000 = 0x973ECF)

int main()
{
    if (!getProc()) throw std::logic_error("Failed to get Process.");

    typedef mach_vm_address_t(__cdecl* autoSave)(int saveType, const char* saveMessage);
    autoSave save = (autoSave)(runtimeBase + funcBase);
    for(;;)
    {
        save(0, "AutoSave");//    <-- Error Here: Thread 1: EXC_BAD_ACCESS (code=1/2, address=0x10a106ecf)
        //sleep(5); //add sleep after I get save to work.
    }
}

/*
 saveType:
    0 = Save local.
    1 = Save server.

 saveMessage: Message for history/save log.
 */

More detail I get from code=1 error is:
error: memory read failed for 0x10a106e00  <-- Thread 1: EXC_BAD_ACCESS (code=1, address=0x10a106ecf)

And for code=2 is:
0x10a106ecf: addb   %al, (%rax)            <-- Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf)
0x10a106ed1: addb   %al, (%rax)
0x10a106ed3: addb   %al, (%rax)
0x10a106ed5: addb   %al, (%rax)
0x10a106ed7: addb   %al, (%rax)
0x10a106ed9: addb   %al, (%rax)
0x10a106edb: addb   %al, (%rax)
0x10a106edd: addb   %al, (%rax)
0x10a106edf: addb   %al, (%rax)
0x10a106ee1: addb   %al, (%rax)
0x10a106ee3: addb   %al, (%rax)
0x10a106ee5: addb   %al, (%rax)
0x10a106ee7: addb   %al, (%rax)
0x10a106ee9: addb   %al, (%rax)
0x10a106eeb: addb   %al, (%rax)
0x10a106eed: addb   %al, (%rax)

A: With assembly explanations from @Peter Cordes I managed to solve my issue.

@Peter Cordes: addb   %al, (%rax) is how 00 00 decodes. Crashing there indicates that execution jumped to some memory that's all zeros, perhaps due to overwriting a return address or function pointer. Or if you have any hand-written asm, due to getting something wrong with the stack.

@Peter Cordes: The EXC_BAD_ACCESS (code=2, address=0x10a106ecf) is from trying to deref whatever garbage is in RAX, for read+write. The 00 00 garbage machine code decodes as instructions that try to access that "bad pointer". I haven't used LLDB much, or MacOS for development at all, but I'm guessing code=1 vs 2 might be read vs. write. (And I haven't really looked at the details of your question, just wanted to help out by explaining that seeing execution in a whole block of addb   %al, (%rax) instructions means you jumped to a region full of zeros; any mem access it attempts is already bogus.)

So, as @Peter Cordes said  addb   %al, (%rax) is how 00 00 decodes. Crashing there indicates that execution jumped to some memory that's all zeros.
From this we can infer that when Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf) happens it is because we jumped to a place in memory that is all zeros. But why are we jumping to a place in memory with all zeros? I am thinking it's because of how MacOS handles memory. Each process has its own memory space, and I was trying to jump to the address 0x10a106e00 in MY OWN process' memory, which does not exist. There are a multitude of resources explain how process memory works on modern OS's, just do a quick google search if you want to learn more.
So what we know now is:

*

*Thread 1: EXC_BAD_ACCESS (code=1, address=0x10a106ecf) happens because my program fails to read the memory for the specified address.

*Thread 1: EXC_BAD_ACCESS (code=2, address=0x10a106ecf) happens because we are jumping an invalid place in memory, and for the wrong process.

There was also some issues with the code, I was using code better suited for Windows, To create a function based on the memory address I did,
typedef mach_vm_address_t(__cdecl* autoSave)(int saveType, const char* saveMessage);
    autoSave save = (autoSave)(runtimeBase + funcBase);

And this is what I'm thinking a better/correct way of creating a function based on the memory address is:
int (*autoSave)(int saveType, const char* saveMessage) = (int (*)(int , const char *))(runtimeBase + funcBase);

The last thing I did was create a Dylib instead of a Command Line Utility. I did this because it is MUCH easier to access the target process' memory. Though what I am trying to achieve is probably possible through a Command Line Utility(CLU) and attaching to the target process as if the CLU was a debugger or some other method, for me it was much simpler and easier to just create a dylib.
If anyone reading this has any questions about my explanation, or want more detailed explanation/example of my solution. Feel free to send me a message or comment.
I once again want to thank @Peter Cordes for his explanations. They helped even though they said `I haven't used LLDB much, or MacOS for development at all'. The explanations were still extremely helpful and were explained in an easy to understand way.


text:
Q: PHP - page redirection when refreshed Is it possible to redirect the user to the start page of my site (it's written using PHP), when the user decides to refresh the site's page?
I'm new to PHP and haven't been able to figure it out on my own so far.
So, if it is possible, how should I do it?

A: try using header("Location:your_site_url_here"); for redirection ...

A: header('Location:your_url_here '); //Use something like this


text:
Q: GitHub Enterprise public vs. private repo If we are using GitHub Enterprise inside the company and the Private Mode is enabled, what's different between a public and private repo?

A: Typically, your Github Enterprise instances are visible to developers within your organization. However, also within your organization, you might want to have a more fine-grained control of who is allowed to see which repository.
Because of that, Github Enterprise knows two visibilities of repositories - private and public.
It's straight forward, as the documentation tells us:

Public repositories are a great choice for getting started! They're visible to any user on your GitHub Enterprise instance, so you can benefit from a collaborative community.
Private repositories require a little more setup. They're only available to you, the repository owner, as well as any collaborators you choose to share with.

Edit for clarification:
The Github Enterprise private mode, does regulate access on a different level: it merely defines that the forge itself cannot be accessed without being logged in.

A: Since May 23rd, 2019, you also have the internal repository visibility (still in beta)

The internal repository visibility option is available to customers with an Enterprise account.
This new visibility option makes it easier to innersource code and projects to your organization members while restricting access to outside collaborators.

That might be easier to manage than a private repo, where you need to add collaborators: here, every collaborators (to your organization) is already added to an internal repo: the rest of the world is not.
See more at "Creating an internal repository":

You can use internal repositories to practice "innersource" within your enterprise account. Members of organizations in your enterprise account can collaborate using open source methodologies without sharing proprietary information publicly. For more information on innersource, see GitHub's whitepaper "An introduction to innersource."
All members of the enterprise account have read permissions to the internal repository and can create issues in the repository.
Members of the enterprise account can't edit the repository's code directly, but they can fork the repository and create a pull request from their fork.
Internal repositories are not visible to people outside of the enterprise account, including outside collaborators on organization repositories.

A: Private Mode for the GitHub Enterprise instance is a different concept than Public/Private settings for a Repository.

In private mode, GitHub Enterprise requires every user to sign in to access the installation. Anonymous clones over git:// are disabled and—if built-in authentication is enabled—new users can't sign up and must be invited by an administrator.

So the private mode setting really means that users must log in to access the instance. If your GitHub Enterprise instance is on a public-facing IP, it needs to have private mode enabled.
Public and Private repositories will still affect visibility/access to users that belong to an Organization, Team, or Repository.

A: Public Repositories : They're visible to any user on your GitHub Enterprise instance.
Private Repositories : They're only available to the repository owner. You can add collaborators of your choise to share with.
You can keep all the repositories in the your organization's GitHub Enterprise to Private by default with exception to a few repositories which contain sensitive information. This is a good way to keep reusing the code in the same organization. If you have a repository you want made Public instead of Private you can request to your GitHub Enterprise to white-list it.


text:
Q: Naming of Activity in android I am using someone else's code and they have the following code
Intent j = new Intent();
j.setClass(this, ReplaceActivity_.class);

but the class they have is "ReplaceActivity". Is there a reason for the "_" after the ReplaceActivity? I am using intelliJ and it gives me a compiler error.

A: It's for a framework called AndroidAnnotations. The framework reduces boilerplate code by generating bytecode at compile time. The generated Activities have an underscore appended to their names, which is (presumably) why you see this.

A: try like this
Intent i = new Intent (presentActivity.this,ReplaceActivity_.class);
StartActivity(i);


text:
Q: Eigenvectors of asymmetric graphs Let $G$ be an asymmetric connected graph. Then is it always the case that at least one of the eigenvectors of its adjacency matrix $A$ consists entirely of distinct entries?
Thanks!

A: I think the answer is no. Take the Frucht Graph, the simplest nontrivial asymmetric graph. Its adjacency matrix is
\begin{equation*}
\left(
\begin{array}{cccccccccccc}
 0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 \\\\
 1 & 0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\
 0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\
 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\
 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 \\\\
 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 & 1 & 0 & 0 \\\\
 1 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 1 & 0 \\\\
 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 \\\\
 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\\\
 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 1 \\\\
 1 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 \\\\
 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 0 & 0
\end{array}
\right)
\end{equation*}
none of whose eigenvectors seems to have distinct entries.


text:
Q: When Sauron saw Frodo at Mount Doom, why doesn't he do anything? In the film (3.15), the Eye of Sauron sees Frodo on the corner of Mount Doom.
Maybe he didn't think that they are the ones trying to destroy the ring, but at least he sees someone who is a stranger in his land.
Shouldn't he react this situation in some way?
Edit:
I am talking about this scene:

A:
And far away, as Frodo put on the Ring and claimed it for his own, even in Sammath Naur the very heart of his realm, the Power in Barad-dûr was shaken, and the Tower trembled from its foundations to its proud and bitter crown. The Dark Lord was suddenly aware of him, and his Eye piercing all shadows looked across the plain to the door that he had made; and the magnitude of his own folly was revealed to him in a blinding flash, and all the devices of his enemies were at last laid bare. Then his wrath blazed in consuming flame, but his fear rose like a vast black smoke to choke him. For he knew his deadly peril and the thread on which his doom now hung.
From all his policies and webs of fear and treachery, from all his stratagems and wars his mind shook free; and throughout his realm a tremor ran, his slaved quailed, and his armies halted, and his captains suddenly steerless, bereft of will, wavered and despaired. For they were forgotten. The whole mind and purpose of the Power that wielded them was now bent with overwhelming force upon the Mountain. At his summons, wheeling with a rending cry, in a last desperate race there flew, faster than the winds, the Nazgûl, the Ringwraiths, and with a storm of wings they hurtled southwards to Mount Doom.
— TRotK

He did respond — he sent the Nazgûl. But he was too late, the Ring was eaten, and he was defeated.

A: The Book
In the book he doesn't spot Frodo until it is too late because he is focused upon the fight between his forces and the armies of Gondor/Rohan who although outnumbered are still interesting enough to warrant watching. It is like if I was watching a film in which I knew the outcome (the fight) instead of two ants crawling across the floor (the Hobbits). Also Sauron wanted to watch the defeat of his greatest enemies: the Númenóreans and Gandalf.
In the book he only notices Frodo when he claims the Ring.
The Film
In the film he sees them but presumably doesn't know they have the Ring and decides to ignore them for now and focus on more interesting things. They will probably get killed by orcs anyway.

A: If you watch it again, you will notice that the Nazgûl turn around to Mount Doom and attempt to take Frodo out. Now Sauron no longer has a powerful physical form  (see the four fingers passage in the book) at that time and therefore cannot do anything about Frodo. So, he does react by calling the Nazgûl's attention to the situation, but he himself cannot do anything.


text:
Q: Monitor custom kubernetes pod metrics using Prometheus I am using Prometheus to monitor my Kubernetes cluster. I have set up Prometheus in a separate namespace. I have multiple namespaces and multiple pods are running. Each pod container exposes a custom metrics at this end point, :80/data/metrics . I am getting the Pods CPU, memory metrics etc, but how to configure Prometheus to pull data from :80/data/metrics in each available pod ? I have used this tutorial to set up Prometheus, Link

A: You have to add this three annotation to your pods:
prometheus.io/scrape: 'true'
prometheus.io/path: '/data/metrics'
prometheus.io/port: '80'

How it will work?
Look at the kubernetes-pods job of config-map.yaml you are using to configure prometheus,
- job_name: 'kubernetes-pods'

        kubernetes_sd_configs:
        - role: pod

        relabel_configs:
        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
          action: keep
          regex: true
        - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
          action: replace
          target_label: __metrics_path__
          regex: (.+)
        - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
          action: replace
          regex: ([^:]+)(?::\d+)?;(\d+)
          replacement: $1:$2
          target_label: __address__
        - action: labelmap
          regex: __meta_kubernetes_pod_label_(.+)
        - source_labels: [__meta_kubernetes_namespace]
          action: replace
          target_label: kubernetes_namespace
        - source_labels: [__meta_kubernetes_pod_name]
          action: replace
          target_label: kubernetes_pod_name

Check this three relabel configuration
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: ([^:]+)(?::\d+)?;(\d+)
    replacement: $1:$2
    target_label: __address__

Here, __metrics_path__ and port and whether to scrap metrics from this pod are being read from pod annotations.
For, more details on how to configure Prometheus see here.

A: The link provided in the question refers to this ConfigMap for the prometheus configuration. It that ConfigMap is used then prometheus is already configured to scrape pods.
For that configuration (see relabel_configs) to have prometheus scrape the custom metrics exposed by pods at :80/data/metrics, add these annotations to the pods deployment configurations:
metadata:
  annotations:
    prometheus.io/scrape: 'true'
    prometheus.io/path: '/data/metrics'
    prometheus.io/port: '80'

See the configuration options for Kubernetes discovery in the prometheus docs (scroll down) for settings related to scraping over https and more.
Edit:
I saw Emruz Hossain's answer only after I posted mine. His answer currently lacks the prometheus.io/scrape: 'true' annotation and specified = instead of : as annotations' name/value separator which is invalid in yaml or json.


text:
Q: Can't Install PIL 1.7 I have python 2.7.3 and I want to install PIL 1.7.
I downloaded "PIL-1.1.7.win32-py2.7" and try to install it but it shows me an error messege that it can't find python 2.7 in the registry.

"python version 2.7 requried, which wasn't found in the registry".

I double check and I'm sure that I have python 2.7.3.
what is the problem?

A: As the message says, PIL installer can't find registry keys, this because python installer put values in 32 bit OS version path "HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.7" but for 64 bit OS version it should be set in "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7".
Easy fix is to copy and paste below in a text file, then change the extension to .reg and run it, it will add the required registry, then install PIL.
Copy from here to the end:
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help\Main Python Documentation]
@="C:\\Python27\\Doc\\python273.chm"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath]
@="C:\\Python27\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Modules]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\PythonPath]
@="C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk"

A: Try pre compiled Windows binaries:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil


text:
Q: Google Tag Manager (GTM) intermittently not firing in ASP The Google Analytics / Conversions / Transactions indicate that the Tag only works sometimes - if I perform the tasks and watch what happens and/or debug it always works but when the public/others do it sometimes it works and sometimes it doesn't
The implementation is a step by step, wizard approach, Rental Car Booking. At the end of the process, we store the booking in a database, draw up a Thankyou page, firing te GTM to record the transaction in GA, and we send a confirmation email to the user.
The Setup:
GTM
Created Tag "Booking Value Transaction" - Type=Universal Analytics, Enabled Display Advert Features, Track Type = Transaction
Added 2 Rules
    Rule Name = "BookNow" - Conditions    {{url}} contains thankyou   + {{event}} contains gtm.dom
    Rule Name = "BookNow_Mobile"  - Conditions   {{url}} contains mobileBooking  + {{event}} contains gtm.dom
ASP page
At the beginning of the

Later in the page various ASP code calls database functions etc to store data and retrieve data for display and builds the data to populate the GTM datalayer
Eventually it produces the following (with appropriate values set):

Following the above and before the end of the  (because putting it at the top beneath the datalayer definition looked like an issue) the rest of the GTM script is inserted

<% 'at the bottom of the page because the gtm.DOM async might not be performing like we want %>

I have tried all sorts to get to the bottom of this but I am completely stumped.
How do I get this to reliably fire all the time?

A: The dataLayer.push() only gets the data into the dataLayer; it does not send the data to Google. You need some sort of tag that fires to carry the dataLayer data with it.
Usually this is done with the standard page view tracker, but you have to have all of the data in the dataLayer BEFORE the page view tracker fires. In a standard GTM implementation, the page view tracker fires as soon as the GTM container code is finished loading. The loading order in your thank you page should be as follows:

*

*Declare dataLayer with all e-commerce information. Do not use
dataLayer.push(). You should have all of the necessary data to
populate dataLayer in your e-commerce system before the the page
loads. Retrieve this data and put it into dataLayer.

*Load your GTM container. This is the standard code provided by GTM.

All of this should be done immediately after the  open tag and not at the bottom of the page code before the  close tag.
If you can not populate dataLayer before the GTM container code loads, then you will have to fire a GA event tag on gtm.dom to carry the transaction data.
It's likely that your inconsistent firing of the transaction data is due to the race conditions caused by improper GTM implementation.


text:
Q: Common Lisp symbol equality In most of the examples on the Internet, symbol equality is straight-forward:
(eq 'sym 'sym)
t

In my program, I want to compare symbols in a custom package:
(defpackage #:my-package
  (:use    #:common-lisp)
  (:export #:my-function))

(in-package #:my-package)

(defun my-function (value)
  (cond
    ((eq value 'sym)
     (format t "SYM: YES~%"))
    (t
     (format t "SYM: NO~%"))))

(in-package #:common-lisp)

(my-package:my-function 'sym)

But when this code is executed, it displays:
SYM: NO

It seems like the 2 symbols are different:
(eq 'sym 'my-package::sym)
nil

The reason seems easy to understand, a symbol interned in a given package is not equal to a symbol with the same name interned in another package. Fair enough! But what is the idiom to compare 2 symbols, regardless the package?
Should we convert it to a string in a first place and compare strings?
(defpackage #:my-package
  (:use    #:common-lisp)
  (:export #:my-function))

(in-package #:my-package)

(defun my-function (value)
  (cond
    ((string= (symbol-name value) "SYM")
     (format t "SYM: YES~%"))
    (t
     (format t "SYM: NO~%"))))

(in-package #:common-lisp)

(my-package:my-function 'sym)

The result is better, but there is an obvious issue regarding the character case.
How to check that 2 symbols are the same regardless their package?

A: The usual idiom is string=, which compares the names of symbols without regard to identity.
For example:
(eq 'x:a 'y:a) => nil
(string= 'x:a 'y:a) => t

A: I think you are confused about what 'being the same symbol' means.
Two symbols are the same symbol iff they are eq, which means that if they are not eq they are not the same symbol.  In particular if two symbols have home packages which are different (again: not eq) they are not the same symbol.
If you want to know if two symbols have the same name then simply compare their symbol-names, as strings.  But two symbols which merely have the same name are not necessarily the same symbol (for instance (eq '#:foo '#:foo) is false).
There are cases where it is useful to know whether two symbols have the same name (for instance the loop macro must do this so that (loop for ...) and (loop :for ...) mean the same thing) but these cases are fairly rare.
If what you want to do is know if two symbols have the same names you quite likely should be using strings instead.
If what you actually want to know is whether two symbols accessed from different packages are really the same symbol (so (eq 'x:foo 'y:foo), say) then eq is the appropriate test, and understanding the package system also helps.


text:
Q: POST AJAX returning empty array, even console.log has value My ajax postdata is returning empty array on my php side. but if i console.log there is value of my post data. WHy im still receiving empty array?

this is my ajax code
$(document).on("submit","#form_registrationalumni", function(e){
    var postData = $(this).serializeArray();
       console.log(postData);
    $.ajax({
        url: baseUrl+"/register/registeralumni/",
        type: 'POST',
        data: postData,
        cache: false,
        success: function(data){
            if(data == 1){
                showSuccess('Thank you for Registering Louisian! Your registration is subject to evaluation, you will be receiving an email once registration is approved by the administrator.');
                clearForm('#form_registrationalumni');
            }else{
                showError(data);
            }
        }
    });
    e.preventDefault();
});

on my backend im just trying to simply display the array but it return 0
my whole code works on may localhost. this error is showing in my web server.
can anyone help me fix this. thanks in advance
this is my backend, i tried also checking my network if it is posted


text:
Q: MVC How to count records in related Models? I have two models, First is Relations, which is opened with Date, second model is Reservations, now i need to count record in reservations which have choiced Date of Relations. The tables is in Relationship relID from first i record in second table in DatumRID.
How to count records in Reservations which is related by ID to Relations
Model Relations:
  public tbl_relacii()
        {
            tbl_rezervacii = new HashSet<tbl_rezervacii>();
        }
        [Key]
        public int relID { get; set; }
        [Column(TypeName = "date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DatumR { get; set; }
        public int sedista { get; set; }
        public string vozilo { get; set; }
        [StringLength(50)]
        public string shofer1 { get; set; }
        [StringLength(50)]
        public string shofer2 { get; set; }
        public string noteR { get; set; }
        public virtual ICollection<tbl_rezervacii> tbl_rezervacii { get; set; }
        public string DatumForDisplay
        {
            get
            {
                return DatumR.ToString("d");
            }
        }

Model Reservations:
 public partial class tbl_rezervacii
    {
        [Key]
        public int rID { get; set; }
        public int AgentID { get; set; }
        [StringLength(10)]
        public string karta_br { get; set; }
        public int DatumRID { get; set; }
        public int patnikID { get; set; }
        public int stanicaOD { get; set; }
        public int stanicaDO { get; set; }
        public decimal cena { get; set; }
        public bool povratna { get; set; }
        public DateTime? DatumP { get; set; }
        public string noteP { get; set; }
        public virtual tbl_agenti tbl_agenti { get; set; }
        public virtual tbl_patnici tbl_patnici { get; set; }
        public virtual tbl_relacii tbl_relacii { get; set; }
        public virtual tbl_stanici tbl_stanici { get; set; }
        public virtual tbl_stanici tbl_stanici1 { get; set; }
       public string relacija
        {
            get
            {
                return tbl_stanici.stanica + "=>" + tbl_stanici1.stanica;
            }
        }
        public string relacijaP
        {
            get
            {
                return tbl_stanici.stanica + "=>" + tbl_stanici1.stanica + "=>" + tbl_stanici.stanica;
            }
        }
    }

And here is Controller for Relations Index:
  public ActionResult Index()
        {
               return View(db.tbl_relacii.ToList().OrderByDescending(x => x.DatumR));
        }

How to count records in Reservations then put Number of records to index of Relations?

A: I think you can achieve using LINQ query. Please find the sample below.
var q = from d in Model.Reservations
        select new Relations
        {
            Count = d.Reservations.Count()
        };

A: I solved simply.  In relations model i added just this:
   public int Count
    {
        get
        {
            return tbl_rezervacii.Count;
        }
     }

And problem is Solved. Thank you


text:
Q: Where to store ODP.NET Managed Driver Connection Strings? Finally got ODP.NET configured and the Oracle.ManagedDataAccess DLL referenced in the project.
I was testing with a TNS connection in the code behind in a WPF project (see below).
This question is probably elementary, but I can't find any good information on this, as all examples/jump-starts show embedding the connection string like this.
Is there a better (more common) way to store the connection string for ODP.NET to make it easier to maintain (i.e. it should be a configuration change that doesn't require completely rebuilding the code if it should change)?  For example, similar to storing in app.config for SQL Server and IIS?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;

namespace TEST
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private OracleConnection con;

        public MainWindow()
        {
            InitializeComponent();

            try
            {
                con = new OracleConnection("User Id=*****; Password=******; Data Source=******");
                con.Open();

            }
            catch (OracleException oracleErr)
            {
                MessageBox.Show(oracleErr.Message);
            }
            finally
            {
                con.Close();
            }
        }

    }
}

A: In case you used the tnsnames.ora from the Oracle Client for the unmanaged version then for the managed version you just have to copy the tnsnames to your project directory.


text:
Q: How to make linear regression for time intervals? I have two to three hours data measured in seconds. I want to split this up in 11 intervals and make a linear regression on each interval.
The first time interval can be from 7-17 minutes and the next 18 - 27 minutes. My data has a column of seconds and and a column for the measuring in the champer.
I have started to make a plot
library(readr)
s24kul05p <- read.delim("C:/Data/24skulp05.txt", quote="")
View(s24kul05p)
s24kul05p
head(s24kul05p)
tail(s24kul05p)
data("s24kul05p")
plot(Ch1~Min, data=s24kul05p, ylim =c(170,250), xlim=c(1, 151), col="red")
abline(lm(Ch1~Min, data=s24kul05p))

After this I get a plot with one linear model, and it could be nice if it was possible make 11 linear models?

A: Drop it into a matrix of 11 columns, then turn it into a data.frame again. You'll have 11 variables to run regression.
Y <- runif(231)
M <- matrix(Y, ncol = 11)
M <- as.data.frame(M)


text:
Q: Pseudo terminal problems (Mac/Linux): SIGTTOU & Inappropriate ioctl I am working on a pseudo terminal library. The code is implemented in C code and the code is used by a web based terminal. The code works as long as I do not use sudo or login.
This is the error I get when I run the server on a Mac:
sh-3.2$ sudo ls
Password:
[1]+  Stopped(SIGTTOU)
sh-3.2$

The above works on Linux:
$ sudo ls
  readme.txt

However, I get the following on Linux with sudo bash:
$ sudo bash
bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
]0;root@ubuntu: /tmproot@ubuntu:/tmp#

Note: the above works, but I have no job control.
I have probably forgot to set some controlling bits on the terminal, but Google has not been very helpful in finding this.
Also, do you know of any good books that explains Pseudo terminal management in great detail.
I have the setsid call, but I am not using openpty. I use the following code when opening the pty:
static int createPty(lua_State* L, char* ttyName, int* pty)
{
   *pty = getpt();
   if (*pty < 0 || grantpt(*pty) < 0 || unlockpt(*pty) < 0)
      return lDoErr(L,"Cannot open PTY: %s",strerror(errno));
   if(ptsname_r(*pty, ttyName, PTY_NAME_SIZE-1))
      return lDoErr(L,"ptsname_r: %s",strerror(errno));
   return 0;
}

I have edited the code below and this code works. The reason my first version did not work was that I tried to create two PTY channels. I wanted to be able to differentiate between stdout and stderr, but the Linux kernel does not allow multiple TIOCSCTTY calls.
static int
childOpenTTY(const char* ttyName)
{
   struct termios termbuf;
   int fd=open(ttyName, O_RDWR);
   if(fd < 0)
      doClientError("open %s: %s",ttyName, strerror(errno));
   tcsetpgrp(fd, getpid());
   ioctl(fd,TIOCSCTTY,NULL);
   tcgetattr(fd, &termbuf);
   cfmakeraw(&termbuf); /* turn off NL to CR/NL mapping on output. */
   tcsetattr(fd, TCSANOW, &termbuf);
   return fd;
}

if( (ret = createPty(L, ttyName, &te->pty)) != 0)
   return ret;
if ((te->pid = zzbafork()) < 0)
   return lDoErr(L,"fork: %s",strerror(errno));
if(te->pid == 0)
{  /* Child process */
   static const char efmt[]={"Cannot set '%s' (dup2 err)"};
   int fd;
   if(setsid() < 0) /* make new process group */
      doClientError("setsid: %s",strerror(errno));
   fd=childOpenTTY(ttyName);
   if(dup2(fd, STDIN_FILENO) != STDIN_FILENO)
      doClientError(efmt,"stdin");
   if(dup2(fd, STDOUT_FILENO) != STDOUT_FILENO)
      doClientError(efmt,"stdout");
   if(dup2(fd, STDERR_FILENO) != STDERR_FILENO)
      doClientError(efmt,"stderr");
   if(fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
      close(fd);
   execve(cmd, (char**)cmdArgv, environ);
   /* execve should not return, unless error exec cmd */
   doClientError("Executing %s failed: %s",cmd,strerror(errno));
}

A: It's hard to be sure since there's no actual code shown here, but I suspect you're running into POSIX-style "session" management.  You need to execute a setsid call, then open the pty (slave side) such that it becomes the controlling terminal.  The openpty and login_tty routines do the low level grunge work for you; are you using those?


text:
Q: aws-sdk-php + zend framework 2 skeleton => signal Segmentation fault (11) I'm trying to use AWS S3 in my recent project built on Zend Framework 2.
Something really strange happened and I have not been able to find the solution.
I started a fresh Zend Framework 2 Skeleton application and installed aws/aws-sdk-php via composer.
A simple S3::putObject request was created:
$client = S3Client::factory(array(
        'key' => 'xxx',
        'secret' => 'xxx',
        'region' => 'xxx',
    ));

$client->putObject(array(
                'Bucket' => $bucket,
                'Key' => '/test/test.html',
                'Body' => 'This is a test' . time(),
                'ContentType' => 'text/html',
                'Acl' => CannedAcl::PUBLIC_READ
            ));

The above code works fine when I test it in PHPUnit. However when I open the browser to see result from same IndexController, Firefox just reported 'The connection was reset'. PHP doesn't throw any exceptions
I opened Apache's error log and see:
[Tue Jul 08 04:58:58 2014] [notice] child pid 33428 exit signal Segmentation fault (11)
[Tue Jul 08 04:59:15 2014] [notice] child pid 33439 exit signal Segmentation fault (11)
[Tue Jul 08 04:59:16 2014] [notice] child pid 33361 exit signal Segmentation fault (11)
[Tue Jul 08 05:02:02 2014] [notice] child pid 33452 exit signal Segmentation fault (11)
[Tue Jul 08 05:02:50 2014] [notice] child pid 33142 exit signal Segmentation fault (11)
[Tue Jul 08 05:04:34 2014] [notice] child pid 33317 exit signal Segmentation fault (11)
[Tue Jul 08 05:04:35 2014] [notice] child pid 33143 exit signal Segmentation fault (11)
[Tue Jul 08 05:06:18 2014] [notice] child pid 33522 exit signal Segmentation fault (11)
[Tue Jul 08 05:06:19 2014] [notice] child pid 33534 exit signal Segmentation fault (11)

I googled the error and found different answers to this problem but none seems to apply to me.
After trying the latest Zend Server 7 I managed to nail down the problem in Guzzle\Http\Curl\CurlMulti, seems that something happened during curl_multi_* operations. I think the problem should be PHP is in infinite loop, but how come it works fine under PHPUnit? It has nothing to do with running from CLI because I just tried curl the same URL and got:
curl: (52) Empty reply from server

So it looks like the problem still come from inside the code...
Some posts from Google stating this curl problem might because of OSX Maverick's openssl issue but I don't think I have this problem since my curl works fine with any https requests.
And my research on this problem stops here :(
aws-sdk-php has been out for quite a long while I don't believe it is the lib's fault, can it be my machine? Here is my software environment
OSX Mavericks 10.9.4
Zend Server 7 with PHP 5.5.13
curl --version
curl 7.30.0 (x86_64-apple-darwin13.0) libcurl/7.30.0 SecureTransport zlib/1.2.5
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp
Features: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz

A: I spent hours tracking down the same problem, it happens when openssl support is not built into the version of libcurl used to build the curl extension:
build.log
checking for openssl support in libcurl... no

You'll need to install curl with openssl support, e.g. using brew: brew install curl --with-openssl (--with-openssl may not be required).
Once an openssl supported libcurl is available, you'll need to add the option --with-curl to your build command, for me this was phpbrew .. --with-curl=/usr/local/opt/curl.


text:
Q: Would removing spaces between product variant ids decrease index size in solr5? I have been saving some product specifications into Solr 5. Most of the products contain unique variant ids that use dashes or dots, like this: Samesung TV 54 : AD-oi-230, Sony TV 24 : 1.849.32s.s.
But occassionally, I come across some variant ids that use spaces instead of dashes, like Samsung 54 : OPD 1 jud, Sony 32 : s1 90 b33 9 337.
Since those ids don't have much meaning, if I removed those spaces (Samsung 54 : OPD1jud, Sony 32 : s190b339337), would it scale better or make the index size smaller?
Here is my field that stores the model name. I have enabled the WordDelimiterFilterFactory:
  <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    <analyzer>
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.WordDelimiterFilterFactory" preserveOriginal="0" generateNumberParts="1" splitOnCaseChange="0" catenateWords="1" splitOnNumerics="1" stemEnglishPossessive="0" generateWordParts="1" catenateAll="0" catenateNumbers="0"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.LengthFilterFactory" min="2" max="20"/>
    </analyzer>
  </fieldType>

A: Index size is not an issue here. Especially, since whatever you do with analyzers, you still have the original stored values.
However, what you describe (removing spaces) makes sense for normalization of values and to ensure that search matches whether the ID contained spaces or dashes. So, that's a better reason to look at this anyway.


text:
Q: Gcc extension or macro to check the bits used for some fundamental types at compile time At compile time, with some using static_asserts I would like to check the size in bits of some simple type like unsigned int or char, the important thing that it will be granted to happen at compile time given my usage .
I haven't found anything about this in the gcc manual nor I have any knowledge of a similar feature offered by clang, anyone knows how to check the number of bits used by a type ?
No sizeof please, my focus is on the bits and compile time .

A:
No sizeof please, my focus is on the bits and compile time .

Keep an open mind ;-P
#include <cstdint>

static_assert(sizeof(X) * CHAR_BIT == 32, "type X must be 32 bits in size");

A: 1. How to find the number of bits in a type without using the CHAR_BIT macro
If the type is a numeric type (like int and char), you can get the number of significant bits using std::numeric_limits<T>::digits, assuming that T is a binary type (that is, that std::numeric_limits<T>::radix == 2). Those are constexpr so they can be used in static_assert.
It is possible that the implementation is not capable of using all of the stored bits in some numeric type (other than char), in which case the number of significant digits may not relate to the physical size in bits. Also, the sign bit doesn't count, so you need to add std::numeric_limits<T>::is_signed to get the number of non-padding bits.
Since char types are not allowed to have padding and char, signed char and unsigned char are required to be exactly the same size, std::numeric_limits<unsigned char>::digits must be the number of bits in a char, otherwise known as the required macro CHAR_BIT. So you could use the two expressions interchangeably, and consequently the bit-size (physical, not meaningful) of any type T will be sizeof(T)*std::numeric_limits<unsigned char>::digits.
I don't believe that the compiler itself needs to know what the bitsize of char is (although most compilers probably do). It does need to know what sizeof(T) is for every primitive type. There is no standard-mandated way of figuring out what the value of  std::numeric_limits<unsigned char>::digits is without including some header file.
2. Why you shouldn't worry about it.
In a freestanding environment, <numeric_limits> is not required, but <climits> still is, so you can count on the CHAR_BIT even in a freestanding environment, while you can only count on std::numeric_limits<unsigned char>::digits in a hosted environment.
In other words, the compiler is obliged to have some way of providing the results of #include <climits>, because that header is required by the standard even in freestanding environments (that is, environments without a standard library or even operating system). That's the "built-in" you are looking for; even if you don't provide <climits> in your standard library implementation, and even if you don't have a standard library handy, the compiler must still arrange for the macro CHAR_BIT to be correctly defined following the occurrence of #include <climits>. How it does that is up to the compiler; <climits> does not have to be an actual file.
Notes

*

*None of the above will work with C, but then neither will static_assert so I am assuming that tagging this question as C was an oversight. As @mafso points out in a comment, C11 does have a static_assert declaration, but it only works with C11-style constant expressions, not C++-style constant expressions. C++ constant expressions can use things like constexpr functions, which might be built-in. C constant expressions, on the other hands, can only involve integer literals. They are still useful (for non-purists) because macro expansion happens first, and the macro can expand to an integer literal (or even an expression involving several integer literals).

A: According to this document, the gnu compiler will define these macros for you:
__CHAR_BIT__      // bits

__SIZEOF_INT__    // bytes
__SIZEOF_LONG__
__SIZEOF_LONG_LONG__
etc...

You can define your own Bit macros from the Byte macros by just multiplying by 8.
Edit:  Since you apparently need to know the "word size" and consider pointers to be the same size as a "word", then use this:
__SIZEOF_POINTER__


text:
Q: Laravel extend/include layout if variable == 0 Im using laravel 4.0 im tyring to display a layout only if a variable ==0 (just in case a user tries to navigate to the url instead of clicking through) (i know I can redirect instead of extending but this is undesirable for now)
I am trying to get the layout to only extend when the user navigates to the page manually,  noajax is set to true if their is no ajax request being sent when it goes to the function, so if the user where to navigate to the url manually it will still display  the page but extend the layout.
@if ($noajax==1)

@extends('layouts.master')
@endif
@section('content')

//controller
public function test($id,$model)
{

    if (Request::ajax())
        {
//$foreign_key and $model must be <> null
            if ($id == null || $model == null) {
                $this->render('../Errors/missing_arg', 'error');
                return;
            }

            if($model=="ArtObj")
            {
                $partable = "art_objects";
                $path='img/art-objects/';
            }

            $parid=$id;
            $noajax=0;

        $mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
        $response = Response::Json($mediaimgs);
        return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));

        }
        else{

            if($model=="ArtObj")
            {
                $partable = "art_objects";
                $path='img/art-objects/';
            }

            $parid=$id;

        $mediaimgs = Media::where('parent_id' , $id )->where('parent_table', $partable)->paginate(15);
        $response = Response::Json($mediaimgs);
        $noajax = 1;
        return View::make('/Admin/manageimage/manage_image',compact('parid','mediaimgs','model','path','noajax'));
        }
}

A: In this case you should use 2 views in controller.
In controller you should use:
if ($noajax) {
   return View::make('noajax');
}
else {
   return View::make('ajax');
}

In noajax view you can extend from any other view and if noajax and ajax have common code, you should put it in separate file and use @include in those both views to include common part of code.


text:
Q: Laravel & Redis - job killed after 10 minutes despite timeout set to 1800s I am using multiple redis queues on my laravel application for managing reoccurring tasks.
Everything is working fine except the jobs that are pushed to a queue that are usually running longer than 10 minutes - round about 9-15 minutes.
On Laravel forge I created a new worker on a redis queue with timeout 1800 but still jobs running longer than 10 minutes got terminated. Jobs under 10 minutes are working as intended.
Is there any configuration I am missing?

A: You should set the retry_after value to 1800 in config/queue.php.
You can create multiple redis queues which use the same connection, and dispatch your job on a specified queue.
queue.php:
'redis' => [
    'connection' => env('QUEUE_REDIS_CONNECTION'),
    'driver' => 'redis',
    'queue'  => 'default',
    'retry_after => 60
],
'redis_low' => [
    'connection' => env('QUEUE_REDIS_CONNECTION'),
    'driver' => 'redis',
    'queue'  => 'email',
    'retry_after => 1800
]

In your job:
Job::dispatch()->onQueue('email');


text:
Q: Excel VBA: Index = ZOrderPosition in a Shapes collection? Is the Index of a Shape in a Shapes collection of a Worksheet always the same as its ZOrderPosition? (One cannot in principle inquire directly about the Index of a given Shape).
I have verified this is true in a few cases (with up to 3000 Shapes), but I found no documentation on this.
I have traversed the whole collection, inquiring about possible differences between Index and ZOrderPosition:
Sub dump_shapes()
' Dump information on all shapes in a Shapes collection
    Dim shc As Shapes
    Set shc = ActiveSheet.Shapes
    Dim shp As Shape
    For Each shp In shc
      Dim sh2 As Shape
      Set sh2 = sh2idxzosh_shc(shp)
      Dim zoidx As Long
      ' The second argument is not actually the Index, but since we are traversing the
      ' whole collection, and Index and ZOrderPosition are at most permutations, we are
      ' covering all of the possible Indexes.
      zoidx = idx2zo_shc(shc, shp.ZOrderPosition)
    Next shp
End Sub

The functions used for inquiring are shown below. Since the warning in the MsgBox'es never popped, that means that Index=ZOrderPosition, for the cases evaluated.
' Functions between the set of shapes S and the set of natural numbers N.
' O=ZOrderPosition : S -> N  (function exists)
' D=From Index : N -> S  (function exists)
' D^-1=Index : S -> N  (function does not exist)
' f=OoD : N -> N  (can be constructed; this is expected to be only a permutation,
'  i.e., bijective)
' g=DoO : S -> S  (can be constructed)

Function sh2idxzosh_shc(ByRef sh As Shape) As Shape
    Dim shc As Shapes
    Set shc = sh.Parent.Shapes
    Dim zo As Long
    zo = sh.ZOrderPosition
    Dim sh2 As Shape
    Set sh2 = shc(zo)
    ' g=DoO : S -> S
    ' Test Shape : g(S)=S for all s? If so, g=DoO=I ; D=O^-1 ; D^-1=O. Thus, the Index
    '  is equal to the ZOrderPosition.
    ' Use ZOrderPosition to test Shape : O(g(s))=O(s) for all s? I.e., OoDoO=O? If so,
    '  given that O is bijective, OoD=I ; D=O^-1 ; D^-1=O. Thus, the index is equal to
    '  the ZOrderPosition.
    Dim zo2 As Long
    zo2 = sh2.ZOrderPosition
    If (zo2 <> zo) Then
      MsgBox ("Compound ZOrderPosition: " & zo2 & ", ZOrderPosition: " & zo)
    End If
    Set sh2idxzosh_shc = sh2
    'Set sh2 = Nothing
End Function

Function idx2zo_shc(ByRef shc As Shapes, idx As Long) As Integer
    Dim sh As Shape
    Set sh = shc(idx)
    Dim zo As Long
    zo = sh.ZOrderPosition
    ' f=OoD : N -> N
    ' Test index : f(i)=i for all i? If so, f=OoD=I ; D=O^-1 ; D^-1=O. Thus, the Index is
    '  equal to the ZOrderPosition.
    If (zo <> idx) Then
      MsgBox ("Index: " & idx & ", ZOrderPosition: " & zo)
    End If
    idx2zo_shc = zo
End Function

PS: I have adapted the functions for the ChartObjects collection of a Worksheet, and the equivalence Index=ZOrder was also verified.
PS2: One may ask if this is typical of (or even guaranteed for) any collection. In Excel VBA: non sequential numbering of ZOrderPosition in Shapes collection I reported a case where, not only this is not true, but Index and ZOrderPosition are not even permutations (note that it was the Shapes collection of the Shape associated with a ChartObject, a case different from that mentioned above).
Edit: See Edit in Excel VBA: How to obtain a reference to a Shape from the ChartObject.

A: The rule "ZOrderPosition = index" for the shapes of an excel sheet is ** NOT ** true if you make a group of shapes. For example if you have the shapes "A","B","C","D,"E","F" in Zorder 1 to 6 and then you group shapes "B", "C", "D" together, you will break the "ZOrderPosition = index" rule for the shapes "E" and "F". If you list the shapes(i) you will get the following:

index  ZOrder  Name
 1       1      "A"
 2       2      "Group 1"
 3      *6*     "E"
 4      *7*     "F"

Here the code for getting the previous info:
Sub DebugListInfoOfShapes()
    Dim i As Long
    Debug.Print "Index   ZOrder   Name"
    For i = 1 To ActiveSheet.Shapes.Count
        Debug.Print i & "         " _
                      & ActiveSheet.Shapes(i).ZOrderPosition _
                      & "      " _
                      & ActiveSheet.Shapes(i).Name
    Next i
End Sub

Hoping this clarify you question!
Regards, Andres
PD: If you want to see shapes "B", "C", "D" you have to loop inside the group using for example: ActiveSheet.Shapes(2).GroupItems(i) for the case above.


text:
Q: How to run ggvis function on remote dplyr tbl? My apologies if this is not a reproducible example but I am not aware of any public db I could use for it (please comment if you have any suggestions and I'll edit the question).
I have a shiny app that calls to a db (Database: mysql 5.6.27-log), and then plots using ggvis. I am using the following pkgs version:
[1] ggvis_0.4.3   dplyr_0.5.0   RMySQL_0.10.9 DBI_0.5

What I have is a bunch of reactive tbls that need a collect() before going into a ggvis function. I thought compute() could work as well and would have made the app faster, but I can't get ggvis to inherit what is coming from a dplyr query.
For example something like:
tbl(con, 'graduation') %>%
  select(first, second) %>%
  compute() %>%
  ggvis(~first, ~second)

Gives me this error message

Error in UseMethod("prop_type") :
    no applicable method for 'prop_type' applied to an object of class "c('tbl_mysql', 'tbl_sql', 'tbl_lazy', 'tbl')"`

So the question would be how can I pass remote tables to ggvis; but besides that, I would like a feedback on whether what I am trying to do makes sense at all and could in fact speed up the application.


text:
Q: php passing a utf-8 encoded string fails on soapCall passing a correctly encoded utf-8 string to a php soapCall and it returns that it is not a valid utf_8 character.

$source = "test"-@– '— " ½ ℗ ↄ⃝ it′s 'single'
echo mb_detect_encoding( $source, "auto" ) is UTF-8
hex = E2 80 9C 74 65 73
74 E2 80 9D 2D 40 E2 80 93 20 27 E2 80 94 20 22 20 C2 BD 20 20 E2 84
97 20 20 E2 86 84 E2 83 9D 20 20 69 74 E2 80 B2 73 20 E2 80 98 73 69
6E 67 6C 65 E2 80 99
Error: processSalesOrder interupted because of SOAP-ERROR: Encoding:
string '\x9c...' is not a valid utf-8 string

returns: �TEST�-@� '� " ½  � ��  IT�S �SINGLE�
added 'encoding' => 'UTF-8' to both the soapClient init options and to the soapCall options.
mariadb Database, table, column are utf8mb4, collation utf8mb4_unicode_ci
php.ini default_charset = "UTF-8"
database connection is set to utf8mb4
html page set to charset=utf8
Displays correctly on webpage.
encoding detect shows UTF-8 right before sending to soapCall, but is rejected by soapCall.
What am I missing?
EDIT:
I also used suggestion from PHP DOMDocument::save() saves as ASCII instead of UTF-8 but it didn't help.

$xmlDomDoc->encoding = 'UTF-8';

I finally resolved the issue changing settings in php.ini for [iconv] and [mbstring] to UTF-8

iconv.input_encoding = UTF-8
iconv.internal_encoding = UTF-8
iconv.output_encoding = UTF-8
mbstring.internal_encoding = UTF-8
mbstring.http_input = UTF-8

A: When trying to use utf8/utf8mb4, if you see Black Diamonds with question marks,
one of these cases exists:
Case 1 (original bytes were not utf8):

*

*The bytes to be stored are not encoded as utf8.  Fix this.

*The connection (or SET NAMES) for the INSERT and the SELECT were not utf8/utf8mb4.  Fix this.

*Also, check that the column in the database is CHARACTER SET utf8 (or utf8mb4).

Case 2 (original bytes were utf8):

*

*The connection (or SET NAMES) for the SELECT was not utf8/utf8mb4.  Fix this.

*Also, check that the column in the database is CHARACTER SET utf8 (or utf8mb4).

Black diamonds occur only when the browser is set to <meta charset=UTF-8>


text:
Q: thread1:EXC_BAD_ACCESS (code=1,address=) ios I have been facing this issue on iOS simulator (6 & 7). Tried resetting phone but same problem.
Getting this error when loading another view controller
#   Event Type  ∆ RefCt RefCt   Timestamp   Responsible Library Responsible Caller
0   Malloc  +1  1   00:33.396.540   UIKit   UINibDecoderDecodeObjectForValue
1   Retain  +1  2   00:33.397.009   UIKit   -[UIRuntimeConnection initWithCoder:]
2   Retain  +1  3   00:33.397.047   UIKit   UINibDecoderDecodeObjectForValue
3   Retain  +1  4   00:33.397.064   UIKit   UINibDecoderDecodeObjectForValue
    Retain/Release (2)          00:33.397.537   UIKit   -[UIViewController setView:]
6   Retain  +1  5   00:33.397.548   UIKit   -[UINib instantiateWithOwner:options:]
7   Release -1  4   00:33.397.592   UIKit   -[UINibDecoder finishDecoding]
    Release (2) -2      00:33.397.647   UIKit   -[UINibDecoder finishDecoding]
10  Release -1  1   00:33.397.712   UIKit   -[UIRuntimeConnection dealloc]
11  Release -1  0   00:33.409.138   UIKit   _UIApplicationHandleEvent
12  Zombie      -1  00:35.524.392   UIKit   ___updateViewDependenciesForConstraint_block_invoke_0

Tried profiler, zombie got below error but unable to process further. Can someone guide next steps?
An Objective-C message was sent to a deallocated UIView object (zombie) at address: 0xbede440.
updateViewDependenciesForConstraint_block_invoke_0+0x4d"
+0x3f   movl                2704706(%edi), %ecx
+0x45   movl                %eax, 8(%esp)
+0x49   movl                %ecx, 4(%esp)
+0x4d   movl                %esi, (%esp)
+0x50   calll               "DYLD-STUB$$objc_msgSend"
+0x55   addl                $16, %esp
+0x58   popl                %esi`enter code here`
+0x59   popl                %edi
+0x5a   popl                %ebp
+0x5b   ret
+0x5c   nopl                (%eax)

Sample code
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)tableIndexPath {

//Logic for validation
XXXXXXXXXXx

[self performSegueWithIdentifier:@"ADDXXXX" sender:self];
        return;

}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"ADDXXXX"]){
        ADDXXXX *myVC = [segue destinationViewController];
        myVC.setXXX
        NSLog(@"INIT %p", self);
    }
}

A: ok, was able to resolve it by referring to this thread in stack overflow. Thanks all for your response.
[UIView _forgetDependentConstraint:]: message sent to deallocated instance