text:
Q: How to work and update nested, sortable records How to work with nested, sortable records
I'm not a developer, but I'm trying to achieve some new skills. I have little experience with PHP, let's say I've created few small apps already and they work pretty well.
As my job is mainly working with Linux Systems, I decided to learn python and change my focus as it can help me for web as well as scripting for automation etc...
So here is what I'm currently trying to achieve.
The task:
We have some regular events where multiple teams have to participate and work on different tasks, one team might need to complete a task that is blocking other team to start part of their things...
That said I need to create something like live multiplayer ToDo app updated realtime and tasks are nested and sorted the proper way.
Example would look like this:
Main Taks
|
|-> Child task ---------------------------------------- [action button][action button][...]
|      |-> Child of the child task -------------------- [action button][action button][...]
|          |-> etc... --------------------------------- [action button][action button][...]
|-> Another child task -------------------------------- [action button][action button][...]
|   |-> Another nested child -------------------------- [action button][action button][...]
|-> Another child task -------------------------------- [action button][action button][...]
etc...

I'm thinking of creating a backend API using python, and I guess vuejs or react for the front end as it needs to be realtime.
Digging through articles and howtos I found the proper way to structure my database table so I can have unlimited nesting:
----------------------------------
| id | parent_id | order | etc.. |
----------------------------------

So pretty much I can have incremental id, then the parent id could be 0 for the root and relative id for the parent.
I have the order as well so with recursive function in python I can generate a nice json to send to frontend.
My problem is, how to work with re-ordering the tree?
I really can't figure out how to perform this. Like from the example that I provided, how can I properly move the last "Another child task" to be as 4th level and child of the "Child of the child task".
Also all childs must be in percise order as they need to be performed in strict order.
I want this to be drag and droppable. Still learning javascript but I found a lot ready to go solutions that look pretty cool. I just can't figure out how to update the order of all the childs...
I guess the language is not that important, mostly the logic that has to be implemented.
What should I send from frontend when something on the tree changes and how to process this on the backend....
Any ideas?
UPDATE:
I still haven't done much. I initially tried with PHP but then realized I would do it with python using Flask. Currently still learning Python/Flask. It's like those projects where you do something while you learn and at the end you get something that you could use in real life. Currently I have written only the route and mechanism to fetch all tasks and return them as json:
Note: I'm using SQLAlchemy
class TreeView(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer)
    order = db.Column(db.Integer)
    name = db.Column(db.String(200))

That;s the DB model
def todo():

    output = []
    records = TreeView.query.all()
    for record in records:
        robj = {}
        robj['id'] = record.id
        robj['parent_id'] = record.parent_id
        robj['order'] = record.order
        robj['name'] = record.name
        output.append(robj)

    return jsonify(output)

That's the query and return json.
Currently checking vuejs with examples how I need to nest the json so it's properly formatted to be digested by the nested tree.
The main blocker for me though is to work out how to really sort things especially when updating.


text:
Q: getting null values back from SQL lite db I've been playing with a sample application I found online. Just changing things to see how it works. Yesterday this was not an issue. Today is a different story. I seem to write the correct info to the db. I've checked through log outputs. When I return the information through a cursor I get "null". So, say I enter "Eggs","Bread", and "Candy". I get back "null","null", and "null".
It all starts with the listener for the add grocery button. Adds to the db and writes the list to an label.
Any help?
  private void addEvent(String title) {
    SQLiteDatabase db = eventsData.getWritableDatabase();
    ContentValues values = new ContentValues();
    Log.v(TAG, "Adding " + title);
    values.put(EventsDataSQLHelper.TITLE, title);
            db.insert(EventsDataSQLHelper.TABLE, null, values);

  }

  private Cursor getEvents() {
    SQLiteDatabase db = eventsData.getReadableDatabase();
    Cursor cursor = db.query(EventsDataSQLHelper.TABLE, null, null, null, null,
        null, EventsDataSQLHelper.TITLE);
    startManagingCursor(cursor);
    return cursor;
  }

  private void showEvents(Cursor cursor) {
    StringBuilder ret = new StringBuilder();
    while (cursor.moveToNext()) {
      String title = cursor.getString(1);
      ret.append(title + "\n");
      Log.v(TAG, "SHOWING RET VARIABLE" + ret);
    }
    t.setText(ret);

  }
  View.OnClickListener myhandler = new View.OnClickListener()
  {
      @Override
      public void onClick(View GLview)
        {
            EditText eT = (EditText)findViewById(R.id.itemName1);
            editTextStr = eT.getText().toString();
            Log.v(TAG, editTextStr);
            if(editTextStr != null)
            {
                addEvent(editTextStr.toString());
                Cursor cursor = getEvents();
                showEvents(cursor);
                eT.setText(null);
            }
        }
  };

A: Make sure cursor points to the first element of the result cursor.moveToFirst();
Then call cursor.moveToNext()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vuetify dialog component to correctly delete item from parent component I have a delete dialog component that when clicking Cancel or Delete nothing happens, not even errors. What am I missing to correctly delete or cancel
<template>
  <v-dialog
    v-bind="$attrs"
    v-on="$listeners"
    max-width="500px"
    persistent
  >
    <v-card>
      <v-card-title
        class="headline"
      >
        {{ title }}
      </v-card-title>
      <v-card-text>
        {{ message }}
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn
          color="grey darken-1"
          text
          @click="$emit('closeDeleteDialog')"
        >
          Cancel
        </v-btn>
        <v-btn
          color="primary darken-1"
          text
          @click="$emit('deleteItem')"
        >
          Delete
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  name: 'DeleteDialog',
  props: {
    title: {
      type: String,
      required: true
    },
    message: {
      type: String,
      default: ''
    }
  },
  emits: ['closeDeleteDialog', 'deleteItem']
}
</script>

This is how I use my component:
        <DeleteDialog
          v-model="dialogDelete"
          title="Delete location"
          message="Are you sure you want to delete this location?"
        />

On the same view as where I import my component I have my methods.
export default {
  components: {
    DeleteDialog: () => import('@/components/Shared/DeleteDialog'),
  },
  data: () => ({
    locationId: null,
    dialog: false,
    dialogDelete: false,
  })
  },
  methods: {
    deleteItem () {
      this.$store.dispatch('deleteFirebaseDoc', { docId: this.locationId, collection: 'locations' })

      this.locationId = null
      this.dialogDelete = false
    },
    deleteItemConfirm (item) {
      this.locationId = item.docId
    },
    closeDeleteDialog () {
      this.dialogDelete = false
    }
  }
}
</script>

How can I correctly access my component to delete and item or cancel the dialog?

A: In the parent component you need to to listen to those events you emit
<DeleteDialog
  v-model="dialogDelete"
  title="Delete location"
  message="Are you sure you want to delete this location?"
  @close-delete-dialog="dialogDelete = false" // or call closeDeleteDialog ()
  @delete-item="deleteItem()"
/>

I've never used camelCase for events emitting so I'd rather write it like $emit('close-delete-dialog') and $emit('delete-item')


text:
Q: Unable to compile class for jsp in tomcat 6.0.2.0 Everything is fine according to me but Still i am getting an exception as "org.apache.jasper.JasperException: Unable to compile class for JSP: "
Please look into it

*

*RootDircetory:- CallActionJsp

*RootDircetory/action.jsp

*RootDircetory/index.html

*RootDircetory/meta-inf

*RootDircetory/web-inf/classes/foo/Person.class

*RootDircetory/web-inf/web.xml

========================================================================
Index.html

<title>Index Page</title>

<form action="action.jsp" method="get">

Password: <input type="text" name="Password" />

<input type="SUBMIT" name="SUBMIT" />
</form>

</html

Person.java
package foo;
public class Person
{
String name ;
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return name;
    }
}

action.jsp
<%@ page import="foo.*,java.util.Date"%>

<title>Action JSP</title>

Standard Actions are used Here.

<%
    Person p = new Person();
    Date date = new Date();
    out.print(date);
    String param = request.getParameter("Password");
    out.print("
"+param);
%>

Call Again

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <servlet>
        <servlet-name>ActionJsp</servlet-name>
        <jsp-file>/action.jsp</jsp-file>
    </servlet>

    <servlet-mapping>
        <servlet-name>ActionJsp</servlet-name>
        <url-pattern>/CallActionJsp</url-pattern>
    </servlet-mapping>

</web-app>

Regards
Ankur

A: Quick guess - Person is not found because of a lowercase web-inf in RootDircetory/web-inf/classes/foo/Person.class?
WEB-INF must be an upper case name, could you try renaming it?


text:
Q: Can't use an XDocument in Silverlight? I'm creating a Windows Phone 7 application that will consume an exposed webservice. For now, I want to load a dummy xml file and parse information from that.
I'm used to using XDocument for things like this, but it seems I can't type in the using namespace in my code.
Any other ideas?

A: The XDocument class is in the System.Xml.Linq namespace, with dll of the same name.
Have you added a reference to the System.Xml.Linq.dll?

A: Take a look at How to Use XDocument class in SilverLight Project (C#)


text:
Q: What is the difference between *.* and * in regex? I want to know more specifically, what is the difference between *.* and * in search pattern of winapi FindFirstFile?
GetWindowsDirectoryA( buffer2, sizeof(buffer2) );
strcat(buffer2, "\\*");
handle = FindFirstFileA(buffer2, &data);

A: These are not regular expressions. They are simple wildcard based search patterns.
There is in fact no difference between * and *.*. The rules for these wildcard patterns date back to DOS. Raymond Chen explains the DOS rules here: How did wildcards work in MS-DOS? Because *.* was the same as * in DOS, this equivalence was maintained in Win32 for the sake of compatibility.

But some quirks of the FCB matching algorithm persist into Win32 because they have become idiom.
For example, if your pattern ends in .*, the .* is ignored. Without this rule, the pattern *.* would match only files that contained a dot, which would break probably 90% of all the batch files on the planet, as well as everybody's muscle memory, since everybody running Windows NT 3.1 grew up in a world where *.* meant all files.


text:
Q: Is there a quick way to replace column values in R? Suppose we have a data frame containing numeric values which looks like:
Temperature Height
32          157
31          159
33          139

I want to replace Height values with pic_00001, pic_00002 etc. so that the end result is:
Temperature Height
32          pic_00001
31          pic_00002
33          pic_00003

There are 10,000+ rows in the full data frame, hence I need a quicker way than doing this manually.

A: You can do:
id <- seq_len(nrow(data))
new_values <- paste("pic_",id,sep = "")

data$Height <- new_values

A: You can also use the following solution:
library(dplyr)
library(stringr)

df %>%
  mutate(across(Height, ~ str_c("pic_", str_pad(row_number(), 5, "left", "0"))))

  Temperature    Height
1          32 pic_00001
2          31 pic_00002
3          33 pic_00003

A: to achieve final output (from original by monjeanjean, i cant comment yet lol):
id <- seq_len(nrow(data))
new_values <- paste("pic_",formatC(x,width=5,flag="0",format="fg"),sep = "")

data$Height <- new_values

A: You can use sprintf:
# create the example used by the OP
dat <- data.frame(Temperature = 31:33,
                  Height = c(157, 159, 139))

# use sprintf along with seq_len
dat$Height <- sprintf("pic_%05d", seq_len(NROW(dat)))

# show the result
dat
#R>  Temperature    Height
#R> 1          31 pic_00001
#R> 2          32 pic_00002
#R> 3          33 pic_00003

You can change the 05d if you want more leading zeros. E.g. 07d will give a seven digit sequence. The manual page for sprintf have further details.


text:
Q: How are results sorted when the query is empty? I can't find any informations on Azure Search documentation  about how the results are sorted when the query sent is empty. I've also read the  Empty Search section of ElasticSearch but still can't find any answer.
Is this sorting by Key?
Is the backend sending a batch of parallel requests and concatenate the results since the sorting doesn't matter?

A: in case of empty query, the sort order is unspecified. You cannot rely on any particular order. If you need a specific order, ask for it using orderby query parameter.
HTH,
Eugene


text:
Q: How to know if SqlSessionTemplate has closed the DB connection gracefully I am using MySQL with Spring and SqlSessionTemplate.
I know SqlSessionTemplate automatically close a connection after it has been used, so we don't need to do anything about this.
But when I checked my MySQL status I found out that Aborted_clients is too high. total connection is 26030 and Aborted_clients 25861. So I think I should check out if SqlSessionTemplate not able to close connections well.
How can I handle this? I sincerely ask the members who are more capable than me.
-------Here is the status of Mysql.(show status)---------------------

| Aborted_clients                               | 25861                                            |
| Aborted_connects                              | 17                                               |
| Binlog_cache_disk_use                         | 0                                                |
| Binlog_cache_use                              | 0                                                |
| Binlog_stmt_cache_disk_use                    | 0                                                |
| Binlog_stmt_cache_use                         | 0                                                |
| Bytes_received                                | 419                                              |
| Bytes_sent                                    | 839                                              |
| Compression                                   | OFF                                              |
| Connections                                   | 26030                                            |
| Innodb_buffer_pool_dump_status                | Dumping of buffer pool not started               |
| Innodb_buffer_pool_load_status                | Buffer pool(s) load completed at 180301  6:06:08 |
| Innodb_buffer_pool_resize_status              |                                                  |
| Innodb_buffer_pool_pages_data                 | 7251                                             |
| Innodb_buffer_pool_bytes_data                 | 118800384                                        |
| Innodb_buffer_pool_pages_dirty                | 0                                                |
| Innodb_buffer_pool_bytes_dirty                | 0                                                |
| Innodb_buffer_pool_pages_flushed              | 205767                                           |
| Innodb_buffer_pool_pages_free                 | 719                                              |
| Innodb_buffer_pool_pages_misc                 | 221                                              |
| Innodb_buffer_pool_pages_total                | 8191                                             |
| Innodb_buffer_pool_read_ahead_rnd             | 0                                                |
| Innodb_buffer_pool_read_ahead                 | 59873                                            |
| Innodb_buffer_pool_read_ahead_evicted         | 8173                                             |
| Innodb_buffer_pool_read_requests              | 1440265221                                       |
| Innodb_buffer_pool_reads                      | 774163                                           |
| Innodb_buffer_pool_wait_free                  | 320                                              |
| Innodb_buffer_pool_write_requests             | 2132490                                          |
| Innodb_data_fsyncs                            | 186887                                           |
| Innodb_data_pending_fsyncs                    | 0                                                |
| Innodb_data_pending_reads                     | 0                                                |
| Innodb_data_pending_writes                    | 0                                                |
| Innodb_data_read                              | 13672354304                                      |
| Innodb_data_reads                             | 834643                                           |
| Innodb_data_writes                            | 351504                                           |
| Innodb_data_written                           | 5460674560                                       |
| Innodb_dblwr_pages_written                    | 120165                                           |
| Innodb_dblwr_writes                           | 31004                                            |
| Innodb_log_waits                              | 0                                                |
| Innodb_log_write_requests                     | 116504                                           |
| Innodb_log_writes                             | 75883                                            |
| Innodb_os_log_fsyncs                          | 114047                                           |
| Innodb_os_log_pending_fsyncs                  | 0                                                |
| Innodb_os_log_pending_writes                  | 0                                                |
| Innodb_os_log_written                         | 99709440                                         |
| Innodb_page_size                              | 16384                                            |
| Innodb_pages_created                          | 1881                                             |
| Innodb_pages_read                             | 834489                                           |
| Innodb_pages_written                          | 205850                                           |
| Innodb_row_lock_current_waits                 | 0                                                |
| Innodb_row_lock_time                          | 0                                                |
| Innodb_row_lock_time_avg                      | 0                                                |
| Innodb_row_lock_time_max                      | 0                                                |
| Innodb_row_lock_waits                         | 0                                                |
| Innodb_rows_deleted                           | 176                                              |
| Innodb_rows_inserted                          | 316819                                           |
| Innodb_rows_read                              | 5737344217                                       |
| Innodb_rows_updated                           | 170644                                           |
| Innodb_num_open_files                         | 156                                              |
| Innodb_truncated_status_writes                | 0                                                |
| Innodb_available_undo_logs                    | 128                                              |
| Key_blocks_not_flushed                        | 0                                                |
| Key_blocks_unused                             | 13396                                            |
| Key_blocks_used                               | 9                                                |
| Key_read_requests                             | 328                                              |
| Key_reads                                     | 53                                               |
| Key_write_requests                            | 0                                                |
| Key_writes                                    | 0                                                |
| Last_query_cost                               | 0.000000                                         |
| Last_query_partial_plans                      | 0                                                |
| Locked_connects                               | 0                                                |
| Max_execution_time_exceeded                   | 0                                                |
| Max_execution_time_set                        | 0                                                |
| Max_execution_time_set_failed                 | 0                                                |
| Max_used_connections                          | 11                                               |
| Max_used_connections_time                     | 2018-03-09 15:40:45                              |
| Not_flushed_delayed_rows                      | 0                                                |
| Ongoing_anonymous_transaction_count           | 0                                                |
| Open_files                                    | 0                                                |
| Open_streams                                  | 0                                                |
| Open_table_definitions                        | 144                                              |
| Open_tables                                   | 448                                              |
| Opened_files                                  | 1427                                             |
| Opened_table_definitions                      | 0                                                |
| Opened_tables                                 | 0                                                |
| Performance_schema_accounts_lost              | 0                                                |
| Performance_schema_cond_classes_lost          | 0                                                |
| Performance_schema_cond_instances_lost        | 0                                                |
| Performance_schema_digest_lost                | 0                                                |
| Performance_schema_file_classes_lost          | 0                                                |
| Performance_schema_file_handles_lost          | 0                                                |
| Performance_schema_file_instances_lost        | 4                                                |
| Qcache_free_blocks                            | 1                                                |
| Qcache_free_memory                            | 16760152                                         |
| Qcache_hits                                   | 0                                                |
| Qcache_inserts                                | 0                                                |
| Qcache_lowmem_prunes                          | 0                                                |
| Qcache_not_cached                             | 5899390                                          |
| Qcache_queries_in_cache                       | 0                                                |
| Qcache_total_blocks                           | 1                                                |
| Queries                                       | 11838831                                         |
| Questions                                     | 5                                                |
| Table_locks_immediate                         | 317                                              |
| Threads_cached                                | 5                                                |
| Threads_connected                             | 4                                                |
| Threads_created                               | 13                                               |
| Threads_running                               | 1                                                |
| Uptime                                        | 1663540                                          |
| Uptime_since_flush_status                     | 1663540


text:
Q: MySQL auto increment refresh with new ID I have a table, in MySQL where events are posted by users. Their individual ID is posted, so all the events they post can be related to their account. However, I want to put an auto increment field, that only count the events for 1 user at the time.
Is it possible? If yes, how can I achieve it?
For example, if the user with the ID 544 post 4 events, the 4th one will be marked as 4 in the auto increment column, even if it's the 421 events in the table...

A: You could put in such a field, but you would need a trigger to keep it up-to-date.  Then, if rows are updated or deleted, maintaining becomes challenging.
You can simulate this in a query pretty easily though, using variables:
select e.*,
       @rn := if(@userid = userid, 1, @rn + 1) as UserSequenceNumber,
       @userid := userid
from events e cross join
     (select @rn := 0) const
order by userid;

You can also incorporate this into an update statement, if you want to actually store the values in the table.  Once again, let me say, keeping the value up to date requires a bunch of triggers.
Also, the above works in practice.  However, MySQL does not guarantee that arguments are processed in order.  So, in theory, the @userid could be assigned before @rn, but this doesn't seem to happen in practice.


text:
Q: Exporting response.txt to csv file I'm trying to parse data that I receive from a curl request through python. The data is in the following format:
{'meta': {'from': '1520812800',
          'granularity': 'daily',
          'to': '1523232000',
          'total': 6380},
 'data': [{'count': 660, 'date': '2018-03-12'},
          {'count': 894, 'date': '2018-03-13'}]}

Originally, the data was returned as a string probably because I used response.text to retrieve the data. I converted the string into a dictionary using ast.literal_eval(response.text). I managed to parse the "data" key and ignore "meta". So currently,
data = [{"date":"2018-03-12","count":660},{"date":"2018-03-13","count":894}]}`.

I am trying to export the values for "date" and "count" to a csv file. In my code I have this:
keys = data[0].keys()
print("----------KEYS:---------")
print keys #['date','count']
print("------------------------")

with open('mycsv.csv','wb') as output_file:
  thewriter = csv.DictWriter(output_file, fieldnames =
  ['date','count'])

  thewriter.writeheader()
  thewriter.writerow(data)

However, python does not like this and gives me an error:
Traceback (most recent call last):
  File "curlparser.py", line 45, in <module>
    thewriter.writerow(data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 152, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 148, in _dict_to_list
    + ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: {"date":"2018-03-12","count":660},{"date":"2018-03-13","count":894}


text:
Q: Accepting alphanumeric and 1 dot only in AngularJS I am creating an app using CodeIgniter (back-end) and AngularJS (front-end).
How can I validate user input in AngularJs that only allows characters from a-z-A-Z, numbers and 1 dot (anywhere as long as not in the end of the string)?
/[^A-Za-z0-9\.]/ is that enough?
BTW, my code structure is inspired with this simple example from AngularJS docs. https://docs.angularjs.org/api/ng/input/input%5Btext%5D
UPDATE:

1 dot must not be the first/last character of the string and it must be optional.

A: From what I understood: you want to check that the string is made of only alphanumeric characters and maximum one dot, not located at the end nor the beginning of the string.
You can use (see demo here):
^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)?$

Explanation

*

*[a-zA-Z0-9]+: match all the leading alphanumeric characters (at least one)

*(?:\.[a-zA-Z0-9]+)?: optional non-capturing group - we match a unique dot, followed by  minimum one alphanum

*^$: anchors matching the beginning and end of string, making sure the string is composed only of what we want


text:
Q: Service Fabric - Calling a named partition for a stateful service I can't seem to figure out how to send a call to a specific named partition using ServiceProxy and there doesn't seem to be any documentation specific to this.  This is how you would do it for a Int64RangePartitionInformation
var partitionInformation = (Int64RangePartitionInformation)selectedPartition.PartitionInformation;
var partitionKey = ServicePartitionKey(partitionInformation.LowKey);
IListen listenerClient = ServiceProxy.Create<IListen>(uri,partitionKey );

But there doesn't seem to be a way to get ServicePartitionKey for  NamedPartitionInformation.  Do you include the partition name in the Uri or something?

A: ServicePartitionKey has an overload that takes a string.
var partitionKey = new ServicePartitionKey("partitionName");
IListen listenerClient = ServiceProxy.Create<IListen>(uri,partitionKey);

You shouldn't need to do any more than that.
However, if you don't know the partitions up front and you need to query them:
using(var client = new FabricClient())
{
    var partitions = await client.QueryManager.GetPartitionListAsync(serviceName);

    foreach (var partition in partitions)
    {
        var partitionInformation = (NamedPartitionInformation)partition.PartitionInformation;
        var partitionKey = ServicePartitionKey(partitionInformation.Name);
        IListen listenerClient = ServiceProxy.Create<IListen>(uri,partitionKey);
    }
}


text:
Q: $\ell^\infty(\mathbb{N})$ is not separable
Show, that $\ell^\infty(\mathbb{N})$ is not separable. Use, that $\mathcal{P}(\mathbb{N})$ is uncountable and observe the set $\{1_A\colon A\in\mathcal{P}(\mathbb{N})\}\subseteq\ell^\infty(\mathbb{N})$.

Suppose $\ell^\infty(\mathbb{N})$ is separable. Then it exists a countable, dense set $D=\{d_n\colon n\in\mathbb{N}\}\subseteq\ell^\infty(\mathbb{N})$.
Since $D$ is dense in $\ell^\infty(\mathbb{N})$ exists for every $a_k\in\ell^\infty(\mathbb{N})$ and $\varepsilon>0$ a sequence $(d_k^{(n)})\subseteq D$ with $\|d_k^{(n)}-a_k\|_{\infty}=\|d_k(n)-a_k(n)\|_{\infty}<\varepsilon$
Now I want to construct an $(a_k)$ such that it can not be the limit of any $d_k\in D$.
I am trying to follow the hint in the task:
$a_k=\begin{cases} 0,~~ \text{if}~~ |d_k(k)|>1\\ 1,~~ \text{else}\end{cases}$
Now we have:
$\vert|d_k(n)-a_k(n)\|_\infty=\sup_{n\in\mathbb{N}} |d_k(n)-a_k(n)|\geq 1$ for all $n\in\mathbb{N}$
This is a contradiction. Hence $\ell^\infty(\mathbb{N})$ is separable.
Is this correct?
Thanks in advance for your help.

A: I think your idea is basically okay, but your notation is a little bit wrong. You should consistently write $a(k)$ and $d_n(k)$ to mean the $k$'th entries of the sequences $a$ and $d_n$ (sometimes you are writing things like $a_k$, or $d_k^{(k)}$, the switching notation is a little unclear).
Since you are given a countable set $\{d_n \mid n \in \mathbb{N}\}$, you can define $a$ by $a(k) = 0$ or $2$, if $|d_k(k)|$ is $>1$ or $<1$. (This is changing $a(k)=1$ to $2$. The point is that this way, $|a(k)-d_k(k)| > 1$.)
Now you have $\|a-d_k\| > 1$ for all $k$, so $d_k \not\to a$. Your idea works! Just use notation more consistently (and change $1$ to $2$).
Having said that, @Ian's comments are right too. You can use the hint more directly. You can show that if $A \neq B$, then $\|1_A-1_B\| = 1$. I won't say too much more, but knowing $\|1_A-1_B\|=1$ tells you something about the balls centered at the $1_A$'s, which you can use to show $\ell^{\infty}$ is nonseparable. I hope that helps!

A: Here are two ways to use the hint:
Way 1: Use the subspace topology.
Fact 1: A discrete topological space $X$ is separable if and only if it is countable. (This is easy enough that I don't think you should need help with it.)
Fact 2: Every subspace $A$ of a separable metric space $X$ is separable in its subspace topology. This is less obvious, so I'll sketch the proof. Enumerate your dense subset of $X$ as $d_n$, take a sequence $r_k$ of positive real numbers going to zero, and draw one point from $A \cap B(d_n,r_k)$ whenever this is possible. The result is a countable subset of $A$ which is dense in the subspace topology of $A$. (Note that it won't be dense in $X$ if $A$ wasn't dense in $X$.)
The overall logic of Way 1: if $X$ contains an uncountable discrete subspace, then it cannot be separable, because if it were then the uncountable discrete subspace would also be separable.
Way 2: Use the pigeonhole principle, in the form "if $|A|<|B|$ then there is no surjection from $A$ to $B$".
We have the open balls $B(1_A,1/2)$ ranging over the subsets of $\mathbb{N}$. They are disjoint by the hint. Thus given any countable subset $D$ of $\ell^\infty$, we can excise the countably many balls that intersect $D$ from the union of all these balls, obtaining a nonempty open subset of $\ell^\infty$ which does not intersect $D$.


text:
Q: Movable Type 4: IF / Else logic "if Entry" I would like to have logic in the Meta Description (located in Banner Header) tag that has the following effect:
if rendering an Entry:

     <meta name="description" content="<$mt:EntryBody words="25"$>..." />
else:

     <meta name="description" content="<$mt:BlogDescription$>" />

Thanks for your help!

A: You want the mt:IfArchiveType block tag.
<mt:IfArchiveType archive_type="individual">
  <meta name="description" content="<$mt:EntryBody remove_html="1" words="25" encode_html="1"$>..." />
<mt:Else>
  <meta name="description" content="<$mt:BlogDescription remove_html="1" encode_html="1"$>" />
</mt:IfArchiveType>

I've taken the liberty of adding some handy modifiers that will help avoid invalid output.

A: IfArchiveType is fine if you know you're only going to be doing one test.
With a meta description, on the other hand, there's a good chance you'll want to do something different on category pages, say. While you could just pile up individual IfArchiveType tests for each, you'd do better to familiarize yourself with the archive template variables(which provide a lot more besides) and use the generalized If/Else|If tags:
<mt:if name="entry_archive">
    <meta name="description" content="[Entry archive-specific description]" />
<mt:elseif name="category_archive">
    <meta name="description" content="[Category archive-specific description]" />
<mt:else>
    <meta name="description" content="[Site-wide fallback description]" />
</mt:if>

...which can then be further cleaned up using the Var tag:
<mt:if name="entry_archive">
    <$mt:var name="metaDesc" value="[Entry archive-specific description]"$>
<mt:elseif name="category_archive">
    <$mt:var name="metaDesc" value="[Category archive-specific description]"$>
<mt:else>
    <$mt:var name="metaDesc" value="[Site-wide fallback description]"$>
</mt:if>

<meta name="description" content="<$mt:var name="metaDesc"$>" />

[For clarity, I've omitted the modifiers Mike added, but they are a good idea to include.]


text:
Q: Difficulty with some debugging of a code that calculates the discount you would get with various membership levels Over all, this code is supposed to ask for the customers name, member level, and original purchase price. It should store all of those in their respective variables, if something other than an accepted member level is entered the program is supposed to exit. After all the variables are stored, the customer's name, member level, original purchase price, promotional price, and amount saved should be printed out in the format at the end of this post. Thanks in advance for any help!
import java.util.*;
public class Discount{
  public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);
    double purchase = 0.0;
    double platinum = (purchase * .2);
    double gold = (purchase * .15);
    double silver = (purchase * .1);
    String Platinum = null;
    String Gold = null;
    String Silver = null;
    String customerName = null;
    String level = null;
    double discount = 0.0;

    System.out.print("Please enter a customer name: ");
    customerName = keyboard.nextLine();
    System.out.print("Please enter the customer's member level: ");
    level = keyboard.nextLine();

    if (!level.equals("Platinum") && !level.equals("Gold") && !level.equals("Silver"))
    {
        System.exit(0);
    }

    System.out.print("Please enter the origianl purchase price: ");
    purchase = keyboard.nextDouble();

    System.out.println("Congratualations, " + customerName + "!");

    if (level.equals("Platinum") && purchase > 500)
    {
        discount = (platinum + (purchase*.05));
        System.out.println("As a " + level + " level cardholder, you have received a 25% discount during Bedlam.");
    }
    else if (level.equals("Platinum"))
    {
        discount = (platinum);
        System.out.println("As a " + level + " level cardholder, you have received a 20% discount during Bedlam.");
    }
    else if (level.equals("Gold"))
    {
        discount = (gold);
        System.out.println("As a " + level + " level cardholder, you have received a 15% discount during Bedlam.");
    }
    else if (level.equals("Silver"))
    {
        discount = (silver);
        System.out.println("As a " + level + " level cardholder, you have received a 10% discount during Bedlam.");
    }

Everything works fine up until this point, if I put in M as customerName, Silver as level, and 500.20 as purchase this is what prints out in the command prompt:
Congratualations, M!
As a Silver level cardholder, you have received a 10% discount during Bedlam.
Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
        at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
        at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
        at java.util.Formatter$FormatSpecifier.print(Unknown Source)
        at java.util.Formatter.format(Unknown Source)
        at java.io.PrintStream.format(Unknown Source)
        at java.io.PrintStream.printf(Unknown Source)
        at Discount.main(Discount.java:62)
    System.out.printf("%.2f\n", "Original purchase price: $" + purchase);
    System.out.printf("%.2f\n", "Promotional price: $" + discount);
    System.out.printf("%.2f\n", "Amount saved: $" + (purchase-discount));

This is what it should look like if successfully executed:
Congratulations, Marge Simpson!
As a Silver level cardholder, you received a 10% discount during Bedlam.
Original purchase price: $500.20
Promotional price: $450.18
Amount saved: $50.02 */
    }
}

A: Refer to this.
Try this syntax:
System.out.println( "Original purchase price: $" + String.format("%.2f",purchase));
System.out.println("Promotional price: $" + String.format("%.2f",discount));
System.out.println("Amount saved: $" + String.format("%.2f", purchase-discount));

A: Right now you're basically passing the entire string "Original purchase price: $" + purchase as the argument for %.2f. Use String.format instead:
System.out.println("Original purchase price: $" + String.format("%.2f", purchase));

That also eliminates the need to append "\n" to the string, since you can use System.out.println.


text:
Q: Get trait from inherited class I 've noticed something I cannot explain to myself. I need a little help to check, if an inherited class uses a specific trait. To make it a little clearer, I use the following code.
trait Foo
{
    public function say($what)
    {
        echo $what;
        return $this;
    }
}

class A
{
    uses Foo;
}

class B extends A
{

}

I 'm aware that I should use the class_uses() method, to find all traits used by a class. Butt this does not work on inherited instances.
$b = (new B())->say('hello');

The above example echoes hello. So the trait is inherited successfully and can be used from class B.
$used = class_uses($b);
var_dump($used);

Surprisingly this outputs an empty array. I expected, that class_uses would give me something like Foo. But it does not.
$reflection = new ReflectionClass('B');
$uses = $reflection->getTraits();
var_dump($uses);

Same expectation here. But it just outputs an empty array.
Why the used trait from class A can not be seen in the inherited class B? Are there any alternatives to solve this problem?

A:
class_uses — Return the traits used by the given class.

However, you'd need to cycle through the inheritance tree to get all traits used, and through each trait as well.
To get ALL traits including those used by parent classes and other traits, use this function that I got from php documentation page in comments section here:
function class_uses_deep($class, $autoload = true) {
    $traits = [];
    do {
        $traits = array_merge(class_uses($class, $autoload), $traits);
    } while($class = get_parent_class($class));
    foreach ($traits as $trait => $same) {
        $traits = array_merge(class_uses($trait, $autoload), $traits);
    }
    return array_unique($traits);
}


text:
Q: In ASP.NET MVC, is there a way I can check the if the users logged in to my application through a public network or company's LAN? I am writing an ASP.NET MVC application. I have been asked to allow certain no. of users (no. varies from 10-100) to access my application from both public network and company's network but restrict other users (5 - 500) from accessing application from public network.
These restricted users can only access the application inside company's network. How can I achieve this?
For this, do I need to store I.P address of every user? But they can use other laptops or desktops to access the application.
Can I check the network user is using to access my application?

A:
restricted users can only access the application inside company's
  network

If your company have purchased some IP and use it on the network. You can whitelist them in your ASP.NET MVC Application. For example your company buy a range of IP. You can check the IP of Request is come under that range then yes it's IP of the company.
AFAIK There is no way to know if your user comes from a public network or a company network.


text:
Q: Setup/MSI - Multiple user input directories I'm in need of a setup creation tool (preferably outputing MSI file but not necessary) that is able to prompt the user for a "core" installation directory, and then prompt a second time for a "runfile" directory.
I've messed around a bit in Visual Studio 2010 and with Inno Setup but can't seem to find a solution.
Any suggestions?

A: A list with the best tools available currently: http://en.wikipedia.org/wiki/Windows_Installer#Tools


text:
Q: Creating scatterplot with icons (svg or png) instead of points? I'm just starting with R and I wanted to know if it's possible to create a scatterplot with custom icons (svg or png) instead of points.
I started to import a shapefile, and then I have a set of points (latitude and longitude) that represents the location of the icons.
rm(list=ls())
library(ggplot2)
library(gstat)
library(sp)
library(maptools)
library(rgdal)

#plot
par(mar = c(2, 2, 2, 2))
 root <- "C:/"
Al= readShapeLines("/DZA_adm0.shp")
 require(rgeos)
simple.output <- gSimplify(Al, topologyPreserve = TRUE, tol = 3)
 plot(simple.output,col="black")
(tab <- read.delim(file = paste(root, "/ville.txt", sep = "")))
dat <- SpatialPoints(coords = tab[, 2:3])
(dat <- SpatialPointsDataFrame(coords = tab[, 2:3], data = tab[,
                                                               + c(1, 4)]))
# Rajout des capitales
plot(dat, pch =20, add = T,col="red")

# Extraction des coordonnees
lon <- dat@coords [, "lon"]
lat <- dat@coords [, "lat"]
# Extraction du nom des villes
labs <- as.character(dat@data[, "ville"])

A: rasterImage draws a raster image at a given location and size.
Below is a very rough example, which you can hopefully adjust to your needs. (I made up some location points, you would obviously have to use yours.)
library(rgdal)
library(png)

# load icons in PNG format
iconfile1 <- download.file('http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Status-weather-clouds-icon.png', destfile = 'icon1.png', mode = 'wb')
icon1 <- readPNG('icon1.png')

iconfile2 <- download.file('http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Status-weather-showers-scattered-icon.png', destfile = 'icon2.png', mode = 'wb')
icon2 <- readPNG('icon2.png')

# load shapefile
al <- readOGR("DZA", "DZA_adm0")

# make up some points
library(sp)
set.seed(613)
dat <- spsample (al, 3, type='random')

# need to offset the x/y location for the icon (depends on desired icon size)
offset <- 2

plot(al)
rasterImage(icon1, coordinates(dat)[1,1]-offset, coordinates(dat)[1,2]-offset, coordinates(dat)[1,1]+offset, coordinates(dat)[1,2]+offset)
rasterImage(icon2, coordinates(dat)[2,1]-offset, coordinates(dat)[2,2]-offset, coordinates(dat)[2,1]+offset, coordinates(dat)[2,2]+offset)
rasterImage(icon1, coordinates(dat)[3,1]-offset, coordinates(dat)[3,2]-offset, coordinates(dat)[3,1]+offset, coordinates(dat)[3,2]+offset)
points(dat)


text:
Q: search by multiple search box not working in laravel 5.3 Im currently working in multiple search with two search box one is search box for multiple columns and another one is select box.
Below is my html code for search boxes
<form action="{{ url('/admin/managestudent') }}" method="GET" files="false" id="filter-action">

            <input type="text" class="form-control" name="q" placeholder="Search" value="{{ \Request::input('q') }}">
            <select class="form-control" name="r">
                <option value="">-Select learning mode-</option>
                <option value="1" <?php echo (\Request::input('r') == "1" ) ? 'selected' : '' ; ?>>Online</option>
                <option value="0" <?php echo (\Request::input('r') == "0" ) ? 'selected' : '' ; ?>>Offline</option>
            </select>
              <input type="submit" class="btn btn-success searchsubmit">
             Reset

</form>

Below is my functions to search in controller
public function viewStudent(Request $request) {
    $getStudents = DB::table('student');
    $searchStudent = $request->input('q');
    $searchMode = $request->input('r');
    if (isset($searchMode)) {
        $getStudents->where("learning_mode", $searchMode);
    }
    if (isset($searchStudent)) {
        $getStudents->where("registration_no", "LIKE","%$searchStudent%")
                ->orWhere("enrollment_no", "LIKE", "%$searchStudent%")
                ->orWhere("firstname", "LIKE", "%$searchStudent%")
                ->orWhere("email", "LIKE", "%$searchStudent%")
                ->orWhere("mobile_no", "LIKE", "%$searchStudent%")
                ->orWhere("city", "LIKE", "%$searchStudent%");
    }
    return view('admin.student.grid')->with(['students' => $getStudents->orderBy('id', 'DESC')->paginate(15),'breadcrumb' => array()]);
}

My problem in when i hide inside

if (isset($searchStudent)) {

then $searchMode(search by select box) is working otherwise its not working but i can search using first text box its working anyways.


text:
Q: Airflow duplicating logs I'm using Airflow 1.10.4 and I'm facing a problem when I use logging in my custom modules.
My code be like:
import logging
log = logging.getLogger(__name__)
log.info('hello there')

And the output be like:
[2020-01-22 09:44:29,954] {{logging_mixin.py:95}} INFO - [[34m2020-01-22 09:44:29,954[0m] {{[34mbase_hook.py:[0m84}} INFO[0m - hello there.

The time, file name and logging level are duplicated in every line of my log.
How can I implement the log of Airflow to avoid this? (I used self.log in my operators and there is no problem.)

A: Check the log_format value in your airflow.cfg file.
my default config :
# Log format
log_format = [%%(asctime)s] {%%(filename)s:%%(lineno)d} %%(levelname)s - %%(message)s
simple_log_format = %%(asctime)s %%(levelname)s - %%(message)s

A: Since the default logging format of Airflow is [%%(asctime)s] {%%(filename)s:%%(lineno)d} %%(levelname)s - %%(message)s, you'll always have duplicates in the log, because e.g. the datetime is once shown in the asctime and once in the message itself. So in order to fix that, you need to change the logging format of Airflow to show only the message.
If you're using docker-compose.yaml you need to set it there like this:
AIRFLOW__LOGGING__LOG_FORMAT: '%(message)s'

Otherwise you have to set it in the airflow.cfg as @AliNadi mentioned:
log_format = %%(message)s

Note: I had an additional issue - for me the message was also duplicated. The reason for that was that in the python code I was calling logging.basicConfig() and then additionally configuring the logger like this logger = logging.getLogger(__name__), logger.setLevel(logging.DEBUG) ... The solution was to remove the logging.basicConfig() and leave my custom logging configuration.
Reference: here


text:
Q: Trigger a grow-then-shrink animation on notification from ChangeNotifier in Flutter I have a widget wrapped in a Consumer, that i want to smoothly grow and then return to its original size on notification from a ChangeNotifier.
I've managed to get the animation to grow, but not shrink again, so it just keeps getting bigger and bigger with each notifyListeners() call. I did that with an AnimatedContainer widget. I got the animation i wanted when i defined it in the initState method and manually calling animationController.forward().whenComplete(() => animationController.reverse()).
Any help to do that using Consumer as my trigger.
(edit)
This is the AnimatedContainer. The height and width aren't related to the value coming back from the state, but i'm using state.value ^ 0  just to trigger the resize. I know this will only grow in size, but thats why i'm asking how to shrink the sucker.
AnimatedContainer(
 duration: const Duration(milliseconds: 500),
 curve: Curves.easeIn,
 height: _height * 1.1 * (state.value ^ 0),
 width: _width * 1.1 * (state.value ^ 0),
 child: SomeWidgetUsingTheState()...
),```

A: UPDATE
Since you want to have some kind of "StaggeredAnimaiton", meaning animate between multiple values (here back and forth) and you are using the implicit approach by using AnimatedContainer, the following code could be used (not recommended though):
My state / store
class ContainerState extends ChangeNotifier {
  double height = 100.0;
  double width = 150.0;

  /// Needs the duration of the AnimatedContainer so we know
  /// when we can start the reverse animation (by setting the values
  /// back to normal)
  startWiggle(Duration duration) {
    this.height = 2 * height;
    this.width = 2 * width;
    notifyListeners();
    Future.delayed(duration, () {
      this.height = height / 2;
      this.width = width / 2;
      notifyListeners();
    });
  }
}

Widget tree for reference
class BaseView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /// Since we are using ChangeNotifier as our base type for
    /// indicating State objects, Provider has a designated Widget for that
    return ChangeNotifierProvider(
      create: (context) => ContainerState(),
      builder: (context, _) => Scaffold(
        body: CustomScrollView(
          slivers: [
            SliverAppBar(
              title: Text('Title'),
              pinned: true,
            ),
            SliverList(
              delegate: SliverChildListDelegate(
                [
                  Padding(
                    padding: const EdgeInsets.only(top: 24.0),
                    child: Align(
                      child: GestureDetector(
                        onTap: () => context
                            .read<ContainerState>()
                            .startWiggle(Duration(milliseconds: 500)),

                        /// Gets rebuilded every time notifyListeners is called
                        /// inside ContainerState, therefore when we change the size
                        child: Consumer<ContainerState>(
                          builder: (context, containerState, child) =>
                              AnimatedContainer(
                            duration: const Duration(milliseconds: 500),
                            curve: Curves.easeIn,
                            height: containerState.height,
                            width: containerState.width,
                            color: Colors.red,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

What you want to achieve here is not really suitable for this kind of animation (implicit animation). I would recommend to switch to direct animations using your own AnimationController instead so you have better control of how it should behave. My slides may help you here to get started: https://assets.kounex.com/flutter/uni_project_2020/en/04_flutter_animations.pdf

A: I don't understand what the caret sign is for. But I would do something like this :
animateContainer() async {
    value = containerSize;
    await Future.delayed(Duration(milliseconds: 500));
    value = 0;
}


text:
Q: CA certificate signed jar java I have just changed from signing jar files using a self-signed certificate to using a trusted certificate from Thawte. This works, but there are 2 issues. First, I now get the initial Java Console as before, but this is followed by a second one, then after a while (around 1 minute) the first one closes. Second, when I turn tracing on in the plugin, there are 463 connection requests to the thawte site (in the second console). This is shown as the following repeated over and over again:
security: Certificate validation succeeded using OCSP/CRL
security: Validate the certificate chain using CertPath API
security: SHA-256Certificate finger print: 250B4511AECDA826E699E0D46B4B4B5F4DFDB531AE1E4BE74E35D613F25E1722
security: SHA-256Certificate finger print: AF840CA2B9DFB776BF81AA94C401BC440C52E5C590C43607A13D6680D83E3349
security: SHA-256Certificate finger print: C99157DF28D28EBD87B8B041AACCF023CF1C9AD0D21FD7116149D7F96484FA51
security: SHA-256Certificate finger print: 3F9F27D583204B9E09C8A3D2066C4B57D3A2479C3693650880505698105DBCE9
security: The OCSP support is enabled
security: The CRL support is enabled
security: Failing over to CRLs: Certificate does not specify OCSP responder
network: Connecting http://ocsp.thawte.com/ with proxy=DIRECT
security: OCSP Response: GOOD

Is this triggered every time a class is loaded from the jar file? (I can't seem to turn on the tracing of class load/unload - the -XX:+TraceClassLoading option doesn't seem to work...)
I am just using an  tag to load the applet - no JNLP or anything. (The same happens if I use ):
<object type="application/x-java-applet" width="100%" height="879" id="sfnApplet_1" codebase="java:com/deltascheme/sfn/client/SfnApplet.class">
  <param name="MAYSCRIPT" value="true">
  <param name="type" value="application/x-java-applet;version=1.5">
  <param name="cache_option" value="Plugin">
  <param name="java_codebase" value="/sfn85/Content">
  <param name="cache_archive" value="client.jar,lzma.jar">
  <param name="IMAGE" value="Images/appletSplash.jpg">
  <param name="centerimage" value="true">
  <param name="java_code" value="com/xxx/yyy/client/Applet.class">
  <param name="codebase_lookup" value="false">
  <param name="browserName" value="Netscape">
  <param name="browserVersion" value="5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36">
  <param name="java_arguments" value="-Djnlp.packEnabled=true -XX:+TraceClassLoading -Xmx512M">
</object>

Any help gratefully received (Thawte say it's not their fault and I should speak to Oracle. Hmmm...)


text:
Q: Enforcing redaction and/or redact updates in mongodb In Accumulo, you can enforce what records are returned by the Authorizations and/or server side iterators.
What mechanisms are in place to enforce this type of security in MongoDb?  I know that there is the $redact command for aggregation pipelines, but that relies on the user to restrict their own queries.
Also, how could you enforce that someone doesn't do an update on a document they they don't have sufficient privileges to update?

A: MongoDB authorization is, as of 2.6, collection-level and controls what operations a user can perform, as opposed to what documents they can see. This means, for example, that if a user has authorization to perform find on a collection, they can see all the documents in the collection and there's no way to hide specific documents from them.
You can enforce update privileges on a collection by withholding the update privileges from the user, for example by giving them just the read role.
There's also a conceptual overview of MongoDB's security model in the security section of the manual.


text:
Q: Sync the threaded execution of two methods in Qt Using Qt, I have two instances of a Worker class (which inherits QObject), each of which lives in its own thread by using moveToThread.
The Worker class has a performOperation method that I call from my main thread using:
QMetaObject::invokeMethod(workerLeft, "performOperation");

so that it runs in the worker's thread. That's nice, but I want to run performOperation on my two instances of Worker in parallel, and wait in my main thread for both to finish. Something like having a BlockingQueuedConnection in parallel.
I have tried a different strategy, using QtConcurrent::run and QFutureSynchronizer, like this:
QFuture<QString> runLeft = QtConcurrent::run(workerLeft, &Worker::performOperation);
QFuture<QString> runRight = QtConcurrent::run(workerRight, &Worker::performOperation);

QFutureSynchronizer<QString> sync;
sync.addFuture(runLeft);
sync.addFuture(runRight);

sync.waitForFinished();

But it doesn't work because I'm using a QTcpSocket in my Worker that I work with in performOperation and it fails with:
QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread

I've been able to make it work by creating the QTcpSocket in the performOperation method but I don't like that, it's pretty expensive to create the socket every time.
I think I could achieve it if I could choose which thread the QtConcurrent::run should run in, but I haven't found any similar option.

A: I think there is a confusion :
1/  if you use QtConcurrent, basically you let Qt managing every stuff related to multithreading. In this case uou do not create a worker thread manually at any point neither you move the object to this worker, see the doc :
http://doc.qt.io/qt-5/qtconcurrentrun.html
The contract is simply to pass a (staless) function that will be executed in a background thread. It's a high level parallel programming API.
2/ If you implement a worker object which lives in a worker thread, and you want to synchronise , you must use other methods, like signal/slots for example or QMutex. It's a lower level threading API and it is not meant to work in conjunction with the Concurrent and Future API.


text:
Q: Catching queries from SSAS I am looking for something like SQL Server Data Collection but for Analysis Services to log every executed OLAP query. As far as I know SSAS log doesn't provide this information.

A: You can use Profiler connected to SSAS to watch queries live.
Or you can install ASTrace to log queries or any other trace events to a SQL database without a GUI running.
Or you can use a server side trace to write to .trc files on disk on the SSAS server. Then you can later load those files to a SQL server database for analysis with a PowerShell script like this.
Or you could use XEvents.


text:
Q: Accessing Google Drive like server? Currently I'm working on an Android app that needs some centralized cloud storage location, for example a customer downloads my app and after entering their user ID the app will download their relevant information, ie name, user history, or any arbitrary small piece of information.
Since I've been working with the Google Drive API I thought I would simply set up account X to host all the customers information(none of this information is sensitive), probably in JSON format, and then whenever someone downloads my app it will connect to account X, and pull the relevant information from account X's Google Drive. The problem I have ran into is that on a device that has account X as a user account it works fine but when I try to connect on a device that doesn't have account X as a user account the app crashes.
Is what I have described possible with Drive API? In order to connect to account X's Drive does the device in use have to have it as a user account, or do I have to make the relevant files public(in sharing options) for this to work?

A: In order to connect to account X's Drive does the device in use have to have it as a user account?
No.
What you need is an access token for account X. Once you have that, you can do Drive stuff against account X. The trick is how do you get that access token. Possibilities (not recommendations) include :-

*

*embed a refresh token for account X in your app

*embed a refresh token for account X in a server app, which your Android app invokes to fetch an access token

*use a service account

A: Lots! You should never expose an access token from an account that is not owned by the user. That breaks the oauth protocol purpose. If the access token is not for the users drive then it should never leave the server side.
Unless you are using file specific scopes (this question does not) then the token will be good to delete the entire drive as well. No good.


text:
Q: php download script not work with ob_start("ob_gzhandler"); i always start index.php with ob_start("ob_gzhandler"); and end it with ob_flush();
i use HTTP Download for download files in my filemanager and it works perfectly, but if download request started with ob_start("ob_gzhandler"); in index.php it did not work.
i clean and turn off output buffering before download script
ini_set('zlib.output_compression','Off');
ob_end_clean();

but still user can't download files


text:
Q: Python calling new class object over variable So this is the initialisation of my class:
def __init__(self, x, y, item):
        self.itemHolding = item #Holding = Blueprint to place
        print(str(self.itemHolding))
        self.x = x
        self.y = y
        self.list = []

The string is just for debugging (it prints in example: )
Now I called
def update(self):
    if True:
       self.list.append(self.itemHolding(self.x,self.y))

What it should do is spawn an item on the position of itself (like a itemspawner or infinity barrel does in games sometimes).
This don't seems to work. Then how do I use the itemHolding variable to make an new instance of that class-object?
Complete code: https://github.com/ddragon15/Overlooked-OvercookedFangame-WIP- its in tiles.py at line 109
edit: What I try to do is adding a new instance (in this case a Onion (in the example a book but that doesn't matter) of this class into existens (which means its addeted to the game and into an list-array which holds it if needet)
I fixed some issues with an if statement in another function and now if I call it it says "TypeError: 'Onlion' object is not callable" which leads me to believe that it tries to access the right class, but doesn't make it into a new instance/object/iDunnoHowItsCalledInPhytonSry.
So here the runthrough from what I understand:
I make a storage (calling the init) in another file
this storage spawns (creates) a new Onion into my world if there is none in this position - so think of it like a gumball-mashine.
If the check for the instance is correct (which should work now) - this is the if true part, it should creat the new Onion and packs it into the same x and y coordinate as the storage is located at.

A: I think you need to use self.list instead of list for the second block so it should be
def update(self):
    if True:
        self.list.append(self.itemHolding(self.x,self.y))

This is so it can use the list variable in self

A: Your itemHolding member is supposed to be a type for whole runtime.
It turns out you're substituting it for an instance. It is happening in the parent class.
class All():
    ...
    def itemCheck(self):
        ...
            self.itemHolding = i

In this case, i is an instance of Onion.
Though I'm not completely sure what are you doing there, I thing you want to replace it with
self.itemHolding = type(i)


text:
Q: Hiding cards while routing while clicking on buttons my user module had 5 components:
1.user-dashboard
these are child components of user-dashboard
2.user-history
3.user-result
4.user-start-quiz
5.user-upcoming-quizzes
I want to display a menu on each component.
First, user-dashboard component load
use dashboard page
I want to hide dashboards cards when the user clicks on the button but it appears 'current-quizzes' below cards.

pagenotfound.html

<mdb-navbar  SideClass="navbar fixed-top navbar-expand-lg navbar-dark  mdb-color scrolling-navbar " [containerInside]="false" >

    <mdb-navbar-brand>
            Navbar
        </mdb-navbar-brand>
        <links>

                Dashboard(current)

                    Logout

        </links>
    </mdb-navbar>

                    Hey Welcome !

                      {{userName}}
                      {{userName}}
                      {{userName}}
                      {{userName}}

            <mat-card class="dashboard-cards" style="box-shadow:3px 3px 5px 6px #ccc;" >
              <mat-card-content>

                  <button routerLink="currentQuizzes" routerLinkActive="active" class="btn btn-outline-info btn-lg">Current Quizzes</button>

              </mat-card-content>
            </mat-card>

            <mat-card class="dashboard-cards" style="box-shadow:3px 3px 5px 6px #ccc;" >
              <mat-card-content>

                  <button routerLink="upcomingQuizzes" routerLinkActive="active" class="btn btn-outline-info btn-lg">Upcoming Quizzes</button>

              </mat-card-content>
            </mat-card>

            <mat-card class="dashboard-cards" style="box-shadow:3px 3px 5px 6px #ccc;" >
              <mat-card-content>

                  <button routerLink="history" routerLinkActive="active" class="btn btn-outline-info btn-lg">History</button>

              </mat-card-content>
            </mat-card>

            <mat-card class="dashboard-cards" style="box-shadow:3px 3px 5px 6px #ccc;" >
              <mat-card-content>

                  <button class="btn btn-outline-info btn-lg">Change Password</button>

              </mat-card-content>
            </mat-card>

<router-outlet></router-outlet>

How I can hide dashboard cards while routing but want menu/navigation...?
 defined below cards

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

/*
all components of user module
*/
import { UserDashboardComponent } from './user-dashboard/user-dashboard.component';
import { UserCurrentQuizzesComponent } from './user-current-quizzes/user-current-quizzes.component';
import { UserUpcomingQuizzesComponent } from './user-upcoming-quizzes/user-upcoming-quizzes.component';
import { UserHistoryComponent } from './user-history/user-history.component';
import { UserResultComponent } from './user-result/user-result.component';
import { UserStartQuizComponent } from './user-start-quiz/user-start-quiz.component';

const routes: Routes = [
      {
        path:'',
        redirectTo:'dashboard',
        pathMatch:'full'
      },
      {
        path:'dashboard',
        component:UserDashboardComponent,
        children:[
          {
            path:'currentQuizzes',
            component:UserCurrentQuizzesComponent,
            children:[
                      {
                         path:'startQuiz',
                         component:UserStartQuizComponent,
                      },
                     ],
          },
          {
            path:'upcomingQuizzes',
            component:UserUpcomingQuizzesComponent,
          },

          {
            path:'result',
            component:UserResultComponent,
          },
          {
            path:'history',
            component:UserHistoryComponent,
          },
        ]
      }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserRoutingModule { }

export const userRoutingComponents=[
  UserDashboardComponent,
  UserCurrentQuizzesComponent,
  UserUpcomingQuizzesComponent,
  UserHistoryComponent,
  UserResultComponent,
  UserStartQuizComponent,

]


text:
Q: When using keras and trying to train my model on my GPU my program shuts down because "Integer value: x is too large". How do I fix this? # Create the model
model = Sequential()
model.add(VGG16(weights="imagenet", include_top=False, input_shape=(IMG_SIZE, IMG_SIZE, 3)))
model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dense(128, activation="relu"))
model.add(Dense(64, activation="relu"))
model.add(Dense(4, activation="sigmoid"))

model.layers[-6].trainable = False
model.summary()

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

train = model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=50, batch_size=32, verbose=1)

I have borrowed some code and I am trying to train a model to read licence plates, but as stated in the title I get a integer than is out of bounds for int32. I do not get this problem if I remove a Cudnn library s.t the training is done on the CPU. If anyone recognizes the problem and know how to fix it that would be really helpful!
ps: I am using Windows 10, Visual Studio 2019 community, CUDA11.2, and the most recent Cudnn on a Intel and Nvidia RTX system


text:
Q: create and select the same worksheet In my code gspread creates a new worksheet for statistics, the name is "Year__Month_Day_HourMinute_'XTeam'_vs'Yteam' ", I did it this way so it's more easy to find the right worksheet. How to select this sheet for further usage. As this small program will be used at 2-3 matches in the same time (yay small time ultimate frisbee). Any idea?
I cannot do a simple "worksheet = sh.sheet1", as I don't know what will the # be. My solution would be to left out the minute of the name, that would make it easier, to just copy paste the name creator code part to the select code part, but I am hoping that there will be a better solution.
on_press: root.worksheet = root.np.add_worksheet(title=str(root.localtime.year) + "_" + str(root.localtime.month) + "_" + str(root.localtime.day) + "_" + str(root.localtime.hour) + str(root.localtime.minute) + spinner1_id.text + "_vs_" + spinner2_id.text, rows ="100", cols= "20")

A: I would not recommend using a title that varies like that, as you have to dig all that data back up just to form a search for it. I would use only 3 Varying points in your title at most, such as 'DATE_xTEAM_yTEAM'. DATE would be a STRING value such as "042318" where you can split each element from the string (MONTHDAYYEAR).
This is a method I would personally do for accessing the data easier:
Manifest a JSON file which includes a DICTIONARY of all the spreadsheets (titles) ever created. The KEY would be a NUMBER (1) and the value would be the title. So if you wanted to find the second game in the season,  create a small python script that (using 'import json') would find the value for that key.
Basically a dictionary is the best way to organize the titles.
-Ryan


text:
Q: Reliability of the scale Do we have to calculate  Cronbach's alpha for all the questions ( items) or just the variables? I have 7 variables: 4 independent, 1 dependent, 1 mediating, and 1 moderating, and 23  items  23.
Should calculate the alpha value for 23 items or 7 variables ?

A: You usually calculate alpha for scales that you plan to use. I don't understand your use of the term variable, because if your items are not variables, you (usually) can't calculate alpha.
Say I want to know the correlation between extroversion and intelligence. I might have 10 questions on extroversion (things like "I enjoy parties with lots of people.") I would usually calculate the alpha of the extroversion scale, with these 10 items (which are variables). Then I might calculate a mean or a total of these scores, and create a variable called extroversion.
Then I have 10 intelligence questions (What is 24 * 16?). Again, I have 10 items, I calculate the alpha for the 10 items, and then calculate an intelligence score (and that will be a variable).
Finally, I estimate the correlation between those two scores - of extroversion and intelligence (and they are both variables too).


text:
Q: Fragments and soft keyboard layout issue I have a fragment with a ScrollView and a Button. The ScrollView contains a LinearLayout of some TextViews and EditViews. I would like the button to remain in the bottom when soft keyboard is shown like I did with my app's activities, but it keeps rising up with the keyboard. I've read that the ScrollView may be responsible for that behavior, But without it there will be no access to the bottom EditViews.
The android:isScrollContainer="false" doesn't help either and adding android:layout_above="@+id/button_bar" to the ScrollView is not applicable in Fragments (why, I don't know). Any Ideas?
The XML layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="fragment.ProfileFragment">

    <ScrollView
        android:id="@+id/scroll_profile"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0dp"
        android:fadingEdge="none"
        android:scrollbars="none"
        android:isScrollContainer="false" >

        <RelativeLayout
            android:id="@+id/layout_profile"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="0dp"
            android:orientation="vertical"
            android:padding="0dp">

            <TextView
                android:id="@+id/text_first_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="@string/first_name"
                android:textStyle="bold" />

            <EditText
                android:id="@+id/edit_first_name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:imeOptions="actionNext"
                android:lines="1"
                android:padding="5dp"
                android:inputType="text" />

            <TextView
                android:id="@+id/text_last_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="@string/last_name"
                android:textStyle="bold" />

            <EditText
                android:id="@+id/edit_last_name"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:imeOptions="actionNext"
                android:lines="1"
                android:padding="5dp"
                android:inputType="text" />

            <TextView
                android:id="@+id/text_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="@string/phone_number"
                android:textStyle="bold" />

            <EditText
                android:id="@+id/edit_phone"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:imeOptions="actionNext"
                android:lines="1"
                android:inputType="phone"
                android:padding="5dp" />

            <TextView
                android:id="@+id/text_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="@string/email"
                android:textStyle="bold" />

            <EditText
                android:id="@+id/edit_email"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:imeOptions="actionDone"
                android:lines="1"
                android:padding="5dp"
                android:inputType="textEmailAddress" />

            <TextView
                android:id="@+id/text_help"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="@string/show_help_texts"
                android:textStyle="bold" />

            <CheckBox
                android:id="@+id/check_help"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:lines="1"
                android:padding="5dp" />

            <TextView
                android:id="@+id/text_code"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:layout_marginTop="20dp"
                android:text="@string/employee_code"
                android:textStyle="bold" />

            <EditText
                android:id="@+id/edit_code"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="top"
                android:hint="@string/employee_code_hint"
                android:imeOptions="actionDone"
                android:lines="1"
                android:padding="5dp"
                android:inputType="textPassword" />
        </RelativeLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/button_bar"
        style="?android:attr/buttonBarStyle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@drawable/button_bar"
        android:layout_gravity="bottom"
        android:layout_marginTop="@dimen/activity_vertical_margin">

        <Button
            style="?android:attr/buttonBarButtonStyle"
            android:id="@+id/button_save"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/button_save"
            android:textColor="@android:color/primary_text_dark" />
    </LinearLayout>
</FrameLayout>

A: Did you try to use android:windowSoftInputMode="adjustPan" in your manifest, for your activity element? I think it could help.
I also reccomend to replace your FrameLayout with vertical LinearLayout, if you want to keep the button under your ScrollView.


text:
Q: Replace string with special char I have this string: image/fewe that I want to replace with something else, but I'm not sure how I'm going to do that, any help maybe?

A: str_replace("replace_me", "replace_with", 'image/fewe');

preg_replace() // you'll need to look that up to match your regex with your needs.

Not sure what else you're looking for.

A: $string = 'image/fewe';
$replaceItWith = 'another string';
$result = str_replace('image/fewe', $replaceItWith, $string);

If you want to search for patterns in a string, then use preg_replace().


text:
Q: Laravel multiple count in 1 Query Im new to this Framework, i dont know how to optimize it using db::raw count and aliases and display it to my blade.php using @foreach
im trying to optimize my code, my goals is to count pallet_conditions and store it to my aliases, i dont want to count it one by one like what i did on this code
this is my code not optimize:
//computing the total rapairable
$repairable_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 1)
->count();
//REPAIRABLE

//computing the total good pallets
$good_total = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where('pallet_condition', '=', 0)
->count();
//GOOD

this is the code, what i wanted to learn. just to minimize, and use aliases
$result = DB::table('liip_psrm_items')
->select(DB::raw('COUNT(liip_psrm_items.pallet_condition = 0 ) AS condition_1',
                 'COUNT(liip_psrm_items.pallet_condition = 1 ) AS condition_2'))
                ->where('psrm_items_id', '=' , $psrm_maintenance->id)
                ->get();

A: You can't use single query for two different results, which has totally opposite conditions.
Case 1. You are trying to count the items where pallet_condition = 1;
Case 2. You are trying to count the items where pallet_condition = 0;
Now you want to merge these two cases into single query, which is impossible...
So, For these two cases, you have to use either separate queries ( what you did already )
or you can use single query to grab all the items and then use PHP to separate them.
Like:
$total_items = DB::table('liip_psrm_items')
   ->where('psrm_items_id', '=' , $psrm_maintenance->id)
   ->get();

$repairable_count = count(array_filter($total_items, function($item){
   return (bool)$item->pallet_condition;
}));

$good_count = count(array_filter($total_items, function($item){
   return !(bool)$item->pallet_condition; //just inverse of the above condition
}));

i hope this might help.

A: To count at multiple condition I used this approach
 $lastMonthInvoices = Invoice::select(DB::raw("(COUNT(*)) as count"), DB::raw('SUM(total) as total'),'status')
        ->whereDate('created_at', '>', Carbon::now()->subMonth())
        ->groupBy('status')
        ->get();

i got the result with  groupBy Status and in each group total number of records as count & also their sum as total

these two snaps are of one query result

A: You can, first group by, then get count
Like :
DB::table('liip_psrm_items')
  ->groupBy('pallet_condition')
  ->select('pallet_condition', DB::raw('count(*) as total'))
  ->get();

A: Try to pass a closure like so:
$results = DB::table('liip_psrm_items')
->where('psrm_items_id', '=' , $psrm_maintenance->id)
->where(function($query){
   $query->where('pallet_condition', 1)
      ->orWhere('pallet_condition', 0);
})->count();


text:
Q: search for data LIKE a variable but i want to find data like %?% but of course this doesn't work Im trying to search for data LIKE a variable but i want to find data like %?% but of course this doesn't work i can use LIKE ? but i need to also find all values with e.g D and comes up with Dog
       search=self.text
    with sqlite3.connect('Data.db') as db:
        user_find = db.cursor()
        user_find.execute(
            'select * from "Animal Data" where Animal_ID LIKE ? or Animal_Name LIKE ? or Animal_Type LIKE ? or Animal_Gender LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE? or Animal_colour LIKE ? or Address LIKE ?'
            ,(search,search,search,search,search,search,search,search,search,))
        data = user_find.fetchall()
        print(data)

A: You should be binding to the ? placeholder the entire expression you want to appear in the LIKE statement.  That is, if you wanted to search for any field having the letter D, you would bind the string %D% to your statement.
search = '%' + search + '%'
user_find = db.cursor()
user_find.execute(
    'select * from "Animal Data" where Animal_ID LIKE ? or Animal_Name LIKE ? or Animal_Type LIKE ? or Animal_Gender LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE ? or Animal_breed LIKE? or Animal_colour LIKE ? or Address LIKE ?',
    (search,search,search,search,search,search,search,search,search,)
)
data = user_find.fetchall()
print(data)


text:
Q: Touch Command not working in bash for some reason Something as simple as this is working surely
#!/bin/bash
touch /sdcard/successful.txt

But its not working in my actual bash command
#!/bin/bash
PACKAGE='com.mixplorer'
if [ $(pidof $PACKAGE) ]; then
  am force-stop com.mixplorer && am start -n com.mixplorer/.activities.BrowseActivity
fi

if [ ! $(pidof $PACKAGE) ]; then
  am start -n com.mixplorer/.activities.BrowseActivity
fi

loopcleaner()
{
  rm -rf /sdcard/log.txt
}

while [ $(pidof $PACKAGE) ]
do
  loopcleaner
  sleep 2

  if [ ! $(pidof $PACKAGE) ]; then
    touch /sdcard/successful.txt
    exit 0;
  fi
done

Explanation:

*

*As soon as script is executed , first check if file manager with package name 'com.mixplorer' is active
If yes , then force stop it and open it again
If no , then just simply open it.

*Now that the file manager is already opened , keep deleting a file named 'log.txt' as defined by loopcleaner every 10 seconds in a loop forever as long as file manager process is running.

*The above cleaning activity should work only till file manager process is running , Once it stops create a file named successful.txt .Script should end immediately now.
So after i have exited my file manager , the successful.text doesn't gets created in my internal storage for some reason ( which works well if simply touch command is executed )

A: I fixed it by adding a break after my touch command.
while [ $(pidof $PACKAGE) ]
do
  loopcleaner
  sleep 2

  if [ ! $(pidof $PACKAGE) ]; then
    touch /sdcard/successful.txt
    break
    exit 0;
  fi
done

( although i am very much new to bash and not really confident of myself if this this is the best approach so any further edit/ suggestions to improve it will be lot appreciated )


text:
Q: unable to use WS.url() in Play app tutorial I am doing a tutorial for Play framework with Scala. I am quite early into the tutorial and i am having a problem with ws. In my class WS is not recognized although that says to use WS.url("url-here") and to import play.api.libs._ which i have done both. I have also tried using ws.url("url-here") as well... and here wsis recognized but after that i get a "can't resolve symbol 'url'". Here is my build.sbt:
name := """play_hello"""
organization := "x.x"

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.12.3"

libraryDependencies ++= Seq(
"org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test,
"com.ning" % "async-http-client" % "1.9.29",
guice,
ws
)

And here is the code for my class:
package controllers

import javax.inject.Inject

import com.ning.http.client.oauth.{ConsumerKey, RequestToken}
import play.api.Play.current
import play.api.libs._
import play.api.mvc._

import scala.concurrent.Future

class Application @Inject()(cc: ControllerComponents) extends
AbstractController(cc){
 def tweets = Action.async{
credentials.map { case (consumerKey, requestToken) =>
  WS.url("http://stream.twitter.com")
  Future.successful{
    Ok
  }
}getOrElse{
  Future.successful{
    InternalServerError("Twitter credentials are missing!")
  }
}
}

def credentials: Option[(ConsumerKey, RequestToken)] = for{
apiKey <- current.configuration.getString("twitter.apiKey")
apiSecret <- current.configuration.getString("twitter.apiSecret")
token <- current.configuration.getString("twitter.token")
tokenSecret <- current.configuration.getString("twitter.tokenSecret")
}yield (
new ConsumerKey(apiKey, apiSecret),
new RequestToken(token, tokenSecret)
)
}

I Figure that most likely this is some type of problem with a dependency conflict. Here is a screenshot of ws related libraries in project structure. I would appreciate any help in finding a solution to this. Thank you.

A: The solution was to add ws: WSClient to the parameters of Application class constructor. Apperently standalone WS object has been removed in more recent versions of ws library.
class Application @Inject()(cc: ControllerComponents, ws: WSClient) extends AbstractController(cc)

Now i can use:
ws.url("https://stream.twitter.com/1.1/statuses/filter.json")

Also according to the documentation on play website if you for some reason can not use an injected WSClient, then you can create an instance of one and use that.


text:
Q: Lambda not capturing variable correctly I'm having a bit of an issue with C++ lambdas and variable capture (by reference).  One lambda captures the variable to change its value while the other captures it to read the value.  Everything is running on the same thread.
bool isRunning = true; // variable to be captured

Cedar::Input input;
input.registerOnQuit([&]()->void {
    isRunning = false; // wrong address, value is constrained to lambda
});

Cedar::Platform platform;
platform.run([&](double t, double dt)->bool {
    input.pump(); // internally fires the handler passed to registerOnQuit()
    return isRunning; // correct address
});

If it's any help, internally the lambdas are being boxed into C callbacks using void pointers.  However, I doubt that's where the problem lies because, essentially, the two lambdas are going through the exact same process and one works while the other doesn't.
// boxes the broken lambda
using OnQuit = std::function<void()>;
void registerOnQuit(OnQuit event) {
    Cedar_Input_registerOnQuitC([](void *data)->void {
        (*(OnQuit *)data)();
    }, (void *)&event);
}

// boxes the working lambda
using Hook = std::function<bool(double, double)>;
void run(Hook hook) {
    Cedar_Platform_runC([](double t, double dt, void *data)->bool {
        return (*(Hook *)data)(t, dt);
    }, (void *)&hook);
}

SOLUTION
I gave the Cedar::Input and Cedar::Platform classes fields to store a copy of the lambdas.
// fix to Cedar::Platform::run() is similar
using OnQuit = std::function<void()>;
void registerOnQuit(OnQuit event) {
    m_onQuit = event;
    Cedar_Input_registerOnQuitC([](void *data)->void {
        (*(OnQuit *)data)();
    }, (void *)&m_onQuit);
}

A: You're storing a dangling pointer:
void registerOnQuit(OnQuit event) {
    Cedar_Input_registerOnQuitC([](void *data)->void {
        (*(OnQuit *)data)();
    }, (void *)&event);  // <-- saving a pointer to event here

    // <-- event goes out of scope here
}

This is undefined behavior. You're doing the same thing in the other case too, it just happens to work there.


text:
Q: C#: Mocking and testing protected (or private) methods in sealed classes -- approaches I have a sealed class with protected methods whose behaviour I want to test. This makes it hard to test directly, and hard to mock.
It's in a codebase that wasn't developed in a TDD manner, and I'm now adding unit tests for specific functionality.
What are the general approaches possible in this case? At the moment I have:

*

*Have the class unsealed. Then create a proxy or adapter derived from the class in our test code to tunnel access to the protected method.

*Factor out the behaviour in the protected method to a delegate/functor, and re-inject it. Then test the factored out behaviour independently.

*Test by calling the closest public method in the inheritance hierarchy that uses the protected method. Potentially leads to lots of mocking, and exposure to risk when code other than that under test changes -- creating fragile tests.

*Use reflection to get access to the protected method. Then call it directly.
Are there any more?

A: A protected method in a sealed class is effectively the same as private (I guess if you seal a derived class where the base class has a protected member these can come up naturally.)
And there's no point testing private methods. Because they have no public behavior except that which is accessible through the public methods of the defining class, their behavior should be tested by testing the public methods.

A: Microsoft Moles helps mocking unsealed classes with non-virtual methods. It can't mock private methods, but this is redundant, because you can mock higher level public methods, that used outside particular class and you can emulate all necessary behaviour mocking one public method.
And why you should test private/protected methods? You can use internal methods and InternalVisibleToAttribute to achieve this. But in general you should test only public behaviour (i.e. only public interface).

A: I would generally go for the second option assuming that you have the ability to make the changes reasonably easy. Given that if you cannot test what a protected /private method is doing through it's public interface it probably isn't conforming to Single responsibility principle anyway and the code could probably do with being broken into two classes and use composition instead.

A: You can use some framework for mocking - for example JustMock (by Telerik) supports mock of sealed private methods ... Unfortunately, this part of JustMock is paid, I think, but at least you can try the trial version.

A: You could use the JustMock framework.
For example:
double value = 0;
var fakeFilterSetHelper = Mock.Create<FilterSetHelper>(Behavior.CallOriginal);
Mock.NonPublic.Arrange<double>(fakeFilterSetHelper, memberName: "GetPriceRangeFromSession").Returns(value);


text:
Q: MySQL - Getting Top n records and ordering by a specific column with pagination I have got a problem with getting top n records from database and ordering them by a specific column and paginating them.
For example I want first 100 movies from movie table and order these first 100 records by name and display 10 records per page.
However this doesn't work;
SELECT name FROM movies ORDER BY id DESC, name DESC, LIMIT 0,10

I am quite confused here. In order to paginate I have to use LIMIT in such ways;
LIMIT 0,10 = FIRST PAGE
LIMIT 10,20 = SECOND PAGE

and so on.
In order to get first records, I use ORDER BY id DESC however when I want to list FROM Z to A, ORDER BY id DESC, name DESC doesn't do the trick.
In another words what I want to do is to get first (latest) 100 records out of 10.000 and order this 100 records by name (ASC or DESC) and / or by view (ASC or DESC).
I hope I was clear enough to explain my problem.
I will be glad if you could help me out with this one.

A: Shift the order of your order by statements
(updated)
select   name
from     ( select    *
           from     movies
           order by id desc
           limit 100 )
order by name desc
limit    0,10

It uses the first one first and if equal it looks at the next one

A: Wrap your select in another select;
SELECT name FROM (SELECT * FROM movies ORDER BY id DESC LIMIT 0,100) ORDER BY name DESC LIMIT 0,10

Edit: Updated limits.

A: You could try to use
select name from
(select name from movies order by id desc limit 0,100)
order by name desc limit 0,10


text:
Q: A Service Loaded exe can't 'System.Diagnostics.Process.Start' a URL? I have a simple Tray icon program that opens a site using
System.Diagnostics.Process.Start("URL")

And it works fine independently, however when a service loads it, it gives a file not found exception when trying to open the URL, and after testing it can open normal extensions, e.g .txt (The service has desktop interaction enabled).

A: If you Process.Start a URL, it is loading a browser app, which isn't (for Vista/etc) going to display for a service (for the same reasons as your last question).
If you want the app to interact with the user/desktop, it shouldn't be a service - it should simply run when the user logs in. Note that any child-process that your service spawns will also be in the service's session.
If you just want to get data (through code) from the site, use WebClient etc.


text:
Q: Can I test a replacement iPhone I bought at auction for carrier compatibility by inserting the SIM without screwing up my existing account? I bought a replacement iPhone SE (older model) because battery on my old one was waning. I need to test it before return window expires to make sure it is compatible with my carrier (Verizon) but I don't want to activate it yet.  Is that possible to do by inserting a SIM the carrier sent me?

A: I believe Verizon in the US keeps their gates shut and you need their help to activate devices. There's probably no harm in swapping the sim, especially if you have an alternate way to call them / get support if your phone stops working.

*

*https://www.verizon.com/solutions-and-services/activate-my-device/