text:
Q: Higher kinded types vs generics I'm reading about higher kinded types in Scala and I can't wrap my head around the use of the underscore.
For example:
trait Functor[F[_]] {
  def map[A, B](fa: F[A])(f: A => B) : F[B]
}

val listFunctor = new Functor[List] {
  override def map[A, B](fa: List[A])(f: A => B) = fa.map(f)
}

listFunctor.map(List(1,2,3))(_ + 3)

If I use a parametrised type A in the trait, I get the same result:
trait Functor2[F[A]] {
  def map[A, B](fa: F[A])(f: A => B) : F[B]
}

val listFunctor2 = new Functor2[List] {
  override def map[A, B](fa: List[A])(f: A => B) = fa.map(f)
}

listFunctor2.map(List(1,2,3))(_ + 3)

Is there a significant difference between the two examples?

A: There's no difference between those two ways to express the fact that Functor2 is parametrized over a type constructor. If you notice, in the latter case, A is just a placeholder, as it hasn't been declared elsewhere.
I generally prefer to use the F[_] syntax as it clarifies we want a type constructor and we don't have accidental overlapping in naming between the placeholder and types as referred within the class: in the latter case, even though they happen to refer to the same type parameter, there is no enforced constraint between the A in the constructor signature and the A in the map method signature, and this can also lead to some confusion regarding the nature of the two A and how they are related to each other.


text:
Q: Export data returned by 'fetch' from a separate .js file in React This is my code

const data = () => fetch("https://api.myjson.com/bins/mp441")
      .then(response => response.json())
      .then(obj => data = obj);

const RECORD_NOS=Object.keys(data).length-1;

export {data, RECORD_NOS}

I am trying to get the json data hosted at the above url, save the data in a variable and export it for use in various places in my React application but unfortunately it gives the following error.

./src/resources/index.js
Syntax error: D:/Users/kumahay/Documents/lending-referrals-app/src/resources/index.js: "data" is read-only

  1 | const data = () => fetch("https://api.myjson.com/bins/mp441")
  2 |       .then(response => response.json())
> 3 |       .then(obj => data = obj);
    |                    ^
  4 |
  5 | const RECORD_NOS=Object.keys(data).length-1;
  6 |

I have tried console logging instead of assigning the data but it doesn't work. Apparently the data is not being fetched. How to better frame this code so that it works as expected? I am a beginner in javaScript so any help will be appreciated.

A: I think you should read more about async functions, Promises and fetch. The best way is export getData function, remove .then(obj => data = obj) and use it in any other module like this
getData.js
export const getData = () => fetch("https://api.myjson.com/bins/mp441")
  .then(response => response.json())

anyOtherFile.js
import {getData} from './path/to/getData.js';

export const someFunc = () => {
   getData().then(data => {
       /* do what you want to do in promise resolve callback function */
   })
}

or with async/await notation
getData.js
export const getData = async () => fetch("https://api.myjson.com/bins/mp441")
  .then(response => response.json())

anyOtherFile.js
import {getData} from './path/to/getData.js';

export const someFunc = async () => {
    const data = await getData();
}

A:
Please change the name of data to response data and instead of
  constant use variable. Constant cannot be overwritten but variable
  can.

Example:
var data = "something";
const name ="Japarsathik";

var salary = "$5000";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weka: Results of each fold in 10-fold CV For Weka Explorer (GUI), when we do a 10-fold CV for any given ARFF file, then what Weka Explorer provides (as far as I can see) is the average result for all the 10 folds.
Q. Is there any way to get the results of each fold? For instance, I need the error rates (incorrectly identified instances) for each fold.
Help appreciated.

A: Weka Explorer does not have an option to give the results for individual folds when using the crossvalidation option, there are some workarounds. If you explicitly don't want to change any code, you need to do some manual fiddling, but I think this gives more or less what you want

*

*Instead of Cross-validation, select Percentage split and set it to 90%

*Start classifier

*Click More options... and change the Random seed for XVal / % Split value to something you haven't used before.

*Repeat ten times.

This is not exactly equivalent to 10-fold crossvalidation though, since the pseudo-folds you make this way might overlap.
An alternative that is equivalent to crossvalidation, but more cumbersome, would be to make 10 folds manually by using the unsupervised instance filter RemoveFolds or RemoveRange.
Generate and save 10 training sets and 10 test sets. Then for every fold, load the training set, select Supplied test set in the classify tab, and select the appropriate test fold.

A: I think this is possible using Weka's GUI. You need to use the Experimenter though instead of the Explorer. Here are the steps:

*

*Open the Experimenter from the GUI Chooser

*

*Create a new experiment (New button @ top-right)

*[optional] Enter a filename and location in the Results Destination to save the results  to

*Set the Number of (cross-validation) folds to your liking (start experimenting with 2 folds for easy results)

*Add your dataset (if your dataset needs preprocessing then you should do this in the Explorer first and then save the preprocessed dataset)

*Set the Number of repetitions (I recommend 1 to start of with)

*Add the algorithm(s) you want to test (again start easy, start with one algorithm)

*Go to the Run tab and Start the experiment and wait till it finishes

*Go to the Analyse tab and import the experiment results by clicking Experiment (top-right)

*

*For Row select: Fold

*For Column select: Percent_incorrect or Number_incorrect (or any other measure you want to see)

*You now see the specified results for each fold


text:
Q: Не могу избавиться от ошибки в консоли, которая никак не влияет на работу приложения: Warning: findDOMNode is deprecated in StrictMode Всем привет! Использую React Transition Group для анимации. Анимация работает, но появляется ошибка. Что бы ёе устранить пробовал всякие варианты передачи ref, но всё тщетно.
Вот компонент который рендерит список дел:
import React from "react";
import ToDoItem from "./ToDoItem/ToDoItem";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import "./ToDoList.css";

function ToDoList({ todos, actions }) {
 return todos.length > 0 ? (

     <TransitionGroup component='ul' className="todo_list_inner">
       {todos.map((todo) => {
         return (
           <CSSTransition  key={todo.id} timeout={700} classNames="li">
             <ToDoItem  todo={todo} id={todo.id} {...actions} />
           </CSSTransition>
         );
       })}
     </TransitionGroup>

 ) : (

Пустой список дел...

 );}

export default ToDoList;

И вот компонент ToDoItem
import React, { useState, useRef, useEffect, memo } from "react";
import Input from "../../UI/Input/Input";
import Button from "../../UI/Button/Button";
import "./ToDoItem.css"

function ToDoItem({ todo, completeTodo, deleteTodo, id, editTodo}) {
  const [editing, editingState] = useState(false);
  const [editInputValue, editInputValueState] = useState("");
  const classes = [];
  const inputRef = useRef(null);

  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  });

  const changeTitle = () => {
    editingState(true);
    editInputValueState(todo.title);
  };

  const changeComplite =() => {
    completeTodo(id);
  }

  if (todo.completed) {
    classes.push("done");
  }

  const removeTodo = () => {
    deleteTodo(todo.id);
  };

  const changeValue = (event) => {
    editInputValueState(event.target.value);
  };

  const submitUpdate = (e) => {
    e.preventDefault();
    editTodo(id, editInputValue);
    editingState(false);
    editInputValueState("");
  };

  const handleBlur = (e) => {
    editTodo(id, e.target.value);
    editingState(false);
    editInputValueState("");
  };

  const todoItemInputEdit = () => {
    return (
      <form
        className="form_todoItem"
        onSubmit={submitUpdate}
        onBlur={handleBlur}
      >
        <Input value={editInputValue} onChange={changeValue} ref={inputRef} />
      </form>
    );
  };

  return (
    <>

          <Input
            type="checkbox"
            id={id}
            checked={todo.completed}
            onChange={changeComplite}
          />

          {editing ? todoItemInputEdit() : todo.title}

          <Button
            text={String.fromCharCode(9998)}
            className="btn_edit"
            onClick={changeTitle}
          />
          <Button
            className="btnRemove"
            onClick={removeTodo}
            text={String.fromCharCode(215)}
          />

    </>
  );
}

export default memo(ToDoItem);

A: Это strict мод
import { StrictMode } from 'react'

export const App = () => (
  <StrictMode>

      {/* code */}

  </StrictMode>
)

А это решение проблемы
export const App = () => (

      {/* code */}

)


text:
Q: Cross compatibility with Firebase Database (iOS and Android) I am currently using Firebase as the backend for an iOS and an Android application. The iOS application has been completed, but now when I am writing the application for Android, I am wondering how to structure the data so that it is consistent across iOS and Android?
Suppose for example:
I have a class user on the Android side that I write to the database:
public class User {

    public String uid;
    public String name;
    String email;
    public String gender;
    public boolean first;
    public String phone;
    public String dob;
    public String address;

    public User(String id,String nm,String em,String g,boolean f,String ph,String d,String add)
    {
        uid=id;
        name=nm;
        email=em;
        gender=g;
        first=f;
        phone=ph;
        dob=d;
        address=add;
    }
    public User()
    {

    }
}

Now while reading this data on the iOS side (with something like dataSnapshot.getValue(User.class) in Android), how do I structure the User class in iOS??
Similarly, what should be my approach in the opposite case (iOS to Android)?

A: There is no built-in way to serialize Swift/Objective-C objects to the Firebase Database. You will instead have to code your own mapping between the plain-old swift object and the FIRDataSnapshot/FIRDatabaseReference.


text:
Q: Triangle overlay in right corner css I want to  create an overlay with css over one image like this:

but  I only do a square overlay like this:

how I can make the first shape with css ??
here is my code:
.card-img-overlay {
position: absolute;
top: 0px;
right: 0px;
bottom: 0;
left: 150px;
padding: 1.25rem;
}

thank you for your answers :)

A: Check this out

#triangle-topleft {
  width: 0;
  height: 0;
  border-top: 100px solid #9020d1bb;
  border-left: 100px solid transparent;
  position: absolute;
}

#container {
  position: relative;
}

#container #triangle-topleft,
#overlay {
  position: absolute;
  color: white;
  right: 0;
}

Microsoft

A: I will go with a simple gradient and no need for any extra markup or the use of pseudo element:

body {
  height: 100vh;
  margin: 0;
  background:
  linear-gradient(to top right, transparent 50%, rgba(255, 0, 0, 0.5) 51%) 0 0/100% 200px no-repeat,
  url(https://lorempixel.com/1000/1000/) center/cover;
}
div {
 height:200px;
 text-align:right;
 color:#fff;
 padding:10px;
 font-size:25px;
}

Some content


text:
Q: ADO.NET Long running transactions I'm using Dapper, but this applies the same to ADO.NET code.
I have an operation on a web app that changes a lot of state in the database. To ensure an all-or-nothing result, I use a transaction to manage this. To do this, all my Repository classes share a connection (which is instantiated per request). On my connection I can call Connection.BeginTransaction().
However, this operation can sometimes take a while (say 10 seconds), and it's locking some frequently-read-from tables while it does it's thing. I want to allow other repos on other threads to continue without locking while this is happening.
It looks like I need to do 2 things to make this happen:
1) Set the IsoloationLevel to something like ReadUncommited:
_transaction = Connection.BeginTransaction(IsolationLevel.ReadUncommitted);

2) For all other connections that don't need a transaction, I still need to enroll those connections in a transaction, so that I can again set ReadUncommited. If I don't do this then they'll still lock while they wait for the long running operation to complete.
So does this mean I need ALL my connections to start a transaction? This sounds expensive and sub-performant. Are there other solutions I'm missing here?
Thanks

A: Be aware that there is a trade-off between using locks or not, it's about performance vs concurrency control. Therefore, I don't think you should use ReadUncommited all the time.
If you try to use ReadUncommited on all other transactions that need not to be blocked by this long running transaction, they will by accident not be blocked also by other transactions.
Generally, we use this isolation level when performance is the first priority and does not need data accuracy

I want to allow other repos on other threads to continue without
  locking while this is happening.

I think you can try IsolationLevel.SnapShot on only the transaction that does long locking work: https://msdn.microsoft.com/en-us/library/tcbchxcb(v=vs.110).aspx
Extracted from the link:

The term "snapshot" reflects the fact that all queries in the
  transaction see the same version, or snapshot, of the database, based
  on the state of the database at the moment in time when the
  transaction begins. No locks are acquired on the underlying data rows
  or data pages in a snapshot transaction, which permits other
  transactions to execute without being blocked by a prior uncompleted
  transaction. Transactions that modify data do not block transactions
  that read data, and transactions that read data do not block
  transactions that write data, as they normally would under the default
  READ COMMITTED isolation level in SQL Server. This non-blocking
  behavior also significantly reduces the likelihood of deadlocks for
  complex transactions.

Be aware that an enormous amount of data could be generated in tempdb for version store if there are a lot of modifications.


text:
Q: Radeon HD 6290 terrible performance on a certified laptop I bought Asus K53U laptop, which is Ubuntu certified with pre-installed 11.10. The graphic card is Radeon HD 6290 but 720p playback is terrible. Even page scrolling in Firefox is very laggy. Proprietary drivers are installed by default.
How is this  possible, why is the laptop Ubuntu certified if the performance is poor? Any solution to this?
I just did apt-get autoremove, and after that, this message came out in terminal:
Error inserting vesafb (/lib/modules/3.0.0-15-generic/kernel/drivers/video/vesafb.ko):
No such device

Could that be the problem?

A: update your drivers from the command line CTRL+ALT+T

*

*install the ATI drivers in the terminal with the following command
sudo apt-get install fglrx fglrx-amdcccle

*You may also need to reinstall the updates again:
sudo apt-get install fglrx-updates fglrx-amdcccle-updates

*It can be a pain I know from experience. Sometimes I have had to go back the beginning by cleaning out fglrx (sudo apt-get purge fglrx*) and starting afresh.


text:
Q: how echo this code how echo this code  Already have tried to fix did not work
<img class="comment-avatar pull-left"    '.( !empty( $images[$count] ) ?  '' : '').'

A: Try this
  //$count = 1;
  //$images[$count] = '2';

echo '' : '');

you were missing a period.


text:
Q: UWP ListBox is not responding to changes in the HorizontalAlignment In the XAML below:
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Button Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" Content="Button1"></Button>
        <ListBox Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ListBoxItem>Item1</ListBoxItem>
            <ListBoxItem>Item2</ListBoxItem>
            <ListBoxItem>Item3</ListBoxItem>
        </ListBox>
    </Grid>

Why does the ListBox occupy the entire width, even when the HorizontalAlignment is set to Center?

A: From the code provided by you, you haven't set the Width property of ListBox. The default value of Width is Double.NaN. If the parent element's Width is set, then the width of the ListBox will stretch to available width of its parent element. If the parent element's Width is auto, then the Listbox will just take up required space.
In your scenario, you divided the height of the Grid into two equal parts by two ColumnDefinition tags. Therefore, your ListBox's width will be equal to the cell's width in the Row 1 and Column 0. You could try to set the value of Width property as auto of the first ColumnDefinition to view that the ListBox will only occupy the required width.
If you want center the ListBox in its parent element, you could set the Width of ListBox. Then the ListBox will be in the center of the cell.
For example:
<ListBox Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200">

If you want the items of ListBox in the center, you need to set the HorizontalAlignment property of ListBoxItem.
For example:
<ListBoxItem HorizontalAlignment="Center">Item1</ListBoxItem>
<ListBoxItem HorizontalAlignment="Center">Item2</ListBoxItem>
<ListBoxItem HorizontalAlignment="Center">Item3</ListBoxItem>


text:
Q: Cannot deserialize value of type `java.time.OffsetDateTime` from String in openapi client I have a spring boot application with a java client generated via the gradle plugin:
openApiGenerate {
    generatorName = "java"
    inputSpec = specsYml
    outputDir = "$buildDir/generated".toString()
    apiPackage = "com.customapi.api"
    invokerPackage = "com.customapi.invoker"
    modelPackage = "com.customapi.model"
    configOptions = [
        dateLibrary: "java8",
        library    : "resttemplate"
    ]
}

I have chosen "java8" as dateLibrary as that seems to be the preferred one for a project with java 1.8.
With that generated client I'm executing a request that returns an object that holds a timestamp.
I get the following error:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
    ...
Caused by: org.springframework.web.client.RestClientException: Error while extracting response for type [class com.customapi.model.Info] and content type [application/json];
    ...
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.OffsetDateTime` from String "2020-07-21T12:12:23.000+0200": ...
   ...
...
Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.OffsetDateTime` from String "2020-07-21T12:12:23.000+0200": Failed to deserialize java.time.OffsetDateTime: (java.time.format.DateTimeParseException) Text '2020-07-21T12:12:23.000+0200' could not be parsed at index 23
 at [Source: (ByteArrayInputStream); line: 1, column: 84] (through reference chain: com.customapi.model.Info["buildTimestamp"])
    at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1679) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:935) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.datatype.jsr310.deser.JSR310DeserializerBase._handleDateTimeException(JSR310DeserializerBase.java:86) ~[jackson-datatype-jsr310-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.deserialize(InstantDeserializer.java:218) ~[jackson-datatype-jsr310-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.deserialize(InstantDeserializer.java:50) ~[jackson-datatype-jsr310-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:369) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4218) ~[jackson-databind-2.10.3.jar:2.10.3]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3267) ~[jackson-databind-2.10.3.jar:2.10.3]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:269) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
    ... 17 common frames omitted
Caused by: java.time.format.DateTimeParseException: Text '2020-07-21T12:12:23.000+0200' could not be parsed at index 23
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) ~[na:1.8.0_151]
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777) ~[na:1.8.0_151]
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.deserialize(InstantDeserializer.java:212) ~[jackson-datatype-jsr310-2.10.3.jar:2.10.3]
    ... 24 common frames omitted

The relevant parts of the Info class in question:
...
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-26T14:09:54.137+02:00[Europe/Berlin]")
public class Info {
    ...
    public static final String JASON_PROPERTY_BUILD_TIMESTAMP = "buildTimestamp";
    private OffsetDateTime buildTimestamp;
    ...
    public Info buildTimestamp(OffsetDateTime buildTimestamp) {
        this.buildTimestamp = buildTimestamp;
        return this;
    }

    public void setBuildTimestamp(OffsetDateTime buildTimestamp) {
        this.buildTimestamp = buildTimestamp;
    }
    ...
}

Both setter methods accept OffsetDateTime objects and have no annotations so the conversion must happen elsewhere. The input String again is "2020-07-21T12:12:23.000+0200".
relevant dependencies are
ext {
    swagger_annotations_version = "1.5.22"
    jackson_version = "2.10.3"
    jackson_databind_version = "2.10.3"
    jackson_databind_nullable_version = "0.2.1"
}

dependencies {
    compile "io.swagger:swagger-annotations:$swagger_annotations_version"
    compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
    compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
    compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
    compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
}

There seem to be a lot of problems with jackson and java 8 and most solutions on this site seem to be adding annotations. But I doubt that modifying generated code is the proper solution. Did I overlook an important parameter when generating the client? Does the server supply the wrong format? How can I investigate this?
Update:
When I switch dateLibrary to legacy it works, so I think I receive the correct data.
There is a bug in the (jaxrs) server generator https://github.com/swagger-api/swagger-codegen/issues/3648#issuecomment-244056314  that has the server send out wrongly formatted (without colon) date-time. My solution was to use the legacy dateLibrary for the client which can handle the wrong format.

A: Following my comment in the question, I realize you don't need a Jackson annotation. You just need to adjust the setter. Here is a basic demo:
Assume the following class:
import java.time.OffsetDateTime;
//import com.fasterxml.jackson.annotation.JsonSetter;
import java.time.format.DateTimeFormatter;

public class MyOdt {

    private OffsetDateTime odt;

    public OffsetDateTime getOdt() {
        return odt;
    }

    //@JsonSetter("odt")
    public void setOdt(String odtString) {
        final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSxx";
        DateTimeFormatter dtfB = DateTimeFormatter.ofPattern(pattern);
        this.odt = OffsetDateTime.parse(odtString, dtfB);
    }

}

The class will be created from a JSON fragment such as this:
String jsonTest = "{ \"odt\" : \"2020-07-21T12:12:23.000+0200\" }";

The object mapper:
ObjectMapper objectMapper = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

MyOdt odtTest = objectMapper.readValue(jsonTest, MyOdt.class);

For reference, here is the original comment in the question:

An observation: That is not a valid string to be parsed by OffsetDateTime.parse() because the default datetime format expects the offset to have a colon in it: +02:00. So, this works: OffsetDateTime.parse("2020-07-21T12:12:23.000+02:00")

A: I was helped by switching dateLibrary to java8-localdatetime
See also here.


text:
Q: Suggestions for data structure for keyword search I need to put together a data structure that will efficiently provide keyword search facilities.
My metrics are:

*

*Circa 500,000 products.

*Circa 20+ keywords per product (a guess).

*Products are identified by an ID of about 10 digits but may be any ASCII codes going forward.

I would like to try to fit the data structure in memory if possible. I will be on a server so I can assume some significant memory availability.
Speed is important. Using LIKE database queries will not be an acceptable solution.
Any ideas for a data structure?
My thoughts:
TrieMap
Very efficient for the keywords but there would need to be a list of product IDs hanging off any leaf so seriously memory hungry. Any ideas that could help with that?
Compression
Various compression schemes come to mind but none jump out as of significant value.
Has anyone else put something like this together? Could you share your experiences?
The data may change but not often. It would be reasonable to rebuild the structure on a daily basis to accommodate changes.

A: Have you thought about using lucene either in memory or as a file system index?
It is quite fast and has lots of room for further requirements that might arise in the future.


text:
Q: Spring Data JPA : How to use @PathVariable and JPQL I have two questions about Spring Data JPA.
1st: How to avoid @PathVariable mistakingly recognizing a part of url as a parameter?
The first one is the code about this question.
When I try to access "/sample/insert/", the url is handled as "/sample/{id}/" and I get the error which says like " String 'insert' cannot convert to Integer".
How do I avoid this problem?
2nd: Can JPQL @Query return an instance?
Please refer to the second code.
For now, the method insertInto(String name, String mail) returns int value: the number of Column affected. However, I would like to get the affected column itself as a return value. Can I do this ? Or, should I add another code in a method in a service class to realize that function?
@RestController
public class SampleController{

    @Autowired
    SampleService sampleService;

    @RequestMapping
    public String index(Model model){
       //omitted
    }

    @GetMapping("/sample/")
    public String getAllSample(Model model){
       //omitted
    }

    @GetMapping("/sample/{id}/")
    public String getSampleById(@PathVariable("id") Integer id, Model model){
        System.out.println("===================");
        System.out.println(">> accessed: /sample/{id} ");
        System.out.println("===================");
        return sampleService.getById(id).toString();
    }

    @RequestMapping("/sample/insert/")
    public int insert(Model model){
        System.out.println("===================");
        System.out.println(">> accessed: /sample/insert/ ");
        System.out.println("===================");
        return sampleService.create("NewName", "mail@mail.com");
    }

@Transactional
@Repository
public interface SampleRepository extends JpaRepository<Sample, Integer>{

    @Query("SELECT s FROM Sample s ")
    public List<Sample> showAll();

    @Query("SELECT s FROM Sample s WHERE id = :id")
    public Sample searchById(@Param("id") Integer id);

    @Modifying
    @Query(value = "INSERT INTO sample (name, mail) VALUES (?1, ?2)", nativeQuery = true)
    public int insertInto(@Param("name") String name, @Param("mail") String mail);

}

A: The first error you have is having a controller with {id} the same as /sample/insert/, I suppose because you have /sample/{id}/ before, he can match the /sample/insert/ to the first controller.
Not sure if you swapped between the two methods, But I think it won't work as well. As you are confusing spring on which method should work with.

    @RequestMapping("/sample/insert/")
    public int insert(Model model){
        System.out.println("===================");
        System.out.println(">> accessed: /sample/insert/ ");
        System.out.println("===================");
        return sampleService.create("NewName", "mail@mail.com");
    }

    @GetMapping("/sample/{id}/")
    public String getSampleById(@PathVariable("id") Integer id, Model model){
        System.out.println("===================");
        System.out.println(">> accessed: /sample/{id} ");
        System.out.println("===================");
        return sampleService.getById(id).toString();
    }

What you can do to avoid that is, changing to /sample/get/{id} will fix the issue for sure.
    @GetMapping("/sample/{id}/")
    public String getSampleById(@PathVariable("id") Integer id, Model model){
        System.out.println("===================");
        System.out.println(">> accessed: /sample/{id} ");
        System.out.println("===================");
        return sampleService.getById(id).toString();
    }

    @RequestMapping("/sample/insert/")
    public int insert(Model model){
        System.out.println("===================");
        System.out.println(">> accessed: /sample/insert/ ");
        System.out.println("===================");
        return sampleService.create("NewName", "mail@mail.com");
    }

for the insertInto(String name, String mail), I believe you can do what you want, but first, you need to know what is the column type. then switch the method to return the type instead of int.
And if you can add more clarification about 2nd question, I will edit the answer to add more details.

A: question one:
enter image description here
their request url is same and request method both GET
solution 1: change second request method turn to POST
solution 2: change their request url, like this /smaple/{id}/info

A: question 2: SampleRepository extends JpaRepository. JpaRepository defined many methods, include save method. you can code in sampleService
`@AutoWired
 SampleRepository sampleRepository;
 public Sample insert(String name, String email){
     Sample sample = new Sample();
     sample.setName(name);
     sample.setEmail(email);
     int result = this.sampleRepository.save(sample);
     if (result > 0){
       return sample;
     }
    //error
}`


text:
Q: Apache Kylin: query does not return full result I created an cube in Apache kylin where 'ft' is my facttable and 'ls' is one of the dimensiontables. Both are joint on the column 'lid'. My query
select ft.sid, ls.lid, ls.pos
from(
    select sid, lid
    from ft
    where lid = '1500221'
    group by lid, sid
) as ft inner join (
    select lid, pos
    from ls
    where pos = '14'
) as ls on (ft.lid = ls.lid)

returns one row like

1500  1500221  14

So far, so good. Leaving out the first where-condition, my result is also one row, but this time another...
select ft.sid, ls.lid, ls.pos
from(
    select sid, lid
    from ft
    group by lid, sid
) as ft inner join (
    select lid, pos
    from ls
    where pos = '14'
) as ls on (ft.lid = ls.lid)

returns

0140  0140110  14

Both are correct results, but the second query should return more than just one row and at least the result of the first query also.
Does anyone knows what is going wrong here?
Thanks in advance,
Søren

A: You might have hit a defeat of Kylin dealing with sub-queries.
However, why use sub-query where it is not required? The below simple query should give what you need.
select sid, lid, pos
from ft
inner join ls on ft.lid = ls.lid
where pos = '14'
group by lid, sid, pos


text:
Q: How to find all the indexes of all the occurrences of a substring in a string I am wondering if this is even possible without making any import method. But in a given string it is possible to make a list of all the indexes of all the occurrences.
For instance:
s = 'AACATGAACAAG'
for the occurrence AA the output should be:
result = [0, 6, 9]
which are al the positions...


text:
Q: Yet Another "Why isn't my Favicon showing?" Update

I have just tried "Pinning" my site to the Taskbar again (after removing it) but when I clicked and held down the mouse button on the 16x16px icon inside the address bar (see pic below), you can see my favicon being dragged around with the mouse - so internet explorer has found and got the icon - it's just not displaying it in all the right places! Also updated code below:

As the title suggests, I can't get my favicon to display; in any version of any browser. There is 1 exception, though - which isn't good enough:
IE 9 and IE 10 -

As you can probably see in the screenshot above, the only time I get to see my favicon is after I've added it to my Favorites folder and opened the Favorites Bar. The favicon does not display in the Tab (next to the page title), it does not display in the Taskbar area, and it does not display up the top-left of the browser window if I have "Pinned" my site to the Taskbar.
In every other browser, it simply does not display at all.
I have tried every possible "solution" that I could find online.
Here's the code I have:
    <link rel="icon" type="image/x-icon" href="http://www.mysite.com/favicon.ico"><!-- Major Browsers -->
    <!--[if IE]><link rel="shortcut icon" href="http://www.mysite.com/favicon.ico"/><![endif]--><!-- Internet Explorer-->

I have also tried all common sizes for the favicon; 16x16, 32x32, 64x64, 128x128 and 256x256 - and I've even tried saving all sizes within the same *.ico file.
I have tried deleting the cache file for *.ico files.
Nothing has worked. The exact same code has previously worked on other sites that I've made. I don't get it. What gives?

A: I've edited this answer, leaving only solution to problem presented in question.
Use: <link rel="shortcut icon" href="{ICONURL}"/>
Instead of: <link rel="icon" href="{ICONURL}"/>

A: I had the same problem with my site just now.  Drove myself crazy trying to get an favicon.ico file to work.  What finally got it working correctly for me in IE 11 (on Windows 7), was to dump the favicon.ico file completely and go with a PNG instead:
<link rel="shortcut icon" href="/favicon-32x32.png" type="image/png"/>

I used a PNG file with a transparency layer. Once I did this and uploaded my page, IE began displaying the icon correctly in the Tabs (and the shortcuts/bookmarks) on the very next page refresh.  I double checked and it looks like Chrome and Firefox are cool with this as well.

A: I use
<link rel="icon"
      type="image/ico"
      href="Link Goes Here">

If putting the favicon in a folder:
<link rel="icon"
      type="image/ico"
      herf="Folder/Subfolder"

Make sure the code is in the head tag.
Make sure the image is in the .ico format; It won't work otherwise.


text:
Q: "TypeError: User is not a constructor " while sending object to server in node.js I am trying to save a user to mongodb database using post request as follow, but I got the error TypeError: User is not a constructor. It's a pretty simple set up of the code but i can't figure out anything wrong with it.
//models/users.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
      name: {
          type: String,
         },
     email: {
          type: String,
          required: true
         },
    username:{
          type: String,
          required: true
         },
    password: {
        type: String,
        required: true
      }
   });

 const User = module.exports = mongoose.model('User', UserSchema);

   module.exports.getUserById = function(id,callback){
    User.findById(id,callback);
   }

  module.exports.getUserByUsername = function(username,callback){
    const query = {username:username}
    User.findOne(query,callback);
  }

 module.exports.addUser= function (newUser, callback) {
   bcrypt.gensalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
       if(err) throw err;
       newUser.password=hash;
       newUser.save(callback);
     });
   });
}

routes/users.js
 //routes/users.js

 const express = require('express');
 const router = express.Router();
 const passport = require('passport');
 const jwt = require('jsonwebtoken');
 User = require('../models/users');

  // // Register
  router.post('/register', (req, res, next) => {
    var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
     } else {
      res.json({success: true, msg:'User registered'});
    }

 });

});

  // Authenticate
 router.post('/authenticate', (req, res, next) => {
 res.send('AUTHENTICATE');
 });

  // Profile
 router.get('/profile', (req, res, next) => {
 res.send('PROFILE');
 });

 module.exports = router;

I am using Postman chrome to send data but it is not showing user registered according to program.

A: You are exporting your user model from a different file and trying to import from a different file.
change this line:
 const User = require('../config/database');

to this:
 const User = require('../models/users')  # import your user model


text:
Q: hex encoded string starting with 0x01000000 I have a legacy app that stores values in DB as:
0x010000004C41668D6C5C30B39BB81AB3757E7FD75121F6446802D6120A11103C3C563633C6758A110500AC9635DB46B4363CF5FDEC6BC82FB0237412
This looks like a hex encoded string but when I tried to decode it into utf8 or something, it didn't work... Does anybody know what encoding starts with 0x01000000? And how to decode it?
Please, note that this is an Arabic word.
Any help is appreciated.
Thank you.

A: It could possibly be Unicode text compressed with SCSU or BOCU.


text:
Q: can it possible calling inner repeater in nested-repeater, if possible then how? I have nested Repeater. i am using 3 repeater. For calling(firing) the 1st repeater which is working fine and returning 100% result. But when i am calling(firing) 2nd repeater. it is not firing. I just want to know should i call 2nd repeater event if it is in nested format? Or i can not call. If i can call can u suggest how can i call that event?
<asp:UpdatePanel ID="RepeaterPanel" runat="server">
                            <ContentTemplate>

                                    <asp:Repeater ID="RpterShareDetails" runat="server" onitemcommand="RpterShareDetails_ItemCommand">
                                        <HeaderTemplate>

                                        </HeaderTemplate>
                                        <ItemTemplate>

                                                    <asp:Image ID="Image1" runat="server" ImageUrl="~/ShowImage.ashx" alt="" width="50" height="50" />

                                                    <embed src='<%# Eval("FilePath") %>' type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="150" height="150" runat="server" Visible='<%# IsVisible(Eval("UploadType"))%>'></embed>
                                                    <asp:ImageButton ID="ibtnHolder" runat="server" Width="130" Height="130" ImageUrl='<%# Eval("FilePath") %>' Visible='<%# NotVisible(Eval("UploadType"))%>' />

                                                    <asp:Label ID="UserCommentLabel" runat="server"  Text='<%# Eval("Comments") %>' />

                                                  User Keyword:
                                                    <asp:Label ID="UserKeywordLabel" runat="server" Text='<%# Eval("Keyword") %>' />

                                                            <asp:LinkButton ID = "lnkLike" runat = "server" CommandName = "Like">Like</asp:LinkButton>

                                                            <asp:LinkButton ID="lnk_Comments" runat="server" CommandName="comments" CommandArgument='<%# Eval("Sniffid") %>'>Comments</asp:LinkButton>

                                                            <asp:LinkButton ID="lnk_ShowComments" runat="server" CommandName="Show" CommandArgument='<%# Eval("Sniffid") %>'>Show</asp:LinkButton>
                                                        Share
                                                        <asp:Panel ID="Add_Comments" runat="server" Width="90%" class="message_repeater_panel_left">
                                                        </asp:Panel>
                                                        <asp:Panel ID="Dis_comments" runat="server" Width="90%" class="message_repeater_panel_left">
                                                        </asp:Panel>

                                            <asp:TextBox ID="txt_comment" runat="server" TextMode="MultiLine" Width="300" Visible="false"></asp:TextBox>
                                            <asp:UpdatePanel ID="RepeaterPanel" runat="server" >
                                                <ContentTemplate>

                                                        <asp:Repeater ID="Rbt_comments" runat="server" onitemcommand="Rbt_comments_ItemCommand1" >
                                                            <HeaderTemplate>

                                                            </HeaderTemplate>
                                                            <ItemTemplate>
                                                            <%--
--%>

                                                                        <%--<asp:Image ID = "imgCommentPhotos" runat = "server" ImageUrl = "~/AddCommentPhotos.ashx" Width = "25" Height = "25" />--%>

                                                                    <asp:Label ID="UserCommentLabel" runat="server"  Text='<%# Eval("Comments") %>' />

                                                            <%--

      --%>

                                                                        <asp:LinkButton ID = "lnkLike" runat = "server" CommandName = "SubLike">Like</asp:LinkButton>

                                                                        <asp:LinkButton ID="lnk_Comments" runat="server" CommandName="Subcomments">Comments</asp:LinkButton>

                                                                        <asp:LinkButton ID="lnk_ShowComments" runat="server" CommandName="SubShow">Show</asp:LinkButton>

                                                                        Share

                                                                <%--
--%>

                                                                    <asp:TextBox ID = "txtComment" runat = "server" TextMode="MultiLine" Width="300" Visible = "false"></asp:TextBox>

                                                                  <ContentTemplate>

                                                                                <asp:Repeater ID="rptSubComments" runat="server">
                                                                                <HeaderTemplate>

                                                                                </HeaderTemplate>
                                                                                <ItemTemplate>

                                                                                <%--<asp:Image ID = "imgCommentPhotos" runat = "server" ImageUrl = "~/AddCommentPhotos.ashx" Width = "25" Height = "25" />--%>

                                                                                <asp:Label ID="lblUserSubComment" runat="server"  Text='<%# Eval("Comments") %>' />

                                                                                </ItemTemplate>
                                                                                </asp:Repeater>

                                                                        </ContentTemplate>
                                                            </ItemTemplate>
                                                            <FooterTemplate>
</FooterTemplate>
                                                        </asp:Repeater>

                                                </ContentTemplate>
                                            </asp:UpdatePanel>
                                        </ItemTemplate>
                                        <SeparatorTemplate>

                                        </SeparatorTemplate>
                                        <FooterTemplate>

                                        </FooterTemplate>

                                    </asp:Repeater>

                                <uc1:CustomPagination ID="RepeaterCustomPagination" runat="server" />
                            </ContentTemplate>
                        </asp:UpdatePanel>

protected void Rbt_comments_ItemCommand1(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "Subcomments")
            {
        }
    }
    catch (Exception ex)
    {

    }
}

protected void RpterShareDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    try
    {
        if (e.CommandName == "Like")
        {
            Int32 UserId = Convert.ToInt32(Session["UserID"].ToString());
            LikeShareDetails(UserId);
        }
        if (e.CommandName == "comments")
        {
            LinkButton btn = e.CommandSource as LinkButton;
            if (btn != null)
            {
                TextBox txt = (TextBox)e.Item.FindControl("txt_comment");
                txt.Visible = true;
                txt.Attributes.Add("OnKeyPress", "isNumberKey(this,"+ e.CommandArgument.ToString() +")");
                Panel Panel2 = (Panel)e.Item.FindControl("Add_Comments");
                Literal lt = new Literal(); lt.Text = "
";
                Panel2.Controls.Add(lt);
                Panel2.Controls.Add(txt);
                DataTable dt = new DataTable();
                Repeater gv = (Repeater)e.Item.FindControl("Rbt_comments");
                SqlConnection sqlCon = new SqlConnection();
                sqlCon.ConnectionString = ConfigurationManager.ConnectionStrings["ISnifferDBConnectionString"].ConnectionString;
                //sqlCon.ConnectionString = CommonUtil.GetConfigValue("ISnifferDBConnectionString");
                string strSql = "select Comments from Comments where SniffId in ('" + e.CommandArgument.ToString() + "') order by CommentId desc";
                SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
                sqlCon.Open();
                SqlDataAdapter sqlAdpt = new SqlDataAdapter();
                sqlAdpt.SelectCommand = sqlComd;
                sqlAdpt.Fill(dt);
                int row = dt.Rows.Count;
                if (row >= 1)
                {
                    gv.DataSource = dt;
                    gv.DataBind();
                }
                else
                {
                    dt.Rows.Add("No Comments");
                    gv.DataSource = dt;
                    gv.DataBind();
                }
                Panel Panel1 = (Panel)e.Item.FindControl("Dis_comments");
                Panel1.Controls.Add(gv);
            }
        }

}
}


text:
Q: Is there an R function to do grouped operations on a data frame without collapsing it? Apologies if the question isn't formulated correctly in the title, I am fairly new to this and still not used to the exact terminology.
I need to add a column to a data frame that contains the result of operations (e.g., mean, sum, etc.) grouped by values in other columns. At the same time, I would not like to lose any of the data in the data frame. However, I haven't been able to find a function that does that, or a solution of any kind.
Let me illustrate with an example:
df

    Name Round Points
1   John     1      6
2   John     2      4
3   John     3      6
4   John     4      8
5  Annie     1      7
6  Annie     2      4
7  Annie     3      3
8  Annie     4      6
9   Bill     1      4
10  Bill     2      5
11  Bill     3      8
12  Bill     4      5

I would like to add a column at to the dataframe that contains the average points of each player displayed in each row:
    Name Round Points Avg.points
1   John     1      6        6.0
2   John     2      4        6.0
3   John     3      6        6.0
4   John     4      8        6.0
5  Annie     1      7        5.0
6  Annie     2      4        5.0
7  Annie     3      3        5.0
8  Annie     4      6        5.0
9   Bill     1      4        5.5
10  Bill     2      5        5.5
11  Bill     3      8        5.5
12  Bill     4      5        5.5

However, if I use group_by(Name) I lose part of the data:
df <- df %>%
  group_by(Name) %>%
  summarise(Avg.points = mean(Points, na.rm = TRUE))

df

# A tibble: 3 × 2
  Name  Avg.points
  <chr>      <dbl>
1 Annie        5
2 Bill         5.5
3 John         6

If I use group_by(Name, Round, Points) I don't get the correct average:
df <- df %>%
  group_by(Name, Round, Points) %>%
  summarise(Avg.points = mean(Points, na.rm = TRUE))

df

# A tibble: 12 × 4
# Groups:   Name, Round [12]
   Name  Round Points Avg.points
   <chr> <dbl>  <dbl>      <dbl>
 1 Annie     1      7          7
 2 Annie     2      4          4
 3 Annie     3      3          3
 4 Annie     4      6          6
 5 Bill      1      4          4
 6 Bill      2      5          5
 7 Bill      3      8          8
 8 Bill      4      5          5
 9 John      1      6          6
10 John      2      4          4
11 John      3      6          6
12 John      4      8          8

Thanks to anyone who could help me out with this.

A: Using dplyr and mutate() function:
library(tidyverse)

df <- df %>%
    group_by(Name) %>%
    mutate(Avg.points = mean(Points))

df

    Name  Round Points Avg.points
   <chr> <dbl>  <dbl>      <dbl>
 1 John      1      6        6
 2 John      2      4        6
 3 John      3      6        6
 4 John      4      8        6
 5 Annie     1      7        5
 6 Annie     2      4        5
 7 Annie     3      3        5
 8 Annie     4      6        5
 9 Bill      1      4        5.5
10 Bill      2      5        5.5
11 Bill      3      8        5.5
12 Bill      4      5        5.5

A: You can use the across function within summarize to easily keep any columns that you want to keep. Using across(everything()) will maintain everything in your dataframe.
Try:
library(dplyr)
df <- df %>%
  group_by(Name) %>%
  summarise(across(everything()), Avg.points = mean(Points, na.rm = TRUE))

df

#> # A tibble: 12 × 4
#> # Groups:   Name [3]
#>    Name  Round Points Avg.points
#>    <chr> <dbl>  <dbl>      <dbl>
#>  1 Annie     1      7        5
#>  2 Annie     2      4        5
#>  3 Annie     3      3        5
#>  4 Annie     4      6        5
#>  5 Bill      1      4        5.5
#>  6 Bill      2      5        5.5
#>  7 Bill      3      8        5.5
#>  8 Bill      4      5        5.5
#>  9 John      1      6        6
#> 10 John      2      4        6
#> 11 John      3      6        6
#> 12 John      4      8        6

If you want to order the dataframe by average number of points, add the arrange function:
library(dplyr)
df <- df %>%
  group_by(Name) %>%
  summarise(across(everything()), Avg.points = mean(Points, na.rm = TRUE)) %>%
  arrange(-Avg.points)

df

#> # A tibble: 12 × 4
#> # Groups:   Name [3]
#>    Name  Round Points Avg.points
#>    <chr> <dbl>  <dbl>      <dbl>
#>  1 John      1      6        6
#>  2 John      2      4        6
#>  3 John      3      6        6
#>  4 John      4      8        6
#>  5 Bill      1      4        5.5
#>  6 Bill      2      5        5.5
#>  7 Bill      3      8        5.5
#>  8 Bill      4      5        5.5
#>  9 Annie     1      7        5
#> 10 Annie     2      4        5
#> 11 Annie     3      3        5
#> 12 Annie     4      6        5

Check out the documentation for more info about across, or see this release note from the creators of dplyr.


text:
Q: Интеграция AppoDeal Пытаюсь интегрировать AppoDeal  в свое приложение, все сделал, но если вставить этот код во фрагменте то выскакивает ошибка на слове "this"
String appKey = "2816167553ee1b3ffb303beb7841d4976a8cebf41a72b111";
Appodeal.initialize(this, appKey);


text:
Q: Yammer API: return top level group topics I'm trying to return just the top level topics in a private group via the rest API but not having much luck.
I can return the messages in the group via
https://www.yammer.com/api/v1/messages/in_group/" . $groupID . ".json

This returns all topics, and the conversation under the topic. I just want to get each topic and ignore the conversation.
I know the result from above contains messages.replied_to_id which is either null or the ID of the topic to which I could filter on my side, but would rather not have to return every conversation, filter them out etc. It seems rather wasteful.
Is there an API option I'm not seeing in their documentation?
(Is topic even the right terminology to use here?)

A: I believe using the parameter threaded=true, will return only the first message in each thread (thread starter).


text:
Q: How to synchronize an instance passed to multiple places? I am working on a code which takes a Map in its constructor, and assigns it to a instance variable. Any method using this instance variable map is synchronized.
class Foo {

   Map<Int, Int> map;

   Foo ( Map<Int, Int> map ) {
       this.map = map;
   }

   synchornized void put(int x, int y) {
       map.put(x, y);
   }

}

But - The client created multiple instances of Foo, and passed same map instance to each of them.
Map<Int, Int> map = new HashMap<Int, Int>();
new Foo(map);
new Foo(map);

How does map get synchronized when used on different instances ?
Making question broader, how to synchronize an instance sort of globally ?

A: You should synchronize on the map, not the foo instance itself.
i.e.
void put(int x, int y) {
    synchronized (map) {
       map.put(x, y);
    }
}

Edit:
The key point here is, you need to understand the concept of synchronization, and to identify the "resource" that is shared and need to be synchronized.  In your case, the shared resource is the Map, not the Foo instance itself.  It is the Map being access concurrently which can cause problem, therefore what you should synchronize on is the shared resource - the Map itself.
There are some other answer suggesting usage of ConcurrentHashMap.  ConcurrentHashMap can help in some situation but it is not going to cover the possibilities of synchronized block (or using some other kind of locking machanism)
ConcurrentMap solve the problem of providing some "complex" operations to Map that in the past need multiple access, and hence need explicit locking on Map.  ConcurrentHashMap goes one step further by making thread safe no-lock read etc.
However, it does not necessary solve the problem.
Assuming what I need to perform on Map is not the provided operations:
e.g.
synchronized(map) {
    if (map.contains("key1")) {
        map.put("key3", val1);
    } else if (map.contains("key2")) {
        map.put("key3", val);
    }
 }

, then I will need explicit locking (in such case, ConcurrentHashMap may be even worse because it does not allow me to perform explicit synchronization)

A: I would like to add to the previous answers.
The problem with the pattern you are describing, without further context, is that you don't know what is actually sent in or what it is used for outside your class. The only thing you know is that it implements Map.
If you need to guard (synchronize) input to this map, then the pattern is broken, because the caller, the one who submitted the map to you in the first place, might have submitted it to other classes as well, or might be manipulating it in other ways, without locks.
The only way you can be sure that the map you are manipulating is properly guarded is if you yourself own it and make sure you don't leak a reference to it to someone else.
This means you should copy the submitted map into a private map when you first get it. That way, no one can manipulate it without you knowing.
class Foo {
  private final Map<Integer, Integer> map;

  Foo(Map<Integer, Integer> map) {
    this.map = new HashMap<Integer, Integer>(map);
  }
}

Then, you can also take advantage of the modern locking style in java:
class Foo {
  private final Map<Integer, Integer> map;
  private final ReentrantReadWriteLock mapLock = new ReentrantReadWriteLock();

  Foo(Map<Integer, Integer> map) {
    this.map = new HashMap<Integer, Integer>(map);
  }

  public Integer put(Integer k, Integer v) {
    try {
      mapLock.writeLock().lock();
      return map.put(k, v);
    } finally {
      mapLock.writeLock().unlock();
    }
  }

  public Integer get(Integer k) {
    try {
      mapLock.readLock().lock();
      return map.get(k);
    } finally {
      mapLock.readLock().unlock();
    }
  }
}

Be safe - copy your input and don't leak your references!

A: You could use a ConcurrentHashMap - this type of Map is thread-safe.
Or, synchronize on the class so that any instance of the class will share the same lock.
Or, synchronize on the map.

A: Use ConcurrentHashMap instead of HashMap.

A hash table supporting full concurrency of retrievals and adjustable
  expected concurrency for updates. This class obeys the same functional
  specification as Hashtable, and includes versions of methods
  corresponding to each method of Hashtable. However, even though all
  operations are thread-safe, retrieval operations do not entail
  locking, and there is not any support for locking the entire table in
  a way that prevents all access. This class is fully interoperable with
  Hashtable in programs that rely on its thread safety but not on its
  synchronization details.


text:
Q: How to best calculate Christoffel symbols of metric $du^2 +g^2(u) dv^2$?
Suppose that the first fundamental form is $du^2+g^2(u)dv^2$. Calculate $\Gamma_{11}^1, \Gamma_{11}^2, \Gamma_{12}^1, \Gamma_{12}^2, \Gamma_{22}^1, \Gamma_{22}^2$.

In lectures we've been given 6 formulas for the Christoffel symbols, all of this style: $$\Gamma_{11}^1=\frac{GE_u-2FF_u+FE_v}{2(EG-F^2)}$$ but all slightly different.
We've also been given 6 equations like this: $$\Gamma_{11}^1 \cdot E + \Gamma_{11}^2 \cdot F=\frac{1}{2}E_u$$ and $$\Gamma_{11}^1 \cdot F + \Gamma_{11}^2 \cdot G=F_u-\frac{1}{2}E_v $$ Again, they're all the same style but all slightly different.
What is the best way to calculate the Christoffel symbols? Is it using either of these sets of equations or is there another way?
I ask if there is another way because these aren't the easiest of equations to memorise, especially when there are 6 (or 12) of them so another method would be appreciated.

A: The way that I calculate Christoffel symbols (when I must) is using this formula:
$$\Gamma^{i}_{jk}=\sum_{m=1}^2\frac{1}{2}(g^{-1})^{im}\left(\frac{\partial g_{mj}}{\partial x^k}+\frac{\partial g_{mk}}{\partial x^j}-\frac{\partial g_{jk}}{\partial x^m}\right),$$ where $g$ is the matrix of your first fundamental form, and $x^1=u$ and $x^2=v$ (in comparison with your coordinates). So here, each of the indices $i$, $j$, and $k$ can take the value $1$ or $2$, $g_{11}=E$, $g_{12}=g_{21}=F$, and $g_{22}=G$. Using this formula, we can calculate $\Gamma^1_{11}$ as
\begin{align*}
\Gamma^1_{11}&=\frac{1}{2}(g^{-1})^{11}\left(\frac{\partial g_{11}}{\partial x^1}+\frac{\partial g_{11}}{\partial x^1}-\frac{\partial g_{11}}{\partial x^1}\right)+\frac{1}{2}(g^{-1})^{12}\left(\frac{\partial g_{21}}{\partial x^1}+\frac{\partial g_{21}}{\partial x^1}-\frac{\partial g_{11}}{\partial x^2}\right)\\
&=\frac{1}{2}\frac{G}{EG-F^2}\left(E_u+E_u-E_u\right)+\frac{1}{2}\frac{-F}{EG-F^2}\left(F_u+F_u-E_v\right)\\
&=\frac{GE_u-2FF_u+FE_v}{2(EG-F^2)}.
\end{align*}
In this same way, you can recover all of the formulas you received  in lecture. This one way of calculating the Christoffel symbols is a little more complicated than the formulas you were given, but at least you only have to remember one equation.
Finally, notice that $\Gamma^i_{jk}=\Gamma^i_{kj}$, so you only have to memorize four formulas at most.

A: Use the Euler-Lagrange equations.  If $L = \frac{1}{2} (u'(t)^2 + g(u(t))^2 v'(t)^2)$, the equations $$\frac{\partial L}{\partial u} -\frac{d}{dt}\left(\frac{\partial L}{\partial u'}\right) = 0,\qquad \frac{\partial L}{\partial v} -\frac{d}{dt}\left(\frac{\partial L}{\partial v'}\right) = 0 $$will produce the geodesic equations, from which you can read the Christoffel symbols easily. I'll do the first one, you do the other. $$g(u(t))g'(u(t))v'(t)^2 - \frac{d}{dt}\left(u'(t)\right) = 0 \implies u''(t) - g(u(t))g'(u(t)) v'(t)^2 = 0,$$so $\Gamma_{11}^1 = \Gamma_{12}^1 = 0$ and $\Gamma_{22}^1 =- g(u)g'(u)$.

In general, if $ds^2 = \sum g_{ij} du^i du^j$, the energy of a curve is given by $E = \frac{1}{2}\int_I ds^2_{\gamma(t)}(\gamma'(t),\gamma'(t))\,dt$, and every geodesic is a critical point of the energy functional. The Lagrangian $L = \frac{1}{2} ds^2_{\gamma(t)}(\gamma'(t),\gamma'(t))$ must then satisfy $$\frac{\partial L}{\partial u^k} - \frac{d}{dt}\left(\frac{\partial L}{\partial \dot{u}^k}\right) =0,$$where $(u^1(t),\cdots,u^n(t))$ are the geodesic's coordinates. These equations, after some algebraic juggling show up as $\ddot{u}^k + \sum \Gamma_{ij}^k\dot{u}^i\dot{u}^j = 0 $ .


text:
Q: Can you force the wspace and hspace of figure subplots to a fixed value in matplotlib regardless of figure size I am trying to build a function to plot multiple images in a grid with a single colorbar and histogram. I would like the spacing between all the plots to be a fixed value and for the colorbar to span the height of a all images and histogram to span the width of the images/colorbar.  I have some code that works, but it requires the figure size being set to a specific aspect ratio for it to work.  This is not ideal because I want to use the function for images with varying aspect ratios and for a varying number of images 2x1, 1x2, 2x2, etc.
This code outputs 3 figures of varying aspect ratio.  I would like if any excess dimension would be applied to the border spacing rather than the subplot wspace, hspace spacing.
fig wide: https://i.stack.imgur.com/BB1Cz.png
fig tall: https://i.stack.imgur.com/G5C34.png
fig nice: https://i.stack.imgur.com/AVX6C.png
Here is the code:
import math
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt

def compare_frames(frames, columns, bins=256, alpha=.5, vmin=None, vmax=None, fig=None):
    if vmin is None:
        vmin = min([f.min() for f in frames])
    if vmax is None:
        vmax = max([f.max() for f in frames])
    if fig == None:
        fig = plt.figure()
    color_cycle = plt.get_cmap('tab10')
    rows = math.ceil(len(frames)/columns)
    width_ratios = [1 for col in range(columns)] + [.05]

    gs = mpl.gridspec.GridSpec(rows + 1, columns + 1, figure=fig, width_ratios=width_ratios)
    images = []
    for row in range(rows):
        for col in range(columns):
            idx = row*columns + col
            if idx < len(frames):
                ax = fig.add_subplot(gs[row, col])
                ax.get_xaxis().set_ticks([])
                ax.get_yaxis().set_ticks([])
                for spine in ['bottom', 'top', 'left', 'right']:
                    ax.spines[spine].set_color(color_cycle(idx))
                    ax.spines[spine].set_linewidth(3)
                images.append(ax.imshow(frames[idx], vmin=vmin, vmax=vmax))

    cax = fig.add_subplot(gs[0:-1, -1])
    plt.colorbar(images[0], cax=cax)

    hax = fig.add_subplot(gs[-1, :])
    for i, frame in enumerate(frames):
        hax.hist(frame.ravel(), bins=256, range=(vmin, vmax), color=color_cycle(i), alpha=alpha)

    fig.subplots_adjust(wspace=.05, hspace=.05)

if __name__ == '__main__':
    x_size = 640
    y_size = 512
    frames = []
    for i in range(4):
        frames.append(np.random.normal(i + 1, np.sqrt(i + 1), size=(y_size, x_size)))

    fig_wide = plt.figure(figsize=(12, 8))
    compare_frames(frames, 2, fig=fig_wide)
    fig_tall = plt.figure(figsize=(6, 8))
    compare_frames(frames, 2, fig=fig_tall)
    fig_nice = plt.figure(figsize=(6.9, 8))
    compare_frames(frames, 2, fig=fig_nice)
    plt.show()

A: I've gathered that I should probably be using matplotlib axes_grid1 from mpl_toolkits.  They have a built-in ImageGrid class which does a lot of what I would like to do (fixed spacing for images and colorbar):
def compare_frames(frames, columns, bins=256, alpha=.5, vmin=None, vmax=None, fig=None):
    if vmin is None:
        vmin = min([f.min() for f in frames])
    if vmax is None:
        vmax = max([f.max() for f in frames])
    if fig == None:
        fig = plt.figure()
    color_cycle = plt.get_cmap('tab10')
    rows = math.ceil(len(frames)/columns)

    im_grid = axes_grid1.ImageGrid(fig, 111, nrows_ncols=(rows, columns), axes_pad=.1,
        cbar_mode='single', cbar_pad=.1, cbar_size=.3)
    for i, ax in enumerate(im_grid):
        im = ax.imshow(frames[i], vmin=vmin, vmax=vmax)
        ax.get_xaxis().set_ticks([])
        ax.get_yaxis().set_ticks([])
        for spine in ['bottom', 'top', 'left', 'right']:
            ax.spines[spine].set_color(color_cycle(i))
            ax.spines[spine].set_linewidth(3)
    cbar = fig.colorbar(im, cax=im_grid.cbar_axes[0])

This is great, and I would love to figure out a way to use this ImageGrid class to do most of the work, and then add another axis at the bottom for the histogram.  I haven't been able to crack how to do this however since all of the examples I've found use "append_axes()" on a Divider class. ImageGrid forms a SubplotDivider however, which doesn't have an append_axes function.


text:
Q: Java Agent "java.lang.UnsupportedOperationException: class redefinition failed: attempted to change method modifiers" I am trying to change the method access modifier through an agent via javassist, however, I get an error. So, is it possible to change the access modifier via java agent and how to fix it? Is there any other way to influence the bytecode in runtime?
Agent
public static void premain(String args, Instrumentation instrumentation)
    throws ClassNotFoundException, IOException, UnmodifiableClassException, NotFoundException {

  final ClassPool pool = ClassPool.getDefault();
  pool.appendClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader()));

  final ClassFile file = pool.get("...")
      .getClassFile();
  file.getMethod("...").setAccessFlags(AccessFlag.PUBLIC);

  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  DataOutputStream dos = new DataOutputStream(bytes);
  file.write(dos);

  Class<?> clazz = ...;

  instrumentation.redefineClasses(new ClassDefinition(clazz, bytes.toByteArray()));
}

MANIFEST
Manifest-Version: 1.0
Premain-Class: ...Agent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Can-Set-Native-Method-Prefix: true


text:
Q: Reading unkown file type with strange entries into R I am completely new at this and here, so please have mercy.
I want to open an ASCII data file in R.
After several different attempts, I have tried df=read.csv("C:MyDirectory" ,header=FALSE, sep="").
This has produced a table with several variables, but some rows clearly contain the wrong information, some cells are blank, some contain NA values.
Any ideas what has gone wrong? I have gotten the file from an offical Spanish research institute:
http://www.cis.es/cis/opencm/ES/2_bancodatos/estudios/listaTematico.jsp?tema=1&todos=si
Then BARÓMETRO DE OCTUBRE 2017, to the right is a small link entitled "fichero de datos", which allows you to download after providing them with some info. The file giving the trouble is DA3191. If anyone could go through the trouble of helping me with this, it would be awesome. Thank you.

A: Part 1
This looks like a fixed width format, so you need read.fwf instead of read.csv and friends. I made a screen shot of an almost random place of that file: my hypothesis is that the 99's and 98's etc are missing data codes, so the first 99 marked in yellow would belong to the same column with 4, 2, 0, etc, and the immediately following 99 (not marked) is in the same column with 0, 5, 7, etc.

Part 2
And then look at the file ES3191 -- this looks like SPSS code (pardon my French!) containing the rules about reading in the data file. You can probably figure out the width of each column and what's in there from that file:
DATA LIST FILE= 'DA3191'
/ESTU 1-4 CUES 5-9 CCAA 10-11 PROV 12-13 MUN 14-16 TAMUNI 17 CAPITAL 18 DISTR 19-20 SECCION 21-23
ENTREV 24-27 P0 28 P0A 29-31 P1 32 P2 33 P3 34 P4 35 P5 36 P6 37 P701 38-39 P702 40-41 P703 42-43
P801 44-45 P802 46-47 P803 48-49 P901 50-51 P902 52-53 P903 54-55 P904 56-57 P905 58-59 P906 60-61
P907 62-63 P1001 64 P1002 65 P1003 66 P1101 67 P1102 68 P1103 69 P1104 70 P1201 71 P1202 72
P1203 73 P1204 74 P1205 75 P1206 76 P1207 77 P1208 78 P1209 79 P13 80-81 P13A 82-83 P1401 84-85
P1402 86-87 P1403 88-89 P1404 90-91 P1405 92-93 P1406 94-95 P1407 96-97 P1408 98-99 P1409 100-101
P1410 102-103 P1411 104-105 P1412 106-107 P1413 108-109 P1414 110-111 P1415 112-113 P1416 114-115

I'm not an SPSS expert  but I would guess that what it is trying to tell us is that

*

*columns 1-4 contain the variable "ESTU"

*columns 5-9 contain the variable "CUES"

*etc

For read.fwf you have to calculate each variable's "width" i.e. 4 characters for ESTU (if my reading was right) 5 characters for CUES etc.
Part 3
Using the guesses above, I used the following code to read in your data, and it looks like it works:
# this is copy/pasted SPSS code from file "ES3191"
txt <- "ESTU 1-4 CUES 5-9 CCAA 10-11 PROV 12-13 MUN 14-16 TAMUNI 17 CAPITAL 18 DISTR 19-20 SECCION 21-23
ENTREV 24-27 P0 28 P0A 29-31 P1 32 P2 33 P3 34 P4 35 P5 36 P6 37 P701 38-39 P702 40-41 P703 42-43
P801 44-45 P802 46-47 P803 48-49 P901 50-51 P902 52-53 P903 54-55 P904 56-57 P905 58-59 P906 60-61
P907 62-63 P1001 64 P1002 65 P1003 66 P1101 67 P1102 68 P1103 69 P1104 70 P1201 71 P1202 72
P1203 73 P1204 74 P1205 75 P1206 76 P1207 77 P1208 78 P1209 79 P13 80-81 P13A 82-83 P1401 84-85
P1402 86-87 P1403 88-89 P1404 90-91 P1405 92-93 P1406 94-95 P1407 96-97 P1408 98-99 P1409 100-101
P1410 102-103 P1411 104-105 P1412 106-107 P1413 108-109 P1414 110-111 P1415 112-113 P1416 114-115
P1501 116-117 P1502 118-119 P1503 120-121 P1504 122-123 P1505 124-125 P1506 126-127 P1507 128-129
P1508 130-131 P1509 132-133 P1510 134-135 P1511 136-137 P1512 138-139 P1513 140-141 P1514 142-143
P1515 144-145 P1516 146-147 P16 148 P17 149 P1801 150-151 P1802 152-153 P1803 154-155 P1804 156-157
P1805 158-159 P1806 160-161 P1807 162-163 P1808 164-165 P1809 166-167 P1810 168-169 P1811 170-171
P1812 172-173 P1813 174-175 P19 176 P20 177 P21 178-179 P22 180-181 P23 182-183 P2401 184-185
P2402 186-187 P2403 188-189 P2404 190-191 P2405 192-193 P2406 194-195 P2407 196-197 P2408 198-199
P2409 200-201 P2410 202-203 P2411 204-205 P2412 206-207 P2413 208-209 P2414 210-211 P2415 212-213
P2416 214-215 P25 216 P26 217 P27 218 P27A 219-220 P28 221-222 P29 223 P30 224-225 P31 226 P31A 227-228
P32 229 P32A 230 P33 231 P34 232 P35 233 P35A 234 P36 235 P37 236 P37A 237 P37B 238 P38 239-241
P39 242 P39A 243 P40 244-246 P41 247-248 P42 249-250 P43 251 P43A 252 P43B 253 P44 254 P4501 255
P4502 256 P4503 257 P4504 258 P4601 259-261(A) P4602 262-264(A) P4603 265-267(A) P4604 268-270(A)
P4605 271-273(A) P4701 274-276(A) P4702 277-279(A) P4703 280-282(A) P4704 283-285(A) P4705 286-288(A)
P48 289 P49 290 P50 291 P51 292 I1 293-295 I2 296-298 I3 299-301 I4 302-304 I5 305-307 I6 308-310
I7 311-313 I8 314-316 I9 317-319 E101 320-321 E102 322-323 E103 324-325 E2 326 E3 327-329 E4 330
C1 331 C1A 332-333 C2 334 C2A 335 C2B 336-337 C3 338 C4 339-340 P21R 341-342 P22R 343-344 VOTOSIMG 345-346
P27AR 347-348 RECUERDO 349-350 ESTUDIOS 351 OCUMAR11 352-353 RAMA09 354 CONDICION11 355-356
ESTATUS 357 "

# making a 2-column  matrix (name = left column, position = right column)
m <- matrix(scan(text=txt, what=""), ncol=2, byrow=TRUE)
m <- as.data.frame(m, stringsAsFactors=FALSE)
names(m) <- c("Var", "Pos")
pos <- sub("(A)", "", m$Pos, fixed = TRUE) # some entries contain '(A)' - no idea what it means so deleting it
pos <- strsplit(pos, "-")
starts <- as.numeric(sapply(pos, head, 1)) # get the first element from left
ends <- as.numeric(sapply(pos, tail, 1)) # get the first element from right
w <- ends - starts +1

MyData <- read.fwf("R/MD3191/DA3191", widths = w)
names(MyData) <- m$Var

head(MyData)

  # ESTU CUES CCAA PROV MUN TAMUNI CAPITAL DISTR SECCION ENTREV P0 P0A P1 P2 P3 P4 P5 P6
# 1 3191    1   16    1  59      5       1     0       0      0  1   0  3  2  2  5  1  2
# 2 3191    2   16    1  59      5       1     0       0      0  1   0  4  2  3  5  2  3
# 3 3191    3   16    1  59      5       1     0       0      0  1   0  4  2  2  4  2  2


text:
Q: How to prove that the following complex integral vanishes to 0? Consider the path $\mu:[0,2\pi]\rightarrow\mathbb{C}, t \mapsto \left\{\begin{matrix}
Re^{it} & \text{if  } 0 \leq t\leq \pi\\
\frac{R}{\pi}(2t-3\pi) & \text{if  } \pi \leq t\leq 2\pi\\
\end{matrix}\right. $
(It corresponds to the path with image $[-R,+R]\cup\left \{ \text{upper-half of the circle of radius R} \right  \}$
Now, the function $f(z)=\frac{1}{z^2+z+1}$. I have to prove that when R goes to $\infty$, the integral $\oint_{\mu}f(z)dz$ vanishes to 0.
I have tried to utilize the Estimation Lemma. So,
$\left| \oint_{\mu}f(z)dz\right|\leq \text{length}(\mu)\cdot\max_{z\in D_R}\left|f(z)\right|$, but I can't find the max.
ERROR: I meant the integral over the arc vanishes not the part on the real-axis

A: The integral along the semi-circular part of the contour, $Re^{i[0,\pi]}$ vanishes, but the integral along the $[-R,R]$ part does not vanish.
$$
\int_\mu\frac1{z^2+z+1}\,\mathrm{d}z
=\int_{-R}^R\frac1{x^2+x+1}\,\mathrm{d}x+\int_{Re^{i[0,\pi]}}\frac1{z^2+z+1}\,\mathrm{d}z\\
$$
We can use your estimate that the length of the arc is $\pi R$ and the triangle inequality gives us that $\left|z^2+z+1\right|\ge\left|z^2\right|-\left|z+1\right|\ge R^2-R-1$. Therefore,
$$
\left|\,\int_{Re^{i[0,\pi]}}\frac1{z^2+z+1}\,\mathrm{d}z\,\right|\le\frac{\pi R}{R^2-R-1}
$$
As $R\to\infty$, $\frac{\pi R}{R^2-R-1}\to0$.
We can then use the Residue Theorem to compute the integral along $\mu$ and thus get the integral along the real line
$$
\int_{-\infty}^\infty\frac1{x^2+x+1}\,\mathrm{d}x=2\pi i\operatorname*{Res}_{z=\frac{-1+i\sqrt3}2}\left(\frac1{z^2+z+1}\right)
$$


text:
Q: no way to setProgressDrawable on RemoteViews I'm trying to call setProgressDrawable on a ProgressBar in my RemoteViews
However there doesn't appear to be a setDrawable(<view_id>,<method>,<value>) method on RemoveViews I've tried setBitmap but setProgressDrawable takes a Drawable not a Bitmap and setInt doesn't work either.
I wanted to avoid having loads of different widget layout xml files just to handle different color progress bars.

A: There is no way to do this. My solution was not to create separate layout files, but one that contains all the different ProgressBars with different progressDrawables. In the code you then have to make only one of them visible.
Please note that for older android versions it is not allowed to call setViewVisibility on the Progressbar directly. The trick is to wrap a simple LinearLayout around each bar and to make this wrapper invisible/visible instead. Works fine for me.


text:
Q: how do MPI decide its rank size I am a MPI beginner, If i write a code like this in c++, how would the system dicide how many ranks the program will have?
This is not like the logic we follow in object-oriented language, when you define an array, you know precisely the size.
What mechanism they use in MPI to let the system decide how many rank and the entire size?
Is it flexible? Decide by mechine power? Or just automatically generating when calling?
int main(int argc, char *argv[]){
MPI_Init(NULL, NULL);
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 4)
    master();
else
    slave(rank);
MPI_Finalize();
return 0;}

A: Here is a good reference:

*

*http://mpitutorial.com/tutorials/mpi-hello-world/

*http://mpitutorial.com/tutorials/introduction-to-groups-and-communicators/
And here is a tutorial:

*

*https://computing.llnl.gov/tutorials/mpi/
And here is a related question

*

*What is the difference between ranks and processes in MPI?
To answer your question:

*

*Rank is the (logical) process number (like a thread id)

*Size is the total number of processes (allocated, parallelism)
When you use MPI_Init, see this: https://www.sharcnet.ca/help/index.php/Getting_Started_with_MPI to observe how to set number of processes.
mpirun -n 4 ./parhello

You can construct your argv[] array with "-n N" and specify world size to MPI_init call.
You can also set the world size using environment variables,

*

*https://www.ibm.com/support/knowledgecenter/en/SSFK3V_2.2.0/com.ibm.cluster.pe.v2r2.pe100.doc/am102_mpienvars.htm
Borrowing from another question/answer:

MPI_Comm_size returns the size of a communicator. In our example,
  MPI_COMM_WORLD (which is constructed for us by MPI) encloses all of
  the processes in the job, so this call should return the amount of
  processes that were requested for the job.
MPI_Comm_rank returns the rank of a process in a communicator. Each
  process inside of a communicator is assigned an incremental rank
  starting from zero. The ranks of the processes are primarily used for
  identification purposes when sending and receiving messages.

Rank is used to distinguish processes from one another. You may have a "master" process (rank = 0) that sends out messages to "slave" applications on rank 1-15. Or you may use other topologies to divide workloads.


text:
Q: Squashing complex branch in git I have been pushing from 2 different computers to the same main, and somehow I have ended up with different unnamed branches now (those branches below is not something I have actively created on purpose). And neither have I actively done these "Merge branch 'main' of..". The tree looks like this now:
* ee3f.. (HEAD, main) Test Commit
*   9b42.. Merge branch 'main' of..
|\
| *   6640.. Merge branch 'main' of..
| |\
| | *   2c7b.. Merge branch 'main' of..
| | |\
| | | * 4a01.. Updated GUI 1
| | | * 70b5.. Updated GUI 2
| | | * ead5.. Updated GUI 3
| | * | 2005.. Updated GUI 4
| | |/
| | * 63f9 Added error handling

Now I have 3 questions:

*

*What cause these unnamed branches to appear? Referring to the situation where I work against the main branch all the time and push/pull from 2 different computers.

*And how come they are automatically merged later

*How can I only squash/rebase Updated GUI 1-4 but nothing else? Those branches doesn't have a name since I have chosen anything, but I would like to condensate these 4 commits into one, but I cannot figure it out.

A:

*

*What cause these unnamed branches to appear? Referring to the situation where I work against the main branch all the time and push/pull from 2 different computers.

Answer 1: They're not unnamed.  They're all named main.  Have you ever been to a party where the host is named Bruce, and all the guests are also named Bruce (and they're not all the same person)?
Answer 2: Git doesn't have branches.  Git has, instead, something else called branches.
These two answers aren't wrong, but they aren't right either.  They're a victim of Git terminology.  The most accurate answer is perhaps the least satisfying: Git has two or three or more things called branches.  See What exactly do we mean by "branch"?

*And how come they are automatically merged later

You ran git merge, probably via git pull (in fact the message, even edited, virtually guarantees that it was via git pull).  Remember, git pull means (1) run git fetch, then (2) based on the result from step 1, run another Git command.

*How can I only squash/rebase Updated GUI 1-4 but nothing else?

This is ... difficult, at the least.  In particular, updates 1, 2, and 3 are all neatly linear, but update 4 is on a separate branch, in one of the far too many meanings of the word branch, as you can see from this part:

| | | * 4a01.. Updated GUI 1
| | | * 70b5.. Updated GUI 2
| | | * ead5.. Updated GUI 3
| | * | 2005.. Updated GUI 4

Note how the three * items marking the positions of those three commits in the commit graph neatly stack atop each other, but the fourth one is on a separate "line".
You can effectively produce a single commit that contains the same snapshot as this merge result:

| | *   2c7b.. Merge branch 'main' of..

But if and when you do this, these three commits:

* ee3f.. (HEAD, main) Test Commit
*   9b42.. Merge branch 'main' of..
|\
| *   6640.. Merge branch 'main' of..

would then need to be discarded in favor of new and improved commits that merge the one new commit you'd make.  That may prove too disruptive to others, depending on who else may be using the other Git repositories involved here.
The quick way to do the combining would be to check out commit:

| | * 63f9 Added error handling

(on a newly-created branch name, to keep track of things, e.g.:
git switch -c newbr 63f9

though there's a good chance you need more than just 4 characters of hash ID here), then use git read-tree -u to replace the current index and working tree from the merge 2c7b:
git read-tree -u 2c7b

(again there's a good chance you need more than just the 4 characters here) and commit.  That gives you a new ordinary commit whose parent is 63f9 and whose snapshot is from 2c7b, so that:
git diff newbr 2c7b

should be empty for instance.
You then have to throw out all the subsequent commits and rebuild them, and get everyone else to do the same, and that's the hard part if there is an "everybody else".


text:
Q: Laravel built in Authentication In a Laravel built in authentication, among the many available classes and interfaces, I have narrowed it down to Illuminate\Support\Facades\Auth and Illuminate\Auth\SessionGuardas am trying to figure out how the authentication works, can anyone please explain to me the principle or just how these two correlates such that am able to call Auth::check() or any of the related functions which are implemented by Illuminate\Auth\SessionGuard but not with
Illuminate\Support\Facades\Auth. Thanks in advance.
P.S. Am trying to build my own custom authentication in laravel and i just want to understand this one.


text:
Q: Algorithm to minimize the cost for mechanic There is one straight road. And on some distance some job is present. And every job has some importance.
Now, mathematically, an array of locations is given to us, location[]. and there importance array is given, importance[].
If you move from one point to other, mechanic needs to walk, and do job at that location.
And, mechanic needs to do all jobs.
We need to minimize summation of (importance*distance).
Example for better understanding :-
position     :-  1    6    12   13    14      24
importance   :-  1    2    10   3     5       1

If we start from 6, and move in following way
  6  -->   12 --->  13 ---> 14 --> 1 --> 24

= (10*6) + (3*7) + (5*8) + (1*21) + (1*44) = 186
If we move in following way,
12 --> 13  --> 14 -->  6 --> 1 --> 24

= (3*1) + (5*2) + (2*10) + (1*15) + (1*38)  = 86
So the minimum answer is 86

My approach
First we need to calculate from where we need to start. For that find center of gravity.
For position = 1, (5*2) + (11*10) + (12*3) + (13*5) + (23*1) = 244
For position = 6, (5*1) + (6*10) + (7*3) + (8*5) + (18*1) =  144.
Similarly calculate for all positions, and choose minimum value, i.e., Center of gravity.
But after choosing that point, how to move to other positions, is out of reach for me.
But I am not able to complete the algorithm. Please help in that.


text:
Q: How can I list all users who can su into a generic account I have a generic account several users can su into, I however would like to find the name of all users who can do this.
Thanks,
Oscar

A: su allows you to access someone's account if

*

*You're root or

*You know their password

There's no way to list what users know another users password (and if you could, you should revoke all their access. Users should never give out their password, for any reason, to anyone, including IT).

sudo grants an account authorization to access another account. Instead of knowing the password on the target account, users must know (and enter) their password, to prove who they are. This access is also logged, and you can manage the access lists with the /etc/sudoers file (use the command visudo to actually edit it, don't edit it directly!)
You can read about the format of the sudoers file with man sudoers. Usually, a group is granted sudo access (such as admin or wheel or sudo), and then users are added to that group, and you can list the users in that group to find out who has access.


text:
Q: is it possible to compare environments? I'm trying to find a tool or a PowerShell script which allow me to compare 2 environments,
my goal is to compare my production farm and my pre prod farm and to compare as many settings as possible, including versions etc.

A: They are not powershell scripts but you can try them both.
Run the tool on all your farms that you want to compare and the reports are nicely detailed.

*

*http://www.spdockit.com/ -- This one comes with a price. You can try out for free.

2.http://spsfarmreport.codeplex.com/ -- This one is free but not so good as the above.
You need to manually compare the reports generated from each farm.

A: There are few tool available in the market to do your requirement, and few are below,

*

*Compare SharePoint Farms

*Server Administrator for SharePoint


text:
Q: How to convert arrays of numbers into a matrix in Ruby I have a two simple arrays of numbers, representing the cartesian position of an object.
a = [3, 4]
b = [8, 5]

I want to check if "a" and "b" are beside each other. I would like to convert the two into a matrix and perform a subtractions of the two positions, and then check if the absolute value of either element is "1".
Is there a way to do this?

A: You're getting the uninitialized constant error because you first need:
require 'matrix'

Then you could just:
Matrix[a,b]

Sample interactive output:
irb(main):011:0> require 'matrix'
=> true
irb(main):012:0> Matrix[a,b]
=> Matrix[[3, 4], [8, 5]]

A: I don't think using Matrix class methods is justified here. The only method that would be marginally useful is Matrix#-, but to  use that you need to convert your arrays to Matrix objects, apply Matrix#-, then convert the resultant matrix object back to an array to determine if the absolute value of any element equals one (whew!). I'd just do this:
def adjacent?(a,b)
  a.zip(b).any? { |i,j| (i-j).abs == 1 }
end

adjacent?([3, 4], [8, 5]) #=> true
adjacent?([3, 7], [8, 5]) #=> false
adjacent?([3, 7], [2, 5]) #=> true

For the first example:
a = [3, 4]
b = [8, 5]
c = a.zip(b)
  #=> [[3, 8], [4, 5]]
c.any? { |i,j| (i-j).abs == 1 }
  #=> true

The last statements determines if either of the following is true.
(3-8).abs == 1
(4-5).abs == 1


text:
Q: Handling Model events in Angularjs I'm new to Angularjs and wanting assurance that I'm not implementing an anti-pattern.
I have a Global controller that gets a model thru a factory. That model supplies data to about a dozen directives that sit inside the Global controller's scope.
One of the directives that sits inside the Global controller is a google map and needs to be initialized after I get the lat/long data from the server. I announce the model's arrival using $rootScope.$broadcast("$site:loaded") from a .success() func in the Global controller, and then I listen for it using $rootScope.$on("$site:loaded") in the directive.
Have I implemented an anti-pattern or is this A.O.K.? At first I figured there was already a method I could tap into that would "know" when the model arrived, something like Backbone's onModelChanged event.
Any tips about this or about anything else you see in my code? (If it looks good I'll accept answers that say so and explain a little about why it's good, if you can).
Here's the code, starting with the base template:

<!DOCTYPE html>

        <base href="/ng-test/">
        <meta charset="utf-8" />
        <title></title>

        {% include "DriverSideSiteBundle:Juniper:stylesheets.html.twig" %}
        {% include "DriverSideSiteBundle:Juniper:javascript.html.twig" %}

        {% block head %}
        {% endblock %}

        {#
            These twig files contain <jn-header>
            The scaffolding HTML changes depending on whether the nav is above, below or not
            part of the header
        #}
        {% include 'DriverSideSiteBundle:Juniper:foundation/header.html.twig' with template %}

        create angular 404 page to handle broken links.

        {#
            These twig files contain <jn-sidebar> and <ng-view>
            The scaffolding HTML changes depending on where the nav is and whether there are sidebars
        #}
        {% if template.content.columns == 2 %}
            {% include 'DriverSideSiteBundle:Juniper:foundation/two-column.content.html.twig' with template %}
        {% endif %}

        {% if template.content == 1 %}
            {% include 'DriverSideSiteBundle:Juniper:foundation/one-column.html.twig' with template %}
        {% endif %}

        {# Todo: minify and concatenate into one request. #}
        {% javascripts
            "@DriverSideSiteBundle/Resources/public/vendor/modernizr/modernizr.js"
            "@DriverSideSiteBundle/Resources/public/vendor/angular/angular.js"
            "@DriverSideSiteBundle/Resources/public/vendor/angular-route/angular-route.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/app.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/site.factory.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/global/global.controller.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/homepage/homepage.controller.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/site-description/site-description.controller.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/site-description/site-description.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/my-garage/my-garage.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/services/services.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/coupons/coupons.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/contact-info/contact-info.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/payments/payments.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/certifications/certifications.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/amenities/amenities.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/jn-map/jn-map.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/jn-nav/jn-nav.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/store-hours/store-hours.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/motorev-admin/motorev-admin.directive.js"
        %}
            {# "@DriverSideSiteBundle/Resources/public/juniper/js/libs/underscore.module.js" #}
            {# "@DriverSideSiteBundle/Resources/public/juniper/js/header/header.directive.js"
            "@DriverSideSiteBundle/Resources/public/juniper/js/footer/footer.directive.js" #}

        {% endjavascripts %}

        {# Depending on the layout, include this or that version of the angular templates during initial request #}
        {% javascripts '@DriverSideSiteBundle/Resources/public/juniper/js/homepage/homepage.html' output='bundles/driversidesite/juniper/homepage/homepage.html'%}
      {% endjavascripts %}
        {% block angularTemplates %}
        {% endblock %}

The Site factory is injected into the Global controller which calls the Site's getSite(:siteId) method. This method makes an $http request. The returned data is set to the Site factory; I saw that practice somewhere and thought it looked good.
/**
 *  global.controller.js
 */
(function () {
    'use strict';

    var juniper = angular.module('juniper');

    juniper.controller('Global', [ '$rootScope', 'Site', function($rootScope, Site){
        var self = this;

        // Assign the site model to this controller's `site` attr
        this.site = Site;
        // Use the site model's get method to retrieve the site info
        var promise = this.site.getSite(1409); // Todo: Include the Id dynamically

        promise
            .success( $.proxy(function(data, status, headers, config){
                // Bind to the Site obj
                angular.extend(this, data.data);

                // Broadcast when the data arrives so that other directives and controllers can do something when it arrives
                $rootScope.$broadcast("$site:loaded");

            }, Site)) // Pass in the Site object for the data to bind to
            .error( function(data, status, headers, config) {
                var error = 'error';
                error += '/n data: ' + data;
                error += '/n status: ' + status;
                error += '/n headers: ' + headers;
                error += '/n config: ' + config;

                console.log(error); // Log error
            });
    }]);

}());

The Site factory has a Site object that holds the getter and setter functions as well as all the data returned from the server:
/**
 *  site.factory.js
 */
(function () {
    'use strict';

    var juniper = angular.module('juniper');

    juniper.factory('Site', function($http){

        /**
         *  Site obj is passed to whichever controller needs the site model.
         *  The site obj contains all the methods for getting/setting data as well
         *  as the data itself.
         *
         *  In this case, the site obj is set to the global controller which passes
         *  a reference thru inheritance to all other controllers.
         */
        var Site = {

            /**
             *  Get the site
             *  siteId (int) is the integer id of the site to be retrieved
             */
            getSite: function(siteId) {

                var url = 'http://localhost:8000/api/site/' + siteId;

                return $http({
                    method: 'GET',
                    url: url
                });
            }
        };

        // Return the site obj.
        // You'll need to call the site obj methods once assigning it to a controller's attr.
        return Site;

    });

}());

So that's the Global controller which contains the model fetched by the Site factory. Here's the map directive and map template:

Location

The map directive. Notice that I listen for the $scope.$broadcast which comes from the Global controller. I also set scope:false which gives it the Global controller's scope:
/**
 *  jn-map.directives.js
 */
(function () {
    'use strict';

    // Create template-path variable for easy maintenance
    var path = '/bundles/driversidesite/juniper/';

    var juniper = angular.module('juniper');

    juniper.directive("jnMap", function($rootScope) {
      return {
        restrict: "E",
        transclude: false, // Tell where to transclude the element using the ng-transclude attr
        templateUrl: path + 'jn-map/jn-map.html',
        scope: false,
        link: function(scope, elements, attrs) {

            $rootScope.$on("$site:loaded", $.proxy(function(){
                var mapOptions = {
                  center: {
                    lat: parseFloat(this.site.locations[0].latitude),
                    lng: parseFloat(this.site.locations[0].longitude)
                  },
                  zoom: 8
                };
                var map = new google.maps.Map(document.getElementById('map-canvas'),
                    mapOptions);
            }, scope.glb)); // Pass in the Global controller's model
        }
      }
    });

}());

A: This indeed looks like an anti-pattern to me. I would simply only add the map directive to the DOM once the site is available.
In the controller:
promise.success(function(data) {
    $scope.loadedSite = data;
}

In the template:
<jn-map site="loadedSite" ng-if="loadedSite"></jn-map>

The directive would have a scope containing the site, and would only ever be called once the site is loaded thanks to the ng-if:
juniper.directive("jnMap", function($rootScope) {
  return {
    restrict: "E",
    templateUrl: path + 'jn-map/jn-map.html',
    scope: {
      site: '='
    },
    link: function(scope, element, attrs) {
            var mapOptions = {
              center: {
                lat: parseFloat(scope.site.locations[0].latitude),
                lng: parseFloat(scope.site.locations[0].longitude)
              },
              zoom: 8
            };
            new google.maps.Map(element[0], mapOptions);
          }
  };
});

Note that this directive displays the map in the directive's element, and not in another, unrelated element. element is a jQuery-like element wrapper object, and element[0] is thus the raw DOM element.