text:
Q: Program to eat up all of my CPU please (Windows) I know it might sound like an odd question, but theres a logical explanation behind me doing so, very long story.
So could someone provide a program which will eat up as much of my CPU as possible please, preferably .exe files please

A: Have you considered a fork bomb?

A: Please provide the long story - I need a bit of diversion from real development.
Create as many 'while true do;' threads as there are cores. Raise them to real-time priority.  Set them running. Stand by the power switch.
EXE?  You're 'avin a larrf!  DIY.
Rds,
Martin

A: You can compile the following C code on Windows and run it to eat up all CPU.
https://www.electronproton.com/cpu-mem-load-test/
Note that the above one only eats up single core.
If you want to eat up all multi-cores in your system then use OpenMP threaded program. You can download it from the below link.
https://www.electronproton.com/multi-core-cpu-and-memory-load-test/


text:
Q: CloudSearch performance with frequent updates of small batches I have a use case where I need to upload small document batches (typical 1 to 10 documents of 1KB each) to CloudSearch. Every 2 or 3 seconds a new batch is uploaded. The CloudSearch docs for bulk uploads say:

Make sure your batches are as close to the 5 MB limit as possible. Uploading a larger amount of smaller batches slows down the upload and indexing process.

It's ok if there is a 30 seconds delay before the documents show up in search results. Will my implementation work well as my document count is increasing, let's say to 500.000 docs?

A: Indexing time should be well under your 30 second SLA even with 500k docs, regardless of how or whether you batch your submissions.
I say this based on my own testing with an index of 300k docs and 38 index fields on an m1.small instance type, where it takes less than 3 seconds for a document to be searchable. There are a lot of variables that could affect your own situation, such as how many index fields you have, your instance size, etc, but I think my setup reflects the unfavorable conditions (m1.small instance with complex indexing schema) and is still an order of magnitude faster than your SLA. It's anecdotal evidence of course, but you should be fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relating users based on activity selection I am working with Parse.com and would like to set up a condition where it would show the list of users who have also selected a particular activity page. For example, I have a list of items populated by JSON data, and where each item lead to a particular page. I would want to establish a condition that returns the users who have also selected that particular activity page to the current user.
If you need more information, let me know.
Thanks in advance.
Update:
This is what I have tried so far.
I am thinking of I would create a column called "activity name" in parse, and when a user clicks on that confirm button, the activity name would be recorded. Then in the matching activity, it would populate users where the activity name under the activity name column is equal.  For the matching code, I am thinking of
var activitycompare = new Parse.Query("Activity Name");
activitycompare.equalTo('Activity Name', string);

Something around that line. Any assistance or advice would be helpful.
Update 2
Thank you.
Please advise on the revised code, for I unexpectedly receive the following error:
userActivitySelectionName cannot be resolved to a variable

It would essentially see which users have selected that particular activity name and return it.
  public class MatchingActivity extends Activity {

 private String currentUserId;
    private ArrayAdapter<String> namesArrayAdapter;
    private ArrayList<String> names;
    private ListView usersListView;
    private Button logoutButton;

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

        logoutButton = (Button) findViewById(R.id.logoutButton);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ParseUser.logOut();
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            }
        });

        setConversationsList();
    }

    private void setConversationsList() {
        currentUserId = ParseUser.getCurrentUser().getObjectId();
        names = new ArrayList<String>();

        ParseQuery<ParseUser> query = ParseUser.getQuery();
       query.whereNotEqualTo("objectId", currentUserId);
        query.whereEqualTo("ActivityName",userActivitySelectionName);

        query.findInBackground(new FindCallback<ParseUser>() {
            public void done(List<ParseUser> userList, ParseException e) {
                if (e == null) {
                    for (int i=0; i<userList.size(); i++) {
                        names.add(userList.get(i).getUsername().toString());
                    }

                    usersListView = (ListView)findViewById(R.id.usersListView);
                    namesArrayAdapter =
                        new ArrayAdapter<String>(getApplicationContext(),
                            R.layout.user_list_item, names);
                    usersListView.setAdapter(namesArrayAdapter);

                    usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> a, View v, int i, long l) {
                            openConversation(names, i);
                        }
                    });

                } else {
                    Toast.makeText(getApplicationContext(),
                        "Error loading user list",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void openConversation(ArrayList<String> names, int pos) {
        ParseQuery<ParseUser> query = ParseUser.getQuery();
        query.whereEqualTo("username", names.get(pos));
        query.findInBackground(new FindCallback<ParseUser>() {
           public void done(List<ParseUser> user, ParseException e) {
               if (e == null) {
                   Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
                   intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
                   startActivity(intent);
               } else {
                   Toast.makeText(getApplicationContext(),
                       "Error finding that user",
                           Toast.LENGTH_SHORT).show();
               }
           }
        });
    }
}

A: If you're going to record a single activity per user, then you would probably add it as a property to the User class. The correct query would then be (in Android):
var userQuery = ParseUser.getQuery();
userQuery.whereEqualTo("activityName", someString);
userQuery.findInBackground(new FindCallback<ParseUser>() {
  public void done(List<ParseUser> objects, ParseException e) {
    if (e == null) {
        // The query was successful.
    } else {
        // Something went wrong.
    }
  }
});


text:
Q: Не отображается TabBar после программного перехода Уважаемые знатоки! :)
Задача: авторизировать пользователя и перейти на страницу с TabBar`ом.
При переходе с помощью StoryBoardа (Action Segue) панель TabBara видна. При программном переходе TabBar не отображается.
Программный переход:
let goToMain = self.storyboard?.instantiateViewController(withIdentifier: "MainActivity") as! MainActivity
let navBarOnModal: UINavigationController = UINavigationController(rootViewController: goToMain)
self.present(navBarOnModal, animated: true, completion: nil)

Сторибоард:

Вопрос: Как при программном переходе сделать TabBar видимым?(UITabBarController().tabBar.isHidden = false не помогает)

A: Судя по вашему предоставленному куску кода, вы на UINavigationController переходите, а не на UITabBarController.

*

*Задайте Storyboard ID в вашем сториборде у Tab Bar Controller

*Переход можно осуществить следующим образом:
let storyboardName = "Main"
let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
let identifier = "MainTabBarController"
let tabBarController = storyboard.instantiateViewController(withIdentifier: identifier)
present(tabBarController, animated: true, completion: nil)

A: Обычно, при работе со storyboard из программного кода, вам не нужно вручную вызывать метод instantiateViewController для создания ViewController. Достаточно вызвать метод performSegue и передать в него идентификатор segue, заданный в storyboard.
Может быть я не правильно понимаю причину, по которой Вы используете instantiateViewController, но если вызвать следующий код из правильного ViewController - всё должно сработать.
performSegue(withIdentifier: "Идентификаторв Segue, заданный в storyboard",
             sender: self)


text:
Q: How to Invert Color on Mac running Catalina? I just downloaded the new version of OS, and I found out the shortcut key Ctrl-Opt-Cmd-8 doesn't trigger invert colors anymore. I thought maybe they changed the shortcut, so I tried to search in System Preference but ended with no luck. Did Apple remove invert colors? If not, where can I find it? Is there any shortcut key for it? Thanks!

A: I can only use the keyboard shortcut if I go into System Preferences and explicitly unckeck and re-check the box for Invert Colors.  Once I am done with my session I enable screen saver by going to a designated not corner.  When I come back, the keyboard shortcut only produces the system sound for an alert without inverting the colors.  It is again only when I go back into System Preferences and uncheck/re-check Invert Colors will it work again.  This is highly annoying and frustrating as I rely on this for various apps that do not have a dark mode in my normal daily workflow.

A: As discussed in the comment section with @user3439894, we found there're three locations on OS Catalina where you can find the settings regarding to Invert Colors.
1) System Preferences > Accessibility > Display, use the checkbox to manually activate Invert Colors.
2) System Preferences > Keyboard > Shortcuts > Accessibility, use the checkbox to activate shortcut key Ctrl-Opt-Cmd-8 for Invert Colors. Also, do the following in point 3:
3) System Preferences > Accessibility > Shortcut, use the checkbox "Invert Display Color" to use shortcut key Ctrl-Opt-Cmd-8 for Invert Colors.
If you found the checkboxs for shortcut is already checked, but when you press shortcut key and it's not working, try to uncheck and recheck the checkboxs.

A: I had the same issue. But I found a temporary fix: cmd+alt+F5 to see Accessibility options window, then turn on 'Invert colours'. After that the shortcut will work until next login/screensaver.
I've just reset NVRAM/PRAM and shortcuts seem to work as expected! Finally!
https://support.apple.com/en-us/HT204063


text:
Q: Interpolation in PySpark throws java.lang.IllegalArgumentException I don't know how to interpolate in PySpark when the DataFrame contains many columns. Let me xplain.
from pyspark.sql.functions import to_timestamp

df = spark.createDataFrame([
    ("John",  "A", "2018-02-01 03:00:00", 60),
    ("John",  "A", "2018-02-01 03:03:00", 66),
    ("John",  "A", "2018-02-01 03:05:00", 70),
    ("John",  "A", "2018-02-01 03:08:00", 76),
    ("Mo",    "A", "2017-06-04 01:05:00", 10),
    ("Mo",    "A", "2017-06-04 01:07:00", 20),
    ("Mo",    "B", "2017-06-04 01:10:00", 35),
    ("Mo",    "B", "2017-06-04 01:11:00", 40),
], ("webID", "aType", "timestamp", "counts")).withColumn(
  "timestamp", to_timestamp("timestamp")
)

I need to group by webID and interpolate counts values at 1 minute interval. However, when I apply the below-shown code,
from operator import attrgetter
from pyspark.sql.types import StructType
from pyspark.sql.functions import pandas_udf, PandasUDFType

def resample(schema, freq, timestamp_col = "timestamp",**kwargs):
    @pandas_udf(
        StructType(sorted(schema, key=attrgetter("name"))),
        PandasUDFType.GROUPED_MAP)
    def _(pdf):
        pdf.set_index(timestamp_col, inplace=True)
        pdf = pdf.resample(freq).interpolate()
        pdf.ffill(inplace=True)
        pdf.reset_index(drop=False, inplace=True)
        pdf.sort_index(axis=1, inplace=True)
        return pdf
    return _

df.groupBy("webID").apply(resample(df.schema, "60S")).show()

Error:
py4j.protocol.Py4JJavaError: An error occurred while calling o371.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 77 in stage 31.0 failed 4 times, most recent failure: Lost task 77.3 in stage 31.0 (TID 812, 27faa516aadb4c40b7d7586d7493143c0021c825663, executor 2): java.lang.IllegalArgumentException
    at java.nio.ByteBuffer.allocate(ByteBuffer.java:334)

A: Set the environment variable ARROW_PRE_0_15_IPC_FORMAT=1.
https://spark.apache.org/docs/3.0.0-preview/sql-pyspark-pandas-with-arrow.html#compatibiliy-setting-for-pyarrow--0150-and-spark-23x-24x
def resample(schema, freq, timestamp_col = "timestamp",**kwargs):
    @pandas_udf(
        StructType(sorted(schema, key=attrgetter("name"))),
        PandasUDFType.GROUPED_MAP)
    def _(pdf):
        import os                                      # add this line
        os.environ['ARROW_PRE_0_15_IPC_FORMAT']='1'    # add this line
        pdf.set_index(timestamp_col, inplace=True)
        pdf = pdf.resample(freq).interpolate()
        pdf.ffill(inplace=True)
        pdf.reset_index(drop=False, inplace=True)
        pdf.sort_index(axis=1, inplace=True)
        return pdf
    return _

A: You can also do the resampling in pyspark without using an pandas UDF (or python UDF). The below solution will perform better for big datasets compared to the pandas UDF method and also prevents the error you get:
import pyspark.sql.functions as F

df = spark.createDataFrame([
    ("John",  "A", "2018-02-01 03:00:00", 60),
    ("John",  "A", "2018-02-01 03:03:00", 66),
    ("John",  "A", "2018-02-01 03:05:00", 70),
    ("John",  "A", "2018-02-01 03:08:00", 76),
    ("Mo",    "A", "2017-06-04 01:05:00", 10),
    ("Mo",    "A", "2017-06-04 01:07:00", 20),
    ("Mo",    "B", "2017-06-04 01:10:00", 35),
    ("Mo",    "B", "2017-06-04 01:11:00", 40),
], ("webID", "aType", "timestamp", "counts")).withColumn(
  "timestamp", F.to_timestamp("timestamp")
)
resample_interval = 1*60  # Resample interval size in seconds

df_interpolated = (
  df
  # Get timestamp and Counts of previous measurement via window function
  .selectExpr(
    "webID",
    "aType",
    "LAG(Timestamp) OVER (PARTITION BY webID ORDER BY Timestamp ASC) as PreviousTimestamp",
    "Timestamp as NextTimestamp",
    "LAG(Counts) OVER (PARTITION BY webID ORDER BY Timestamp ASC) as PreviousCounts",
    "Counts as NextCounts",
  )
  # To determine resample interval round up start and round down end timeinterval to nearest interval boundary
  .withColumn("PreviousTimestampRoundUp", F.expr(f"to_timestamp(ceil(unix_timestamp(PreviousTimestamp)/{resample_interval})*{resample_interval})"))
  .withColumn("NextTimestampRoundDown", F.expr(f"to_timestamp(floor(unix_timestamp(NextTimestamp)/{resample_interval})*{resample_interval})"))
  # Make sure we don't get any negative intervals (whole interval is within resample interval)
  .filter("PreviousTimestampRoundUp<=NextTimestampRoundDown")
  # Create resampled time axis by creating all "interval" timestamps between previous and next timestamp
  .withColumn("Timestamp", F.expr(f"explode(sequence(PreviousTimestampRoundUp, NextTimestampRoundDown, interval {resample_interval} second)) as Timestamp"))
  # Sequence has inclusive boundaries for both start and stop. Filter out duplicate Counts if original timestamp is exactly a boundary.
  .filter("Timestamp<NextTimestamp")
  # Interpolate Counts between previous and next
  .selectExpr(
    "webID",
    "aType",
    "Timestamp",
    """(unix_timestamp(Timestamp)-unix_timestamp(PreviousTimestamp))
        /(unix_timestamp(NextTimestamp)-unix_timestamp(PreviousTimestamp))
        *(NextCounts-PreviousCounts)
        +PreviousCounts
        as Counts"""
  )
)

I recently have written a blogpost that explains the reasoning behind the method and compares the performance with the pandas UDF method that you are using: https://medium.com/delaware-pro/interpolate-big-data-time-series-in-native-pyspark-d270d4b592a1


text:
Q: Is there a way to create an ACTION_NDEF_DISCOVERED intent from code For an app i'm writing i am wondering if it is possible to create an ACTION_NDEF_DISCOVERED intent from code. Normally this intent is created by the system when reading an ndef formatted tag. It contains a parcableextra of the type Tag.
The creation of the intent is probably easy but can you also create a Tag from code or is that not supported by the class as i suppose.
The goal is to broadcast a virtual tag with an ndef record to the system that then can be handled by an app that calls on the ACTION_NDEF_DISCOVERED intent.

A: You could get a mock tag object instance using reflection. Something like this should work:
NdefMessage ndefMsg = ...;

Class tagClass = Tag.class;
Method createMockTagMethod = tagClass.getMethod("createMockTag", byte[].class, int[].class, Bundle[].class);

final int TECH_NFC_A = 1;
final int TECH_NDEF = 6;

final String EXTRA_NDEF_MSG = "ndefmsg";
final String EXTRA_NDEF_MAXLENGTH = "ndefmaxlength";
final String EXTRA_NDEF_CARDSTATE = "ndefcardstate";
final String EXTRA_NDEF_TYPE = "ndeftype";

Bundle ndefBundle = new Bundle();
ndefBundle.putInt(EXTRA_NDEF_MSG, 48); // result for getMaxSize()
ndefBundle.putInt(EXTRA_NDEF_CARDSTATE, 1); // 1: read-only, 2: read/write
ndefBundle.putInt(EXTRA_NDEF_TYPE, 2); // 1: T1T, 2: T2T, 3: T3T, 4: T4T, 101: MF Classic, 102: ICODE
ndefBundle.putParcelable(EXTRA_NDEF_MSG, ndefMsg);

Tag mockTag = (Tag)createMockTagMethod.invoke(null,
        new byte[] { (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78 },
        new int[] { TECH_NFC_A, TECH_NDEF },
        new Bundle[] { null, ndefBundle });

The problem with this is that you will not be able to connect to this tag. Consequently, all methods of the Ndef object (that you can get from that mock Tag instance) that require IO operations with a real tag or a real tag that is registered with the NFC service will fail. Specifically, only

*

*getCachedNdefMessage(),

*getMaxSize(),

*getType(),

*isWritable(), and

*getTag()
will work.
So pretty much the same functionality would be available if you do not pass a Tag object as part of the NDEF_DISCOVERED intent and instead just use the EXTRA_NDEF_MESSAGES intent extra.


text:
Q: Do I have enable compression on nginx? I enabled compression on IIS6 and it works. But if I make request through a nginx server (on other server) to my IIS6 server, there is no compression at all.
Do I have to enable compression on nginx? If I have to then there is no need to enable compression on IIS6?

A: There are headers you need to send to indicate the client supports compression.
You may need to add smth like:
Accept-Encoding: gzip, deflate

to your client request. Be careful - you'll need to decompress the result!
Update:
In case your server is nginx (and not IIS6) - here is the section explaining how to enable compression in nginx.


text:
Q: Is this a security issue for WP GraphQL (wordpress)? Using postman I query:
query MyQuery {
  users {
    nodes {
        id
        email
    }
  }

With an authenticated request (and admin rights), I get:
{
    "data": {
        "users": {
            "nodes": [
                {
                    "id": "dXNlcjox",
                    "email": "..."
                },
                {
                    "id": "dXNlcjoz",
                    "email": ".........."
                },
                {
                    "id": "dXNlcjoy",
                    "email": "................."
                }
            ]
        }
    },
    "extensions": {
        "debug": []
    }
}

which returns all users and that's ok
BUT !!!
with a public request I get:
{
    "data": {
        "users": {
            "nodes": [
                {
                    "id": "dXNlcjox",
                    "email": null
                }
            ]
        }
    },
    "extensions": {
        "debug": []
    }
}

Why is the node with: "id": "dXNlcjox" exposed to a public request ?
Is this a security concern ?

A: Actually, this is ok.
Quoting from WP GraphQL page:

WPGraphQL follows WordPress access control rights, and only exposes data publicly that WordPress already exposes publicly. Users that have published posts are considered public entities in WordPress. Users that have not published posts are considered private and will not be included in public GraphQL requests, but will be included in GraphQL requests made by authenticated users with proper capabilities to see the users.
Fields, such as user email addresses, are also protected by WPGraphQL and only exposed to authenticated requests by users with proper capabilities to see the data.

This certain node: "id": "dXNlcjox" happens to be the admin which for wordpress, his existence is a public information (even if his email is not).


text:
Q: Making Data Structure Persistent I read a file in JAVA and based on the users specifications, I convert the data in to a Linked List or a Tree, but how can I save the data in to the file (as a data structure), so that next time I read the data I do not have to make extra effort to parse the file.

A:
You can save the data like this into file it is not a linked list but it will help to understand

//save persons
public void savePersons(){
try{
    PersonsInfo p;
    String line;
    FileWriter fw= new FileWriter("input.txt");
    PrintWriter pw= new PrintWriter(fw);
    for (int i=0 ; i<persons.size();i++){
        p =(PersonsInfo)persons.get(i);
        line = p.getName() +","+ p.getAddress() +","+ p.getPhoneNum();
        pw.println(line);
    }
    pw.flush();
    pw.close();
    fw.close();
} catch (IOException ioEx){
System.out.println(ioEx);
}

and you can retrieve the data like this and you dont need the parse the file every time

public class AddressBook{
ArrayList<PersonsInfo> persons;
public AddressBook (){
    persons = new ArrayList <PersonsInfo> ();
    loadPersons();
}
//Load Person
public void loadPersons (){
String tokens[]=null;
String name,address,phoneNum;
try{
    FileReader fr= new FileReader("input.txt");
    BufferedReader br= new BufferedReader(fr);
    String line=br.readLine();
    while (line !=null)
    {
        tokens = line.split(",");
        name=tokens[0];
        address=tokens[1];
        phoneNum=tokens[2];
        PersonsInfo p = new PersonsInfo(name,address,phoneNum);
        persons.add(p);
        line = br.readLine();
    }

br.close();
fr.close();

}catch (IOException ioEx) {
        System.out.println(ioEx);
}
}

A: It depends on how you want to store the data:

*

*If you don't want to data to be stored in human readable form then you can go ahead with Serialization (example here). Java will take care of storing/constructing the objects/structures during write/read operations respectively.

*If you want to store the data in human readable form then you can convert the data into let's say json and store it in String format. You can use Jackson's ObjectMapper class, e.g.:
ObjectMapper mapper = new ObjectMapper();
YourClass object = new YourClass();
FileOutputStream outputStream = new FileOutputStream("path_to_file");
outputStream.write(mapper.writeValueAsBytes(object));
//Read
YourClass persisted = mapper.readValue("path_to_file", YourClass.class);
Here's the example and here's Jackson's documentation.

A: You can use serialization which is a Java feature so very easy to use :
Save :
ObjectOutputStream oos = null;
try {
      LinkedList<String> list = new LinkedList<>();
      list.add("toto");  list.add("tata");

      oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\..\\Doc\\list.ser"));
      oos.writeObject(list);
} catch ... {
}finally (oos.close) ...{
}

Of course, if it's not a you change LinkedList to whatever you want

Load :
ObjectInputStream ois = null;

try {
    ois = new ObjectInputStream(new FileInputStream("C:\\Users\\..\\Doc\\list.ser"));

    final LinkedList<String> list = (LinkedList<String>) ois.readObject();
    System.out.println(list.toString());   //[toto,tata]
} catch ... {
}finally (ois.close) ...{
}

At writing you use writeObject and at reading you use readObject + casting to the good type (so the order is important, if you write a List then String then Other, you may read List then String then Other)
Serialization Details


text:
Q: Multiple consumers using spring kafka I am looking to setup multiple listeners on a kafka topic inside my application. Below is my setup. it is supposed to be consumed by both the groups, but it is consumed by only one listener. What am i missing here?
@Bean
public Map<String, Object> consumerConfigs() {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, groupName);

    return props;
}

@Bean
public ConsumerFactory<String, String> consumerFactory() {
    ConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory(consumerConfigs());
    return consumerFactory;
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(100);
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

@Bean("notificationFactory")
public ConcurrentKafkaListenerContainerFactory<String, String> notificationFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(100);
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

@Bean("insertContainerFactory")
public ConcurrentKafkaListenerContainerFactory<String, String> insertContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConcurrency(100);

    factory.setConsumerFactory(consumerFactory());
    return factory;
}

@KafkaListener(id = "insert_listener", topics = "${kafka.topic.readlocation}", group = "insert_listener", containerFactory = "insertContainerFactory")
public void receiveForInsert(String message) {
    locationProcessor.insertLocationData(message);
}

@KafkaListener(id = "notification_listener", topics = "${kafka.topic.readlocation}", group = "notification_listener",containerFactory="notificationFactory")
public void receiveForNotification(String message) {
    locationProcessor.processNotificationMessage(message);
}

Edit: Below is the code that worked
@KafkaListener(id = "insert_listener", topics = "${kafka.topic.readlocation}", groupId = "insert_listener")
public void receiveForInsert(String message) {
    locationProcessor.insertLocationData(message);
}

A: You need a different group.id for each; the group property is not the group.id - see the javadocs. In the upcoming 1.3 release, there is a new groupId property and we also can use the id as a group if present.
For earlier version you need a different consumer factory for each.


text:
Q: iOS/UIKit: Keep size during rotation I am trying to have a UIView centered at the middle of the screen that is 320x240 when the device is in the landscape orientation and 240x320 when in the portrait orientation.
For example:

If I let UIKit's layout system do it on its own, I get this when rotating landscape:

And if I try to pin the width and height, I get this:

Basically, is there any way to keep the dimensions of an object during a rotation (but still rotate the object)? Preferably using only Interface Builder, and/or a minimal amount of code if that is not possible.

A: I think JeffCompton is right: there is no way for you to change the size of your view given the orientation using just the XIB / Autolayouts / Autoresizing masks.
I think the simplest way to do that is:
- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    [UIView animateWithDuration:0.3 animations:^(void) {
        if(UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
            self.yourView.frame = CGRectMake([UIScreen mainScreen].frame.size.width-320/2,[UIScreen mainScreen].frame.size.height-240/2,320,240);
        } else {
            self.yourView.frame = CGRectMake([UIScreen mainScreen].frame.size.width-240/2,[UIScreen mainScreen].frame.size.height-320/2,240,320);
        }
    }];
}


text:
Q: How do I find the center of a number of geographic points? If I have a series of points as longitude and latitude, how would I calculate the center of all of those points?

A: Several people have answered to take the mean of the latitudes and longitudes. This is sort of the right idea, but means are more complicated on the sphere.
The latitude/longitude representation is essentially artificial and has discontinuities (at the poles, and opposite the prime meridian if you aren't careful), so it taking means in it doesn't seem likely (to me) to have a sensible geometric interpretation. I think you need to do something like averaging vectors in earth-centered coordinates, and then normalizing the result to put it back on the sphere.
I hope someone with more experience in these matters can comment more concretely.

A: Don't just take averages.
You can convert to 3d coordinates, then take the average (of x,y, and z coords), then project it back onto the sphere and turn that back into lat/long.
The wikipedia page on spherical coordinates has conversion algorithms.

A: First off, you need to define which centre you're interested in. Take these two points:
A.                          .B

The centre is easy, it's halfway between them. Now add a third point:
A. C.                       .B

Is the centre still halfway between A and B or is it weighted towards A because of C? So is the centre the point nearest to all points or just the points on the enclosing polygon?
Also, as it's long/lat you're dealing with the points are on a surface of a sphere so the distance between long 0 and long 90 degrees is much greater at lat 0 than at lat 45 degrees.

A: Geomidpoint covers 3 different methods for calculating this.

A: You're probably looking for the centroid of the simple polygon defined by the points.  There is information on how to calculate it for various geometries in that article.

A: Wolfram Alpha will do this for you if you ask the question in the following form:
centroid of polygon with vertices: (X, Y), (X, Y), (X, Y), (X, Y), (X, Y), etc.
Just remember to convert each "(X, Y)" into decimal form first.
Wolfram Alpha will return the answer in decimal form, which you can then copy and paste into Google Earth.

A: See Moe's answer, although if your points are distributed across the globe, you'll have to be satisfied that your center tends towards the Prime Meridian and not the International Date Line.


text:
Q: Bean Creation exception using spring 4.0.5 enter code hereBelow are the logs, kindly help
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accessControlController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ccube.pod.service.AccessControlService com.ccube.pod.webservice.AccessControlController.accessControlService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ccube.pod.service.AccessControlService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at com.sun.jersey.spi.spring.container.servlet.SpringServlet.getChildContext(SpringServlet.java:176)
    at com.sun.jersey.spi.spring.container.servlet.SpringServlet.getContext(SpringServlet.java:140)
    at com.sun.jersey.spi.spring.container.servlet.SpringServlet.initiate(SpringServlet.java:117)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5262)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5550)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ccube.pod.service.AccessControlService com.ccube.pod.webservice.AccessControlController.accessControlService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ccube.pod.service.AccessControlService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 31 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ccube.pod.service.AccessControlService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 33 more

Servlet context file
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
    http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
    http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving
    up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources
    in the /WEB-INF/views directory -->
<beans:bean

class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.ccube.pod" />

<!-- <context:property-placeholder location="classpath:db.properties" /> -->

<beans:bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="url"
        value="jdbc:mysql://localhost:3306/pod" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="span123" />
</beans:bean>

<beans:bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"></beans:property>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.ccube.pod.model.User
            </beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
            <beans:prop key="hibernate.show_sql">false</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

 </beans:beans>

Controller code
@Component
@Path("/user")
public class AccessControlController
{
@Autowired
private AccessControlService accessControlService;

public AccessControlService getAccessControlService() {
    return accessControlService;
}

public void setAccessControlService(AccessControlService
accessControlService) {
    this.accessControlService = accessControlService;
}

@GET
@Path("/testJersey")
public String testJersey(){
    System.out.println("working");
    return "success";
}

Service layer - auto wire is defined. It contains mapping to DAO layer.I have given the annotations. But still says bean not found.
Can there be some problem related jar files like version conflicts.
public class AccessControlService implements AccessControlServiceInf
{
@Autowired
private AccessControlDAOImp accessControlDAOImp;

public AccessControlDAOImp getAccessControlDAOImp() {
    return accessControlDAOImp;
}

public void setAccessControlDAOImp(AccessControlDAOImp accessControlDAOImp)
{
    this.accessControlDAOImp = accessControlDAOImp;
}

A: It's obvious from error. When Spring tries to create accessControlController bean, there is an @Autowire annotated field. Spring looks up for a bean of type com.ccube.pod.service.AccessControlService, but there is no such bean of that type in Spring context.
Check why you have no bean of required type.

A: After lot of going through the net and questions in Stack overflow
I found the error,
we have to add @service and @repository annotations to the service and dao classes.


text:
Q: Refuse the connection to a service I would create a WCF service with some methods. One of these methods (that is, the Connect method) should be the first to be called in order to use the service: in other words, before you can use all other methods of service, must be called the Connect method. For this reason, I defined it with IsInitiating property set to true, and I have defined the other methods with this property set to false.
In addition, the node offering the service must be able to refuse the connection request from another node (for example, if other nodes are already using the service): is there a way to prevent the use of the service?
Thanks a lot!

A: Well, sure.
First understand that by default, WCF services are an "instance-per-request" construct; The HttpApplications that IIS maintains in the app pool will "new up" a copy of your service contract class, make the call pertaining to the request, then the object will go out of scope and be destroyed. You can override this by stating that your service should run in "instance-per-session" mode:
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyServiceContract
{
   ...
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyServiceImplementation: IMyServiceContract
{
   ...
}

Now, when your service is called, a "session" is established between client and server, and a single copy of your class will be created and remain in memory for the life of that session (unless the app pool is refreshed, which can happen automatically or by a manual action within IIS). This is the first step.
Now, you can do one of two things:

*

*Simply check in any method besides Connect() whether Connect() has been called on this instance since its creation. If not, throw out.

*Have the Connect() method return some instance-scoped token or GUID that the client must then pass to all other method calls. If the GUID the caller provides doesn't match the one kept in instance memory, then throw out of the method.
Understand that sessions can time out between requests. If this happens, your current instance will leave scope and be destroyed, and a new instance will be created to handle subsequent requests. I would thus opt for the second option even though the system can identify instances based on their session; the GUID ensures that both the client AND service instance have not changed since the last call.


text:
Q: Can't count words from richtextbox to label? I'm not sure what's wrong here, but i'm trying to count words in a richtext box, and display that with a label.
I put a richtextbox in a tab control so I can have a tabbed text box. Which seems to make this a lot harder then it should
also this isn't the whole program, I took the parts relating to the richtextbox and word counter
Any help is appreciated :)
    public RichTab()
    {
        InitializeComponent();
        TabPage tp = new TabPage("Document");
        RichTextBox rtb = new RichTextBox();
        rtb.Dock = DockStyle.Fill;
        tp.Controls.Add(rtb);
        tabControl1.TabPages.Add(tp);
        WordCount();
    }

    public RichTextBox RTTB()
    {
        RichTextBox rtb = null;
        TabPage tp = tabControl1.SelectedTab;
        if (tp != null)
        {
            rtb = tp.Controls[0] as RichTextBox;
        }
        return rtb;
    }

    private void WordCount()
    {
        MatchCollection wordColl = Regex.Matches(RTTB().Text, @"[\W]+");
        label2.Text = wordColl.Count.ToString();
    }

A: I would probably just wire up the TextChanged event of the RichTextBox, and count the words there:
rtb.TextChanged += rtb_TextChanged;

Then count the words (using Giorgio Minardi's regex):
private void rtb_TextChanged(object sender, EventArgs e) {
  label2.Text = Regex.Matches(((RichTextBox)sender).Text, @"[\S]+").Count.ToString();
}

A: What's the actual issue ?
Here's a simple routine to count words:
[Test]
public void CountWords()
{
    const string sample = "How you doing today ?";
    MatchCollection collection = Regex.Matches(sample, @"[\S]+");
    var numberOfWords = collection.Count;
    //numberOfWords is 5
    Assert.IsTrue(numberOfWords == 5);
}


text:
Q: how to get the background color of a div inside input - JavaScript I dont know why this code is not working! why is it showing the alert blank?

        <title>Document</title>

        Color <input id="in1" type="text">

when the div is clicked the background color of the div should be written inside the input box and also shown in the alert.

A: Have this, it will compute the rgb color:
`

    var colorTextBox = document.getElementById("in1");
                var div = document.getElementById("dd");

                div.onclick = function(){
                    //colorTextBox.value = div.style.backgroundColor;
            //alert(div.style.backgroundColor);

            const element = document.querySelector('#dd');
            const style = getComputedStyle(element)
            var color= style.backgroundColor;
            alert(color);
                }

            <title>Document</title>

            Color <input id="in1" type="text">

`

A: Element.style.


text:
Q: Sequelize - Trouble with includes association What is happening?
I have a vehicle/announce route that returns all vehicles from the application, I have cars, motorcycles, agricultural machines, and agricultural implements. My problem is when it comes to returning data from agricultural machines and agricultural implements.
Sequelize Query
Annoucement.findAll({
        include: [{
            model: AnnoucementVehicle,
            include: [{
                model: Itens,
                include: [{
                    model: AgriculturalMachine,
                }],
                include: [{
                    model: Vehicle,
                    include: [{
                        model: OptionalHasVehicles,
                        // as: 'Optionals',
                        include: [{
                            model: Optional,
                        }]
                    }, {
                        model: VehicleHasFeatures,
                        include: [{
                            model: Features,
                        }],
                        // as: 'Optionals',
                    }, {
                        model: Fipe,
                        include: [{
                            model: Fuel,
                        }]
                    }]
                }],

            }, {
                model: VehicleImages
            }, {
                model: Person
            }]
        }],
        order: [
            ['id', 'DESC']
        ],
    }).then((result) => {
        return res.json({ success: true, result: result })
    }).catch((err) => {
        return res.status(400).json(err)
    });

JSON with an announcement car
{
  "success": true,
  "result": [
    {
      "id": 311,
      "active": true,
      "announcement_vehicle": {
        "idAnnouncementVehicles": 311,
        "price": null,
        "video": null,
        "description": null,
        "personId": 1,
        "itemId": 297,
        "payed": false,
        "plans_id": null,
        "createdAt": "2020-05-20T19:05:18.000Z",
        "updatedAt": "2020-05-20T19:05:18.000Z",
        "iten": {
          "id": 297,
          "type": "1",
          "vehicle": {
            "item_id": 297,
            "mileage": null,
            "license": null,
            "new": 0,
            "armoured": 0,
            "fuel_id": 1,
            "cambium_id": 1,
            "color_id": 1,
            "door_id": 1,
            "fipe_id": 1,
            "createdAt": "2020-05-20T19:05:18.000Z",
            "updatedAt": "2020-05-20T19:05:18.000Z",
            "optional_has_vehicles": [
              {
                ...
              }
            ],
            "vehicles_has_features": [
              {
                ...
                "feature": {
                  ...
                }
              },
            ],
            "fipe": {
              ....
              "fuel": {
                "id": 2,
                "description": "Gasolina"
              }
            }
          }
        },
        "announcemment_photos": [],
        "person": {
          ...
        }
      }
    },

But when it is an agricultural implement or agricultural machine, it returns me to where the vehicle arrives and shows how vehicle: null.
What have I tried?
I tried to put below at association: AnnouncementVehicle.associations.iten something like
include: [{ association: AnnouncementVehicle.associations.agricultural_machine }].
Returns me the same JSON that I put above
What did I notice?
I realized that it always returns the last association, maybe something that I'm trying to do two include for two tables starting from the same. I put the association of agricultural machines well after the association of vehicles, and returned agricultural_machine: null and not returned vehicles.
Agricultural Machine Model
module.exports = function (sequelize, DataTypes) {
  const agricultural_machine = sequelize.define('agricultural_machine', {
    agricultural_machine_id: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: false,
      primaryKey: true,
      references: {
        model: 'itens',
        key: 'id'
      },
      references: {
        model: 'agricultural_implement',
        key: 'agricultural_implement_id'
      },
      references: {
        model: 'tractor',
        key: 'tractor_id'
      }
    },
    worked_hours: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    year: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    brand_agricultural_machine_id: {
      type: DataTypes.INTEGER(5).UNSIGNED.ZEROFILL,
      allowNull: false,
      primaryKey: true,
      references: {
        model: 'brand_agricultural_machine',
        key: 'id'
      }
    },
    model_agricultural_machine_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      references: {
        model: 'model_agricultural_machine',
        key: 'id'
      }
    }
  }, {
    tableName: 'agricultural_machine',
    timestamps: false
  });

  agricultural_machine.associate = (models) => {
    agricultural_machine.hasOne(models.tractor, { foreignKey: 'tractor_id' });
    agricultural_machine.hasOne(models.agricultural_implement, { foreignKey: 'agricultural_implement_id' });
    agricultural_machine.belongsTo(models.itens, { foreignKey: 'agricultural_machine_id' });
    agricultural_machine.belongsTo(models.brand_agricultural_machine, { foreignKey: 'brand_agricultural_machine_id' });
    agricultural_machine.belongsTo(models.model_agricultural_machine, { foreignKey: 'model_agricultural_machine_id' });
    //announcement_vehicles.belongsTo(models.persons,{foreignKey: 'personId'});
    //announcement_vehicles.hasMany(models.announcemment_photos,{foreignKey: 'annoucements_id', constraints: false});
  };

  return agricultural_machine;
};

Itens Model
module.exports = function (sequelize, DataTypes) {
  const itens = sequelize.define('itens', {
    id: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    type: {
      type: "SET('1','2','3','4')",
      allowNull: false,
      defaultValue: '1'
    }
  }, {
    tableName: 'itens',
    timestamps: false
  });
  itens.associate = (models) => {
    itens.hasOne(models.vehicles, { foreignKey: 'item_id' });
    itens.hasOne(models.agricultural_machine, { foreignKey: 'agricultural_machine_id' });
  }

  return itens
};

Announcement Vehicle Model
module.exports = function (sequelize, DataTypes) {
  const announcement_vehicles = sequelize.define('announcement_vehicles', {
    idAnnouncementVehicles: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: false,
      primaryKey: true,
      references: {
        model: 'annoucements',
        key: 'id'
      }
    },
    price: {
      type: DataTypes.DECIMAL,
      allowNull: true
    },
    video: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    personId: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: true,
      references: {
        model: 'persons',
        key: 'id'
      }
    },
    itemId: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: true,
      references: {
        model: 'itens',
        key: 'id'
      }
    },
    payed: {
      type: DataTypes.BOOLEAN,
      allowNull: true
    },
    plans_id: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: true
    }
  }, {
    tableName: 'announcement_vehicles'
  });

  announcement_vehicles.associate = (models) => {
    announcement_vehicles.belongsTo(models.itens, { foreignKey: 'itemId', constraints: false });
    announcement_vehicles.belongsTo(models.persons, { foreignKey: 'personId' });
    announcement_vehicles.hasMany(models.announcemment_photos, { foreignKey: 'annoucements_id', constraints: false });
  }

  return announcement_vehicles
};

Announcement Model
module.exports = function(sequelize, DataTypes) {
  var annoucements = sequelize.define('annoucements', {
    id: {
      type: DataTypes.INTEGER(11).UNSIGNED.ZEROFILL,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    active: {
      type: DataTypes.BOOLEAN
    }
  }, {
    tableName: 'annoucements',
    timestamps: false
  });
  annoucements.associate = (models) => {
    annoucements.hasOne(models.announcement_vehicles,{foreignKey: 'idAnnouncementVehicles', constraints: false});
  }
  return annoucements
};

JSON that I receive when it's Agricultural Machine or Agricultural Implements
 {
      "id": 306,
      "active": true,
      "announcement_vehicle": {
        "idAnnouncementVehicles": 306,
        "price": "500.000,00",
        "video": null,
        "description": "TESTE TIPO 4",
        "personId": 1,
        "itemId": 292,
        "payed": false,
        "plans_id": null,
        "createdAt": "2020-05-18T23:57:18.000Z",
        "updatedAt": "2020-05-18T23:57:18.000Z",
        "iten": {
          "id": 292,
          "type": "4",
          "vehicle": null
        },
        "announcemment_photos": [],
        "person": {
          "id": 1,
          "email": "teste@gmail.com",
          "password": "$2b$10$3OZVFYWeXKWLfxBMWJBYqua0qJPQkLl3sVgIFvZFuo6qBKj62dMQS",
          "name": "teste",
          "type": "fis",
          "createdAt": "2020-05-14T00:12:59.000Z",
          "updatedAt": "2020-05-14T00:12:59.000Z"
        }
      }
    },

The Diagram with the models mentioned

A: All includes should look like:

 include: [{
        model: AnnoucementVehicle,
        as: 'Alias' // optional if you didn't indicate this alias in an association definition

In case of Itens includes it must be:
model: Itens,
  include: [{
    model: AgriculturalMachine,
  }, {
    model: Vehicle,
    include: [{
    ... // other includes
  }, {
    model: AgriculturalImplements,
  }, {
    model: Vehicle,
    include: [{
    ... // other includes


text:
Q: MongoDB Update object inside Multi Nested Array I am making a project using NodeJS and MongoDB.
I am using mongoose as well.
I have the following collection:
array1:[
    {
        field1:{type:String,default:null}
        array2:[
            {
                id:{type:String,default:null},
                field1:{type:String,default:null},
                field:{type:String,default:null}
            }
        ]
    }
]

So I want to update "field1" and "field2" inside "array2" using the "id" but I am unable to achieve this with update query. Can you please suggest me on how to achieve this using update query?
Currently to update it I used
document.save(function(error,response){});

Thanks in advance.

A: The best way i believe is to set the array2 as an array of a collection, and create a new collection for this object of array2.Doing that and having the id you can easily find it usign Collection.findById, and also it would get a better performance as you won't need to read and allocate memory for all values of array1 and array2 before finding the object you want.


text:
Q: Escaped Strings in Parsing Expression Grammars I am attempting to write a grammar for a small language utility using the python library parsimonious, but I am struggling with writing a part, which covers strings, especially strings with escaped quotes and other special characters.
I have the following:
string         = doubleString / singleString
doubleString   = "\"" escapedString "\""
singleString   = "'" escapedString "'"

escapedString is as if yet undefined, but should accept anything one would reasonably expect a string in a programming language to accept. I cannot think of where to begin. Does anyone have any suggestions?

A: I don't know parsimonious's syntax, but in a regex-style one I'd do something like:
string         = doubleString / singleString
doubleString   = ~'"([^"]|(\"))*"'
singleString   = ~"'([^']|(\'))*'"

i.e. you'd need a different escaped string for each kind of string, each made of a possibly empty sequence of either characters that are not the end quote char or escaped end quote chars.

A: You may want to do two things here.  The first is adding the prefix r before your string.  The other thing you would probably want to do is use triple quotes i.e """.  The use of the prefix will make it so that escape sequences in strings are "interpreted according to rules similar to those used by Standard C".  The second is to take care of any extra quotes/apostrophes that would otherwise make your string quit early.
Consider the following example:
string = r"""this %is m%y crazy s"\tri""'""ng\s\n%\d\\r''\'"""
print string

This may not work if there are also triple quotes in the string you are feeding thou; I'm not sure how one goes about dealing with that.


text:
Q: VBA Multiply Last 3 Cells of 2 Columns to be Expandable I'm trying to multiply 2 values in another worksheet named "DATA" and then multiply 2 more values underneath it. This must be expandable so when more values are added to the spreadhseet, the cells with the calculations update. Those calculations are placed in a worksheet called "Report" in cells C9:C11.
I'm wanting to multiply cell 45 of column B by cell 45 of column C. Then, multiply cell 46 of column B by cell 46 of column C, finally multiply cell 47 of column b by cell 47 of column c.
If new data is added for example another 3 cells to columns B and C, this should update to accommodate the data and multiply those values.
My code which is static:
Range("C9").Select
ActiveCell.FormulaR1C1 = "=DATA!R[30]C[-1]*DATA!R[30]C"
Range("C9").AutoFill Destination:=Range("C9:C11"),  Type:=xlFillDefault

Spreadsheet: https://imgur.com/a/32hXkDk
Where calculations should go: https://i.stack.imgur.com/T61IS.png
Code:
Sub HourStraightOnetoTwo()
Dim lRow As Integer
Dim rangex As Range, rangey As Range, rangey2 As Range, rangey3 As Range, rangey4 As Range
Dim rangexMonth As Range, rangeInvNorm As Range, rangeInvFore As Range
Dim srs As Series
Dim ws As Worksheet

' Selects the entirety of column A and formats the date to be in the format of mmm-dd
Columns("A:A").Select
Selection.NumberFormat = "[$-en-US]mmm-yy;@"

' Deletes the sheet named Report if it exists
For Each ws In Sheets
    If ws.Name = "Report" Then
        Application.DisplayAlerts = False
        Sheets("Report").Delete
        Application.DisplayAlerts = True
        Exit For
    End If
Next

With Sheets("DATA")
.Activate
' Adds titles to forecast columns
.Range("J1").Value = "Production Forecast"
.Range("K1").Value = "Demand Forecast"
.Range("L1").Value = "Inventory Forecast"
' Selects the Last Row
lRow = Worksheets("DATA").Range("B" & Rows.Count).End(xlUp).Row
' Copies the last 3 cells in column 2, Production Units
.Range(.Cells(lRow - 3, 2), .Cells(lRow, 2)).Copy
' Pastes those last 3 cells in column 10, Production Forecast
.Range(.Cells(lRow - 3, 10), .Cells(lRow, 10)).PasteSpecial Paste:=xlPasteValues
' Copies the last 3 cells in column 5, Demand
.Range(.Cells(lRow - 3, 5), .Cells(lRow, 5)).Copy
' Pastes those last 3 cells in column 11, Demand Forecast
.Range(.Cells(lRow - 3, 11), .Cells(lRow, 11)).PasteSpecial Paste:=xlPasteValues
' Calculates Inventory
lRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' Subtracts Production Units from Demand
.Cells(2, "G").FormulaR1C1 = "=RC[-5]-RC[-2]"
' Subtracts Production Units from Demand and adds the previous month's Inventory
.Range(.Cells(3, "G"), .Cells(lRow, "G")).FormulaR1C1 = "=RC[-5]-RC[-2]+R[-1]C"
' Calculates next 3 months of Inventory - Redundant but needed for how this is coded
.Range(Cells(lRow - 3, 12), Cells(lRow, 12)).FormulaR1C1 = "=RC[-2]-RC[-1]+R[-1]C[-4]"
.Range(Cells(lRow - 2, 12), Cells(lRow, 12)).FormulaR1C1 = "=RC[-2]-RC[-1]+R[-1]C"

End With

' Add the Report worksheet
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Report"
 With Sheets("Report")
.Range("A2") = Now()
.Range("A3").Value = "Dear Madam/Sir,"
.Range("A5").Value = "The following are the projected production, inventory, and total costs for the following"
.Range("A6").Value = "three months."
 End With

Sheets("DATA").Activate
' Use this lRow now since the previous one require you to be in a With loop
Range(Cells(lRow - 2, 1), Cells(lRow, 1)).Copy

' THIS IS A WORK IN PROGRESS
With Sheets("Report")
.Activate
' Pastes the last 3 cells of Column A into the Month column
.Range("B9").PasteSpecial Paste:=xlPasteAll
Columns("A:A").ColumnWidth = 13.71
Columns("C:C").ColumnWidth = 13.71
Columns("D:D").ColumnWidth = 13.71
.Range("B8").Formula = "Month"
.Range("C8").Formula = "Production Cost"
.Range("A14").Formula = "Figure below illustrates the production unit, and the demand time series for the past year;"
.Range("A15").Formula = "as well as the forecast for the following three months."
.Range("A28").Formula = "Figure below illustrates the inventory levels for the past year, as well as the forecast for the"
.Range("A29").Formula = "following three months."
.Range("A41").Formula = "Regards,"
.Range("A42").Formula = "name"
.Range("A43").Formula = "email"
' Calculates the Production cost
Range("C9").Select
ActiveCell.FormulaR1C1 = "=DATA!R[30]C[-1]*DATA!R[30]C"
Range("C9").AutoFill Destination:=Range("C9:C11"), Type:=xlFillDefault
' Calculates the Inventory cost
Range("D9").Select
ActiveCell.FormulaR1C1 = "=DATA!R[30]C[3]*DATA!R[30]C"
Range("D9").AutoFill Destination:=Range("D9:D11"), Type:=xlFillDefault
Range("D10").Select
.Range("C14").Select
.Range("D8").Formula = "Inventory Cost"
.Range("E8").Formula = "Total Cost"
.Range("B12").Formula = "Total"
' Sums Production Cost for the last 3 months
.Range("C12").Formula = "=SUM(C9:C11)"
' Fills in the adjacent cells to the right
.Range("C12").AutoFill Destination:=Range("C12:E12"), Type:=xlFillDefault
' Sums Production and Inventory Cost for one month
.Range("E9").Formula = "=SUM(C9:D9)"
' Fills in the cells below
.Range("E9").AutoFill Destination:=Range("E9:E11"), Type:=xlFillDefault
End With


text:
Q: Trying to get rid of unwraps I have this line in my program:
let date = file.metadata().unwrap().modified().unwrap();
Can it be changed into form of if let Ok(date) = file.metadata().something.... and still be one liner?
Forgot to add: can't use ? operator, bc this is in a closure in for_each().

A: Using Result::and_then:
if let Ok(date) = file.metadata().and_then(|md| md.modified()) {
    // stuff
}

Using the "try" operator (?):
// containing function returns `Result<T, E>` where `E: From<io::Error>`
let date = file.metadata()?.modified()?;

A: If you're inside a closure which must return (), and you want to ignore the error, I'd actually recommend using let else as such:
let Ok(metadata) = file.metadata() else { return };
let Ok(date) = metadata.modified() else { return };
// ...

This has the advantage that it doesn't increase the indentation level.


text:
Q: CSS: divs are pushed down in the container I've put together this bit of html and css to display featured items for a homepage, but for some reason the contents of the box seem to make the boxes float to the bottom of the containing div and depending on the amount of text this means the boxes become miss-aligned.
I want the boxes to all remain the same height and all be aligned along the top of the blue div.
CSS:
@import url(http://fonts.googleapis.com/css?family=Bree+Serif);
@import url(http://fonts.googleapis.com/css?family=Open+Sans);

.icon_css { background: url(http://fauxbyte.esy.es/_codepen_resources/icon_css.png) #FFF; background-size: 80px; background-repeat: no-repeat; background-position: center; }
.icon_php { background: url(http://fauxbyte.esy.es/_codepen_resources/icon_php7.png) #FFF; background-size: 75px; background-repeat: no-repeat; background-position: center; }
.icon_jquery { background: url(http://fauxbyte.esy.es/_codepen_resources/icon_jquery.gif) #FFF; background-size: 110px; background-repeat: no-repeat; background-position: center; }
.icon_bootstrap { background: url(http://fauxbyte.esy.es/_codepen_resources/icon_bootstrap.gif) #FFF; background-size: 160px; background-repeat: no-repeat; background-position: center; }

body { margin: 0px; }

h1 {
  text-align: center;
  font-family: 'Bree Serif', 'serif';
  font-size: 50px;
  color: #444;
  font-weight: lighter;
}

.featuredItemWrap {
  background: #E7E7E7;
  width: 250px;
  height: inherit;
  display: inline-block;
  margin-right: 5px;
  margin-left: 5px;
  margin-top: 25px;
  text-align: center;
}

.featuredItemOuterWrap {
  background: #009CEF;
  width: 100%;
  height: auto;
  padding-bottom: 20px;
  text-align: center;

}

.featuredItemInner {
}

.featuredItemDesc {
  background: none;
  padding: 0px 20px 40px 20px;
  color: #444;
  font-family: 'Open Sans', sans-serif;
}

.featuredItemDesc h1 {
  font-family: 'Bree Serif', 'serif';
  font-size: 25px;
}

.featuredItemIcon {
  width: 150px;
  height: 150px;
  margin-left: auto;
  margin-right: auto;
  margin-top: -40px;
  border-radius: 50%;
  border: 10px solid #E7E7E7;
}

CodePen

A: You can use flex layout for .featuredItemOuterWrap container and its' inner items:
.featuredItemOuterWrap{
  display:flex;
  justify-content:center;
}

CodePen

A: Never mind, I solved it myself.
Simply used vertical-align: top; on my .itemDivs.


text:
Q: Compiler warning - something differs in parameter lists I'm trying to compile the following source code which successfully compiles on both gcc and Microsoft's cl.exe.
void SomethingBeforeExit();

void SomethingBeforeExit()
{
    // some code
    _exit(0);
}

int main(int argc, char *argv[])
{
    // some code
    atexit(SomethingBeforeExit);
}

However, I'm getting a C4113 warning from cl.exe with the following message:
SomeCode.c(10): warning C4113: 'void (__cdecl *)()' differs in parameter lists from 'void (__cdecl *)(void)'

As I said, the source code still compiles successfully and appears to work. My goal is to prevent this warning from happening in cl, as gcc doesn't generate any warnings upon compilation.
I assume that the declaration of that function is not being treated as void SomethingBeforeExit(void), however, I don't know how to specifically declare a function's parameter list as void.
I'm using VS14 and C/C++ 19.00.23918 for x86 for cl.exe and gcc v5.4.0 compilers to compare generated warnings.

A: In C, empty parentheses in a function declaration doesn't mean "no parameters." Instead, it means any number of parameters (similar to ... in C++). Perhaps what you meant to declare was void SomethingBeforeExit(void).

A: OP is not using a compliant C99/C11 compiler.  The code is valid C (C99/C11).
// declares function SomethingBeforeExit and no info about it parameters.
void SomethingBeforeExit();

// declares/defines function SomethingBeforeExit and
// indirectly specifies the parameter list is `(void)`
// This does not contradict the prior declaration and so updates the parameter signature.
void SomethingBeforeExit() {
   ...
}

int main(int argc, char *argv[]) {
  ...
  // `atexit() expects a `void (*f)(void))`
  atexit(SomethingBeforeExit);

In C89 the void SomethingBeforeExit() { ...} definition still says nothing about the parameter list.  This is likely the cause of OP's problem.
To fix:
void SomethingBeforeExit(void) {
  ...
}

The prior void SomethingBeforeExit(); declaration need not update, yet would be in good to also update that so parameter checking can happen with code that does not see the definition.


text:
Q: How can I install Microsoft Word & Excel in Ubuntu 14.04? I need to install Microsoft Word & Excel in Ubuntu 14.04.
Please assist step by step as I am new to Ubuntu.
Thanks!

A: You can use Wine AppDB for MS Office 2010 (32-Bit) for running MS Office on your Ubuntu . Wine Version 1.5.13 or better is required for greater compatibility.
Although I'd recommend using Libre Office instead of MS as it's already installed and works as fine as MS .

A: A sure solution is to use  a virtual machine with minimal winxp install using nLite & office 2003. Its is fast and with recent updates to VirtualBox it can be seamless.

A: They can not be installed in Ubuntu. using wine is a nightmare. If you insist using them I suggest install a windows in vbox and install them in windows there.


text:
Q: Show that $\left|\int_a^b f(x) dx\right|\leqslant \frac{M}{12}(b-a)^3$? $f$ is second order diffierentiable over $[a,b]$, $f(a)=f(b)=0$, $|f''(x)|\leqslant M$, Show that $\left|\displaystyle\int_a^b f(x) dx\right|\leqslant \dfrac{M}{12}(b-a)^3$?
To make out the coefficient $\dfrac{1}{12}$, I tried this way:
Write that $c=\dfrac{a+b}{2}$, according to the Taylor's formula,
$$f(x)=f(c)+f'(c)(x-c)+\dfrac{f''(\eta)}{2}(x-c)^2,$$
Putting $x=a, x=b$, notice that $f(a)=f(b)=0$, then
$$
         \begin{split}
          0&=f(c)+f'(c)(a-c)+\dfrac{f''(\eta_1)}{2}(a-c)^2,\\
          0&=f(c)+f'(c)(b-c)+\dfrac{f''(\eta_2)}{2}(b-c)^2,\\
         \end{split}
$$
Then according to Darboux theorem, there exists $\zeta$ such that
$$f(c)=-\dfrac{(b-a)^2}{16}(f''(\eta_1)+f''(\eta_2))=-\dfrac{(b-a)^2}{8}f''(\zeta).$$
Then
$$f(x)=\color{red}{{-\dfrac{(b-a)^2}{8}f''(\zeta)}}+\color{blue}{f'(c)(x-c)}+\color{green}{\dfrac{f''(\eta)}{2}(x-c)^2}.$$
Integrate both sides, the red part gives $-\dfrac{1}{8}$, the blue part gives zero, and the green part gives $\dfrac{1}{24}$, then the coeffcient $\dfrac{1}{12}$ shows up.
However, I cannot get a proper inequality from this.

A: Let $c:=\dfrac{a+b}{2}$. Integration by parts (using $f(a)=0$ and $f(b)=0$) gives $$\int_a^b\,f(x)\,\text{d}x=-\int_a^b\,(x-c)\,f'(x)\,\text{d}x\,.$$
By the Mean Value Theorem, $$f'(x)=f'(c)+(x-c)\,f''\big(\xi(x)\big)\text{ for all }x\in[a,b]\,,$$
where $\xi(x)$ is a number (inclusively) between $x$ and $c$.  That is, we obtain
$$\left|\int_a^b\,f(x)\,\text{d}x\right|=\left|\int_a^b\,(x-c)\,f'(c)\,\text{d}x+\int_a^b\,(x-c)^2\,f''\big(\xi(x)\big)\,\text{d}x\right|\,.$$
Since $\displaystyle \int_a^b\,(x-c)\,f'(c)\,\text{d}x=0$ and $\big|f''(t)\big|\leq M$ for all $t\in[a,b]$, we conclude that
$$\left|\int_a^b\,f(x)\,\text{d}x\right|\leq M\,\left|\int_a^b\,(x-c)^2\,\text{d}x\right|=M\,\left(\frac{(b-a)^3}{12}\right)\,.$$
The inequality becomes an equality if and only if

*

*$f(x)=+M(x-a)(b-x)$ for all $x\in[a,b]$, or

*$f(x)=-M(x-a)(b-x)$ for all $x\in[a,b]$.


text:
Q: Android Programming - locking application Hi all u geeks out there... i'm a novice in Android programming though had tried my hand on blackberry...
currently i was asked 4 the possibility of making an application which can control access to other applications on Android... I mean something like asking password everytime some selected apps are opened... My question is.. "is it possible to make an application which does something like this"... Any feedback will be appreciated.. Thanx in advance guys...

A: It is not possible to create an SDK application as you describe. If you can do that, then malware can do that, holding a user's phone hostage.
As tm1brt indicates, you may be able to do this via your own custom firmware and modifications to the Android OS, but then that will only affect your phones (personal ones or ones you are manufacturing). And modifying the Android OS is not trivial.

A: You would be able to do this by modifying the OS.
Or perhaps writing a new home screen.


text:
Q: Make a grouped column by sum of another column with pandas I have this data set:
+===+=======+======+=======+=======+
|   | Group | Cost | Name1 | Name2 |
+===+=======+======+=======+=======+
| 0 | G1    | 1574 | N1A   | N2A   |
+---+-------+------+-------+-------+
| 1 | G2    | 1322 | N1B   | N2B   |
+---+-------+------+-------+-------+
| 2 | G3    | 1188 | N1C   | N2C   |
+---+-------+------+-------+-------+
| 3 | G3    |  942 | N1D   | N2D   |
+---+-------+------+-------+-------+
| 4 | G4    |  838 | N1E   | N2E   |
+---+-------+------+-------+-------+
| 5 | G5    |    5 | N1F   | N2F   |
+---+-------+------+-------+-------+
| 6 | G5    |    4 | N1F   | N2G   |
+---+-------+------+-------+-------+
| 7 | G5    |    3 | N1G   | N2H   |
+---+-------+------+-------+-------+

Now i want to group by "Group" and add a grouped column with the sum of column "Cost" for each group. Dont know how to explain, so here is the expected result:
+===+=======+======+======+=======+=======+
|   | Group | Sum  | Cost | Name1 | Name2 |
+===+=======+======+======+=======+=======+
| 0 | G1    | 1574 | 1574 | N1A   | N2A   |
+---+-------+------+------+-------+-------+
| 1 | G2    | 1322 | 1322 | N1B   | N2B   |
+---+-------+------+------+-------+-------+
| 2 | G3    | 2130 | 1188 | N1C   | N2C   |
|   |       |      +------+-------+-------+
|   |       |      |  942 | N1D   | N2D   |
+---+-------+------+------+-------+-------+
| 3 | G4    |  838 |  838 | N1E   | N2E   |
+---+-------+------+------+-------+-------+
| 4 | G5    |   12 |    5 | N1F   | N2F   |
|   |       |      +------+-------+-------+
|   |       |      |    4 | N1F   | N2G   |
|   |       |      +------+-------+-------+
|   |       |      |    3 | N1G   | N2H   |
+---+-------+------+------+-------+-------+

How can i achieve this with pandas? Is that even possible? Sorry i am new to this stuff

A: Use GroupBy.transform with sum and then for display your way create MultiIndex by DataFrame.set_index, but 'missing' values in MulitIndex are only not displaing:
df['Sum'] = df.groupby('Group')['Cost'].transform('sum')
df = df.set_index(['Group','Sum','Cost'])

Or:
df1 = (df.assign(Sum = df.groupby('Group')['Cost'].transform('sum'))
         .set_index(['Group','Sum','Cost']))


text:
Q: использование Spring Security имеется REST приложение
Доменная модель: Пользователи, роли, счета, переводы.
нужно настроить доступ к данным:
пользователи видят только свои переводы, админ видит все переводы
научился доставать профиль только авторизованног пользователя, но как разделить на админ - видит все, пользователь - только свое, не могу найти примеры реализации
для примера: вывожу только авторизованного юзера среди всего списка
@GetMapping(value = "/get_users")
@PreAuthorize("hasAnyAuthority('developers:read')")
@PostFilter("filterObject.userName == authentication.name")
public List<UserDto> getUsers() {
    return userService.getAllUsers();
}

схема ДБ


text:
Q: Numpy finding rows in array that correspond to values in another array python I have the following arrays:
arr1 = np.array(['x','y','z'])

arr2 = np.array(['y','a','b','z','c','x'])

arr3 = np.array([['y','d1','d2','d3'],
                 ['a','d4','d5','d6'],
                 ['b','d7','d8','d9'],
                 ['z','d10','d11','d12'],
                 ['c','d13','d14','d15'],
                 ['x','d16','d17','d18']])

and I want to get the following:
answer = np.array([[x,d16,d17,d18],
                   [y,d1,d2,d3]
                   [z,d10,d11,d12]])

How do I do this??

A: I think this should work, or at least get you in the right direction.
idxs = np.where( arr3[:,0] == arr1 )
answer = arr3[idxs, :]

read about np.where: http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

A: inds = [ where( arr3[:,0] == val)[0] for val in arr1 ]
inds = [ i[0] for i in inds if i.size ]
answer = arr3[inds]

A: Take the first row (next()), where the first element equals an element e1 of arr1.
array([
    next(row3 for row3 in arr3 if row3[0]==e1)
      for e1 in arr1])

Out:
array([['x', 'd16', 'd17', 'd18'],
       ['y', 'd1', 'd2', 'd3'],
       ['z', 'd10', 'd11', 'd12']],
  dtype='|S3')

A: The numpy_indexed package (disclaimer: I am its author) has functionality to address this problem efficiently. You can think of it as a vectorized equivalent of list.index. Should be in numpy itself if you ask me; maybe in a future version!
import numpy_indexed as npi
answer = arr3[npi.indices(arr3[:,0], arr1)]


text:
Q: min and max value in excel I want to know how to find the minimum and maximum value in excel sheets using criteria? I try to use this formula but it's not working. I need specific text if is match it will show minimum or maximum value. For your information, I am using Excel 2013.

A: I believe using a pivot table would be simplest, but that said, you can use the following array formulae (Use Ctrl+Shift+Enter instead of Enter):
=MAX(IF(ISERROR(SEARCH(D1,A2:A6)),MIN(B2:B6),B2:B6))
=MIN(IF(ISERROR(SEARCH(D1,A2:A6)),MAX(B2:B6),B2:B6))

A: Like
=MAX(IF(IFERROR(FIND("Shoaib",$A$2:$A$6),0)>0,$B$2:$B$6))

And
=MIN(IF(IFERROR(FIND("Shoaib",$A$2:$A$6),0)>0,$B$2:$B$6))

Entered as array formulas with Ctrl + Shift + Enter

Data

A: For purposes of your reporting, one sensible option here would be to just add a filter on the Name column.  Then, just take the max and min of the entire Marks column.  This would let you quickly obtain the min or max marks for any person using only the Excel GUI.  And it avoids the need to edit a formula for each different name.

A: Input these as ARRAY formula. Means press CTRL+SHIFT+ENTER after putting formula in cell.
=MAX(IF(ISNUMBER(SEARCH("Shoaib",A2:A6)),B2:B6,""))

=MIN(IF(ISNUMBER(SEARCH("Shoaib",A2:A6)),B2:B6,""))


text:
Q: How to get a pop-up If we have any truncate or delete statement - when we are running script in toad or SQL developer Is there any way can i get a pop-up in display , whenever any one runs a script ( script consists of multiple inserts , updates , delete statements )
Example for multiple statements:
Update table set A=A where EmpId= 1;
Delete from Table where Emp_ID =2;

When i run complete this complete commands in script , a popup should be triggered saying "I am trying delete operation & its a production database".
Is there any way i can get popup while i am running sql script ( in a script if any statement with truncate or delete ) can i get a popup in toad and Sql Developer.... ?
Please help me with suggestion

A: Try the ACCEPT command (Docs)

set pause on -- this will wait for user input between pages/queries
set pagesize 200
SELECT employees.first_name,
       employees.last_name,
       employees.salary,
       departments.department_name
  FROM employees
 INNER JOIN departments ON employees.department_id = departments.department_id
 ORDER BY salary desc, last_name asc;

ACCEPT upd CHAR PROMPT 'Cut Salary 10 percent? (y/n):  '  -- add this before bad stuff

update employees set salary = salary * 0.9;

I think your real solution is to never manually run a script in production. You should never even be connected to production in most cases. And when you do need to make a change in production, issue a change order. That would include your script, which would get reviewed by a DBA. It would then get scheduled, and ran through a pre-approved process. And ALL of this would be audited.
This may sound 'crazy', but most DBAs upon reading your question would be very worried for the data in your database.
TL;DR short answer - your tools can't save you. They can only help. For example SQLDev allows you to add a color code to your connections to give you a visual reminder of where you are.


text:
Q: Mock Kotlin class in Java unit test I have this Java test with Mockito:
public class PersistentNodeDeserializerTests {

    @Test
    public void userInfoPersistentNodeDeserializer() {
        PersistentNode node = mock(PersistentNode.class);
        when(node.stringChild("username")).thenReturn("cliff12");
        //more stuff
    }

}

PersistentNode is a Kotlin class:
open class PersistentNode(private val path: PersistentNodePath, val content: Any) {

    val stringPath: String
        get() = path.get()

    val key: String
        get() {
            val parts = stringPath.split("/");
            return parts[parts.size - 1];
        }

    val mapContent: Map<String, Any>
        get() {
            return content as HashMap<String, Any>
        }

    fun stringChild(child: String): String {
        return mapContent.get(child) as String
    }

}

I get this error:

kotlin.TypeCastException: null cannot be cast to non-null type
  java.util.HashMap

How can I mock the property stringChild properly?

A: this library may solve your issue https://github.com/nhaarman/mockito-kotlin
EDIT: sorry, didn't realize you were using a Java test. If it's an option, try writing your test in kotlin too


text:
Q: Are scrapy CONCURRENT_REQUESTS per spider or per machine? Newbie designing his architecture question here:
My Goal
I want to keep track of multiple twitter profiles over time.
What I want to build:
A SpiderMother class that interfaces with some Database (holding CrawlJobs) to spawn and manage many small Spiders, each crawling 1 user-page on twitter at an irregular interval (the jobs will be added to the database according to some algorithm).
They get spawned as subprocesses by SpiderMother and depending on the success of the crawl, the database job get removed. Is this a good architecture?
Problem I see:
Lets say I spawn 100 spiders and my CONCURRENT_REQUESTS limit is 10, will twitter.com be hit by all 100 spiders immediately or do they line up and go one after the other?

A: Most scrapy settings / runtime configurations will be isolated for the current open spider during the run. Default scrapy request downloader will be acting only per spider also, so you will indeed see 100 simultaneous requests if you fire up 100 processes. You have several options to enforce per domain concurrency globally and none of them are particularly hassle free:

*

*Use just one spider running per domain and feed it through redis (check out scrapy-redis). Alternatively don't spawn more than one spider at a time.

*Have a fixed pool of spiders or limit the amount of spiders you spawn from your orchestrator. Set concurrency settings to be "desired_concurrency divided by number of spiders".

*Overriding scrapy downloader class behavior to store its values externally (in redis for example).

Personally I would probably go with the first and if hit by the performance limits of a single process scale to the second.


text:
Q: Get arrays from Csv file to plot a chart I have this Csv file:
DateTime;S1;S2;S3
2020-07-15 16:27:01.221660;652.3826361765446;661.0531016851814;387.24703877989487
2020-07-15 16:27:01.221660;953.4271004457892;873.8955069132078;397.91143086810587

I want to read the file by columns, so:
DateTime_array = [2020-07-15 16:27:01.221660,2020-07-15 16:27:01.221660]
S1_array = [652.3826361765446,953.4271004457892]
S2_array = [661.0531016851814,873.8955069132078]
S3_array = [387.24703877989487,397.91143086810587]

After this I want to plot data, DateTime_array is the X coordinates for each Signal(S1,S2...) and in Signals array are contained the Y coordinates.
How can I do this?
Is there any other way to do it straight from the csv?

A: You can use Python's Pandas to solve your problem. This is what you need:
import pandas as pd

df = pd.read_csv(csv_file_path, sep=";")
df["DateTime"] = pd.to_datetime(df["DateTime"])
df.set_index("DateTime").plot()

A: Python's Pandas package is most convenient way to deal with data, including .csv files.
You can easily read from you csv:
import pandas as pd
my_df = pd.read_csv(path, parse_dates=True)

(some adaptations may needed, as .csv has several formats. But this is right method to call)
Now you have a dataframe object looks exactly like your .csv file. It is easy to manipulate data. For example, if you just want to plot one column:
my_df.plot.scatter(x='DataTime', y='S1')

If you want a more complex plot you should use matplotlib package directly.
And if all you want is to save your data as an array:
DateTime_array = my_df["DataTime"].tolist()
S1_array = my_df["S1"].tolist()

As I said, when dealing with data - pandas' DataFrame object is the right way to manipulate data, so no need to extract values to arrays.


text:
Q: How to parse freebase quad dump using Amazon mapreduce Im trying to extract movie informations from freebase, i just need name of the movie, name and id of the director and of the actors.
I found it hard to do so using freebases topic dumps, because there is no reference to the director ID, just directors name.
What is the right approach for this task? Do i need to parse somehow whole quad dump using amazons cloud? Or is there some esy way?

A: You do need to use the quad dump, but it is under 4 GB and shouldn't require Hadoop, MapReduce, or any cloud processing to do.  A decent laptop should be fine.  On a couple year old laptop, this simple-minded command:
time bzgrep '/film/' freebase-datadump-quadruples.tsv.bz2 | wc -l
10394545

real    18m56.968s
user    19m30.101s
sys 0m56.804s

extracts and counts everything referencing the film domain in under 20 minutes.  Even if you have to make multiple passes through the file (which is likely), you'll be able to complete your whole task in less than an hour, which should mean there's no need for beefy computing resources.
You'll need to traverse an intermediary node (CVT in Freebase-speak) to get the actors, but rest of your information should be connected directly to the subject film node.
Tom

A: First of all, I completely share Tom's point of view and his suggestion. I often use UNIX command line tools to take 'interesting' slices of data out of Freebase data dump.
However, an alternative would be to load Freebase data into a 'graph' storage system locally and use APIs and/or the query language available from that system to interact with the data for further processing.
I use RDF, since the data model is quite similar and it is very easy to convert the Freebase data dump into RDF (see: https://github.com/castagna/freebase2rdf). I then load it into Apache Jena's TDB store (http://incubator.apache.org/jena/documentation/tdb/) and use the Jena APIs or SPARQL for further processing.
Another reasonable and scalable approach would be to implement what you need to do in MapReduce, but this makes sense only if the amount of processing you do is touching a large fraction of Freebase data and it is not as trivial as counting lines. This is more expensive than using your own machine, you need an Hadoop cluster or you need to use Amazon EMR. (I should probably write a MapReduce version of freebase2rdf ;-))
My 2 cents.


text:
Q: fgpa timing constraint on enable signal I have a question regarding setting timing constraints on enable signals.
In my vhdl design I use an enable signal, to gate when the process needs to sample my input data. The enable signal is derived from the input data, using another vhdl component.
My clk is 27MHz, but the enable signal is maximum present at every 2nd cycle, so its period is minimum: 1/13.5MHz.
When I compile my design, I get warnings on the clk timing constraints, due to my algorithm. But can I make some timing constraint on the enable pin, this could probably make the vhdl code compile without warnings, by effectively only requiring half of the clk period.
test : process(reset, clk)
begin
  if reset = '0' then
     ...
  elsif rising_edge(clk) then
    if en = '1' then
      ... vhdl algorithm is here ...
    end if;
  end if;
end process;

A: If you can guarantee that your enable will never be present faster than a particular rate, you can use a multi-cycle path constraint to tell the tools this.  You don't say which FPGA family you are using, but searching the vendors helpfiles for multi-cycle should get you the information you need.
Having said that, in my experience these constraints are hard to verify.  Checking that only the right logic is covered by them is hard, and if some additional logic gets included by accident, the design has a latent timing violation that is unknown to the designer.
So unless I have no other choice, I tend to aim for clock-speed improvement (for example using a better synthesiser, or pipelining, or..).  Then I can run that logic at full speed, even though I don't have to, and I don't have to worry about validating complex multi-cycle path constraints.


text:
Q: saveEventually and saveInBackground are failing to function after sometime It seems to work fine but after sometime all calls to saveEventually and saveInBackground are not saving data to parse (there is no callback and there is no error message as well). It seems it is silently discarded. When this happens, we are still able to fetch data from Parse i.e. all read queries work. We are using local storage. The updates start working again once we clear the app data. What could be causing this? How can we debug the requests that are silently discarded?

A: You are using a synchronous function saveInBackground. If you want to have callbacks, you need to call the asynchronous version saveInBackgroundWithBlock instead.
Please read the Parse documentation carefully before posting a question here.


text:
Q: How to modify the PTE to point to another physical address (only modify the physical page frame number PFN in the PTE) I'm writing a Linux kernel module, and I'd like to modify the PTE to point to another physical address. It is worth noting that I require that only the physical page frame number PFN in the PTE be modified, and no other permission bits need to be modified.
The specific requirements are as follows:
The original PTE (PTE0) points to a physical address phys0. After modifying the PFN in PTE0 to the PFN corresponding to the target physical address phys1, it points to phys1.
I know that there are some macros in linux that can create pte (mk_pte). However, it changes the permission bits of PTE0 (I think so, please point out if it is incorrect).
How can I achieve the above goals?


text:
Q: Disposing a background worker Is it necessary to dispose off the Background Worker after I have done the processing work inside the DoWork event, or being a managed object this will automatically get disposed eventually?
Previously, I was performing some functions inside the timer_elapsed i.e to perform a task every thirty seconds.
Now, I am doing the same processing inside the BackGround Worker's DoWork event. How do I loop this bgWorker event to be performed after every 30 seconds (say) bgworker.RunWorkerAsync();
If I put this bgWorker.RunWorkerAsync() indie timer_elapsed, how do I dispose it after every timer elapse?

A:
Is it necessary to dispose off the Background Worker after ...

No. The BackgroundWorker does implement the IDisposable interface but only as a blanket feature inherited from Component. It serves no purpose.

If I put this bgWorker.RunWorkerAsync() in timer_elapsed

Doubtful if you should do that at all. But if you do, just create a new Backgroundworker each time.
A Backgroundworker is a relatively 'light' object, it holds no resources. The thread is borrowed from the ThreadPool.
If you are a stickler for principal, you may call Dispose() on the old one before creating a new one. But it won't make much difference.