text:
Q: How to configure Next.js project to use @Atlaskit open source React UI library (Compile Time Error)? I am using Next.js version 8 with Atlaskit but getting compile time error which you see as below, I tried many bubble plugin and web-pack configs but didn't work as I am new to web-pack and bubble
/Users/UserName/Desktop/work-space/with-styled-components-app/node_modules/@atlaskit/theme/index.js:1
(function (exports, require, module, __filename, __dirname) { import { css } from 'styled-components';
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/Users/Desktop/work-space/with-styled-components-app/node_modules/@atlaskit/icon/cjs/components/Icon.js:30:14)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

and my package.json has these dependencies
"@atlaskit/avatar": "^15.0.1",
    "@atlaskit/css-reset": "latest",
    "@atlaskit/icon": "^16.0.5",
    "@atlaskit/logo": "^10.0.1",
    "@atlaskit/navigation-next": "5.0.1",
    "@atlaskit/theme": "^8.0.1",
    "@zeit/next-css": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "apollo-boost": "^0.3.1",
    "apollo-link-context": "^1.0.17",
    "babel-plugin-styled-components": "^1.10.0",
    "cookie": "^0.3.1",
    "graphql": "^14.1.1",
    "isomorphic-unfetch": "^3.0.0",
    "jest-styled-components": "^7.0.0-2",
    "next": "^8.0.3",
    "react": "^16.8.4",
    "react-apollo": "^2.5.2",
    "react-dom": "^16.8.4",
    "styled-components": "^4.0.0"


text:
Q: How can I extract EDB (ms exchange storage file) to PST Under Linux? (preferably in Python) I can extract and read messages from PST files using libpst , but i want to extract from edb files too (not online exchange server but from offline files). And in Linux.
Any python lib or any kind for linux commandline tool should help.
Thanks.

A: Take a look at Joachim Metz' work. He reverse engineered the edb format and analyzed the exchange database to a limited extend. It's open source and there's even some documentation about the tables and columns:
http://sourceforge.net/projects/libesedb/files/
However it doesn't create a PST or anything similar. It merely extracts all tables into separate files and tries to decode some of the data. In order to extract the Emails from your EDB file you need to get into the documentation and do plenty of coding as the data is rather scattered around within the databse (of course it just looks like scattered. Microsoft definitely didn't just want to make the lifes of the reverse engineers miserable).
Good luck

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass proxy to mailjet php api? I'm using mailjet to send emails from my website, but mailjet has blocked my ip (shared ip), so I'm trying to use a proxy but I don't find how to, I tried that:
        MAIL::$mj=new \Mailjet\Client(apikey,apisecret,true,[
                                                    'version' => 'v3',
                                                    'proxy' => [
                                                    'http' => "http://proxyuser:proxypassword@proxywebsite.tld:22225",
                                                ],]);


text:
Q: How to assign an if statement's result into an equation? I'm new to python and I have to run a program to get the correct interest rate based on user input and use the interest rate obtained to compute monthly interest earned.
For the computation of interest earned, I'm trying to use the print result to create a formula for calculating monthly interest earned. However, I've tried so many things and I'm not sure how to correct this.

transaction_category = [2000, 2500, 5000, 15000, 30000]
first_50k_1_category_rates = [0.05, 1.55, 1.85, 1.90, 2.00, 2.08]

if (count == 1) and (account_balance <= 50000) and (total_eligible_monthly_transactions < transaction_category[0]):
    print(f'Interest rate applicable is: {first_50k_1_category_rates[0]: .2f}%')

if (count == 1) and (account_balance <= 50000) and (transaction_category[0] <= total_eligible_monthly_transactions < transaction_category[1]):
    print(f'Interest rate applicable is: {first_50k_1_category_rates[1]: .2f}%')

A: Your question is rather unclear, but I guess you are looking for something like
if (count == 1) and (account_balance <= 50000) and (transaction_category[3] <= total_eligible_monthly_transactions < transaction_category[4]):
    applicable_interest_rate = first_50k_1_category_rates[4]

elif (count == 1) and (account_balance <= 50000) and (total_eligible_monthly_transactions >= transaction_category[4]):
    applicable_interest_rate = first_50k_1_category_rates[5]

print(f'Interest rate applicable is: {applicable_interest_rate: .2f}%')

This is just a sketch; you will have to make sure the new variable is always defined, then use that in your final equation instead.
Probably the repeated conditions should be refactored, too, so you don't compare the same things over and over.
if (count == 1) and (account_balance <= 50000):
    if transaction_category[3] <= total_eligible_monthly_transactions < transaction_category[4]:
        applicable_interest_rate = first_50k_1_category_rates[4]
    elif total_eligible_monthly_transactions >= transaction_category[4]:
        applicable_interest_rate = first_50k_1_category_rates[5]

but again, without seeing the complete script, it's not clear exactly how to refactor. This is just one example to illustrate the idea.

A: So you could do if/else in one code block, or turn those print statements into variables and return them. Both would say result as var name.
def foo(condition1, condition2):

    if condition1 < condition2:
        result = (1 + 1)

    if 1 == False:
        result = (1 - 1)

    return result

print(foo(1, 2))

*

*there's better ways to do this in a more functional programming aspect like this: (lambda :f"b:{b}",lambda :f"a:{a}")[a>b](), but it seems this code style is imperative so stick w that.

A: If you are having trouble with scope, you can try this (safe) hack:
_scope = {
    "applicable_interest_rate1": first_50k_1_category_rates[4],
    "applicable_interest_rate2": first_50k_1_category_rates[5],
}

def foo(condition1, condition2):

    if condition1 < condition2:
        result = _scope["applicable_interest_rate1"]

    if 1 == False:
        result = _scope["applicable_interest_rate2"]

    return result

print(foo(1, 2))


text:
Q: SQLite query with where clause I am using SQLite database in my application and I want to fetch the rows from the table where I have some particular value in corresponding and when I fetch all rows my app works fine but when I use where clause then I get no data in the cursor object ?
below is my method of SQLite helper class to get data
public Cursor getAllNames(String belongsId){
        SQLiteDatabase myDb = this.getReadableDatabase();
        return myDb.rawQuery(" SELECT * FROM "+ TABLE_NAME_names + " WHERE BELONGS =" + belongsId ,null);
    }

and this is my function call:-
Cursor cursor = myDb.getAllNames(belongsId);

myDb is the object of my SQLite helper class.
my tble is below:-
 sr        names         BELONGS
 1          joe          abc
 2          sid          def
 3          david        abc

so basicall I wanna fetch only rows 1 and 3 and all other rows where BELONGS = abc
any little help will be appriciated thanks!
error is below :-
Caused by: android.database.sqlite.SQLiteException: no such column: abc (code 1): , while compiling: SELECT * FROM names WHERE BELONGS = abc
please click to see full error message


text:
Q: How to select all commits from somebody on one branch and insert into another branch? There are two branches:
master: there's no commits from userA
branchA: there are some commits from userA, also some trash commits from other users
Now I need to insert all commits from userA on branchA into master(preserve date).
How can I do that?

A: You can write a quick one liner to do this.
First filter the commits on branchA by author, get their commit id and then cherry-pick them on master.
$ git checkout master
$ git log branchA --author='userA' | awk '/commit/ {print $2}' | while read commit; do git cherry-pick $commit; done

A:
Cherry-pick is what you need.

Merging a specific commit from one branch to another is pretty easy: use the
 git cherry-pick
 command.
The syntax is:
git cherry-pick <commit hash>.
Here is how you go about doing it.
First make a note of the commit hash using the git reflog or git log command.
Then, switch to the branch where you'd like to merge the commit and run git cherry-pick with the commit hash, as shown in the example below.
$ git cherry-pick d4d8e7c
Now you will have merged the specific commit from one branch to the other.


text:
Q: python3 os.chdir throwing a syntax error when using a variable I'm trying to remove numbers from files in a given directory.
For some reason whenever I try pass a variable into os.chdir I get a syntax error.
I have tried converting the norm_direc to a str using str() to no avail.
I researched online but could only find people getting errors for forgetting their quotation marks but as I understand it they're not needed for a variable.
Source Code;
#Setup
import os
import datetime
print ("Started on "+ str(datetime.datetime.now()))

#Get the norms
norm_direc = os.getcwd()
file_list = os.listdir(r"/home/damhan/Downloads/Tyler - Wolf 2013")

def rename_files():
        #Workings
        os.chdir("/home/damhan/Downloads/Tyler - Wolf 2013")

        #Start the loop
        for file_name in file_list:
                os.rename(file_name, file_name.strip("0123456789")

        #Cleanup
        os.chdir(norm_direc)
rename_files()
print("Done :)")

The error;
  File "numberdestroyer.py", line 20
    os.chdir(norm_direc)
     ^
SyntaxError: invalid syntax

A: You missing a closing bracket in:
 os.rename(file_name, file_name.strip("0123456789") #<-- need one more )


text:
Q: Concatenating strings from a multidimensional array overwrites the target string in Perl I've built a two dimension array with string values. There are always 12 columns but the number of rows vary. Now I'd like to build a string of each row but when I run the following code:
$outstring = "";
for ($i=0; $i < $ctrLASTROW + 1; $i++) {
    for ($k=0; $k < 12; $k++){
       $datastring = $DATATABLE[$i][$k]);
       $outstring .= $datastring;
    }
}

$outstring takes the first value. Then on the second inner loop and subsequent loops the value in $outstring gets overlaid. For example the first value is "DATE" then the next time when the value "ABC" gets fed to it. Rather than being the hoped for "DATEABC" it's "ABCE". The "E" is the fourth character of DATE. I figure I'm missing the scalar / list issue but I've tried who knows how many variations to no avail. When I first started I tried the concatenation directly from the @DATATABLE. Same problem. Only quicker.

A: When you have a problem such as two strings DATE and ABC being concatenated, and the end result is ABCE, or one of the strings overwriting the other, a likely scenario is that you have a file from another OS, with the line endings \r\n, which are chomped, resulting in the string DATE\rABC when concatenated, which then becomes ABCE when printed.
In other words:
my $foo = "DATE\r\n";
my $bar = "ABC\r\n";   #  \r\n line endings from file
chomp($foo, $bar);     #  removes \n but leaves \r
print $foo . $bar;     #  prints ABCE

To confirm, use
use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper $DATATABLE[$i][$k];   # prints $VAR1 = "DATE\rABC\r";

To resolve, instead of chomp use a regex such as:
$foo =~ s/[\r\n]+\z//;


text:
Q: PHP choose a word from a string in the string XX is always changed and string can be longer or shorter and it can be without searched word, where XX is a number
example:
1 kom. nije naručeno, obično dolazi za 5 dana., slični: sony-6am6ptb1a (0 kom.), sony-s006pb1a (-9 kom.)

So from that I need to output just: obično dolazi za 5 dana
So how can I chose just &find in any case?
$find = "obično dolazi za XX dana.";

$string ="1 kom. nije naručeno, obično dolazi za XX dana.";

if (strpos($string,$find) !== false) {
  echo '$string contains $find';
}

I think this is it:
$string = "1 kom. nije naručeno, obično dolazi za XX dana.";

for(int intIndex = 1; intIndex <= 31; intIndex++)
{
 $find = "obično dolazi za " . strval(intIndex) . " dana."

 if (strpos($string,$find))
 {
 echo '$string contains $find';
 }
}

A: I am assuming that the 'search string' has a portion (XX) that changes and you don't necessarily know what it will be in a given situation. So you can't use strpos because of the unknown segment.
You'll have to use a regular expression based on the left and right parts of the search string.
Please see PHP Manual: preg_match for more details.
Without knowing what `XX' represents I can't offer anything more.
Or...
If you want to return the XX and the left-most and right-most parts are constant...
// given '1 kom. nije naručeno, obično dolazi za XX dana.'

$string = str_replace("1 kom. nije naručeno, obično dolazi za ", "", str_replace(" dana.", "", $string));
// $string now contains the value of 'XX'

print $string;

Output is XX.
Or...
Is this good enough for your needs..? [It is based on what you came up with! :)]
<?php
    // just throwing '23' in there to demonstrate the awesome power!
    $string = "1 kom. nije naručeno, obično dolazi za 23 dana.";
    for ($intIndex = 1; $intIndex <= 31; $intIndex++) {
        $find = "1 kom. nije naručeno, obično dolazi za " . strval($intIndex) . " dana.";

        // we test that it's not 'false', because it could be '0'
        if (strpos($string, $find) !== false) {
            echo "$string contains $find";
        }
    }
?>

A: I want to guess you have issues with the output ... and its returning
 $string contains $find

Use " instead of '
$find = "obično dolazi za XX dana.";
$string ="1 kom. nije naručeno, obično dolazi za XX dana.";
if (mb_stripos($string,$find) !== false) {
  echo "$string contains $find";
}

Output
 1 kom. nije naruÄeno, obiÄno dolazi za XX dana. contains obiÄno dolazi za XX dana.


text:
Q: How to enable terraform module only with a specific workspace I define a provider containing modules.
I can call terraform apply at the provider level with two different workspace:
workspace list
  default
  wk-p1
* wk-p2

I would like the following module only to be launch when I use the workspace wk-1:
module "sync" {
  source = "./../test-modules/sync"

  workspace="${local.workspace}"
  entity = "${local.entity}"
}

I would like something like this:
module "sync" {
  if ("${local.workspace}" == "wk-p2") {
    source = "./../test-modules/sync"

    workspace="${local.workspace}"
    entity = "${local.entity}"
  }
}

Do you have any idea?

A: For this you could use the terraform.workspace variable in conjuction with the count directive
 count = (terraform.workspace == "wk-p2") ? 1 : 0

This way when the workspace is wk-p2, terraform will create an instance of the module.
On the other hand if it evaluates to false it will create 0 instances of the modules, meaning it will not create anything

A: Maybe try with "count". Something like:
count = terraform.workspace == "default" ? 1 : 0


text:
Q: My ClearType won't become monochrome I'm having a problem where my ClearType settings made with the built-in ClearType Tuner won't apply to any other applications, or even the operating system.
I've set my Cleartype so that the text is anti-aliased but monochrome:

But when I finish this setup and I go back to Windows (even after reboot), the settings remain the same. Even in Windows Explorer:

How do I make sure the ClearType settings apply?
edit I also tried to run cttune.exe as administrator with elevated privileges, but that doesn't work either.

A: ClearType uses sub pixel rendering. Sub pixels have colors. The trade off is improved intensity variation by sacrificing color fidelity. There will always be some color artifacts depending on the font - some display fonts were designed with ClearType in mind and look better in this regard.
Also keep in mind a zoomed in bitmap capture of the text isn't a true representation of how the subpixels are lit on the actual LCD screen or how they are perceived by the viewer. Same type of effect can happen if you run the desktop at a non-native resolution of the LCD panel or when ClearType is wrong about the subpixel layout of an LCD (the tuner is supposed to fix this).

A: According to Winaero:
https://winaero.com/blog/change-cleartype-settings-windows-10/
Note that Universal Windows Platform apps do not use ClearType text rendering, but instead rely on greyscale antialiasing. So the parts of Windows 10 which use Universal Windows Platform like the Start Menu or tray applets will not see any difference in text rendering even after you tune ClearType. Only those desktop apps that do not explicitly use DirectWrite, continue to use ClearType.
additional tips:
Tips for improving your WPF text rendering experience
https://blogs.msdn.microsoft.com/text/2006/10/18/tips-for-improving-your-wpf-text-rendering-experience/

A: If you want monochrome text which is antialiased, then you should turn ClearType off.
Uncheck the box:

You will see that it is monochrome:

Then click next on every screen and do not change from the defaults.  Then it will apply without need to reboot:

And it is now grayscale, yet still antialiased.

A: This might be eventually a monitor issue too. On one of my monitors (HP w2207h) I can get rid of those colored fringes by resetting the monitor to factory defaults. I have ClearType enabled (Windows XP) and done some simple profiling in Windows using Adobe tools. Under normal circumstances the sub pixel rendering is only visible using a magnifying glass. To the naked eye all characters appear monochrome and quite sharp.
Nevertheless after some months the monitor settings degrade for no obvious reasons and I might see color fringes. A reset to factory defaults usually helps.


text:
Q: 12:4: error: variable-sized object may not be initialized Update:
It could be complied in OS X but could not in Linux and Windows with MinGW.

Given the rainfall in mm for each month, display a horizontal, text-based histogram showing the rainfall per month.
Here's my code
    // This variation prints out the actual names of the months instead of numbers.

    #include <stdio.h>
    #include <string.h>

    int main(int argc, char *argv[])
    {
        const int WIDTH = 70;
        const int NUM_MONTHS = 12;
        int max = 0;
        int rainfall[NUM_MONTHS];
        char months[NUM_MONTHS][11] = { "January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
        int i;

        for(i = 0; i < NUM_MONTHS; i++)
        {
            printf("Enter %s rainfall: ", months[i]);
            scanf("%d", &rainfall[i]);
            if(rainfall[i] > max)
            {
                max = rainfall[i];
            }
        }

        for(i = 0; i < NUM_MONTHS; i++)
        {
            printf("%s", months[i]);
            int len = strlen(months[i]);
            int j;
            for(j = len; j < 10; j++)
            {
                printf(" ");
            }
            int num_stars = WIDTH * (rainfall[i]/(float)max);
            for(j = 0; j < num_stars; j++)
            {
                printf("*");
            }
            printf("\n");
        }

    }

When I try to compile it with gcc, it shows error and warning.
.\rainfall-graph-names.c: In function 'main':
.\rainfall-graph-names.c:12:4: error: variable-sized object may not be initialized
    char months[NUM_MONTHS][11] = { "January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

.\rainfall-graph-names.c:12:4: warning: excess elements in array initializer [enabled by default]
.\rainfall-graph-names.c:12:4: warning: (near initialization for 'months') [enabled by default]

I don't know why it doesn't work and I don't know why.
Is there anyone could help?
Thanks

A: The declaration
char months[NUM_MONTHS][11] = {...};

makes months a variable length array even though NUM_MONTHS is declared as
const int NUM_MONTHS = 12;

The C99 standard does not allow initialization of variable length arrays using the syntax:
char months[NUM_MONTHS][11] = {...};

From the standard (emphasis mine):

6.7.8 Initialization
3 The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

You can use a pre-processor macro.
#define NUM_MONTHS 12

and remove the line
const int NUM_MONTHS = 12;

The effectively makes months:
char months[12][11] = {...};

Since months is not a variable length array any more, it can be initialized using the syntax you have in your posted code.
Update
It's better still to use (Thanks @JonathanLeffler):
enum {NUM_MONTHS = 12};

When you use an enum, NUM_MONTHS becomes part of the debugger's symbol table and you can see its value in the debugger. You cannot do that if you use a pre-processor macro.
See this answer to another SO question for further details.

A: The NUM_MONTHS is a variable. For array size you must define it as a integer
constant.

See http://randu.org/tutorials/c/arrays.php for examples of declaration. Hope it helps.


text:
Q: Aptana Studio 3 not finding gems with rvm I'm trying to use Aptana Studio 3 on a Ruby project I'm working on. I'm on Mac OS X 10.8, and have Ruby installed with RVM.
When I try and execute a .rb file in Aptana Studio, it gives me errors as follows:
/Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- resque (LoadError)
    from /Users/.../.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/.../q_test.rb:3:in `<main>'

From within the Aptana Studio 3 Terminal, when I type
rvm gemset list

I can see that the right version of ruby is selected, but it seems Aptana is disregarding the gemset?
What's going on? Can anybody help?
Update
I suspect the issue to be something to do with this:
https://aptanastudio.tenderapp.com/discussions/problems/3306-switching-rvm-ruby-and-gemsets-on-fly

A: It should be possible to define a default gemset with the --default option
rvm 1.9.2-p320
rvm gemset create rails_gemset
rvm --default use ruby-1.9.2-p320@rails_gemset

Maybe this helps?
BTW, I would recommend to use simple editors such as Sublime Text, Textmate or Emacs instead of Aptana Studio. They are faster, leaner and neater than the big bloated IDEs (which are needed for Java, but not for Ruby).


text:
Q: How to get user information on app installation Is there a way (if possible) to fetch some user info, such as users language or app version (to store in server), on app installation, before the app is launched or maybe on app launch but only once.
I looked into NSUserDefaults but i don't think it will exactly serve what i want.
I can get the user info i need in the app delegate - didFinishLaunchingWithOptions, but i want the info stored only once at app installation (time & date) and not every time user will launch the app.
couldn't find info on google or SO that will help accomplishing exactly what i want...
any help will be very much appreciated.
thanks in advance

A: There are many open source projects doing exactly this. Just take a look at one of these projects to get an impression on how to access this information. Just as an example: Countly
If you want to access this information only once, just set a BOOL in NSUserDefaults that indicates whether or not you already got it.


text:
Q: prevent clients sending messages socket.io I'm wondering how to prevent connected clients hack into code and send messages.
nodejs server code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http ,{serveClient: false});
var port = process.env.PORT || 3000;
var request = require("request")
var url = "http://localhost/api/index.php";
events = require('events'),
    serverEmitter = new events.EventEmitter();
app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){

    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            io.emit('chat message', body);
        }
    });

});

http.listen(port, function(){
    console.log('listening on *:' + port);
});

I'm using webSocket to keep users up-to-date with currencies prices.
I would like to prevent users sending data to other clients.

A: Steps involved in a client to client interaction.
For simplicity, I'm using a custom socket event name as 'chat'

*

*A client emits an event 'chat'

*Server listens for the 'chat' event and gets the message

*Server then emits a 'chat' event to send the message

*The appropriate client(s) listens for 'chat' and receives the message

Every message passes through your server.So you can restrict any client to client interaction.

Also, the socket.io (written in the question) sends currency prices to all connected clients everytime a new client connects. Instead, send prices when a client connects through GET request.Then send updated prices whenever the price gets updated.
Replace your socket code with your new code that follows the above pattern


text:
Q: In a N x M matrix find the max number of neighbours equal to the number they are neighbouring in optimal time If you are wondering no, this is not my homework it's just am execise that I found online and couldn't get my head around it.
You are given an N x M matrix only with ones and zeroes in it. . A neighbour can by a number up, down, left, down or on the diagonal. Most numbers have 8 neighbours while those on the side have 5 and those on each of the four corners have 3. I have to find the max number of neighbours that are equal to a number in the matrix.
The problem is that I don't know how to do it without checking every number in the matrix (N x M checkings).

A: You cannot avoid checking every element of the matrix.
Think of a "checkerboard" matrix:
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1

Ignoring the edges for the time being, every element has four equal neighbors. But if you negate any one element (turning a 0 to a 1 or a 1 to a 0), some position will have five equal neighbors. So if you come up with an algorithm that never looks at the element at row r and column c when processing the checkerboard matrix, then you will certainly get the wrong answer for one of these two possible matrices: the checkerboard matrix above, and the checkerboard that has position (r,c) negated.


text:
Q: Prove that A + B is invertible iff $I_n$ + $A^{-1}$B is invertible (matrices) We are given that a matrix $A$ in $R^{n\times n}$ is invertible. We must show that $A + B$ (also in $R^{n\times n}$) is invertible if and only if $I_n$ + $A^{-1}$$B$ is invertible.
I cannot figure out how to do this proof. It is probably something simple I am missing but I just can't get my head around it. In particular, the $I_n$ (multiplicative identity) is putting me off. Anyone have any suggestions or hints to help me get going?
Thanks!

A: If $A+B$ is invertible, then
$$(A+B)^{-1}A(I_n + A^{-1}B) = (A+B)^{-1}(A + B) = I$$
By a fundamental theorem in linear algebra, we have $(I_n + A^{-1}B)(A+B)^{-1}A = I$ as well and therefore $(I_n + A^{-1}B)$ is invertible and $(I_n + A^{-1}B)^{-1} = (A+B)^{-1}A$.
If $I_n + A^{-1}B$ is invertible, then
$$(I_n + A^{-1}B)^{-1}A^{-1}(A+B) = (A(I_n + A^{-1}B))^{-1}(A+B) = (A+B)^{-1}(A+B) = I$$
Similarly, $A+B$ is invertible and $(A+B)^{-1} = (I_n + A^{-1}B)^{-1}A^{-1}$.


text:
Q: tengo este error illegal start of type / illegal start of expression, cómo lo resuelvo? Tengo este error justo en la línea de @JoinTable y no estaría encontrando la solución. No puedo correr el código en maven porque el error afecta a todo mi proyecto. No entiendo dónde se encuentra específicamente el error que me salta. Si alguien fuera tan amable de explicarme qué hacer. Desde ya muchísimas gracias.
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotNull
private String nombre;
@NotNull
@Column (unique = true)
private String nombreUsuario;
@NotNull
private String email;
@NotNull
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "usuario_rol", joinColumns = @JoinColumn(name = "usuario_id"),
inverseJoinColumns = @JoinColumn(name = "rol_id"));
private Set<Rol> roles = new HashSet<>();
.
.
.
//Continua código

}

A: Debes definir las anotaciones sin terminar con ";" ya que esto provocará que no las reconozca como tal, en este caso la anotación es:
@JoinTable(name = "usuario_rol", joinColumns = @JoinColumn(name = "usuario_id"),
inverseJoinColumns = @JoinColumn(name = "rol_id"))

por lo tanto define de esta forma la variable roles
@JoinTable(name = "usuario_rol", joinColumns = @JoinColumn(name = "usuario_id"),
inverseJoinColumns = @JoinColumn(name = "rol_id"))
private Set<Rol> roles = new HashSet<>();


text:
Q: Blocking kernel updates with dpkg I'd like to block all distribution-shipped kernel updates due to a nasty thing that recently happened to me. (I'm on a Ubuntu 12.04 amd64 derivative.)
I'd like to block all updates to installed kernels of the minor version 3.2 to the linux-headers, linux-headers-generic, linux-image, and linux-image-extra packages. The problem I'm encountering is that these all have a version and if I block a specific version, nothing is gained because a new version will be installed (eg: if I block linux-image-3.2.0-35, linux-image-3.2.0-36 is not blocked and could still potentially be installed with a dist-upgrade from apt.)

A: What you need to use is a feature of apt-get called holding
You can either do this via Synaptic or Dpkg, Here is how I would hold my kernel using the dpkg method.
First check your kernel image name
dpkg -l | grep linux-image

output for me:
ii  linux-image-3.2.0-4-amd64              3.2.35-2                           amd64        Linux 3.2 for 64-bit PCs
ii  linux-image-amd64                      3.2+46                             amd64        Linux for 64-bit PCs (meta-package)

then tell dpkg to hold the metapackage (the generic version without any version numbers)
echo linux-image-amd64 hold | sudo dpkg --set-selections

You can then check this worked via dpkg -l linux-image-amd64
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                       Version            Architecture       Description
+++-==========================-==================-==================-==========================================================
hi  linux-image-amd64          3.2+46             amd64              Linux for 64-bit PCs (meta-package)

Notice the 'hi' at the bottom, h means held and i means currently installed. This package is installed but will not be upgraded.
You can reverse this via
echo linux-image-amd64 install | sudo dpkg --set-selections

and again can check via dpkg -l linux-image-amd64
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                       Version            Architecture       Description
+++-==========================-==================-==================-==========================================================
ii  linux-image-amd64          3.2+46             amd64              Linux for 64-bit PCs (meta-package)

Notice 'ii', the first i means this package is set to install and the second i means it is currently installed. This package is installed and will be upgraded.
For more information on these flags see man dpkg specifically the 'package selection states' sections.


text:
Q: Use HTMLPurifier to filter out everything but instagrm embed code I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
I have been trying to configure HTMLPurifier to accept instagram embed code.
Instagram embed code

 <div style=" background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAsCAMAAAApWqozAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAMUExURczMzPf399fX1+bm5mzY9AMAAADiSURBVDjLvZXbEsMgCES5/P8/t9FuRVCRmU73JWlzosgSIIZURCjo/ad+EQJJB4Hv8BFt+IDpQoCx1wjOSBFhh2XssxEIYn3ulI/6MNReE07UIWJEv8UEOWDS88LY97kqyTliJKKtuYBbruAyVh5wOHiXmpi5we58Ek028czwyuQdLKPG1Bkb4NnM+VeAnfHqn1k4+GPT6uGQcvu2h2OVuIf/gWUFyy8OWEpdyZSa3aVCqpVoVvzZZ2VTnn2wU8qzVjDDetO90GSy9mVLqtgYSy231MxrY6I2gGqjrTY0L8fxCxfCBbhWrsYYAAAAAElFTkSuQmCC); display:block; height:44px; margin:0 auto -44px; position:relative; top:-22px; width:44px;">

 有人問我整理書櫃的方法  搬完家後我還沒時間整理,就把最近比較想讀的放在外圍這樣

囧星人(@shintarokyon)分享的貼文 於 <time style=" font-family:Arial,sans-serif; font-size:14px; line-height:17px;" datetime="2017-04-11T05:10:48+00:00">2017 年  4月 月 10 10:10下午 PDT</time> 張貼

HTMLPurifier setting
return [
'encoding'      => 'UTF-8',
'finalize'      => true,
'cachePath'     => storage_path('app/purifier'),
'cacheFileMode' => 0755,
'settings'      => [
    'default' => [
        'HTML.Doctype'             => 'XHTML 1.0 Transitional',
        'HTML.Allowed'             => 'div,b,strong,p,i,em,blockquote[class|style],a[href|title],ul,ol,li,p[style],br,span[style],img[width|alt|src],iframe[src|width|height|class|frameborder]',
        'CSS.AllowedProperties'    => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align',
        'HTML.AllowedAttributes'   => 'style,src',
        'AutoFormat.AutoParagraph' => true,
        'AutoFormat.RemoveEmpty'   => true,
        "HTML.SafeIframe"          => true,
        "URI.SafeIframeRegexp"     => "%^(http://|https://|//)(www.youtube.com/embed/|player.vimeo.com/video/|api.soundcloud.com/tracks/)%",
    ],
    'test'    => [
        'Attr.EnableID' => true
    ]
],

I have been trying to  allow "style" in 'HTML.AllowedAttributes' setting.But it was not working.And tried to allowed css properties-'box-shadow'...etc,but some properties was not supported.
Thanks for your help !!

A: https://github.com/mewebstudio/Purifier/issues/32
Adding new properties is not supported by this package.


text:
Q: How to verify a user's ID token in firestore using Javascript? I am building a react native application and am using Firebase, more specifically firestore, in order to manage my data. My current objective is to implement an auto login feature on my app, where if the user exits the app, I want them to stay signed in, unless they manually hit the Sign Out button before exiting the app. Here is my current process of doing this:
When the user logs into the app, I sign them in by:
firebase.auth().signInWithEmailAndPassword(email, password).
I then get their idToken by:
  let authIdToken = "";
  firebase
    .auth()
    .currentUser.getIdToken(true)
    .then(function (idToken) {
      authIdToken = idToken
    })
    .catch(function (error) {
      console.log(error)
    });

I then want to save this token into the phone, so when the user opens the app again, I can fetch this token and check its validity. If it is valid, then I can log the user in using their idToken. In react native, I can do this by doing:
AsyncStorage.setItem(
    "userData",
    JSON.stringify({
      token: token,
    })
  );

Now when the app loads up:
const startScreen = props => {
   useEffect(() => {
    const tryLogin = async () => {
     const userData = await AsyncStorage.getItem("userData");
     const transformedData = JSON.parse(userData);
     const { token } = transformedData;

     await firebase
       .auth()
       .verifyIdToken(token, true)
       .then((payload) => {
         console.log(true)
       })
       .catch((error) => {
         if (error.code == "auth/id-token-revoked") {
           // Token has been revoked. Inform the user to reauthenticate or signOut() the user.
           console.log("revoked")
         } else {
           console.log("error")
         }
       });
    };
    tryLogin();
 }, []);

The Issue: When I try to verify the token this way, I am met with the following error: firebase.auth().verifyIdToken is not a function.
I read through the documentation and am unsure of how else to verify this token using JS. How do I verify it? Let me know if my verification process is incorrect and how it should be done. I am new to using firestore and doing authentication in general and hope to learn how to do it the right way.
Another helpful note: This is how I am configuring my firestore: !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : {};
Thanks!

A:
I then want to save this token into the phone, so when the user opens the app again, I can fetch this token and check its validity.

This is completely unnecessary.  Firebase Auth with persist the signed in user, and automatically refresh the token without you having to do anything.  All you need to do is listen to when updates to the token are made available, and act on the new token as needed.  You can establish an ID token listener using onIdTokenChanged as shown in the linked API documentation:
firebase.auth().onIdTokenChanged(function(user) {
  if (user) {
    // User is signed in or token was refreshed.
  }
});

Once you have this token, you know that the user is successfully signed in.  There is nothing left to do.  There is no need to use it to sign in.
Also, you can't verify the token on the frontend.  The verifyIdToken method you're looking at is for the Admin SDK only, which only runs on the backend.  The idea is that you get the token on the fronend, then pass it to the backend as described in the documentation for the Admin SDK.  The backend uses this to securely determine if the user on the frontend is who they say they are.
Since you didn't say if you have a backend or not, dealing with this token might not be necessary at all.  If you just want to know when the user is signed in (even if they are just returning to the page after being away, then you can skip everything above and just use an auth state observer.  Again, Firebase Auth persists information about the user so you don't have to sign them in again.  The observer will tell you when the automatic sign-in is complete, or if they are not signed in at all.


text:
Q: Round pandas data frame/series I have a column in a pandas data frame that looks like this (much longer but here's the top few rows):
>df_fill['col1']

0      5987.8866699999998672865
1     52215.5966699999989941716
2       201.8966700000000003001
3         3.8199999999999998401

I want to round the entire column to 5 decimal places. I can round it to integers, but not to any amount of digits after the decimal. The type for the column is float.
> np.around(df_fill['col1'], 0)

0      5988
1     52216
2       202
3         4

> np.around(df_fill['col1'], 5)

0      5987.8866699999998672865
1     52215.5966699999989941716
2       201.8966700000000003001
3         3.8199999999999998401

> (df_fill['col1']).round()

0      5988
1     52216
2       202
3         4

>(df_fill['col1']).round(5)

0      5987.8866699999998672865
1     52215.5966699999989941716
2       201.8966700000000003001
3         3.8199999999999998401

> (df_fill['col1']).round(decimals=5)

0      5987.8866699999998672865
1     52215.5966699999989941716
2       201.8966700000000003001
3         3.8199999999999998401

> str((df_fill['col1']).round(decimals=5))
'0      5987.8866699999998672865\n1     52215.5966699999989941716\n2       201.8966700000000003001\n3         3.8199999999999998401\

What am I missing here?

A: Floats can only represent a subset of the real numbers. It can only exactly represent those decimals which are sums of negative powers of two ("binary fractions").
After you round a float to 5 digits, the new float may not be the real number which has 5 decimal digits since the decimal part may not be exactly expressible as a binary fraction. Instead rounding returns the float closest to that real number.
If you have set
pd.options.display.float_format = '{:.23g}'.format

then Pandas will show up to 23 digits in its string representation of floats:
import pandas as pd

pd.options.display.float_format = '{:.23g}'.format

df_fill = pd.DataFrame({'col1':[ 5987.8866699999998672865, 52215.5966699999989941716,
                                201.8966700000000003001, 3.8199999999999998401]})

#                       col1
# 0 5987.8866699999998672865
# 1 52215.596669999998994172
# 2 201.89667000000000030013
# 3 3.8199999999999998401279

print(df_fill['col1'].round(5))
# 0   5987.8866699999998672865
# 1   52215.596669999998994172
# 2   201.89667000000000030013
# 3   3.8199999999999998401279
# Name: col1, dtype: float64

But if you set the float_format to display 5 decimal digits:
pd.options.display.float_format = '{:.5f}'.format

then
print(df_fill['col1'].round(5))

yields
0    5987.88667
1   52215.59667
2     201.89667
3       3.82000
Name: col1, dtype: float64

Note the underlying float has not changed; only the manner in which it is displayed.

A: Your problem is due to a precision issue in representing floating point numbers. The number 5987.88667 cannot be represented exactly in a float, the nearest number that can be represented is 5987.8866699999998672865. Thus you already have the number closest to the number you want in the array, and rounding it to 5 decimal places will thus have no effect. You already have the correct invocation:
(df_fill['col1']).round(5)

You can see that it works if you try to round to 2 decimal places instead. So I suggest you don't worry about it. If the issue is how the number is displayed on the screen, then you can print the number to a string to the correct number of decimal places:
print "%.5f"%(df_fill['col1'])


text:
Q: Using dataAnnotation regular expression validation attribute in Wpf Mvvm IDataErrorInfo with different windows Hore the more detailled solution! I use nearly the same code like shown here from Karel:
Using dataAnnonation regular expression validation attribute in Wpf Mvvm IdataErrorInfo
and it works like a charm!
I have a Model where I want to use the Attributes and IDataErrorInfo for Validation which works perfect.
  simplified Model:

  public class SiESTAModel : BaseModel
  {
         [Required]
          public string MyTestsceanrioNameTemp { get; set; }
  }

In my BaseModel Class I have this Code which runs:
public class BaseModel : INotifyPropertyChanged, IDataErrorInfo
{
        private static List<PropertyInfo> _propertyInfos;
        public Dictionary<string, string> Errors { get; set; } = new Dictionary<string, string>();

            public string this[string columnName]
            {
                get
                {
                    CollectErrors();
                    return Errors.ContainsKey(columnName) ? Errors[columnName] : string.Empty;
                }
            }

     private void CollectErrors()
            {
                Errors.Clear();
                PropertyInfos.ForEach(
                    prop =>
                    {
                        //Validate generically
                        var errors = new List<string>();
                        var isValid = TryValidateProperty(prop, errors);
                        if (!isValid)

                            Errors.Add(prop.Name, errors.First());
                    });
                // we have to this because the Dictionary does not implement INotifyPropertyChanged
                OnPropertyChanged(nameof(HasErrors));
                OnPropertyChanged(nameof(IsOk));
                // commands do not recognize property changes automatically
                OnErrorsCollected();
            }

        private List<PropertyInfo> PropertyInfos
        {
            get
            {
                return _propertyInfos
                       ?? (_propertyInfos =
                           GetType()
                               .GetProperties(BindingFlags.Public | BindingFlags.Instance)////////////////////////////////////////////
                                .Where(prop => prop.IsDefined(typeof(ValidationAttribute), true))
                               .ToList());
            }
        }

        private bool TryValidateProperty(PropertyInfo propertyInfo, List<string> propertyErrors)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(this) { MemberName = propertyInfo.Name };

                var propertyValue = propertyInfo?.GetValue(this);

                    // Validate the property
                    var isValid = Validator.TryValidateProperty(propertyValue, context, results);

                    if (results.Any())
                    {
                        propertyErrors.AddRange(results.Select(c => c.ErrorMessage));
                    }
                    return isValid;

            }
}

This Model is created in my ViewModel:
public class DataErrorInfoViewModel : BaseViewModel
{
   public SiESTAModel SiESTA { get; set; }

    public DataErrorInfoViewModel()
    {
        // create SiESTA
        SiESTA = new SiESTAModel();
    }
 }

In my MainView I have some textboxes where a login is implemented and I check the Input Values. This Login is implementes in the View as an Usercontrol which works perfect for the whole propertiesin my MainView.
For example:
TextBox  Text="{Binding CurrentUser.SiestaIp, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnDataErrors=True}" MinWidth="180"  Width="AUTO" Margin="10,0,10,0"

But now I want to add some new Devices via a new window and I want to check also in this window the input values. I have implemented this with MVVM light and messenger.
ViewModel:
public RelayCommand OpenAddWindowCommand { get; private set; }

        OpenAddWindowCommand= new RelayCommand(() =>
        {

            MessengerInstance.Send(new OpenAddWindowMessage());
        });

Message:
public class OpenAddWindowMessage
{
    public OpenAddWindowMessage()
    {

    }

}

In my view project I have Message Listener Class implemeted like this which is called via a binding.
    public class MessageListener
    {

        public AddWindow TempAddWindow;

        public MessageListener()
        {
            InitMessenger();
        }
 private void InitMessenger()
        {
            Messenger.Default.Register<OpenAddWindowMessage>(this, msg =>
                {
                    TempAddWindow = new AddWindow();

                    TempAddWindow.ShowDialog();

                }

            );
         }
     }

And in this AddWindow view I have textboxes which should be checked for required to see on the begin of the post. The Data Context is also my MainViewModel like in my MainView.
        <TextBox  FontSize="16"  Text="{Binding SiESTA.MyTestsceanrioNameTemp, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnDataErrors=true}"  Grid.Column="1" Grid.Row="0"></TextBox>

Now to the Problem! If I only have the MainView Window open, IdataErrorInfo works perfect. But when the 2nd Window is opened and got the focus the get Value from my Property crashes out of the Base model.
Line of the crash:
var propertyValue = propertyInfo.GetValue(this);

Exception:

System.Reflection.TargetException--> Object doesn't match to the target type.

This is because the reflection collects the values not only from the new opened AddWindow it collects also from the mainview Window my Loginvalues which I want only check if the MainWindow is open. And the getvalues from the the property of the Main View crashes.
protected List<PropertyInfo> PropertyInfos
{
    get
    {
        return _propertyInfos
               ?? (_propertyInfos =
                   GetType()
                       .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                       .Where(prop => prop.IsDefined(typeof(ValidationAttribute), true))
                       .ToList());
    }
}

So, what can be done so that the Reflection collects only the values from the actual opnened window? or can it be solved other? Thanks! I hope this explains nough :)


text:
Q: Making Simple Post Request With Axios, React.js and Spring I'm new to both React and Spring and am having trouble creating a simple JSON Post request. The post request is being logged successfully in the console but no data is being added. Here are the relevant scripts:
package com.sdproject.teammanager.model;

public class Team {
    private String id;
    private String name;
    private int seeding;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSeeding() {
        return seeding;
    }

    public void setSeeding(int seeding) {
        this.seeding = seeding;
    }

}

package com.sdproject.teammanager.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sdproject.teammanager.exception.TeamNotFoundException;
import com.sdproject.teammanager.model.Team;
@CrossOrigin(origins ="http://localhost:3000")
@RestController
public class TeamController {
    private static Map<String, Team> teamRepo = new HashMap();
    static {
        Team nuig = new Team();
        nuig.setId("1");
        nuig.setName("NUIG");
        nuig.setSeeding(1);

        teamRepo.put(nuig.getId(), nuig);
    }

    @RequestMapping(value = "/teams")
    public ResponseEntity<Object> getTeam() {
        return new ResponseEntity<>(teamRepo.values(), HttpStatus.OK);
    }

    @RequestMapping(value = "/teams", method = RequestMethod.POST)
    public ResponseEntity<Object> createTeam(@RequestBody Team team) {
        teamRepo.put(team.getId(), team);
        return new ResponseEntity<>("Team has been registered", HttpStatus.CREATED);
    }

    @RequestMapping(value = "/teams/{id}", method = RequestMethod.PUT)
    public ResponseEntity<Object> updateTeam(@PathVariable("id") String id, @RequestBody Team team) {
        if (!teamRepo.containsKey(id))
            throw new TeamNotFoundException();
        teamRepo.remove(id);
        team.setId(id);
        teamRepo.put(id, team);
        return new ResponseEntity<>("Team Has Been Updated Successfully", HttpStatus.OK);
    }

    @RequestMapping(value = "/teams/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
        if (!teamRepo.containsKey(id))
            throw new TeamNotFoundException();
        teamRepo.remove(id);
        return new ResponseEntity<>("Team Has Been Deleted", HttpStatus.OK);
    }
}

import React from 'react';
import axios from 'axios';

export default class TeamInput extends React.Component {
    state = {
        name: '',
    }

    handleChange = event => {
        this.setState({ name: event.target.value });
    }

    handleSubmit = event => {
        event.preventDefault();

        const Team = {
            name: this.state.name
        };

        axios.post(`http://localhost:8080/teams`, { team })
            .then(res => {
                console.log(res);
                console.log(res.data);
            })
    }

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label>
                        Team Name:
                        <input type="text" name="name" onChange={this.handleChange} />
                    </label>
                    <button type="submit">Add</button>
                </form>
            </div>
        )
    }
}

After hitting my button to submit a team with default parameters, I can see it being successfully submitted. But it doesn't show up in the repo or when I use postman to get the JSON files.

A: Looks like your Java class, Team doesn't have a getter method defined.
Either you should have used the spring annotation for getter or should have defined a getter.
This might be the root cause of your problem.
If not, could you be more clear on the issue?

A: i hope it can work for you
async handleChange = event => {
        await this.setState({ [event.target.name]: event.target.value });
    }

  handleSubmit = e => {
        e.preventDefault();
        const data = {
                name: this.state.name
          };
        axios({
          method: "post",
          url: `http://localhost:8080/teams`,
          data
        })
          .then(res => {
            this.setState({
               name: '',
            });
          })
          .catch(err => {
            console.log(err);
          });
      }


text:
Q: How to put bullets in the margin? I'm no typography expert, but I heard that the bullets and numbers in itemize/enumerate environments are better placed outside of the main body of text, i.e. in the margin. How can I do that in LaTeX?
And a bonus question, how can I do that in ConTeXt? :)
EDIT:
One use is in this thesis: http://www.duo.uio.no/sok/work.html?WORKID=81971&lang=en
but I did not find any nested list there.
Another case is this eBook: http://designingfortheweb.co.uk/book/part3/part3_chapter13.php

A: The ConTeXt part is easy:
\startitemize[inmargin]
\item foo
\item bar
\item baz
\stopitemize

A: I've never seen placement of the bullets of a list in the margin. The text within a list isn't just body text. So, why line it up with body text. It's a good idea to indent it like you would do with a quotation.
Let's think of choosing this style. What about a nested list? In consequence, its items would have to be aligned at the left margin of the parent list, so at the left margin of the document as well.
What about enumerated lists? Should the numbers be placed in the margin?
To sum up, bulleted list with bullets in margins and items in line with body text seems questionable. Though, it can easily be achieved.
With enumitem, better specify a style in the preamble than to each list by an optional argument. This is consistent and allows easy changes. If you later decide to change the list style, you just need to apply the modification once in the preamble for the whole document.
Martin's example modified under this point of view:
\documentclass{article}
\usepackage{enumitem}
\setitemize[1]{leftmargin=0ex}
\usepackage[showframe]{geometry}
\begin{document}
\begin{itemize}
\item text
\end{itemize}
\end{document}

A: you could use the enumitem package to adjust the leftmargin.
I have, however, never seem bullets in the margin.

\documentclass{article}
\usepackage{enumitem}
\usepackage[showframe]{geometry}
\begin{document}
\begin{itemize}[leftmargin=0ex]
    \item Some text in here
\end{itemize}
\end{document}

A: I actually found the source for that thesis somewhere, and extracted the following (ok, I added a . for the enum-list!)
Here is the thesis source, if anyone else is interested later on.
% Enumeratable list
\newenvironment{enum}{%
  \begin{list}{\arabic{enumi}.}{%
    \setlength{\topsep}{\onelineskip}
    \setlength{\partopsep}{0pt}
    \setlength{\parsep}{\parskip}
    \setlength{\itemsep}{\parskip}
    \setlength{\leftmargin}{0pt}
    \setlength{\itemindent}{0pt}
    \usecounter{enumi}
  }
}{\end{list}}

% Itemized list
\newenvironment{items}{%
  \begin{list}{\textbullet}{%
    \setlength{\topsep}{\onelineskip}
    \setlength{\partopsep}{0pt}
    \setlength{\parsep}{\parskip}
    \setlength{\itemsep}{\parskip}
    \setlength{\leftmargin}{0pt}
    \setlength{\itemindent}{0pt}
  }
}{\end{list}}

% Definitions in lists
\newcommand{\iterm}[1]{\item \term{#1}}


text:
Q: KSQL UDF: DataException: Struct schemas do not match I am tryin to create a stream as select (CSAS), the stream is created successfully, but when I tried to push messages I am getting the below exception.
Caused by: org.apache.kafka.connect.errors.DataException: Struct schemas do not match.
    at org.apache.kafka.connect.data.ConnectSchema.validateValue(ConnectSchema.java:247)
    at org.apache.kafka.connect.data.Struct.put(Struct.java:216)
    at io.confluent.ksql.serde.GenericRowSerDe$GenericRowSerializer.serialize(GenericRowSerDe.java:116)
    at io.confluent.ksql.serde.GenericRowSerDe$GenericRowSerializer.serialize(GenericRowSerDe.java:93)
    at org.apache.kafka.common.serialization.Serializer.serialize(Serializer.java:62)
    at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:162)
    at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:102)
    at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:89)

Below are the main stream, the persistent stream and the udf function details from the ksql-cli, not sure why the schema is not compatible, as you can see below the processed stream have a field called article with schema exactly as the same as the returned value from the UDF function, Am I missing something here.
ksql> create stream main_stream ( article struct< _id VARCHAR, title VARCHAR, text VARCHAR, action VARCHAR, url VARCHAR, feed_id VARCHAR, mode VARCHAR, score INTEGER, published_at VARCHAR, retrieved_at VARCHAR> ) with  (KAFKA_TOPIC='articles', value_format='JSON');

ksql> create stream processed as select  test(article) article from main_stream;

ksql> describe processed;

Name                 : processed
 Field   | Type
-------------------------------------------------------------------------------------------------------------------------------------------------------------
 ROWTIME | BIGINT           (system)
 ROWKEY  | VARCHAR(STRING)  (system)
 ARTICLE | STRUCT<_ID VARCHAR(STRING), RAW_TITLE VARCHAR(STRING), RAW_TEXT VARCHAR(STRING), PROCESSED_TITLE VARCHAR(STRING), PROCESSED_TEXT VARCHAR(STRING)>
-------------------------------------------------------------------------------------------------------------------------------------------------------------
For runtime statistics and query details run: DESCRIBE EXTENDED <Stream,Table>;

ksql> show queries;

 Query ID      | Kafka Topic | Query String
--------------------------------------------------------------------------------------------------------------------------------------------------------------
 CSAS_processed_20 | processed       | CREATE STREAM processed WITH (REPLICAS = 1, PARTITIONS = 1, KAFKA_TOPIC = 'processed') AS SELECT TEST(MAIN_STREAM.ARTICLE) "ARTICLE"
FROM MAIN_STREAM MAIN_STREAM;
--------------------------------------------------------------------------------------------------------------------------------------------------------------

ksql> describe function test;

Name        : TEST
Overview    : test udf
Type        : scalar
Jar         : /Users/ktawfik/libs/custom-udf.jar
Variations  :

    Variation   : TEST(article STRUCT<_ID VARCHAR, TITLE VARCHAR, TEXT VARCHAR, ACTION VARCHAR, URL VARCHAR, FEED_ID VARCHAR, MODE VARCHAR, SCORE INT, PUBLISHED_AT VARCHAR, RETRIEVED_AT VARCHAR>)
    Returns     : STRUCT<_ID VARCHAR, RAW_TITLE VARCHAR, RAW_TEXT VARCHAR, PROCESSED_TITLE VARCHAR, PROCESSED_TEXT VARCHAR>
    Description : test
    article     : A complete article object

Also below the UDF code I used
@Udf(description = "test",
                    schema = "struct< _id VARCHAR, raw_title VARCHAR, raw_text VARCHAR, processed_title VARCHAR, processed_text VARCHAR>")
    public Struct processDocument(
            @UdfParameter(
                    schema = "struct< _id VARCHAR, title VARCHAR, text VARCHAR, action VARCHAR, url VARCHAR, feed_id VARCHAR, mode VARCHAR, score INTEGER, published_at VARCHAR, retrieved_at VARCHAR>",
                    value = "article",
                    description = "A complete article object") Struct struct) {

        Schema ARTICLE_SCHEMA = SchemaBuilder.struct()
                .field("_id", Schema.STRING_SCHEMA)
                .field("raw_title", Schema.STRING_SCHEMA)
                .field("raw_text", Schema.STRING_SCHEMA)
                .field("processed_title", Schema.STRING_SCHEMA)
                .field("processed_text", Schema.STRING_SCHEMA)
                .build();

Struct proStruct = new Struct(ARTICLE_SCHEMA);
        proStruct.put("_id", "1234");
        proStruct.put("raw_title", "RAW_TITLE___1234");
        proStruct.put("raw_text", "RAW_TEXT___1234");
        proStruct.put("processed_title", "TITLE____1234");
        proStruct.put("processed_text", "TEXT____1234");
        System.out.println(proStruct);
// Struct{_id=1234,raw_title=RAW_TITLE___1234,raw_text=RAW_TEXT___1234,processed_title=TITLE____1234,processed_text=TEXT____1234}
        return proStruct;

    }

A: I was trying to solve the problem the same way but I'm struggling with the following case:
UDF:
@UdfDescription(name = "ValueUnpacker", description = "..")
public class ValueUnpacker {
    private Schema valueSchema = SchemaBuilder.struct()
            .field("LABEL", Schema.INT32_SCHEMA)
            .build();

    @Udf(description = "Test a string", schema = "struct<LABEL INT>")
    public Struct unpackValue(@UdfParameter(value = "thingType", description = "a thing type") String thingType) {
        Struct ret = new Struct(valueSchema);
        int i = 5;
        ret.put("LABEL", i);
        System.out.println("Ret: " + ret);
        return ret;
    }
}

Running ksqldb and type:
ksql> SELECT valueunpacker('test') FROM SOME_STREAM EMIT CHANGES;
|{LABEL=5}
|{LABEL=5}

and it works fine. But creating a stream as
CREATE STREAM CONSTANT_STREAM AS SELECT valueunpacker('test') FROM SOME_STREAM;

failes with no output of the stream. The log of ksqldb result in the same problem: "Schemas do not match".

A: I was able to figure out the problem and solve it, basically it is the fact that KSQL engine translate schema fields to UPPER case, hence when I send fields with lower case it wasn't able to match it, which is not clear in the docs.
The fix is that I have to have:

*

*All the fields in the programmatically defined SCHEMA in upper case, AS WELL AS the schema field in the @UDF annotation.

*All the fields in the programmatically defined schema should match exactly all the fields (names and types) in the schema field in the @UDF annotation.

Code finally looked like:
@Udf(description = "test",
                    schema = "struct< _ID VARCHAR, RAW_TITLE VARCHAR, RAW_TEXT VARCHAR, PROCESSED_TITLE VARCHAR, PROCESSED_TEXT VARCHAR>")
    public Struct processDocument(
            @UdfParameter(
                    schema = "struct< _id VARCHAR, title VARCHAR, text VARCHAR, action VARCHAR, url VARCHAR, feed_id VARCHAR, mode VARCHAR, score INTEGER, published_at VARCHAR, retrieved_at VARCHAR>",
                    value = "article",
                    description = "A complete article object") Struct struct) {

        Schema ARTICLE_SCHEMA = SchemaBuilder.struct()
                .field("_ID", Schema.STRING_SCHEMA)
                .field("RAW_TITLE", Schema.STRING_SCHEMA)
                .field("RAW_TEXT", Schema.STRING_SCHEMA)
                .field("PROCESSED_TITLE", Schema.STRING_SCHEMA)
                .field("PROCESSED_TEXT", Schema.STRING_SCHEMA)
                .build();

Struct proStruct = new Struct(ARTICLE_SCHEMA);
        proStruct.put("_ID", "1234");
        proStruct.put("RAW_TITLE", "RAW_TITLE___1234");
        proStruct.put("RAW_TEXT", "RAW_TEXT___1234");
        proStruct.put("PROCESSED_TITLE", "TITLE____1234");
        proStruct.put("PROCESSED_TEXT", "TEXT____1234");
        System.out.println(proStruct);
        return proStruct;

    }


text:
Q: Elasticsearch and Searckick: Unable to get partial match on a joined field I am trying to implement elasticsearch on Rails using Searchkick.
The goal is to search on 5 field of order, 2 of which are joined fields, and ideally partial matches using word_middle
For search_data

class Order < ApplicationRecord

searchkick word_middle: [:po_number, :tracking_number]  #Works
#searchkick word_middle: [:po_number, :tracking_number, :purchaser.name]  #does not work

...

def search_data
attributes.merge(
  order_content: self.order_content,
  ship_name: self.purchaser,
  vendor_name: self.vendor,
  po_number: self.po_number,
  tracking_number: self.tracking_number
)
end

And in the actual search:
search_query = Order.search "#{search_query}", where: {archived: false},fields: [{po_number: :word_middle}, {tracking_number: :word_middle}]

#search_query = Order.search "#{search_query}", where: {archived: false},fields: [{po_number: :word_middle}, {tracking_number: :word_middle}, {ship_name: :word_middle}]  #Did not work

I can get the expected search results for PO_NUMBER and Tracking_Number, but when I try to include ship_name or purchaser.name   I don't get any matches including ones that should match on PO and tracking numbers

A: # searchkick word_middle: [:po_number, :tracking_number, :purchaser.name]  # does not work

Shouldn't the :purchaser.name be :ship_name which matches the field you imported & searched in the ElasticSearch?


text:
Q: By definition of $\mathbb E(X\mid \sigma(Y))$ calculate $\mathbb E(X\mid Y=y)$ when $X$and $Y$ are discrete random variables. By definition of $\mathbb E(X\mid \sigma(Y))$ i want to show
$$\mathbb E(X\mid Y=y)=\sum x \mathbb P(X=x\mid Y=y)$$
 when $X$and $Y$ are jointly discrete  random variables.( Absolutely continues  case is here ).  I want to know is my steps right or no. I need some explanation in the steps from start to end(declared with sign ?)
let $Y$ is a discrete random variable that take values
$\{ a_1 ,a_2,\cdots ,a_n\}$. So $\sigma(Y)=\sigma(\{a_1\},\cdots , \{ a_n\})$ (??)
By definition $\forall A\in \sigma(Y)$
$$ \mathbb E \left( \mathbb E \color{red}{(}X\mid \sigma(Y)\color{red}{)}1_A\right)
=\mathbb E(X1_A)$$
since $A\in \sigma(Y)$ so $1_A$ is a function of $Y$ so i think i can write
$$\mathbb E \left( \mathbb E \color{red}{(}X|\sigma(Y)\color{red}{)}1_B(Y)\right)=\mathbb E(X1_B(Y))$$
$$RHS=\mathbb E(X1_B(Y))=\sum_{y\in B} \sum_{x} x \mathbb P(X=x,Y=y) $$
$$LHS=\mathbb E \left( \mathbb E \color{red}{(}X\mid \sigma(Y)\color{red}{)}1_B(Y)\right)
=E \left( \mathbb E \color{red}{(}X\mid Y\color{red}{)}1_B(Y)\right)
$$
$$=\mathbb E \left( g(Y) 1_B(Y) \right)=\sum_{y\in B} g(y) P(Y=y)
=\sum_{y\in B} \mathbb E(X\mid Y=y) P(Y=y)
$$
By unifying $LHS$ and $RHS$  , $\forall B$
$$\sum_{y\in B}  \mathbb E(X\mid Y=y)  \mathbb P(Y=y)=\sum_{y\in B} \sum_{x} x \mathbb P(X=x,Y=y)$$
I think(??) for $y\in \{ a_1 ,a_2,\cdots ,a_n\}$ i can write (since equation is for all $B$ ??)
$$ \mathbb E(X\mid Y=y)  \mathbb P(Y=y)= \sum_{x} x \mathbb P(X=x,Y=y)$$
so for $y\in \{ a_1 ,a_2,\cdots ,a_n\}$
$$ \mathbb E(X\mid Y=y) = \sum_{x} x \frac{ \mathbb P(X=x,Y=y)}{ \mathbb P(Y=y)}= \sum_{x} x \mathbb P(X=x\mid Y=y)$$.
This proof was for finite support(like $Y$ is binomial), is this valid
for countable support ?(like Poisson?).
Thanks in advance for any help you are able to provide or any clarification.

A: Again, this is essentially correct, but now you are overcomplicating things: the discrete case can be handled much easier.
Namely, for any $y$ such that $\mathbb P(Y=y)>0$,
$$
\mathbb E[ \mathbb E[ X\mid Y]1_{Y=y}] = \mathbb E[ X 1_{Y=y}]\\ = \mathbb E\Bigl[\sum_x x1_{X=x}1_{Y=y}\Bigr] = \sum_x x\mathbb E[ 1_{X=x,Y=y}] = \sum_x x\mathbb P(X=x,Y=y).
$$
On the other hand,
$$
\mathbb E[ \mathbb E[ X\mid Y]1_{Y=y}] = \mathbb E[ X\mid Y=y]\mathbb E[ 1_{Y=y}]  = \mathbb E[ X\mid Y=y]\mathbb P(Y=y).
$$
Dividing these equalities by $\mathbb P(Y=y)$, we arrive at the statement.


text:
Q: Error while trying to test React app that uses Mobx I am trying to write tests on my React app and receiving an error from the context.
The error I receive is :Cannot read property 'Provider' of undefined
My test looks like that:
 import { render, screen } from "@testing-library/react"
import userEvent from "@testing-library/user-event";
import EmailLoginForm from "../features/users/EmailLoginForm";

test('if no email and no password, button disabled', async () =>{

    render(<EmailLoginForm/>);

    expect(await screen.findByRole('button', {  name: /login/i})).toBeDisabled();

      userEvent.type(screen.getByPlaceholderText(/email id/i),"test@test.com");
      userEvent.type(screen.getByPlaceholderText(/password/i),"testpw");

      expect(await screen.findByRole('button',{name :/login/i})).toBeEnabled();
})

My main store looks like that:
   import {createContext, useContext} from "react";
//..some imports that are not relevant

interface Store{
    // .. interface of which stores
}

export const store: Store = {
    //.. store declerations

}

export const StoreContext = createContext(store);

export function useStore(){
    return useContext(StoreContext);
}

My EmailLoginForm is an observer.
The index.tsx looks like that:
  import React from 'react';
import ReactDOM from 'react-dom';
import '../src/app/layout/App';
import App from '../src/app/layout/App';
import reportWebVitals from './reportWebVitals';
import { createBrowserHistory } from 'history';
import { Router } from 'react-router-dom';
import './app/layout/index.css'
import { store, StoreContext } from "./app/stores/store"
import ScrollToTop from './app/layout/ScrollToTop';

export const history = createBrowserHistory();

ReactDOM.render(
  <StoreContext.Provider value={store}>
    <Router history={history}>
      <ScrollToTop />

          <App />

    </Router>
  </StoreContext.Provider>,
  document.getElementById('root')
);

I am pretty lost here and don't know where is the issue and how to fix it.
Any help would be appreciated.


text:
Q: Start Activities from onItemClick of ListView in fragments So I have two fragments linking to layout files which display ListViews. The ListViews are defined in the xml and have entries from a string array. I want to click on items in the ListView and open new activities. There are 8 items in one ListView and 9 in the other. In the onItemClick code, how do I create intents to start activities based on the item clicked? I will create 1 class per item as its own activity. How can I start the activities in the classes via intents inside the onItemClick methods of this code?
class CommunityFragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        View view = inflater.inflate(R.layout.community_fragment, container, false);
        ListView lv = (ListView) view.findViewById(R.id.communityListView);
        lv.setOnItemClickListener(new OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
                // TODO Auto-generated method stub

            }
        });
        return view;
    }
}
class ResourcesFragment extends Fragment{
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        View view = inflater.inflate(R.layout.resources_fragment, container, false);
        ListView lv = (ListView) view.findViewById(R.id.resourcesListView);

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub

            }
        });
        return view;
    }
}

A: Implement your  OnItemClickListener() like below
listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub

                    Intent intent = new Intent(getActivity(), nextactivity.class);
                    startActivity(intent);

        }
    });

A: on Item Click you will get Position based on position you can start fragment
listView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
    int position, long id) {
    Toast.makeText(getApplicationContext(),
      "Click ListItem Number " + position, Toast.LENGTH_LONG)
      .show();
       switch(position) {
        case CONST_FRAGMENT_1 :
                  //Start fragment 1
            ...
            ...
       }
  }
});

A: Make switch statement for each items click and open activities accordingly as below:
   lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
                     int itm=arg0.getItemAtPosition(arg2);
                switch (itm) {
                case 0:
                Toast.makeText(m_context, "Position Zero", Toast.LENGTH_SHORT).show();
                                 Intent intent = new Intent(getActivity(), FirstActivity.class);
                startActivity(intent);
                    break;
                case 1:
                  Intent intent1 = new Intent(getActivity(), SecondActivity.class);
                   startActivity(intent1);
                              break;
                case 2:
                          //..............................

        }
    });

A: one Generic solution can be ..
Create an array of items that hold class name of activity you want to open ..
 like ..
Class[] activityArray = new Class[numberOfItemsInListView];
            activityArray[0] = Activity1.class;

//add all activities like that..............
now on ListView onItemCLick :
lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view,
                int position, long arg3) {

                    Intent intent = new Intent(CommunityFragment.this.getActivity(), activityArray[postion]);
                    CommunityFragment.this.getActivity.startActivity(intent);

        }
    });

A: Use this to start next intent in your onItemClickListener:
Intent intent = new Intent(getActivity(), nextactivity.class);
                    startActivity(intent);

A: I think following code help you.
public class PdfListViewFragment extends Fragment {
    ListView listView;
    Activity rootView;
    Activity context;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        View rootView = inflater.inflate(R.layout.pdf_list_view, container, false);
        context = getActivity();
        // Get ListView object from xml
        listView = (ListView) rootView.findViewById(R.id.list);

        // Defined Array values to show in ListView
        String[] values = new String[]{"Android List View",
                "Adapter implementation",
                "Simple List View In Android",
                "Create List View Android",
                "Android Example",
                "List View Source Code",
                "List View Array Adapter",
                "Android Example List View"
        };

        // Define a new Adapter
        // First parameter - Context
        // Second parameter - Layout for the row
        // Third parameter - ID of the TextView to which the data is written
        // Forth - the Array of data

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);

        // Assign adapter to ListView
        listView.setAdapter(adapter);

        // ListView Item Click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position == 0) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 1) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 2) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 3) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 4) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 5) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 6) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity1.class);
                    startActivityForResult(myIntent, 0);
                }

                if (position == 7) {
                    Intent myIntent = new Intent(view.getContext(), ListItemActivity2.class);
                    startActivityForResult(myIntent, 0);
                }

                // ListView Clicked item index
                int itemPosition = position;

                // ListView Clicked item value
                String itemValue = (String) listView.getItemAtPosition(position);

                // Show Alert

                Toast.makeText(context.getApplicationContext(), "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();

            }

        });

        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("XYZ");
    }

}

A: If you use an adapter to display the items in a list, it is important to differentiate the following:
The ID of the list AdapterView#getId() is different than the ID of the items in the list ArrayAdapter<String>#getId(), because the view of the list contains the views of the elements.
Suppose an example where you are going to launch activities with user roles. You will have to do the transformation for your particular case.
public class SignInFragment extends Fragment implements AdapterView.OnItemClickListener {

    //TODO: Declare constants (GUEST, HOST, EMPLOYEE...)

    private ArrayAdapter<String> userRolesAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_sign_in, container, false);

//            ListView Instance
        ListView userRolesList = root.findViewById(R.id.user_roles_list);

        String[] userRoles = {
                GUEST,
                HOST,
                EMPLOYEE
        };

//            Initialize the adapter
        userRolesAdapter = new ArrayAdapter<>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                userRoles
        );

//            Link to the list with the adapter. This reference starts the process of filling the list.
        userRolesList.setAdapter(userRolesAdapter);

//            Events
        userRolesList.setOnItemClickListener(this);

        return root;
    }

    /**
     * @param adapterView: View using the adapter from the list
     * @param view: View of the item that has been pressed
     * @param i: Refers to the position of the item that the adapter handles
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (adapterView.getId() == R.id.user_roles_list) {

//              Obtain the item pressed on the adapter with the entry position
            String currentUserRol = userRolesAdapter.getItem(i);

            assert currentUserRol != null;
            switch (currentUserRol) {
                case GUEST:
                    startActivity(Host.class);
                    break;
                case HOST:
                    startActivity(Host.class);
                    break;
                case EMPLOYEE:
                    startActivity(Employee.class);
                    break;
                default:
                    Log.d("Error", "The activity passed as an argument to startActivity() does not exist");
                    break;
            }
        }
    }

    /**
     * PRECONDITION: The class given as an argument exists.
     */
    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(getActivity(), cls);
        startActivity(intent);
    }
}

Best :)


text:
Q: SignUp ViewController With Steps. How to best way I am creating a registration page in my app, using parse.com for data management .. In this view controller I have a container view which should show three different viewController in sequence when the user clicks on the "Next Step "in a few words .. I'm trying to make a recording made with three steps.
I'm looking on the net but I can not find anything clear, can anyone help me find the right way to figure out how to show three-View-Controller in a ContainerView and show them through the use of a button?


text:
Q: Complex backbone app with multiple build configurations using Browserify I'm working on a large Backbone app that is designed to be very configurable due to being multi-tenancy and designed to run on many platforms.  Currently the apps are built via Grunt and environment variables are used to determine which Backbone files are included in the finished version of the app.
At present some of the files that get included are extending or overwriting others that are included earlier.
As an example:
BaseHeader.js:
var BaseHeader = Backbone.View.extend({
    // code
});

Header.js:
var Header = BaseHeader.extend({
    // code
});

At the moment my finished app is built with Grunt which creates an .html file with a bunch of script tags so all the files will be loaded by the browser.
I'd like to use Browserify to bundle my JS into a single file, so now I have:
BaseHeader.js:
var Backbone = require("backbone");

var BaseHeader = Backbone.View.extend({
    // code
});

module.exports = BaseHeader;

Header.js:
var Backbone = require("backbone");
var BaseHeader = require("/path/to/BaseHeader.js");

var Header = BaseHeader.extend({
    // code
});

module.exports = Header;

But I'm confused as to how to work things.
The entry point for all my apps is the same App.js file which makes a require call to BaseHeader.js, it doesn't however make a require call to Header.js as this file is platform/client specific.
As Browserify simply recurses through the requires in order to find and bundle dependencies it will never pick up Header.js
So, how can I create a build task to optionally require Header.js when needed?

A: Your looking for the require option to browserify:
This option will include the module or file as part of the bundle even if it isn't referenced in the entry app. It should also expose the said module to your HTML page via a global require() function.
From the docs:

b.require(file, opts)
Make file available from outside the bundle with require(file).
The file param is anything that can be resolved by require.resolve().
file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable.
If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts.
Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular')


text:
Q: How can I adapt this code to work on Google Sites? I'm currently trying to develop a random redirect button and I need to make two adjustments to the following code:

<form method="post">

<input type="button" name="B1" value="Continue" onclick="randomlink()">
 </form>

The above code produces a button which appears to do nothing on clicking it on the published website. How can I make the button actually redirect? I'd also like to resize the button to be 5x larger and centre aligned.
Thanks for your help.

A: The reason why it won't open, was the .open method used in your function.
Here is the new code utilizing window.open:
window.open(randomlinks[Math.floor(Math.random()*randomlinks.length)]);

For formatting the button you should use CSS.
Check out something like this


text:
Q: How much do R2-D2 and BB-8 weigh? The question is self-explanatory:  How much do the astromech droids R2-D2 and BB-8 weigh, in-universe?

A: R2-D2:

*

*Wookieepedia says (citing "Star Wars Rebels: Head to Head") 32 kg.

*Apparently the same number was in EU/Legends, in "Star Wars: Head-to-Head Tag Teams, pg 50" as per the same page.
BB-8

*

*couldn't find in-universe evidence in the film, novelization, or Visual Dictionary page.

*Sphero's out of universe popular toy is ~200 g (at the height of 11cm, compared to real one's Databank height of 0.67m). If we proportionally size the weight up by 6^3=216 times, we get ~42kg.
Which probably isn't accurate, since I assume TGFFA has much better/lighter materials than Sphero (since R2-D2 could fly and BB-8 has liquid metal cables that hold its weight and pull him up).

*Doing very back of the envelope guessing it looks like his body is ~20-30% of R2-D2 by volume. (they fit in same size X-Wing astromech socket.

*

*R2-D2's body seems to be exactly 1.5 times BB-8 body, since his body+head fits exactly 2 BB-8 bodies and his head is an exact hemisphere of the same radius. That gives us 9.42+4.19/2=11.5 for R2-D2 volume given radius of 1 (for simplicity of comparison), excluding appendages. BB-8 is 4.19 for the body and roughly 0.26 for head (half a sphere size of half the body), totalling 4.45.

Assuming he's not made of some advanced ultralight composites that severely affected his density by comparison the above gives us ~12.4kg. It may be less because of more advanced materials, or because I didn't count the volume of R2-D2's legs; or it can be less because I assume a spherical droid's internal space has less empty lacunae due to better space packing. Without better canon info, I'll call those factors a wash for hand-waved calculation purposes and settle on 12kg.


text:
Q: Path issue in parsec.json file I am an user of gem5 simulators and I am encountering an issue while trying to validate the parsec.json file. The error is shown below:
image issue
Do you have any ideas?
Thank you in advance!
I have tried to enter another path thinking that will solve the issue, but I had no result.


text:
Q: How to change the paintcomponent in JPanel from a button panel in java I am having a hard time figuring out how I can change the color of a paint component within a DrawPanel.
The method we need to use is that the color of the paint component can be changed via a ButtonPanel.
The problem is that I can't seem to find a way to get the handler to recognize the panel and change it's color.
How to change the paintcomponent in JPanel from a button panel in java
main.java
import javax.swing.SwingUtilities;

public class main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                new Window();
            }
        });
    }
}

Window.java
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.Dimension;

public class Window extends JFrame {

    public Window () {
        // `super ' calls a function inherited from the parent class ( JFrame )
        super();
        setTitle("Callbacks");
        setSize (new Dimension(420, 350));

        // Make sure the window appears in the middle of your screen
        setLocationRelativeTo(null);

        // Determines what should happen when the frame is closed
        setDefaultCloseOperation (EXIT_ON_CLOSE);

        // Chooses a certain layout type for the elements in this frame
        getContentPane().setLayout (new BorderLayout());

        // TODO : add elements to the content pane
        DrawPanel dp = new DrawPanel ();
        ButtonPanel bp = new ButtonPanel ();

        // Places the DrawPanel in the center of the frame
        getContentPane (). add (dp , BorderLayout . CENTER );
        // Places the ButtonPanel in the top of the frame
        getContentPane (). add (bp , BorderLayout . NORTH );

        // Set the window to visible ! Yup ... This is necessary
        setVisible (true);
    }
}

DrawPanel.java
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.*;

public class DrawPanel extends JPanel {

    private Color color;

    public DrawPanel(){
        super();
        color = Color.BLACK ;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(getColor());
        g.fillRect(100 , 30, 200 , 200);
    }

}

ButtonPanel.java
import javax.swing.JButton;
import javax.swing.JPanel;

public class ButtonPanel extends JPanel {

    public ButtonPanel () {
        super ();
        // Add a button to the panel . The argument to the JButton constructor
        // will become the text on the button .
        JButton b = new JButton ("Change color!");
        JButton c = new JButton ("Test");
        add (b);
        add (c);
        b.addActionListener(new InputHandler());

    }
}

InputHandler
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import com.sun.prism.paint.Color;

public class InputHandler implements ActionListener {

    public InputHandler() {
        // TODO Auto-generated constructor stub
    }

    public void actionPerformed (ActionEvent e) {
        // TODO : add code here that will
        // be ran when the button is clicked
    }
}

Hope you guys can help me or send me in the right direction.

A: Make them friends to each other so that the Listener will know the Panel:
// Window
DrawPanel dp = new DrawPanel ();
ButtonPanel bp = new ButtonPanel (dp); // pass panel to button

then:
public class ButtonPanel extends JPanel {
    public ButtonPanel (DrawPanel d) {
        super ();
        // Add a button to the panel . The argument to the JButton constructor
        // will become the text on the button .
        JButton b = new JButton ("Change color!");
        JButton c = new JButton ("Test");
        add (b);
        add (c);
        b.addActionListener(new InputHandler(d)); // pass panel to listener
    }
}

and:
public class InputHandler implements ActionListener {
    DrawPanel d;
    public InputHandler(DrawPanel d) {
        this.d = d;
    }
    public void actionPerformed (ActionEvent e) {
        d.setColor(Color.BLUE); // whatever
        d.repaint(); // force painting
    }
}

then:
public class DrawPanel extends JPanel {
    private Color color;
    public DrawPanel(){
        super();
        color = Color.BLACK ;
    }
    public void setColor(Color c) {
        this.color = c;
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(getColor());
        g.fillRect(100 , 30, 200 , 200);
    }
}


text:
Q: button always return the last ID, not the correct one I'm creating a menu in gaffer that populate automatically from a string list called "shotlist"
the idea is to have a custom menu for each entry of the list and have an action relative to each entry too, like :

*

*click on sh001 = sh001

*click on sh002 = sh002

*click on sh003 = sh003

my problem is that my code return :

*

*click on sh001 = sh003

*click on sh002 = sh003

*click on sh003 = sh003

I understand that when I click on a button, it always return the 3rd value of "shotlist", as it's the last one than the loop worked on, but I dont understand how to set the loop differently to have the right result
actually my code is :
def shotSelection( menu ):
shotVar=str(shotName)
print shotName
scriptWindow = menu.ancestor( GafferUI.ScriptWindow )
root = scriptWindow.scriptNode()
root["variables"]["projectshot"]["value"].setValue( shotVar )

root=application.root()
shotlist=["sh001","sh002","sh003"]
for shotName in shotlist:
    GafferUI.ScriptWindow.menuDefinition(application).append("/Pipeline/ShotSwitcher/{0}".format(shotName), { "command" : shotSelection } )

I have also tried with the method described here but i dont understand well enough how it's work to apply it to my script.
the menu creation part from gaffer works well. but I dont found a way to set up my menu from the list and have the right action on it at the same time
thank you
EDIT:
actually I found the problem but not sure how to fix it
GafferUI.ScriptWindow.menuDefinition(application).append("/Pipeline/ShotSwitcher/{0}".format(shotName), { "command" : shotSelection }

shotSelection does not transmit any info of the shot clicked on

A: i fixed my issue with functools(), allowing to transmit the value in each loop


text:
Q: using the NumberFormat import in System.out.format I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for
"Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.
-- A
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // SPLASH
    // CONSTANT
    // OBJECT
    Scanner input = new Scanner(System.in);
    NumberFormat money = NumberFormat.getCurrencyInstance();

    // VARIABLES
    double investment;
    double investTotal;
    double rate;
    double intrest;
    int year;

    // INPUT
    do
    {
        System.out.print("Enter yearly investment (min $100.00 deposit): ");
        investment = input.nextDouble();
    }
    while (investment < 100);

    do
    {
        System.out.print("Enter intrest rate (%): ");
        rate = input.nextDouble()/100;
    }
    while (rate <= 0);

    do
    {
        System.out.print("Enter number of years: ");
        year = input.nextInt();
    }
    while (year <= 0 || year > 15);

    // PROCESSING
    investTotal = investment;
    for (int perYear = 1; perYear <= year; perYear++)
    {
        intrest = investTotal*rate;
        investTotal = (investment+intrest);
        System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
        investTotal = investTotal + investment;
    }
    // OUTPUT
}

}

A: getCurrencyInstance returns a String and therefor can't be formatted using %.2f.
You better look how NumberFormat works:
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g:
System.out.format("%2s | %.2f\n", 1.001, 1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.


text:
Q: Azure Log Analytics query for api calls by user I've my Azure APIM setup, I want to query the logs for users who made a call to API. I've integrated Azure AD as well.
I want to know how can I retrieve information for the users that have signed in and made calls to a particular API in the developer portal. can I do that?
Something like...
this user with username (or maybe ID) has made calls to this API, this number of times.
is this achievable?

A: You may query by the API Management UserId
requests
| summarize count() by user_AuthenticatedId

This refers to the user of the subscription key, which was used to make the API call - so it has the same granularity as
requests
| extend Subscription_Name = tostring(customDimensions.["Subscription Name"])
| summarize count() by Subscription_Name

From within Log Analytics / App Insights you have no further details on the user making the API call itself. I usually use a Jupyter notebook to query Log Analytics over API and then query API Management users to enrich this information.
But initially you may also just download the query result into a spreadsheet, extract userId and Name from API Management with e.g. Azure PowerShell and use some spreadsheet magic to merge the information.