text:
Q: In tensorflow why for a same dropout value of 0.8 when run with adam optimiser with 50epochs give different accuracy each time i run it? I am building ANN as below:-
model=Sequential()
model.add(Flatten(input_shape=(25,)))
model.add(Dense(25,activation='relu'))
model.add(Dropout(0.8))
model.add(Dense(16,activation='relu'))
model.add(Dropout(0.8))
model.add(Dense(5,activation='relu'))
model.add(Dense(1,activation='sigmoid'))

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])

model.fit(xtraindata,ytraindata,epochs=50)
test_loss,test_acc=model.evaluate(xtestdata,ytestdata)
print(test_acc)

I am adding different features into the model and checking whether the newly added feature decreases or increases the accuracy but the problem is that each time I run this code with the same values I get different accuracy, sometimes it gets as low as 0.50 and so, I have few doubts and kindly answer them:-

*

*Is the model giving different accuracy each time because in dropout reg. there are random dropouts in nodes and each time I run diff. nodes get silenced so thereby giving different accuracies i.e sometimes low and sometimes high?

*How can I trust the accuracy of the model if each time it gives different accuracies? How can I know that the feature I have added has resulted in a decrement or increment of the accuracy?

*If I get high accuracy and wanted to reproduce these results how do I save the parameters that the model has used?

A: Great questions. Answers:

*

*I think your theory is right; it's the dropout. That's the only layer with an element of randomness each run, so it's likely the culprit. Try removing that layer, leaving everything else fixed, and run multiple times. Check if the accuracy is the same.

*Cross validation. This article explains how it works, but the gist is that it is a statistical technique that trains and checks the accuracy of multiple runs of your model, all with different slices of data. The average accuracy of all runs is used. So highs and lows will be averaged to a true(ish) accuracy. That being said, if your model has inconsistent results by just varying dropout, it's an indicator that when you move the model to production and use real data, it will perform poorly.

*Keras api has a method model.save("model_name") to save models. You can use keras.models.load_models("model_name") to get it back. As I said in point 2 though; if your model is so finicky that some trainings drastically affect accuracy, then even if you train and get good accuracy, it probably won't be useful on new data. So when you say "If I get high accuracy and wanted to reproduce these results", really you shouldn't be thinking along these lines. Instead, try to get consistently high training accuracy.


text:
Q: Does Akamai support anycasted origins? I wonder if Akamai supports origins with anycast IP addresses?
Or will requests to origins be routed within Akamais networks to just one (almost random) location?
I'd expect Akamai to route the request to the origin closest to the edge server.

A: Yes, Akamai does support AnyCast IP-addresses for your Origin Server. When the Akamai EdgeServer has to go forward to your origin, it will do a look-up based on IP or hostname you provided.
/akamaimike

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redux store is filled with a bunch of strange properties I've been using Redux for my project to store the application state, and until now it was working as expected. Then, I came to a stage where I needed to persist the store state across the app, and after looking online I tried integrating react-persist library.
The integration seems went well, and the store state is now persisted in the app.
HOWEVER, when I go to check out the store state in the redux dev in the browser I see a whole bunch of properties that I do not recognize AT ALL, and I do not see the slices that I created. I also see a bunch of unknown actions dispatched and when I dispatch my own action it does not show up in the actions list, but again, the app works perfect as I expect it to
This worries me because I used this dev tool very often to make the app work, but for future updates, I don't know how to debug.
Here is a screenshot of what the current store looks like in the dev tool.

I am not sure if any of the code would be useful, as I have no clue which part of the code could be a result of this. If you need to see a piece of code, I can add it upon request. Thank you.

A: I found out myself that the issue was that while integrating redux-persist I switched from configureStore() to createStore() (not sure if I could still keep it that way, but the library's example was with createStore()), and I did not add window.REDUX_DEVTOOLS_EXTENSION_COMPOSE to the store.
So, the code I added was
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

and, passed this composeEnhancers to the createStore() like this:
export default  createStore(persistedReducer, composeEnhancers());


text:
Q: How to handle data returned from thread functions in main function in Python I have a python script where I have created a thread. Below is the code snippet
stop_thread = False
get_data = False
status = ""
subject_id = ""

def get_data_function():
    global stop_thread
    global get_data
    global status
    global subject_id

    while stop_thread is False:
        if get_data:
            # SOME CODE
            # SOME MORE CODE
            (status, subject_id) = tive.extract_data()

            get_data = False

        time.sleep(1)

def main():
    global stop_thread
    global get_data
    global status
    global subject_id

    thread = Thread(target=get_data_function)
    thread.start()
    res_dict = dict()
    while True:
        # SOME CODE
        # SOME MORE CODE

        if some_condition:
            get_data = True

            res_dict['status'] = status
            res_dict['subject_id'] = subject_id

        # SOME CODE
        # SOME MORE CODE

In above code I have defined a thread and its function get_data_function(). This function calls tive.extract_data() which gives status, subject_id. I have defined these variables as global so that once we have the value of these variables , I can use it in main function.
In main function, after some_condition is True we need to get the values of status and subject_id so I set global variable get_data as True which enables the get_data_function main code and returns the data but the problem is that tive.extract_data() takes 2-3 secs to respond due to which res_dict['status'] = status and res_dict['subject_id'] = subject_id in main function gives error for that 2-3 secs and after that it starts working fine.
Is there any other way of handling the values of these variables in optimized way so that until we don't have values for these variables, we don't get errors. Please help. Thanks

A: I would define a thread class. I have bad experience using globals.
# ==================================================================================
class ThreadGetData(Thread):

    def __init__(self):
        super().__init__()

        self.stop_thread = False
        self.get_data = False
        self.status = ""
        self.subject_id = ""
        self.data_present = False

    # ------------------------------------------------------------------------------
    def get_data_function(self):

        if self.get_data:
            # SOME CODE
            # SOME MORE CODE
            (self.status, self.subject_id) = tive.extract_data()
            self.data_present = True
            self.get_data = False

        time.sleep(1)

    # ------------------------------------------------------------------------------
    def run(self):
        while not self.stop_thread:
            self.get_data_function()

# ==================================================================================
def main():

    thread = ThreadGetData()
    thread.start()

    res_dict = dict()
    while True:
        # SOME CODE
        # SOME MORE CODE

        if some_condition:
            thread.get_data = True

       if thread.data_present:
            res_dict['status'] = thread.status
            res_dict['subject_id'] = thread.subject_id
            self.data_present = False

        # SOME CODE
        # SOME MORE CODE

A: I would use Python 3's asyncio module, and use a coroutine instead of a thread. You can then move all of the operations that can be done before you need the value that the first coroutine returns into a second coroutine. Then, use asyncio.gather() to run both coroutines in parallel, waiting until both are finished.
Here is a simple example which demonstrates this pattern:
import asyncio
import datetime

async def main():
    print("Starting at " + str(datetime.datetime.now()))
    values = await asyncio.gather(get_value(3), do_other_stuff())
    print("Received: " + str(list(values)[0]))
    print("Finished at " + str(datetime.datetime.now()))

async def get_value(n):
    await asyncio.sleep(3)
    return n*10

async def do_other_stuff():
    print("doing things 1")
    await asyncio.sleep(1)
    print("doing things 2")
    await asyncio.sleep(2)
    print("doing things 3")

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


text:
Q: Convert string to unsigned char array/byte array How could I convert the following string:
std::string str = "x89x30x50";

to this following unsigned char array/byte array with escape sequences:
unsigned char char_arr[1024] = "\x89\x30\x50";

A: If I understand your question correctly you want to split a string of hexadecimal values (prefixed by 'x') into byte values.
You could achieve this by tokenizing the string (with a delimiter of 'x') and converting each token to the byte value:
Something like this:
#include <string>
#include <sstream>

int main()
{
    std::string str = "x89x30x50";
    unsigned char char_arr[1024] = "";
    std::istringstream iss(str);
    std::string token;
    int i = 0;
    while (std::getline(iss, token, 'x'))
    {
        if (token.empty()) continue;
        char_arr[i++] = static_cast<unsigned char>(std::stoi(token, nullptr, 16));
    }
    //char_arr = {0x89,0x30,0x50,0,0,...}
}


text:
Q: Travis build OpenJDK10 with JavaFx support Since a few days travis does not support the jdk option oraclejdk10 anymore. So I tried to move to openjdk10. The problem is, that I need JavaFX support, and I get various error messages for various tries to get it working:
Try 1:
language: java

install: true

script: "cd Aggregation; mvn test -B"

sudo: false
jdk:
    - openjdk10

notifications:
  email:
    recipients:
      - junktogo@web.de
    on_success: change
on_failure: always

Travis error:
Multiple packages like javafx.application do not exist
Try 2 (Install the openjfx package):
I added the following section:
before_install:
    - sudo apt install -y openjfx

Travis error:
E: Unable to locate package openjfx
The command "sudo apt install -y openjfx" failed and exited with 100 during.

This problem remains even if adding sudo apt update.
Try 3:
before_install:
    - sudo apt-get build-dep libopenjfx-java
    - sudo apt-get --compile source libopenjfx-java

Travis error:
E: Unable to locate package libopenjfx-java
The command "sudo apt-get build-dep libopenjfx-java" failed and exited with 100 during.

A: As Jan S. suggested including JavaFX using a Maven dependency instead of trying to build it using Travis works just fine.
Add something like the following to your Maven dependencies section:
<dependency>
    <groupId>org.openjfx</groupId>
    <artifactId>javafx-controls</artifactId>
    <version>11</version>
</dependency>

A: Teavis build with OpenJDK 8
language: java
dist: bionic
jdk:
  - openjdk8
before_install:
  - sudo apt-get update -q
  - sudo apt install openjfx=8u161-b12-1ubuntu2 libopenjfx-java=8u161-b12-1ubuntu2 libopenjfx-jni=8u161-b12-1ubuntu2
  - chmod +x deploy.sh
after_success:
  - ./deploy.sh

A: You need a proper setup of OpenJFX to bring it to work since JavaFX is not included in OpenJDK and also you should upgrade to OpenJDK 11 since Java 10 is EOL (End of Life).
Checkout the official documentation:
https://openjfx.io/
OpenJDK 11:
https://jdk.java.net/11/


text:
Q: Trouble Linking Matlab C++ libraries/headers with Xcode 7.3 I'm trying to write a program in C++ to write static arrays and matrices to .mat files so that I can load them into Matlab, and I'd also like to be able to read them. I've done a lot of reading and I'm aware that there's some framework I need to properly set up in XCode in order for things to work. I'm using Matlab R2015b and Xcode 7.3.
I'm modeling my code initially to be simple like what the author mentions in Reading data from matlab files into C but I can't locate my libraries. The folder /glnxa64/ does not exist on my machine. I know that my headers I want to include are in applications/MatlabR2015/extern/include for mat.h, matrix.h.
I have two problems: Under my project settings in XCode, what do I modify to make sure my project finds mat.h and matrix.h, is it under the "Precompiled Headers Cache Path" or elsewhere? Also, where do I find those library files and how do I link them in XCode, is it just under the Project Build Phase link binary with libraries?
Thanks for the help!

A: I found the solution to the second part of my question. The first part was just me messing with the project build settings instead of the target build settings.
The folder for the libraries that Matlab has depends on what operating system and version of Matlab you're on. Opening matlabR2015b.app by making the finder show package contents, then navigating to applications/MatlabR2015b.app/bin/maci64/ is where the library binaries are located on my machine. The name maci64 changes depending on the OS (since I'm on a mac 64-bit OS, I believe that's where my path name came from) and manually paging through the list of libraries found it, since using the file search doesn't really work inside a package.
My code still won't compile because it looks like I need to include all of the right codependent libraries, and I don't know which other ones I need (I only included libmex.dylib and libmat.dylib), but I found where the libraries are stored.


text:
Q: AngularFire - New Provider Syntax What is the purpose of these providers, that the @angular/fire package add on ng add in the app.module.ts imports:
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAnalytics(() => getAnalytics()),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore()),
    provideFunctions(() => getFunctions()),
    provideMessaging(() => getMessaging()),
    providePerformance(() => getPerformance()),
    provideRemoteConfig(() => getRemoteConfig()),
    provideStorage(() => getStorage()),

What function do they provide? I still need to import the AngularFirestoreModule when I want to use the Dependency Injection for AngularFirestore to not receive a NullInjectorError on it.
Can I just remove them without issue? Why would I keep these imports?

A: AngularFire 7 came with a new modular SDK in addition to the existing one which is now exported via the compat import paths.
The ng add schematic adds the module imports for the new SDK. When you use the new SDK module imports, you need to inject different classes to your components, services for it to work (as already mentioned in the comments). Check out the the samples folder for the modular SDK in the AngularFire repo for code examples.
The docs pages in the AngularFire repo are not yet updated with the new modular SDK. There is a PR open for the new docs with some changes already to the docs pages. You could check out that branch as well.
To answer your questions:

Can I just remove them without issue?

If you want to keep using the old SDK (via the compat imports), then yes. Note, that - as far as I know - Firebase AppCheck is not available in the old SDK.

What function do they provide? Why would I keep these imports?

You need them, if you want to use the new modular SDK, which uses the tree-shakable Firebase JS SDK under the hood.


text:
Q: blueJ kareltje making ports in world Kareltje needs to walk trough the maze
Now I would like to create a list of coordinates that Kareltje must find. These coordinates are ports (walls).
When Kareltje walking to this ports, it puts a wall down so he can not go back.
My problem is that I don't know how to make the walls and coordinates. Can someone help me with this?
This is the code I got now:
import wereld.Robot;

public class OefenRobot4 extends Robot  {

    boolean finish = false;

    public OefenRobot4(String naam)
    {
        super(naam);
    }

    public void hoofdProgramma()
      {
          vraagBegin();
          Verplaatsen();
          Lopen();
      }

    public String vraagBegin() {
        String deVraag = vraagTekst("Wil je karel helpen zodat de piepbal op zijn plek terecht komt?");
            if(deVraag.equalsIgnoreCase("ja"))
                {
                    zeg ("Oke laten we snel gaan beginnen!");
                }
            else if(deVraag.equalsIgnoreCase("nee"))
                {
                    zeg("Kareltje is verdrietig want zijn piepbal kan hij nu niet terugbrengen ");
                }
    return deVraag;
    }

    public void Verplaatsen(){

      if(pos_x==1&&pos_y==1)
        {
            mijnWereld.verplaats(this, 26,19);
            piepbalMeenemen();
        }

    }

      public void Lopen() {

          while(finish != true) {
              int D = dobbel();

              switch (D) {
                case 1: linksom();
                        break;
                case 2: rechtsom();
                        break;
                default: if (!voorObstakel()) {
                          stap();
                          positieControle();
                         }
                        break;

                }

        }
    }

       public boolean piepbalMeenemen() {
        opPiepbal();
            {
                pakPiepbal();
            }
        return heeftPiepbal();
    }

    public void positieControle()
    {
        if (pos_x==1&&pos_y==1)
            {
                legPiepbal();

                zeg("Ik heb de piepbal terug gebracht!");
            }
    }
}

And this is the code from de oefenwereld:
// Code voorbeeld voor een robot met de naam Kareltje

import wereld.*;

public class OefenWereld4 extends Wereld
{

    OefenRobot4 robot;

    public static void main(String args[])
    {
        OefenWereld4 wereld = new OefenWereld4();
    }

    public OefenWereld4()
    {
        super(myworld);
        setSlaaptijd(1);
        robot = new OefenRobot4("Kareltje");
        plaats(robot, 1, 1);
    }
}

A: In order to help you, we also need the code that comprises the Wereld and
Robot classes.


text:
Q: Why strange behaviour with operator()? I have simple class,
class Func
{
public:
    Func()
    {
        cout<<"Constructor"<<endl;
    }

    int operator()(int)
    {
        cout<<"Operator ()";
        return 0;
    }
};

*

*When I create it's object by giving parenthesis, Func f();, it prints nothing, it should print Constructor. But when I create object without parenthesis it prints Constructor which is expected. What is the different between these two?

*When I try to use operator() f(2) it gives me compilation error.

error C2660: 'f' : function does not take 1 arguments

Isn't it strange behaviour or I am missing something?

A:
Func f();, it prints nothing, it should print Constructor

That is not true whatsoever.
Here is how you create a Func:
Func f;

When I try to use operator() f(2) it gives me compilation error. error C2660: 'f' : function does not take 1 arguments. Isn't it strange behaviour or I am missing something?

Yes, it's strange, but it's not unexpected. When you wrote Func f() you declared a function called f returning a Func. Everything you try to do with f after that is, naturally, broken.

A: This is a bit interesting here.
Func f();

is a forward declaration for a function, which takes no argument and return Func type object.
Check the below code:
#include <iostream>
using namespace std;

class Func
{
public:
    int operator()(int)
    {
        return 0;
    }
};

int main ()
{
    Func f();
    f();
    return 0;
}

Func f ()
{
    cout << "My Func" << endl;
    Func * f = new Func;
    return *f;
}

It will output "My Func" on stdout.


text:
Q: paint $\mathbb{R}^2$ with two colors Can we paint $\mathbb{R}^2$ with two colors (say, black and white) so that any horizontal line pass through countable black points and any vertical line pass through countable white points?

Update. I was amazed that this is a classical problem! Actually what I wanted to do is using set theory to prove that there exist incomparable Turing degrees.

A: If the continuum hypothesis holds, the answer is yes by a nice straightforward transfinite recursion:
By CH, let $\{l_\eta:\eta<\omega_1\}$ be a list of all the vertical and horizontal lines in the plane. We build a coloring of the plane by recursion, as follows: at step $\alpha$, we take the points on line $l_\alpha$ that haven't been colored yet and color them

*

*White, if $l_\alpha$ is a horizontal line

*Black, if $l_\alpha$ is a vertical line.
For each line $l$ (horizontal or vertical), only countably many other lines "came before" it in our construction. The lines of the same type as $l$ don't intersect $l$, so how we colored them won't affect what the points on $l$ will be colored; and each of the lines of the opposite type intersect $l$ exactly once. So only countably many points on $l$ will be colored "wrong" (that is: black if $l$ is horizontal, white if $l$ is vertical).

I suspect that this is not doable in ZFC alone.


text:
Q: Laravel search return data repeatedly I have this function for my search and it returns results over and over
Controller
function search(Request $request)
{
    $q = $request->input('searchinput');
    if($q != ''){
        $links = Link::where('status', '1')
           ->where('name','LIKE', "%{$q}%")
           ->orWhere('body','LIKE',"%{$q}%")
           ->paginate(6);
        if ($request->ajax()) {
          $view = (String) view('front.links.more',compact('links'));
          return response()->json(['html'=>$view]);
        }
        return view('front.search.index', compact('links', 'q'))->withQuery($q);
    }else{
        Session::flash('warning', 'You need to fill search field.');
        return redirect()->back();
    }
}

form
<form class="form-inline" action="{{route('searchin')}}">
  @csrf
  <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="searchinput">
</form>

Route
Route::any('search', 'Front\SearchController@search')->name('searchin');

JavaScript

screenshot

Video
https://streamable.com/qwh34
Any idea?
update to Aditya Thakur comment
network

console console.log(page++);

console console.log(page);

Update 2
dd($request->all());
array:2 [▼
  "_token" => "eNio8rDaCL2du4I7KAzt5UU3ukrvHHnco3x2orUp",
  "searchinput" => "test"
]

dd($request->ajax()); returns true
dd($request->input('page')); returns null
Update 3
Dan's response
removing if condition in my controller removed second ajax request and fixed some parts.
Sandeep Sudhakaran response,
here is my latest result after removing if condition. PS: I marked duplicated data.

Update 4
load button
@if(count($results)>0)

                                  {{__('links.loading')}}

                                {{__('links.loadmore')}}

                                <button type="button" class="btn btn-secondary btn-3" disabled>{{__('links.nomore')}}</button>

            @endif

A: Change your ajax call like below.
$.ajax({
url: '',
data:{'page':page}
type: "get",
beforeSend: function(){
    $('.ajax-load').show();
    $('.spinner-border').show();
})


text:
Q: Does a FULLTEXT index speed up LIKE conditions? We have a system that is migrating from an older VARCHAR using LIKE setup to one that uses FULLTEXT indexes. So far everyone is enjoying the switch, but we still have some code that isn't catered to the FULLTEXT queries.
Currently we have a column that is a VARCHAR(255) and we want to remove the 255 character limit. What will happen to areas that are using the LIKE queries?

A: A fulltext index does not help to speed up queries using LIKE.
But an ordinary index can speed up LIKE conditions that start with a fixed string, for example LIKE 'FOO%'.


text:
Q: Make an accent-insensitive RegExp in JavaScript I have a small worry with RegExp in JavaScript. I would like to make an RegExp that is insensitive to accents.
For example if I do:
var str = 'césar';

var i = New Regexp (str, 'desired parameter, similar to <i> for example').exec('cesar');

console.log(i) // césar or cesar should print

Does something like this exist?

A: There is no RegExp parameter that you can pass to alter the way accents are treated. What you would need to do is build up a matrix of characters that should substitute each other and then construct a RegExp pattern from these substitute characters.

const e = ['È', 'É', 'Ê', 'Ë', 'è', 'é', 'ê', 'ë'],
    a = ['à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ']

const substitutions = {
  e, E: e, a, A: a
}

var str = 'Cesar';
const pattern = Array.from(str).map(c => substitutions[c] ? `[${c}${substitutions[c].join("")}]`: c).join("")
console.log(pattern)

var i = new RegExp(pattern, "gi").exec('césar');
console.log(i)


text:
Q: Calculating date KPIs from tabular (molten) data in DAX I have a rather large logfile of sales pipeline data in a tabular format that contains timestamps stemming from an SQL Server. I am asking for help on calculating two different types of measures in DAX for a KPI report.
Lets say the pipeline goes through the following stages in the sales pipeline:

*

*Lead

*Opportunity

*Indicative offer

*Firm offer

*Contractual offer

*Contract

The pipeline may or may not go through all stages, so for example there might be some cases where Indicative or Firm offers are skipped and the pipeline goes directly from Opportunity stage to Contractual stage. Or there might be no Lead to start with and the pipeline starts with Opportunity. There Id that tells us which projects belong together.
So an example would be:
Stck

Id
Stage
LagDate
TimestampDate
Duration

1
Lead
null
2023-01-01
null

1
Oppty
2023-01-01
2023-01-02
1

1
Ind_offer
2023-01-02
2023-01-04
2

1
Firm_offer
2023-01-04
2023-01-05
1

1
Contr_offer
2023-01-05
2023-01-08
3

1
Contr
2023-01-08
2023-01-10
2

2
Lead
null
2023-01-07
null

2
Oppty
2023-01-07
2023-01-08
1

2
Contr_offer
2023-01-08
2023-01-10
2

2
Contr
2023-01-10
2023-01-15
5

3
Oppty
null
2023-01-08
null

3
Ind_offer
2023-01-08
2023-01-10
2

3
Firm_offer
2023-01-10
2023-01-11
1

3
Contr_offer
2023-01-11
2023-01-16
5

3
Contr
2023-01-16
2023-01-20
4

I am looking for a solution to calculate measures of two types:
Type one:
Averaging the SUM of durations between two arbritrary stages:
Eg. Opportunity to Contract KPI1 = AVG(SUM(Duration between stages Oppportunity and Contr))
Would be in this case:
((1 + 2 + 1 + 3 + 2) + (1 + 2 + 5) + (2 + 1 + 5 + 4)) / 3 = 9.67
So this would aggregate the durations that are within two arbitrary boundaries in the pipeline
For this I was thinking about creating a helper table to mark stages that are valid for that specific KPI and joining to the base table such as:
HelperTable

Stage
IsValidKPI1

Lead
true

Oppty
true

Ind_offer
true

Firm_offer
true

Contr_offer
true

Contr
true

And the DAX would be something like this:

KPI1 =
Var Summa =
CALCULATE (
            SUMX (Stck, 'Stck'[Duration] ),
                FILTER (
                'Stck',
                RELATED(HelperTable[IsValidKPI1]) = TRUE)
)

Var Counter =
CALCULATE (
            DISTINCTCOUNT( 'Stck'[Id] ),
                FILTER (
                'Stck',
                RELATED(HelperTable[IsValidKPI1]) = TRUE)
)

Return DIVIDE(Summa, Counter)

Type two:
Calculating durations of arbitrary stages using difference of timestamps:
Eg: Lead to Contract KPI2 = AVG(Date difference(Date of Lead, Date of Contract))
This would be in this case:
AVG((2023-01-01 to 2023-01-10 = 9 ), (2023-01-07 to 2023-01-15 = 8), (N/A for the third project)) = 8.5
The DAX would be something like this:

KPI2 =
Var FromDate =
CALCULATE (
            MINX (Stck, 'Stck'[TimestampDate] ),
                FILTER (
                'Stck',
                Stck[Stage]="Lead")
)

Var ToDate =
CALCULATE (
            MAXX( Stck, 'Stck'[TimestampDate] ),
                FILTER (
                'Stck',
               Stck[Stage] = "Contr")
)

Var Counter =
    ROUNDDOWN(
        CALCULATE (
                COUNT( 'Stck'[Id] ),
                FILTER(
                'Stck',
                Stck[Stage] ="Lead" || Stck[Stage] = "Contr"
                )
    )/2, 0)

Return DIVIDE(DATEDIFF(FromDate, ToDate, DAY), Counter, BLANK())

The problem is that I would like to have this calculation on a row level (row level KPIs) and THEN average them over the whole pipeline using different filters.
When I put the above KPIs in a table it is obvious that it does not return the correct values for the Totals row for KPI2 as the minium and maximum values will be for the whole table:

Id
KPI1
KPI2

1
9.00
9.00

2
8.00
8.00

3
12.00

Total
9.67
9.5

Is there a way to do this? Or is the only way to have another helper table in which I calculate the above KPIs on Id level and then aggregate using measures? Also will this work on a large table?


text:
Q: Spring request mapping folders Respect,
I have some problems with request mapping with spring, now I use spring 4.1
I have 2 controllers in my application and I want handle request mapping in specific way.
In first controller I want handle all mapping folders
@RequestMapping(value={"/", "/**"})
In another controller I want also handle all sub folders of app/ folder
@RequestMapping(value={"/app", "/app/**"})
and this works good, but now I ca not access my src files css, images etc..
all this files are located in src/css/ folder.
How to solve this problem.
maybe I must create one more controller only for src folder
@RequestMapping(value={"/src", "/src/**"})

A: Resources such as /css , /images, /js etc., are to be placed  under WEB-INF/resources
For eg.
WEB-INF/resources/css
WEB-INF/resources/js
Pls try to rearrange to above structure...


text:
Q: How I can Sync Between Iphone 5s and Ubuntu 16.04 LTS I have Iphone 5s and I want to have access to my photos, videos, music from Ubuntu laptop 16.04 LTS
I tried these 4 answers which are in this question and it did not work
How can I mount my iPhone 6s on Ubuntu 16.04?


text:
Q: Rails 4 Multiple Pictures with Paperclip I am trying to add multiple pictures to a project using the Paperclip gem in Rails 4.
The pictures are not being uploaded to the DB. Using MySQL.
I keep getting this error:
2 errors prohibited this forum topic from being saved:
Photos photo content type is invalid
Photos photo is invalid
Request parameters:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zoMHhVTJOy0/VVGNCcVrTaFwmSRvYoonQEtc+TAqwCM=",  "project"=>{"photos_attributes"=>{"0"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0x007f98f0d4b468 @tempfile=#<Tempfile:/var/folders/gp/jz4_vlrs2l96__g4jrnsc3y40000gn/T/RackMultipart20141010-4840-1gtf4ao>, @original_filename="glyphicons-halflings-white.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"project[photos_attributes][0][photo]\"; filename=\"glyphicons-halflings-white.png\"\r\nContent-Type: image/png\r\n">}}, "title"=>"sadfsadfdsa", "description"=>"sdfsdafsdf"}, "commit"=>"Create Project"}

I have added the necessary files below.
** New Project Erb/HTML File**
<% provide(:title, "New Project") %>

New Project

<%= form_for @project, :html => { :multipart => true } do |f| %>
 <% if @project.errors.any? %>

<%= pluralize(@project.errors.count, "error") %> prohibited this forum topic from being saved:

   <% @project.errors.full_messages.each do |msg| %>

<%= msg %>

   <% end %>

  <%= f.fields_for :photos do |f| %>

     <%= f.file_field :photo , class: 'form-group' %>

<% end %>

 <%= f.text_area :title, class: 'form-control input-lg', placeholder: 'Topic Title' %>

 <%= f.text_area :description, rows: 4, class: 'form-control', placeholder: 'Topic Description' %>

 <%= f.submit class: 'btn btn-success'%>

<% end %>

Projects Controller:
class ProjectsController < ApplicationController
  before_filter :authenticate_user!, except: [:show, :index]
  before_filter :set_project, except: [:index, :new, :create]

def index
 @projects = Project.find(:all)
end

def show
end

def new
 @project = Project.new
 3.times {@project.photos.build}
end

def create
 @project = current_user.projects.build(project_params)
  if @project.save
    flash[:success] = "Project Created!"
    redirect_to @project
  else
    render :new
  end
end

def edit
 3.times {@project.photos.build}
end

def update
 if @project.update_attributes(project_params)
  flash[:notice] = "Successfully updated your project."
  redirect_to @project
 else
   render :edit
  end
end

def destroy
end

private

# Never trust parameters from the scary internet, only allow the white list through.
def project_params
 params.require(:project).permit(:title, :description, photos: [], photos_attributes:[:photo, :id])
end

def set_project
 @project = Project.find(params[:id])
end

Project Model:
  class Project < ActiveRecord::Base
    belongs_to :user, counter_cache: true
    has_many :photos

  default_scope -> { order('created_at DESC') }
   validates :title, presence: true, length: {maximum: 50}
   validates :description, presence: true, length: { maximum: 1000 }
   validates :user_id, presence: true

  accepts_nested_attributes_for :photos, :reject_if => lambda { |t| t[:photo].nil? }

  def photos=(files = [])
   files.each{|f| (@images ||= []) << photos.create(image: f) }
  end
 end

Photo Model:
 class Photo < ActiveRecord::Base
 belongs_to :user, counter_cache: true
 belongs_to :project, counter_cache: true

 has_attached_file :photo, :styles => { :small => "150x150>", :large => "320x240>" }
 validates_attachment_presence :photo
 validates_attachment_size :photo, :less_than => 5.megabytes
 validates_attachment :photo, content_type: { content_type: ["photo/jpg", "photo/jpeg", "photo/png", "photo/gif"] }
 end

Photo Migration:
class AddPhotosToPhotos < ActiveRecord::Migration
 def self.up
  add_column :photos, :photo_file_name,    :string
  add_column :photos, :photo_content_type, :string
  add_column :photos, :photo_file_size,    :integer
  add_column :photos, :photo_updated_at,   :datetime
 end

def self.down
 remove_column :photos, :photo_file_name
 remove_column :photos, :photo_content_type
 remove_column :photos, :photo_file_size
 remove_column :photos, :photo_updated_at
 end
end

Photo Migration for Indexes
class CreatePhotos < ActiveRecord::Migration
 def change
  create_table :photos do |t|
    t.integer :user_id
    t.integer :project_id
    t.timestamps
   end
  end
 end

Development.rb
Paperclip.options[:command_path] = "/usr/local/bin/"

A: First, the content type error - change your validates_attachment to image types:
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }

As for the other error, it looks like it's arising here:
  <%= f.fields_for :photos do |f| %>

      <%= f.file_field :photo , class: 'form-group' %>

  <% end %>

There could be an issue with a singular photo in plural fields_for. Admittedly I have not checked the documentation. If not, will need more detail on the error to troubleshoot. What happens when you call project_params in the create action?


text:
Q: Django Endless pagination url rewrite I'm using Django Endless pagination. ( https://github.com/frankban/django-endless-pagination ) . Is there anyway to change http://example.com/customers/?page=3 to http://example.com/customers/page/3/.
My template

        {% if customers %}

                    Name
                    Email
                    Mobile
                    Address
                    Action

                {% load endless %}
                {% paginate customers %}
                {% for customer in customers %}

                    {{ customer.name }}
                    {{ customer.email }}
                    {{ customer.mobile }}
                    {{ customer.address }}

                {% endfor %}

            {% get_pages %}

Showing Customers {{ pages.current_start_index }} - {{ pages.current_end_index }} of {{ pages.total_count }}

                {% show_pages %}

        {%else %}

Nothing found.

        {%endif %}


text:
Q: Django Many to Many arrange sequence of selected item Hey all have created a model in django and using django admin i want to import values in many to many fields according to their values placed in order the results are displayed
IN my case :-
max_combo then max_table etc
How can a user from front end choose this particular sequence in django admin Click to view image


text:
Q: How to list items and count(*) in PostgreSQL I'm not sure if it's even possible. Let's say, I have a table A having 100 records. I want to select top five records and also return a total number of elements in this table in one query. How can I do this?

A: You can add the count as an additional column using window functions:
select a.*, count(*) over () as records_in_table
from a
order by <whatever>  -- however you define "top five"
fetch first 5 rows only;


text:
Q: Limitations of SharePoint OOTB forms against infopath what are the limitations of OOTB SP forms against InfoPath forms?
can we create multiple views on the same list using OOTB forms? how about rules, change the width height etc.

A: OOTB is what you see is what you get. You can configure the forms if you want in SPD (SharePoint designer) to have what you want in the forms like you suggest. or directly edit it which i dont suggest ;)
do you mean multiple forms like edit, add? or views of the list?
as for infopath yes it can do a lot more than OOTB but its being phased out so why use it? You should be embracing "Forms" / "PowerApps" and "Flow", these newish 365 applications should be used to create new forms and workflows. You could still use SPD for now or keep on using it as i dont think its going any time soon. Because both apps are still new they wont have full functionality but should be able do what you want.

A: The InfoPath form surpasses the default SharePoint form in the following:

*

*Validation and Verification

*Rules

*No Code solutions

*Cascading drop-downs without JavaScript

*Quick development/deployment

*Suitable for development by power users.

*Form layout organization

*Conditional Formatting

*Can receive from / send to multiple data sources

Can we create multiple views on the same list using OOTB forms?

*

*NO. you can only create the normal list views, not form vies

How about rules?

*

*No automation rules, but you can use the column validation setting or workflows to manage rules.

Change the width height?

*

*No, each new field will be added one below one based on your column order settings. Meanwhile, you can use the SharePoint designer and CSS to customize it.

[Update based on comment]
PowerApps and Microsoft Flow are the successors to InfoPath and SharePoint Designer for many common business scenarios, especially custom forms used in SharePoint lists.
Check the details at Sharepoint designer 2016 and InfoPath 2016 in sharepoint server 2016/SharePoint Online, what're the alternatives?


text:
Q: MStest > OpenQA.Selenium.DriverServiceNotFoundException
OpenQA.Selenium.DriverServiceNotFoundException: The chromedriver.exe
  file does not exist in the current directory or in a directory on the
  PATH environment variable. The driver can be downloaded at
  http://chromedriver.storage.googleapis.com/index.html.

I have some automation in Visual Studio and I want to integrate it with Jenkins by MStest, I tested it by console but it shows me that error, already tried several things but I have not yet been able to, I don't know if I should create a service I have seen it in some comments but not I know how to do it, if anyone can help me I would really appreciate it
Visual Studio 2019, Csharp, MSTest


text:
Q: Adding Google Maps to an Android App Me and my group members have been trying to add Google Maps in one of our activities but all attempts failed. We'd like to ask for some help.
We followed the steps here.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exapp.maptrial01"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="17"
    android:targetSdkVersion="22" />

<permission
    android:name = "com.exapp.maptrial01.permission.MAPS_RECEIVE"
    android:protectionLevel = "signature" />

<uses-feature
    android:glEsVersion = "0x00020000"
    android:required = "true" />

<uses-permission android:name = "com.exapp.maptrial01.permission.MAPS_RECEIVE" />
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" />

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

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

    <meta-data
        android:name = "com.google.android.maps.v2.API_KEY"
        android:value = "intentionally left blank" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
</application>

</manifest>

MainActivity.java
package com.exapp.maptrial01;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

static final LatLng MarqueeMall = new LatLng(15.163350, 120.609495);
private GoogleMap gMap;

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

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onMapReady(GoogleMap arg0) {
    // TODO Auto-generated method stub
    gMap = arg0;

    // Add a marker in Sydney, Australia, and move the camera.
    LatLng sydney = new LatLng(15.163350, 120.609495);
    gMap.addMarker(new MarkerOptions().position(sydney).title("Marker in MQ"));
    gMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  }
}

activity_main.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MainActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />

A: I believe you have to have the android key which is described in step 4. and replace
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="intentionally left blank" />

with
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="xxxxxxxxxxxxxxxxx" />


text:
Q: How to set max length in preprocessing before using BERT function? BERT_MODEL = "https://tfhub.dev/google/experts/bert/wiki_books/2"
PREPROCESS_MODEL = "https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3"

preprocess = hub.load(PREPROCESS_MODEL)
bert = hub.load(BERT_MODEL)
inputs = preprocess(sentences)
outputs = bert(inputs)

I'm trying to get BERT embeddings for text-to-image generation. But I could not find how to change max length in these functions. Can you please explain how to do it?

A: BERT can only take input sequences up to 512 tokens in length. This is quite a large limitation, since many common document types are much longer than 512 words. It inherits it's architecture from the transformers, which themselves use self-attention, feed-forward layers, residual connections, and layer normalization as their foundational components.
The problems with BERT and large input documents are caused by a few aspects of BERT's architecture:

*

*Transformers are autoregressive in and of themselves, and the designers of BERT saw a considerable drop in performance when using documents longer than 512 tokens. As a result, this limit was set to protect against low-quality output.

*The self-attention model has a space complexity of O(n2). Because of the quadratic complexity, the modes require a lot of resources to fine-tune. The more input you provide, the more resources you will need to fine-tune the model. For most users, the quadratic complexity makes this too expensive.
On how to deal with long sequences please refer to this. Thank you!


text:
Q: Как мне глобализировать переменную Нужно передать переменную sss в качестве аргумента для go func().
Но я не могу передать переменную в качестве аргумента так как переменная лежит выше, компилятор пишет что переменную sss не найдено.
func main() {
    host := os.Args[1]
    bat := []string {
        "hello",
        "goodbye",
        "chain",
    }
    for _, ranges := range bat { //чисто для примера цикл for
        sss := fmt.Sprintf("%s", ranges) //которую нужно использовать в функции ниже
    }

    const (
        rps = true;
    )

    if rps == true {
        go func(host string, header string) {
            req, err := http.Get(host)
            if err != nil {
                fmt.Println(err)
            } else {
                fmt.Println(req.Body, req.Header)
            }

        } ("http://google.com", sss) // переменная которая лежит в цикле for
    }
}

A: переменная лежит в for и после того как он отрабатывает онa уничтожается GC. Вам надо объявить ее выше. и еще убрать : в for. (sss обявите перед for и все полетит)
var sss string


text:
Q: Should I say Where Have You Been To or Where Have You Been In? If I want to ask someone how many places he/she has visited before. Should I say in or to?
What if I want to restrict the place in a country, like the US. How should I ask then?
For example, which is correct of these two sentences:
...
Where have you been to in the US?
or
Where have you been in the US?
...
Thanks

A: If you're in the middle of a conversation "Where have you been?" would work fine.
If you're starting up a new conversation or if you want to restrict the question to only places in the US you would need more context. In this case, "Which cities have you visited in the United States?" would be good.


text:
Q: Unity) How Can I see through the canvas? When I do Unity, I want to make the particles pierce through the UI while leaving the canvas as an overlay. Also, Can I make it possible to see through matter? Is there any way?
Want to See through the canvas

A: A canvas, by default, is completely transparent/there's nothing to render. The objects within a canvas are not necessarily transparent.
Individually you can change the alpha of the materials/images in the canvas. For something like an image, RawImage and Image, you access the alpha through the color property.
To make a whole canvas transparent consider using a canvas group component

A: In Unity, when the canvas is overlayed, objects behind it cannot be seen. That's why I change the rendering type with the camera, but if you want to see it through an overlay state, how about using a shader? How about putting a shader on the UI to make it transparent?
enter link description here


text:
Q: Copy protection via license file for ModelBuilder models? I've build a large model in the ArcGIS ModelBuilder and I want to share this toolbox with some other people BUT I don´t want to lose control over it. The first step was to set a password to my script, but this only protects the script not the functionality. If someone have my toolbox, he could use it when and where he wants and share it with others like he wants. That's not the way I want it.
Is there a way to build something like my own license file? My idea was to use python (or any other option) at the beginning of the model to check if there is an license file on my Gdrive account, something like an *.txt or *.html. The model only should work, if this file was found (I´ve done that on a local machine - and it works - but not with using the cloud).

A: I wouldn't do this, especially not with some home-brewed license "server".
If you're certain your IP is valuable enough to protect by licensing, you should purchase a commercial licensing solution.
But I don't think this is necessarily the best solution as any form of DRM only inconveniences legitimate users and will not stop determined people reverse engineering your work. Consider how easy it is to get a pirated version of Windows...
I recommend you simply require users to agree to a license agreement. This will have the same effect as DRM - i.e legitimate users will respect it and pirates will break it.
If you are absolutely determined to retain complete control of your source, then you can not release your work, at all. Instead, set up an ArcGIS Server instance and publish your model as a geoprocessing service.  That way your source never leaves your control and you can easily restrict who has access to the service.


text:
Q: PHP Get Contents and Include Not Quite What I Need I've got a function like:
function get_div(){

   $fileLocation = 'form.php';
   $returnString = '
' . get_php_file($fileLocation) . '
';

   echo $returnString;

}

function get_php_file($file){
   return file_get_contents($file);
}

the problem is I have PHP in that file that I want executed as if it were part of the script.  (Instead of outputting <?php my_function() ?> throughout my page)
If I use include $file instead of file_get_contents() I end up with the included file, but the rest of my $returnString is shot...
Thoughts?

A: You want output buffering.
ob_start();
include($file);
$returnString = ob_get_clean();

A: I'm still a little confused by what exactly you are looking to do, but couldn't you just include the php file and w/in that feel have some string ($contentsToReturn) that you keep appending to?  get_php_file would become:
function get_php_file($file){
  require_once($file)
  return $contentsToReturn;
}

Or am I missing something?

A: If you need to interpret php code, you can use include or require. Include will warn if it cannot find the file, require will stop execution. Here's what PHP.net says about it:

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

oops, sorry didn't see you response about needing to buffer the string. Then ob_start as suggested is the proper way, then ob_get_contents when you need it.


text:
Q: Finding trailing zero of n!
Question:  Given an integer n, find the number of trailing zeroes in
  n!

I looked up the solution, it was implemented in C++:
// we are given n, we want to find its n! trailing zeroes

int count = 0;
while(n)
{
  count += n/5;
  n /= 5;
}
  return count;
}

I couldn't work my head around why I need to keep divide by 5, and then sum. Although this is a programming question, given its mathematical nature, I think it is more suitable for this forum because we have so many math genius here.
Please help me out.

A: A trailing 0 means the number is divisible by 10, i.e. it is divisible by 2 and 5.  The number of 0s at the end is the same as the highest power you could write for the 10 in a factorization of the number, or, the power on either the 2 or the 5 in the prime factorization (take the minimium on the two powers, e.g. if your factorization yields $2^4\cdot 5^3$ the number of $10$s you have is $3$, since you could rewrite it as $2^1\cdot 10^3$).
Since $n!$ is the product of all the numbers less than or equal to itself and $5>2$, the number of $5$s will never exceed the number of $2$s.  Therefore, you only need the power on the $5$ in the prime factorization of $n!$
To find this, first see how many multiples of $5$ there are $\leq$ n.  Then the number of multiples of $25$, and so on.  The correct answer is given by the sum of all these values since each $5$ adds one to the power, each $25$ adds $2$, each $125$ adds $3$, and so on.
Consider $30!$
$5,10,15,20,25,30$ all contribute a factor of $5$ to $n!$
But $25$ contributes an extra $5$.
Therefore, the answer is $6+1=7$ zeros for $30!$.


text:
Q: Scaling Wordpress images to same height inside Bootstrap flex-row flex-nowrap I have Bootstrap integrated with Wordpress Underscores Template.
I want to make a horizontaly scrollable container with images that have the same height.
I'm stuck on the point, that I have scrollable container, but images height is not the same;

/*for example purposes*/
.example{
  background:pink;
}

/*underscores style.css*/
img {
    height: auto;
    max-width: 100%;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>

text1

text2

text3

text4

text5

    </div

A: When you want to match the size of images and you don't know the specific size of each of them, it is best to make them fit using css.
The object-fit property is great. It helps us resize an  or  to fit its container. It works just like a background-image.
It has different properties that will be useful depending on what you want to do. It is important to define the size of the container so that it fits correctly.
Here more information about this property
The interesting thing is that it has a property to align the position of the element inside the container, this is called object-position
Check this in your style.
Define a height for the images, the rest is done.
img {
    height: 250px;
    width: 100%;
    object-fit: cover;
}


text:
Q: JSON data through jQuery AJAX request I've having issues with parsing JSON data from a php file through to JQuery.I've had quite a difficult time finding the most appropriate way of doing this and any help would be appreciated. It needs to be in a function
At the moment I've gotten to the point of:
$.ajax({

    url: "Scripts/Interactions.php",
    type: "POST",
    dataType: "json",
    success: function(data){
        $.each(data, function(i, grab){
        alert(grab.AgentFullName);

        })

    }

})

While this works, one issue is it presents a row 'Undefined' before the first row, no matter what column I suggest.
Here is a sample of my Json Output data. It's mostly just random Ipsum Lorem at this text, as I'm still in early stages of development. I've checked the data through various online json format checkers and it's come back as valid.
http://pastebin.com/KFKtiSD4
Thanks in advance for any help!

A: The first element in your array is not an object, it's a string.  That's why you're getting undefined for the first element when you say grab.AgentFullName—the string "results" has no such property.
You could change
[
   "results",
   {
      "InteractionID":"1",
      "AgentFullName":"Peter Germein",
      "InteractTopics":"Behaviour, Attendance, Attitude, Performance, Closing",
      "InteractDiscussion":"Cras at nisl lorem, a lacin...",
      "InteractAction":"Morbi quis nunc in odio eg...",
      "InteractNotes":"Quisque et ante ut nis..."
   },

to
[
   {
      "InteractionID":"1",
      "AgentFullName":"Peter Germein",
      "InteractTopics":"Behaviour, Attendance, Attitude, Performance, Closing",
      "InteractDiscussion":"Cras at nisl lorem, a lacin...",
      "InteractAction":"Morbi quis nunc in odio eg...",
      "InteractNotes":"Quisque et ante ut nis..."
   },

Or, were you trying to do this:
{
   "results": [
   {
      "InteractionID":"1",
      "AgentFullName":"Peter Germein",
      "InteractTopics":"Behaviour, Attendance, Attitude, Performance, Closing",
      "InteractDiscussion":"Cras at nisl lorem, a lacin...",
      "InteractAction":"Morbi quis nunc in odio eg...",
      "InteractNotes":"Quisque et ante ut nis..."
   },
   {
      "InteractionID":"2",
      "AgentFullName":"Peter Germein",
      "InteractTopics":"Behaviour, Attendance, Attitude, Performance, Closing",
      "InteractDiscussion":"....",
      "InteractAction":"Morbi quis nunc in ...",
      "InteractNotes":"Quisque et ante ut nisi ..."
   },

Which would be parsed like this:
$.each(data.results, function(i, grab){
   alert(grab.AgentFullName);

})

A:
[
   "results",
   {
      "InteractionID":"1",
      "AgentFullName":"Peter Germein",

referring the beginning of your json, you probably want to put "results":, instead of "results",


text:
Q: AttributeError: module 'dateutil.parser' has no attribute 'parse' pandas on python 3.7 I tried install pandas via command pip install pandas and got error:
import pandas
../python3.7/site-packages/pandas/compat/__init__.py", line 440, in <module>
parse_date = _date_parser.parse
AttributeError: module 'dateutil.parser' has no attribute 'parse'

A: pip install python-dateutil==2.5.*
and then install pandas. It solves that problem.


text:
Q: Custom links to create defect in an app with sdk 2.0 I wrote an application which displays testCases in a treePanel. In that pannel, I have a specific column with icons for actions user can perform on a test case (show details, edit, add a bug...). In the column config, the renderer call this function, where data is an object with a _ref attribut like /testcase/123456/ :
_gridDataFormatTestCaseIcons:function(data)
{
    var IconsString = Ext.String.format('', Rally.nav.Manager.getDetailUrl(data));
    IconsString+= ' ';
    IconsString+= '';
    IconsString+= ' ';
    IconsString+= '';

    return IconsString ;
}

My first icon opens a new tab with details about the TestCase : OK. My 2nd icon opens a popup where I can edit my TestCase : OK. My third icon opens a popup where I can create a new bug. OK, but... I need to fill all the fileds, included the ones I guess it could be filled automatically.
So my question is about the third icon and the arguments of the function Rally.nav.Manager.create('defect') : the SDK 2.0rc2 docs here says it can take another argument args but don't give any details about it. Can i use it to specify the Owner and Test Case fields for example and how ?

A: You are correct, the args parameter can be an object that includes default attributes to populate into the Create Dialog. Only a limited subset of fields are accepted however:
Allowed args keys
User Story:
defaultName
rank
iteration
release
parent
dpyOid {dependency}

Defect:
defaultName
defectSuiteOid {Defect Suites}
testCaseResult
testCase
requirement
iteration

Defect Suite:
defaultName
rank
iteration

Portfolio Item:
defaultName
rank
parent

Task:
workProduct

Test Case:
testfolderOid {Test Folder}
artifactOid {Artifact}

It looks like the docs are a bit misleading, i.e., since we're creating a new object, instead of including a ref to an existing defect:
//Launch the create dialog
Rally.nav.Manager.create('/defect/12345');

The docs should read:
//Launch the create dialog
Rally.nav.Manager.create('defect');

Here's a quick example that pops and editor using a Button and sets the Defect Name and Default Iteration. Note that the Rally.nav.Manager functions generally only work when the app is installed and running inside Rally.
<!DOCTYPE html>

    <title>Create Example</title>


text:
Q: Why does a flat metric imply coordinates? When in a completely flat spacetime, a metric $\eta_{\mu\nu} $ implies that in a stationary reference frame, you are dealing with three cartesian space coordinates, and one time coordinate.  On a curved manifold, however, the GR book I'm reading seems to imply that if you can find coordinates such that the metric looks like $\eta_{\mu\nu} $, then at least locally, the coordinates look again like 3 cartesian coordinates and one time coordinate.
This doesn't sit well with me, because it seems on a manifold with some curvature, the coordinates necessary to make the metric look flat at a certain point may be different than coordinates in flat space that make a metric look like $\eta_{\mu\nu} $.  So then, regardless of curvature, what about a flat metric at a certain point implies that the coordinates locally look like three cartesian space coordinates and one time coordinates?
I don't believe this is a duplicate of the other post because I understand that any curved manifold looks locally flat, and that coordinates can be chosen such that the metric looks like $\eta_{\mu\nu} $.  I am asking about the physical interpretation of those locally flat coordinates.

A: Specification of the metric components as a matrix inevitably lands you to a certain coordinate set-up. Look at it this way: You have a pair of events separated infinitesimally so that the spacetime interval is $ds^2$ between them. In a generic coordinate system, this would mean that $g_{\mu\nu}dx^{\mu}dx^\nu=ds^2$. Now, if I go to a reference frame where the metric components look Minkowskian (i.e., my metric components are $\eta_{\alpha\beta}$) then what it means to say so is that the spacetime interval between the two events will be described by $(ds^2=)\eta_{\alpha\beta}dx^\alpha dx^\beta$ where ${x^\alpha}$ are my coordinates. In other words, the spacetime interval, in the reference frame in which the metric looks Minkowskian is given by $-dt^2+dx_1^2+dx_2^2+dx_3^2$ where the $t$ and the $x$s are the coordinates. And this is the very definition of Cartesian coordinates that they add in this way to give you the spacetime interval. So, the fact that when your metric is Minkowskian, your coordinates are Cartesian is not so much of a miracle but sort of a consistency requirement of the definitions involved. But the amazing (in the sense of non-trivial) fact is that at each point (no matter the curvature of the global spacetime) you can always find a frame in which the metric looks Minkowskian locally.
Edit I should add that a space being flat doesn't pin down your metric to Minkowskian nor does the fact that you can always (locally) choose a Minkowskian metric make you able to state that you can always make your space-time locally flat. Flatness is about the triviality of the Riemann tensor, which being a tensorial fact, remains independent of your choice of frame.

A: The physics comes from the Equivalence principle where gravity is equivalent to being in an accelerated frame (and various other ways of stating the equivalence of inertial and gravitational mass). So if free floating in a gravitational field you are in an approximately inertial frame - feels like no forces locally.
So you can use those local coordinates to feel locally no gravity (i.e., no forces). That means the metric locally can be said to be Minkowski, and the connection or derivatives of the metric are locally zero. The second derivatives won't be all zero, meaning that there is some covariant curvature. It's a tidal force, you only feel if you're too big, and therefore no longer local enough. Because of the equivalence principle all parts of your body, if local enough, feel the same force, so you feel no forces exerting any relative acceleration on your body parts (if local enough, if not you'll start feeling the tidal forces due to second derivatives of the metric, i.e., curvature)
This also says that locally special relativity holds, as one would want with no gravitational field.


text:
Q: Select Specific Elements in Array for Dropdown I am trying to use JavaScript and jQuery to generate a dropdown list from the values in one particular element of an array.
My array is defined as a variable and looks like this:
var ht_parties = [
  {
    "id_Group": "41DC3C63-F423-4941-ACF7-63118BD9CE19",
    "name": "Ayiti An Aksyon",
    "nameAbbreviated": "AAA",
    "nameAcronym": "AAA"
  },
  {
    "id_Group": "9AF9E215-0376-460F-B69A-F380F35729CA",
    "name": "ACAAU",
    "nameAbbreviated": "ACAAU",
    "nameAcronym": "ACAAU"
  }
]

The code to generate the dropdown is as follows:
var select = document.getElementById("selectNumber");
var options = ht_parties;

for ( var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.text = opt;
    el.value = opt;
    select.appendChild(el);
};

I want the dropdown to populated with the values of the array element "name". However, this is currently generating a dropdown with the list items as "[object Object]". How do I select only the element "name" from the array and populate the dropdown with it?

A: you need to specify which key on opts you want to set to the el's text and value
el.text = opt;
el.value = opt;

needs to be something like
el.text = opt.name;
el.value = opt.name;

(or whichever keys you want to set)

A: use this
var select = document.getElementById("selectNumber");
var options = ht_parties;

for ( var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.text = opt.name;
    el.value = opt.name;
    select.appendChild(el);
};


text:
Q: How keep the image rotated during the reverse movement? I'm having a trouble with the effect I want to create. My body in the HTML file it's just a div with two images.
I was trying to give animation to the first image in the following way:

*

*in 0% it starts at the beginning of the div  (the fish's head is on the right)

*in 100% it ends in the end, but at this point I want to rotate the image and keep that effect until it gets 0% again. (that is, the fish should point towards the left during the reverse motion)

But it just rotates in 100% and no more. I don't know if this happens because I don't understand some concept of the animation property.
This is all my code:

@keyframes fish01 {
  0% {
    left: 0%;
    transform: rotateY(180deg);
  }
  1% {
    transform: rotateY(0deg);
  }
  99% {
    transform: rotateY(0deg);
  }
  100% {
    left: 90%;
    transform: rotateY(180deg);
  }
}
body {
  background-color: black;
}
div {
  position: absolute;
  margin-left: 18%;
  margin-top: 3%;
  width: 800px;
  height: 500px;
  border: 5px double #DDDDDD;
  border-radius: 1em 1em;
  background-image: url("https://i.onthe.io/vllkyt28101smv87bg.349283fe.jpg");
}
div img:nth-child(1) {
  float: left;
  position: absolute;
  margin: 0px;
  top: 20%;
  width: 100px;
  height: 50px;
  transform: scale(1.5, 1.5);
  animation-name: fish01;
  animation-duration: 5s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-timing-function: ease-in;
}
div img:nth-child(2) {
  float: left;
  position: absolute;
  top: 20%;
  left: 60%;
}

I've tried everything in the @keyframes and looked into W3Schools website about animation property, but it didn't help me. Any suggestions?

A: Reason:
The behavior that is seen is expected one based on your @keyframes and the animation-direction setting. When the animation's direction is set to alternate, the UA executes the animation from 0 to 100 for the odd numbered iterations, 100 to 0 for the even numbered iterations.
As per your keyframes, the transform goes from rotateY(180deg) to rotateY(0deg) at 1% of the animation's duration itself and so during the odd numbered iterations you don't see any visible rotation (as duration is  pretty small) and it goes from rotateY(180deg) (at 100%) to rotateY(0deg) (at 99%) because of which you don't get to see any visible rotation during even numbered iterations also.
The problem in writing keyframes for forward direction and re-using the same for the reverse (using animation-direction) is that it can be done only when the states are the same for both. In this case, it is not because the element should be in unrotated state during forward movement and should have rotateY(180deg) during the reverse movement.
Solution:
For the element to be seen in its rotated state, the transform must be retained for some time. So, for your case it is better to do away with the animation-direction: alternate setting and write both the forward and reverse motions within the keyframes itself like in the below snippet.
(Note: Since we are writing both forward and reverse motions within the keyframes, you may have to double the animation-duration).

@keyframes fish01 {
  0% {
    left: 0%;
    transform: rotateY(0deg);
  }
  49.5% {
    left: 90%;
    transform: rotateY(0deg);
  }
  50.5% {
    left: 90%;
    transform: rotateY(180deg);
  }
  100% {
    left: 0%;
    transform: rotateY(180deg);
  }
}
body {
  background-color: black;
}
div {
  position: absolute;
  margin-left: 18%;
  margin-top: 3%;
  width: 800px;
  height: 500px;
  border: 5px double #DDDDDD;
  border-radius: 1em 1em;
  background-image: url("https://i.onthe.io/vllkyt28101smv87bg.349283fe.jpg");
}
div img:nth-child(1) {
  float: left;
  position: absolute;
  margin: 0px;
  top: 20%;
  width: 100px;
  height: 50px;
  transform: scale(1.5, 1.5);
  animation-name: fish01;
  animation-duration: 10s; /* double of original time */
  animation-fill-mode: forwards;
  animation-iteration-count: infinite;
  animation-timing-function: ease-in;
}
div img:nth-child(2) {
  float: left;
  position: absolute;
  top: 20%;
  left: 60%;
}

A: The problem was that you had animation-direction: alternate; in your CSS. To compensate for removing this, you also need to make the img moving to left: 90% being at the 50% mark in the animation, not the 100% mark.
Hope this helps! :)

@keyframes fish01{
        0% {
      left: 0%;
      transform: rotateY(0deg);
     }

     49% {
      transform: rotateY(0deg);
     }

     50% {
         left: 90%;
      transform: rotateY(180deg);
     }

     99% {
      transform: rotateY(180deg);
     }
        100% {
      left: 0%;
      transform: rotateY(0deg);
     }
}

body {
 background-color: black;
}

div {
 position: absolute;
 margin-left: 18%;
 margin-top: 3%;
 width: 800px;
 height: 500px;
 border: 5px double #DDDDDD;
 border-radius: 1em 1em;
 background-image: url("https://i.onthe.io/vllkyt28101smv87bg.349283fe.jpg");
}

div img:nth-child(1) {
 float: left;
 position: absolute;
 margin: 0px;
 top: 20%;
 width: 100px;
 height: 50px;
 transform: scale(1.5, 1.5);
 animation-name: fish01;
 animation-duration: 5s;
 animation-iteration-count: infinite;
 animation-timing-function: ease-in;
}

div img:nth-child(2) {
 float: left;
 position: absolute;
 top: 20%;
 left: 60%;
}
<!DOCTYPE html>

  <meta charset="UTF-8"/>
  <title>CSS rotate animation</title>
  <link rel="stylesheet" href="Transicion02.css"/>


text:
Q: Aligning overlayed divs in bootstrap My first question here :)
I decide to copy recreate this front page:
www.liveform.pl
in order to practice my fresh skills on the battlefield.
Here's my starting page:
http://donkey.ninja/lf/
I'm having hard time aligning the red box with triangle, which are respectively a div(rectangle) and a p(triangle), that look like that:
.ontop1 {
position: absolute;
top: 94%;
bottom: 0;
left: 42%;
right:0;
z-index: 99999;
width: 300px;
height: 60px;
pointer-events:none;
background-color: rgba(255, 0, 72, 1);
padding-top: 11px;
}

.triangle1 {
position: absolute;
top: 98.8%;
bottom: 0;
left: 48%;
right:0;
z-index: 99999;
width: 0;
height: 0;
text-indent: -9999px;
border-right: 40px solid transparent;
border-top: 40px solid rgba(255, 0, 72, 1);
border-left: 40px solid transparent;
}

First part with "Our newest projects!" more or less holds (although the triangle does it's own magic when i start to resize)
But the i'm having problem with "Who are we?" and "What do we do?".
How do i position those elements so that they remain glued to certain place?

A: 1) I would put your red box in the row element that it relates to
2) I would set position: relative on that row element (that way, the red box will positions relatively to that row)
3) I would set a top: -60px on the red box (and something similar on the arrow) to move it slightly over the row
4) I would set a left: 50% and margin-left: -150px (half the red box's width) on the red box (and something similar on the arrow) to center it horizontally. left: 0; right: 0; margin: auto; might also work;
Maybe it would be easier to put the arrow and the box into a single element, and change the position of that single element instead of both those elements.
EDIT: for instance:

Our newest projects!


text:
Q: How can I add a default for a column and update all rows with the default value in a single batch in SQL Server? I am trying to execute the following code as part of a migration in a transaction, but the code fails unless I put the GO statement after the ADD CONSTRAINT statement:
ALTER TABLE T ADD C INT NULL
ALTER TABLE T ADD CONSTRAINT DF_T_C DEFAULT ((1)) FOR C
GO
UPDATE T SET C = DEFAULT
ALTER TABLE T ALTER COLUMN C INT NOT NULL

If I leave out the GO statement I get the following error:

Invalid column name 'C'.

The code executing the migration cannot handle the GO statement, how can I get this to work in a single transaction?

A: You can use EXEC for the problematic statements so they get compiled as a different batch.
EXEC('UPDATE T SET C = DEFAULT;
      ALTER TABLE T ALTER COLUMN C INT NOT NULL')

But you can also do
ALTER TABLE T ADD C INT NOT NULL CONSTRAINT DF_T_C DEFAULT ((1))

Rather than doing all these individual steps yourself.

A: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

SET XACT_ABORT ON;

BEGIN TRANSACTION;

ALTER TABLE T ADD C INT NULL;

ALTER TABLE T ADD CONSTRAINT DF_T_C DEFAULT ((1)) FOR C;
EXEC ('UPDATE T SET C = DEFAULT');

ALTER TABLE T ALTER COLUMN C INT NOT NULL;

COMMIT TRANSACTION;

A: I ended up with this, which does everything in one statement:
ALTER TABLE T ADD C INT NOT NULL CONSTRAINT DF_T_C DEFAULT ((1)) WITH VALUES

Works with SQL Server.


text:
Q: How do I display the resuls of my ajax DB query? I am querying my DB with some query which returns 2 fields. I'm just wondering what's the better/best way of displaying the search results.
in the old days, I would have been using string concatenation.
example:
var html="";
$.each(data, function () {
    var html = html + "
" + this.field1 + "
" + this.field2 + "

";
});

I'm hoping things would've have improved and something better like jquery can be used? I did search the net but can't find anything useful.
Thanks a lot.

A: String concatenation is still quite popular. But with jQuery you can create elements using object syntax:
$.each(data, function() {
    var field1 = $("", { text: this.field1 });
    var field2 = $("", { text: this.field2 });
    $("
").append(field1, "
", field2).appendTo("#results");
});

However, it's quite possible that this will be slower than the concatenation version. This makes lots of calls to DOM functions to create elements and append them to the DOM, one at a time. String concatenation, on the other hand, is relatively efficient. If you do all the concatenation, and then finally do $("#results").html(html) at the end, it will make use of the browser's internal HTML parser to construct all the elements in one fell swoop. This is optimized very heavily in all browsers.

A: You could use the append function in JQuery.
$(document).ready(function () {
   var div = $("

");
   var span1 = $("");
   span1.append("value 1");
   var span2 = $("");
   span2.append("value 2");
   div.append(span1).append("
").append(span2).append("
");
   $("body").append(div);
});

Replace the text values with the values you are returning from your query.
See my JSFiddle


text:
Q: set 2 characters as one I have a TextView(bt) containing two strings..
bt.setText("\u06AD" + ":");

I want to consider this two strings as one and when I hit the delete button, both should be clear.
How can I do that?
Thanks a lot.

A: bt.setText("");

Or what you are meaning?:)


text:
Q: writing a VTK aplication in WPF, trying to follow MVVM So I'm pretty new to WPF and MVVM, and while I understand the premise, a lot of this stuff is like trying to read hieroglyphs for me.
Basically, my situation is this: I'm using Activiz, a c# wrapper for VTK, which is an image processing/visualization library. So, in this library, there's a WinForms control called vtk:RenderWindowControl, which is an opengl control containing the class that handles all of the visualization functionality. I think it'd be easier to just use WinForms, but that's not really an option for me.
So, to use vtk:RenderWindowControl in a WPF application, I just need to shove it into a WindowsFormsHost and then I can use it more or less just like the example code, in the code behind (if that's the correct term for the .xaml.cs file)
That's fine for a test app, but in practice, I'd like to follow MVVM if possible. This is where I've run into a wall. If "renderControl" lives in the View class, how can I reference it and use it from the ViewModel? I think binding is the answer to that question, but I only really know how to do that for simple types and commands.
Following ideas in another thread I found, I managed to set up something like this answer
My codebehind looks like this:
public partial class RenderPanel_View : UserControl
{
    public static readonly new DependencyProperty RWControlProperty =
        DependencyProperty.Register("RWControl", typeof(RenderWindowControl), typeof(RenderPanel_View), new PropertyMetadata(null));

    public RenderWindowControl RWControl
    {
        get { return (RenderWindowControl)GetValue(RWControlProperty); }
        set { SetValue(RWControlProperty, value); }
    }

    public RenderPanel_View()
    {
        // This is necessary to stop the rendercontrolwindow from trying to load in the
        // designer, and crashing the Visual Studio.
        if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) {
            this.Height = 300;
            this.Width = 300;
            return;
        }

        InitializeComponent();
        this.RWControl = new RenderWindowControl();
        this.RWControl.Dock = System.Windows.Forms.DockStyle.Fill;
        this.WFHost.Child = this.RWControl;
    }
}

My .xaml looks like this
<UserControl x:Class="vtkMVVMTest.RenderPanel.RenderPanel_View"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:vtk="clr-namespace:Kitware.VTK;assembly=Kitware.VTK"
         xmlns:rp="clr-namespace:vtkMVVMTest.RenderPanel"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300"
         RWControl="{Binding VMControlProperty}">
    <Grid>
        <WindowsFormsHost x:Name ="WFHost"/>
    </Grid>
</UserControl>

So two things. One, That last line of the xaml header is an error, "The member 'RWControl' is not recognized or accessible". I don't really understand why. Second, for what I'm guessing is the ViewModel half of the equation, how is VMControlProperty supposed to be defined?
Am I at least on the right track here, or is this way off base?

A: Some controls are not MVVM friendly and you have make the ViewModel aware of View interface and allow interact with it directly. Do not open the whole control to the ViewModel it will ruin the ability to write tests, put an interface on top for example IRenderPanelView and open in the interface only the functionality you need to access from ViewModel. You can then create a DP property of this type in the view, set it in the constructor and bind it to ViewModel.View property in xaml.


text:
Q: How to autostart an application in GDM3? GDM3 version 3.28.2-4.
Is there a directory or configuration option for programs that GDM3 executes when login screen appears?

In my current setup the auto-login shell command is run from rc.local:
 sh -c "sleep 30; echo -n 1 >/dev/autologin" &

The 30-second delay is taken from experience, but it is random and uncertain. What I would like to do is to run echo -n 1 >/dev/autologin exactly when login screen appears.

/dev/autologin is "arduino pro micro" which enters user password via keyboard when it receives a signal via TTY. The following sketch is used:
void setup()
{
  TXLED0;
}

void loop()
{
  while (Serial.read() == -1) ;

  Keyboard.press(KEY_RETURN);
  delay(50);
  Keyboard.release(KEY_RETURN);

  delay(1000);

  Keyboard.press('1');
  delay(50);
  Keyboard.release('1');

  delay(1000);

  Keyboard.press(KEY_RETURN);
  delay(50);
  Keyboard.release(KEY_RETURN);
}

(Also note that for this to work, udev rule must be added to create /dev/autologin and probing by ModemManager must be disabled for this device.)

A: https://help.gnome.org/admin/gdm/stable/configuration.html.en

5.2. Autostart Configuration
  The /gdm/autostart/LoginWindow directory contains files in the format specified by the "FreeDesktop.org Desktop Application Autostart Specification". Standard features in the specification may be used to specify programs that should auto-restart or only be launched if a GConf configuration value is set, etc.
Any .desktop files in this directory will cause the associated program to automatically start with the login GUI greeter. By default, GDM is shipped with files which will autostart the gdm-simple-greeter login GUI greeter itself, the gnome-power-manager application, the gnome-settings-daemon, and the metacity window manager. These programs are needed for the greeter program to work. In addition, desktop files are provided for starting various AT programs if the configuration values specified in the Accessibility Configuration section below are set.


text:
Q: Set color of specific item within a DataGridViewComboBox dropdown list In the following example, how can I highlight (change the background color) of specific items in the dropdown list? To be specific, I am talking about the items in the "dropdown list" for the DataGridViewComboBox.
I want to highlight for the user the specific item(s) that are bad choices.
Please provide a working code example in vb.net.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As New DataTable

    dt.Columns.Add("id", GetType(Integer))
    dt.Columns.Add("list", GetType(String))
    dt.Columns.Add("goodChoice", GetType(Boolean))

    dt.Rows.Add(10, "Lemon")
    dt.Rows.Add(20, "Apple")
    dt.Rows.Add(30, "Star Fruit", False)
    dt.Rows.Add(40, "Orange")

    Dim newColumn As New DataGridViewComboBoxColumn()
    With newColumn
        .HeaderText = "Choices"
        .Name = "Choices"
        .DataSource = dt
        .DisplayMember = "list"
        .ValueMember = "id"
    End With
    DataGridView1.Columns.Add(newColumn)
End Sub

A: Try handling the EditingControlShowing event to subscribe to the ComboBox.DrawItem event. In this event handler you'll grab the underlying DataTable DataSource. When that item's goodChoice is False and the item is not the focused item, fill it's background color.
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    If TypeOf e.Control Is ComboBox Then
        Dim cb As ComboBox = TryCast(e.Control, ComboBox)
        cb.DrawMode = DrawMode.OwnerDrawFixed
        RemoveHandler cb.DrawItem, AddressOf DrawGridComboBoxItem
        AddHandler cb.DrawItem, AddressOf DrawGridComboBoxItem
    End If
End Sub

Private Sub DrawGridComboBoxItem(sender As Object, e As DrawItemEventArgs)
    If e.Index <> -1 Then

        e.DrawBackground()

        Dim cb As ComboBox = TryCast(sender, ComboBox)
        Dim dt As DataTable = TryCast(cb.DataSource, DataTable)

        If (e.State And DrawItemState.Focus) <> DrawItemState.Focus AndAlso cb.DroppedDown Then
            If dt.Rows(e.Index).Item("goodChoice") Then
                e.Graphics.FillRectangle(Brushes.White, e.Bounds)
            Else ' Added for follow-up question.
                e.Graphics.FillRectangle(Brushes.Red, e.Bounds)
            End If
        End If

        e.Graphics.DrawString(dt.Rows(e.Index).Item("Name"), e.Font, Brushes.Black, e.Bounds)

        e.DrawFocusRectangle()
    End If
End Sub

My follow-up question is, if and when the red colored item is selected, how can I make the color stick when exiting the edit mode of the control?

Set the BackColor of the cell itself. (Note: This will also alter the dropped down items, so we add an Else statement to the DrawGridComboBoxItem method above.)
Set the color when the cell value changes:
Private Sub DataGridView1_ValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    If TypeOf DataGridView1.CurrentCell Is DataGridViewComboBoxCell Then
        Dim cell As DataGridViewComboBoxCell = TryCast(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex), DataGridViewComboBoxCell)
        Dim dt As DataTable = TryCast(cell.DataSource, DataTable)
        Dim row() As DataRow = dt.Select("ID = " & cell.Value)

        cell.Style.BackColor = If(row(0).Item("goodChoice"), SystemColors.ControlLight, Color.Red)
    End If
End Sub

Then use that color by manually painting the background:
Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
    If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then
        If TypeOf DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex) Is DataGridViewComboBoxCell Then
            Dim cell As DataGridViewComboBoxCell = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
            Dim color As Color = If(cell.Style.ForeColor.Name = "0", Color.Black, cell.Style.ForeColor)

            Using backbrush = New SolidBrush(cell.Style.BackColor)
                Using brush = New SolidBrush(color)
                    Using format = New StringFormat()
                        e.Paint(e.ClipBounds, DataGridViewPaintParts.Background)
                        e.Paint(e.ClipBounds, DataGridViewPaintParts.Border)
                        e.Paint(e.ClipBounds, DataGridViewPaintParts.ContentBackground)
                        e.Paint(e.ClipBounds, DataGridViewPaintParts.ErrorIcon)
                        e.Paint(e.ClipBounds, DataGridViewPaintParts.Focus)
                        e.Paint(e.ClipBounds, DataGridViewPaintParts.SelectionBackground)

                        format.LineAlignment = StringAlignment.Center

                        Dim rect = New Rectangle(e.CellBounds.X + 1, e.CellBounds.Y + 1, e.CellBounds.Width - 19, e.CellBounds.Height - 3)

                        e.Graphics.FillRectangle(backbrush, rect)
                        e.Graphics.DrawString(cell.FormattedValue, e.CellStyle.Font, brush, e.CellBounds, format)
                        e.Handled = True
                    End Using
                End Using
            End Using
        End If
    End If
End Sub


text:
Q: new File("") vs. new File("."): Feature or Bug? new File("") and new File(".") yield the same canonical path, yet the former object is unsubable. Consider below code, and how both objects return the same canonical path. The documentation states the canonical path is "both absolute and unique". Yet only the File created with the "." argument is actually usable.
Shouldn't an exception be thrown at some point? Either in the empty string constructor call (since the object created doesn't seem valid), or at least in getCanonicalPath (which at least declares IOException)?
import java.io.File;
import java.io.IOException;

public abstract class Test {

    public static void main(String[] args) throws Exception {
        testFile("");
        testFile(".");
    }

    private static void testFile(String arg) throws IOException {
        System.out.format("File constructor argument: \"%s\"\n", arg);
        File g = new File(arg);
      System.out.format("toString()            = \"%s\"\n", g.toString());
        System.out.format("getAbsolutePath()     = \"%s\"\n", g.getAbsolutePath());
        System.out.format("getAbsoluteFile()     = \"%s\"\n", g.getAbsoluteFile());
        System.out.format("getgetCanonicalPath() = \"%s\"\n", g.getCanonicalPath());
        System.out.format("getgetCanonicalFile() = \"%s\"\n", g.getCanonicalFile());
        System.out.format("exists()              = %s\n", g.exists());
        System.out.format("isDirectory()         = %s\n", g.isDirectory());
        System.out.println();
  }
}

And the output that it produces:
File constructor argument: ""
toString()            = ""
getAbsolutePath()     = "C:\usr\workspace\Test"
getAbsoluteFile()     = "C:\usr\workspace\Test"
getgetCanonicalPath() = "C:\usr\workspace\Test"
getgetCanonicalFile() = "C:\usr\workspace\Test"
exists()              = false
isDirectory()         = false

File constructor argument: "."
toString()            = "."
getAbsolutePath()     = "C:\usr\workspace\Test\."
getAbsoluteFile()     = "C:\usr\workspace\Test\."
getgetCanonicalPath() = "C:\usr\workspace\Test"
getgetCanonicalFile() = "C:\usr\workspace\Test"
exists()              = true
isDirectory()         = true

A: According to the javaDocs :
Every pathname that denotes an existing file or directory has a unique canonical form.
In your first example, you are referring to "the file that has no name".
As that one does not exist, I don't think it's a bug that new File("") and new File(".") yield the same canonical path.

A: While using the constructor with the empty String, you create a File instance that has two properties :

*

*It does not actually exists.

*Its absolute pathname is the "empty abstract pathname"

When using File("."), you create a different file :

*

*It DOES exist on the file system

*Its absolute pathname contains the "." character

This second file exists, not the first. The second file is consequently the only one that is supposed to respect the rule explained in getCanonicalPath :

Every pathname that denotes an existing file or directory has a unique canonical form.

As the first file is not real, the fact that their canonical paths are equal is meaningless.
Consequently, the behviour you've pointed is not a bug. It's the one we expected from the JVM.
You'll find all the infos in the javadoc

A: By passing an empty string to the constructor, you are creating an empty 'abstract pathname'. From the java.io.File Javadoc:

If the given string is the empty
  string, then the result is the empty
  abstract pathname.

The 'empty abstract pathname' in this case does not physically exist, hence exists() evaluates to false. The reason you get a directory for the empty string is described in the Javadoc of getAbsolutePath:

If this abstract pathname is the empty
  abstract pathname then the pathname
  string of the current user directory,
  which is named by the system property
  user.dir, is returned.


text:
Q: Require semigroup to be associative in scala A semigroup is required to be associative, but I could define a Semigroup like:
trait Semigroup[T] {
  def op(t1:T, t2:T) : T
}

def plus = new Semigroup[Int] { def op(t1:Int, t2:Int) = t1 - t2 }

I am able to implement plus which is not associative, yet the class is still a Semigroup.  Is there a safeguard in place against this or is the user expected to rely on testing to prevent this?

A: There will be no compilation exception, that the associativity property does not hold. In other words, it's up to you to make sure it's implemented correctly.
But if you use cats, you can use laws to make sure all the properties required for the semigroup and other structures defined in cats. Take a look at the documentation. You can create a test to check if the semigroup you defined is alright:
class TreeLawTests extends AnyFunSuite with Discipline {
  checkAll("YourSemigroup[YourType].SemigroupLaws", SemigroupTests[YourSemigroup[YourType]].semigroup)
}


text:
Q: Why doesn't jquery turn my array into a json string before sending to asp.net web method? So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like:
$.ajax({
  type: 'POST',
  url: 'personalization.aspx/SetPersonalization',
  data: "{'backerEntries':" + backerEntries + "}",
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: postcardManager.SetPersonalizationComplete
});

The post:
{'backerEntries':[object Object],[object Object],[object Object]}

The error response:
Invalid JSON primitive: object.

For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here?

A: The data you are passing you are trying to pass it as a string already.  If you want jQuery to transform it leave the whole thing as an object, e.g.
data:{backerEntries: backerEntries }

Assuming of course backerEntries is an array.  jQuery should transform this and will append it to the querystring as that is its default behaviour.  Your current code is relying on default JavaScript behaviour which won't by default convert an array into its string representation.

A: Since you're using ASP.NET, you can use the built-in ASP.NET AJAX serialization library:
var backerEntriesJson = Sys.Serialization.JavaScriptSerializer.serialize(backerEntries);

then pass that directly in your jQuery ajax call:
...
data: backerEntriesJson,
...

A:
data: "{'backerEntries':" + backerEntries + "}",

..is the same as
data: "{'backerEntries':" + backerEntries.toString() + "}",

...which is pretty much useless. Use Duncan's suggestion if you just want to pass an encoded list of values with the name "backerEntries" in your querystring. If you want to JSON-encode the data, then get a JSON library and call JSON.stringify().

A: This is NOT valid JSON: { 'foo': 'bar' }
Isn't, wasn't ever, never will be. JSON processors are often very forgiving, which of course is a false convenience.
Read the specification. A string is defined to be enclosed in double quotes, not single quotes, not smiley face characters, not pieces of metal bent at right angles, not bricks. There's no mention of single quotes, period.
Now, property names are JSON strings. By definition, they MUST are enclosed in double quotes.
Valid: { "foo": "bar" }
valid" { "foo": 100 }
valid: { "foo": true }
valid: { "foo": [ "one", "two" ], "bar": false }
see www.json.org
see www.jsonlint.com


text:
Q: Irreducible representations of $su2$ in dimension $d$ : how do we know it exists? I am studying in a book the way to find the irreducible representations of $su(2)$.
They start by assuming that it exists a basis of the representation in a vectorial space of dimension $d$ ($d$ is any).
And they do all the work after it.
But it all started with the assumption that such a representation exist for any dimension $d$.
How do we know that ?

A: When you finally arrive at an understanding of how a $d$-dimensional irreducible representation should look like, you've identified it's basis and how $\mathfrak{su}(2)$ acts on this basis. Now we can safely turn things around: take a $d$-dimensional vector space and define the action of $\mathfrak{su}(2)$ on it's basis by the rules that you've derived, and you get this representation.
Alternatively, you can take the defining 2-dimensional representation $V$ of $\mathfrak{su}(2)$, and take it's symmetric powers $S^d V$, which appear to be $d+1$-dimensional and irreducible, proving the existence. This has the advantage that corresponding irreducible representations of the group $SU(2)$ can also be found the same way, using symmetric powers of the defining representation.


text:
Q: Multiselect items in view model Grid View (Metro app) I have a GridView and i have set its data template to another view.
What i want is to have a SelectedItems property in the view model, that will hold All the selected items of gridview.
SelectedItems  field  in gridView is readonly (also not dependency property), hence it could not bound.

A: I had created a behavior to maintain sync between different item controls.
Behaviors are not supported natively, WinRTBehaviors library is used. it is an Open Source for providing behavior support. This library is excellent, and provides a behavior extension, exactly similar to the WPF framework.
Details are listed in the article
Managing Multiple selection in View Model (.NET Metro Style Apps)


text:
Q: QGIS fix invalid geometry for intersection on Corine Land Cover files There are many posts on this but I was wondering on which layer should I do my operations. I explain: I am using the Corine Land Cover (CLC) files for 2006 and I am just interested in one part in Germany. So I did an intersection between my layer with entire europe and the one with an adm area. In the log I can see that I have many invalid geometries and as a result I am losing a lot of objects.
How can I fix that and on which layer should I act upon (the CLC layer which is very big?)
Could it be due because the CLC files are rasters rather than vectors?

A: *

*Fix geometries

*If that isnt enough you can try and buffer the output with a very small distance, or even zero