text:
Q: How to set configuration in Hive-Site.xml file for hive metastore connection? I want to connect MetaStore using the java code. I have no idea how to set configuration setting in Hive-Site.xml file and where I'll post the Hive-Site.xml file. Please help.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;

public class HiveMetastoreJDBCTest {

    public static void main(String[] args) throws Exception {

        Connection conn = null;
        try {
            HiveConf conf = new HiveConf();
            conf.addResource(new Path("file:///path/to/hive-site.xml"));
            Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
            conn = DriverManager.getConnection(
                    conf.getVar(ConfVars.METASTORECONNECTURLKEY),
                    conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
                    conf.getVar(ConfVars.METASTOREPWD));

            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(
                "select t.tbl_name, s.location from tbls t " +
                "join sds s on t.sd_id = s.sd_id");
            while (rs.next()) {
                System.out.println(rs.getString(1) + " : " + rs.getString(2));
            }
        }

    }
}

A: Add these lines in your hive-site.xml:
<property>
  <name>hive.metastore.local</name>
  <value>true</value>
</property>
<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://localhost:3306/hive</value>
</property>
<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>hiveuser</value>
</property>
<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>hivepass</value>
</property>

In jdbc:mysql://localhost:3306/hive, 3306 is your default mysql port; hive is our mysql database name for hive metastore.
Change hiveuser to your mysql hive username and hivepass to your mysql hive password.
Do this step in terminal, if you haven't created a database for hive metastore in mysql:
mysql -u root -p
Enter your mysql root password.
mysql> create database hive;
mysql> create user 'hiveuser'@'%' IDENTIFIED BY 'hivepass';
mysql> GRANT all on *.* to 'hiveuser'@localhost identified by 'hivepass';
mysql>  flush privileges;
Here, hiveuser and hivepass are whatever username and password you give for hive metastore respectively.

NOTE: You need to have mysql-jdbc-connector.jar in $HIVE_HOME/lib and
  $HADOOP_HOME/lib

A: Regarding Hive-site.xml here is sample from my testing machine. This is for setting up hive metastore with MySql server installed on localhost.
<configuration>
<property>
 <name>javax.jdo.option.ConnectionURL</name>
 <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
 <description>metadata is stored in a MySQL server</description>
</property>
<property>
 <name>javax.jdo.option.ConnectionDriverName</name>
 <value>com.mysql.jdbc.Driver</value>
 <description>MySQL JDBC driver class</description>
</property>
<property>
 <name>javax.jdo.option.ConnectionUserName</name>
 <value>hive</value>
 <description>user name for connecting to mysql server </description>
</property>
<property>
 <name>javax.jdo.option.ConnectionPassword</name>
 <value>123456</value>
 <description>password for connecting to mysql server </description>
</property>
</configuration>

This file you need to place inside <system_path>/apache-hive-x.xx.x-bin/conf directory
I do not have much idea about how to use this file in java. But by specifying connection string in java code you can do it as below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class WriteToHive {
    private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
    static Connection con;
    static Statement stmt;

    public WriteToHive() throws SQLException, ClassNotFoundException, Exception {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e){
            e.printStackTrace();
            throw new ClassNotFoundException("No JDBC Hive Driver found");
            //System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
            //System.exit(1);
        }

        con = DriverManager.getConnection("jdbc:hive://localhost:10000/rajen","","");
        stmt = con.createStatement();
    }

    public static void main(String[] args) throws SQLException {
        try {
            Class.forName(driverName);
        } catch (ClassNotFoundException e){
            e.printStackTrace();
            System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        con = DriverManager.getConnection("jdbc:hive://localhost:10000/rajen","","");
        stmt = con.createStatement();
        //Connection con = DriverManager.getConnection("jdbc:hive://","","");
        String tableName = "company_mas_hive_eclipse_trial";

        ResultSet res = stmt.executeQuery("use rajen");

        String sql = "DROP TABLE IF EXISTS " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);

        sql = "CREATE TABLE IF NOT EXISTS rajen.company_mas_hive_eclipse_trial (" +
              "Name string," +
              "dateofincorporation string," +
              "country string)" +
              "ROW FORMAT DELIMITED FIELDS TERMINATED BY \",\"";
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);

        sql = "show tables '" + tableName + "'";
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);

        if (res.next()){
            System.out.println(res.getString(1));
        }

        sql = "describe " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        System.out.println("=========================================");
        while (res.next()) {
          System.out.println(res.getString(1) + "\t" + res.getString(2));
        }
        System.out.println("=========================================");

        // load data into table
        // NOTE: filepath has to be local to the hive server
        // NOTE: /tmp/a.txt is a ctrl-A separated file with two fields per line
        String filepath = "/home/seo/Refrence_Doc/sampledata/companymas"; //"/rajen/companymas";
        sql = "load data local inpath '" + filepath + "' into table " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);

        // load data into table
        // NOTE: filepath has to be local to the hive server
        // NOTE: /tmp/a.txt is a ctrl-A separated file with two fields per line
        filepath = "/rajen/companymas";
        sql = "load data inpath '" + filepath + "' into table " + tableName;
        System.out.println("Running: " + sql);
        //res = stmt.executeQuery(sql);

        // select * query
        sql = "select * from " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(String.valueOf(res.getString(1)) + "\t" + res.getString(2));
        }

        // regular hive query
        sql = "select count(*) from " + tableName;
        System.out.println("Running: " + sql);
        res = stmt.executeQuery(sql);
        while (res.next()) {
            System.out.println(res.getString(1));
        }
    }

    public void createTable(String def, String dbname) throws SQLException{
        @SuppressWarnings("unused")
        ResultSet res = stmt.executeQuery("use " + dbname);
        stmt.executeQuery(def);
    }

    public static void loadData(String filepath, String tableName) throws SQLException{
        stmt.executeQuery("load data local inpath '" + filepath + "' into table " + tableName);
    }
}


text:
Q: webjob message poisoning for servicebuss (type queue) I am trying to handle my message poisoning by it doesn't hit my poison method. I am following this article from Microsoft and this is my code:
public static void ProcessQueueMessage([ServiceBusTrigger("emailqueue")] EmailModels.EmailSendModel message, TextWriter log,[SendGrid()] out Mail mail)
    {
        log.WriteLine(message);
        mail = new Mail(){Subject = message.Title};
        mail.From = new Email("me@gmail.com");
        mail.AddPersonalization(new Personalization()
        {Tos= message.To.Select(t=>new Email (t.Email)).ToList()});
        mail.AddContent(new Content("text/plain", $"The message {message.Body}' was successfully processed."));
    }

    public static void ProcessPoisonMessage([ServiceBusTrigger("emailqueue-poison")] EmailModels.EmailSendModel message, TextWriter logger)
    {
        logger.WriteLine($"start poisoning");
        logger.WriteLine($"Poisoning message for proposal id {message.ProposalId} for list {JsonConvert.SerializeObject(message.To)}");
    }

The send method gets hit 5 time and fails (intentionally) but then the poisoning doesn't get hit and my message ends up in the dead-letter messages without any action :|
What am I doing wrong?

A: The article you quoted is describing Azure Storage Queues, not Service Bus. They are distinct services, and poison message handling is quite different.
Try marking your trigger with
[ServiceBusTrigger("emailqueue/$DeadLetterQueue")]

redpajama_set_name: RedPajamaStackExchange


text:
Q: itertools.ifilter with IPython Parallel For some problem [proven to be NP hard] I have no other option but exhaustive search. I have a set of data — for simplicity, S = ['A', 'B', 'C', ... ,'Z'] and want to apply a function f to all subsets of length N < len(S) of this set.  I cannot use lists here since binomial coefficients binom(len(S),N) are some billions. But the result of f(x), x∈S is zero for almost all the values of S. Therefore in simple cases all works great with

   from itertools import ifilter, combinations
   answer = list(ifilter(lambda x: f(x) > 0, combinations(S,N)))

But in real life, len(S) ~ 10⁴ and N ~ 10². What I want is to spread the work among CPU engines using ipyparallel. I have a small cluster with a hundred of CPU cores. But I still cannot afford to store combinations as lists, therefore I need something like separate generators.
There are a couple of examples of how to split generator into chunks, but as far as I understand they are still consecutive generators. There is also an idea of @minrk that is related but it performs really bad for some reason.
So the questions are:

*

*is there any way to implement itertools.ifilter directly with ipyparallel? or

*is it possible to separate python generator into a set of independent generators (to send them to ipcluster engines independently)?

A: Exhaustive search is utterly hopeless here, no matter how you parallelize it. With len(S) and N at such high orders of magnitude, you would need to search through about 6e241 solution candidates. This is far beyond the capacity of any computational system humanity could ever hope to build.
You will need to use a smarter algorithm.


text:
Q: Broken SelectedItems comparison in Access While loop To allow portability of an Access database, I want to force the user to select its folder if it's copied to another computer. I have run into a stumbling block, though, in trying to test for the folder's path.
In the code below, the if statement block works when not commented out, but the while statement above it does not. I get:

Run-time error '5': Invalid procedure call or argument.

I've looked at Tools > References, and the appropriate pieces seem to be in place. I've tried fd.SelectedItems.Count = 0, but that doesn't prevent an unwanted string from being passed.
Private Sub btn_CorrectPath_Click()
   Dim sHostName As String, strSQL As String, sFolder As String
   Dim rs As Recordset, db As Database, fd As FileDialog
   Dim intResult As Integer

   Set db = CurrentDb
   ' Get Host Name / Get Computer Name
   sHostName = Environ$("computername")
   Set rs = CurrentDb.OpenRecordset("SELECT * FROM t_ComputerInfo")

   If rs!ComputerName <> sHostName Then
      Set fd = Application.FileDialog(msoFileDialogFolderPicker)
      fd.AllowMultiSelect = False
      fd.Title = "Select database folder"

      intResult = fd.Show
      While intResult = False
         intResult = fd.Show
         While fd.SelectedItems(1) = vbNullString 'folder path was not selected
            intResult = fd.Show
         Wend
      Wend
      sFolder = fd.SelectedItems(1)
      strSQL = "UPDATE t_ComputerInfo SET [t_ComputerInfo].[ComputerName] = '" & sHostName & _
             & " [t_ComputerInfo].[DBPath] = '" & sFolder & "' WHERE [t_ComputerInfo].[ID] = 1"
      CurrentDb.Execute strSQL, dbFailOnError

'      If fd.Show = True Then 'Action button was pressed
'         MsgBox ("Directory was given. fd.SelectedItems(1)= " & fd.SelectedItems(1))
'         If fd.SelectedItems(1) <> vbNullString Then
'            sFolder = fd.SelectedItems(1)
'            strSQL = "UPDATE t_ComputerInfo SET [t_ComputerInfo].[ComputerName] = '" & sHostName & _
                     "', [t_ComputerInfo].[DBPath] = '" & sFolder & "' WHERE [t_ComputerInfo].[ID] = 1"
'            MsgBox ("SQL statement = " & vbCrLf & strSQL)
'            CurrentDb.Execute strSQL, dbFailOnError
'         End If
'      Else 'Cancel button was pressed
'         sFolder = fd.SelectedItems(1)
'         MsgBox ("The location of the database is required and will be requested later. fd.SelectedItems(1)= " & sFolder)
'      End If
      Set fd = Nothing
   End If

   db.Close
End Sub

A: Firstly, note that you have doubled-up the ampersand in this concatenation:
strSQL = "UPDATE t_ComputerInfo SET [t_ComputerInfo].[ComputerName] = '" & sHostName & _
         & " [t_ComputerInfo].[DBPath] = '" & sFolder & "' WHERE [t_ComputerInfo].[ID] = 1"
         ^----- Here

For the rest of your code, I believe you can remove the while loop entirely (unless you really want the user to be stuck in a loop until they select a folder...?).
I might suggest something along the lines of the following:
Private Sub btn_CorrectPath_Click()
    Dim fdr As String
    Dim pcn As String

    pcn = Environ$("computername")
    If Nz(DLookup("computername", "t_computerinfo"), "") <> pcn Then
        With Application.FileDialog(4)
            .AllowMultiSelect = False
            .Title = "Select Database Folder"
            If .Show Then fdr = .selecteditems(1)
        End With
        If fdr <> "" Then
            With CurrentDb.CreateQueryDef("", "update t_computerinfo t set t.computername = @pcn, t.dbpath = @fdr where t.id = 1")
                .Parameters(0) = pcn
                .Parameters(1) = fdr
                .Execute dbFailOnError
            End With
        End If
    End If
End Sub

Here, I've used DLookup in place of opening a recordset, as this seemed overkill when querying a single value, though, you will probably want to supply DLookup with some criteria.
I've also used a parameterised SQL statement in place of concatenating values, as this is better practice and also takes care of the data types.

A: I don't see need for nested While. Consider:
Dim booResult As Boolean
...
While booResult = False
    If fd.Show = True Then 'folder path was selected
        booResult = True
        sFolder = fd.SelectedItems(1)
    End If
Wend


text:
Q: Getting Error 500 from Firestore request - Having issues with Firestore on NodeJS (functions). I have an API with the following:
export const getPost = (req: any, res: any): any => {
  let postData: any = {};
  postData.postId = req.params.postId;
  db.collection("posts").doc(`${req.params.postId}`)
    .get()
    .then((doc) => {
      if (!doc.exists) {
        return res.status(404).send({ error: "Post not found", success: false });
      }
      if( doc.data() && postData.postId)
      {
        postData = doc.data();
      postData.postId = req.params.postId;
      let commentsRef = db.collection("comments");
      return commentsRef.orderBy("createdAt", "desc").where("postId", "==", req.params.postId).get();
      }

    })
    .then((data) => {

      if(data){
        postData.comments = [];
        data.forEach((doc: any): any => {
          postData.comments.push({ ...doc.data(), commentId: doc.id });
        });
      }
      return res.status(200).send({ data: postData, success: true });
    })
    .catch((err) => {
      res.status(500).send({ error: err, success: false });
    });
};

At the moment, there are no comments. There are posts. Yet I'm getting an Error .
[Error: Request failed with status code 500]
Am I missing something? Pretty confused if I'm honest.
Thanks

A: Ah fixed!
My API was returning the error code, though not the error message content. I created a firestore log collection for error logs. On doing so, found that the error was as follows:

Thankfully, an easy fix, you just follow the link in the error and Firestore makes the index for you. Once I did that a few times (for each required index). It worked a treat.


text:
Q: Does thunderbird contain gecko in it? As new Thunderbird user I was exploring its UI and noticed (besides rather basic HTML typically used in rich-formatted emails) that add-on manager opens a tab with https://addons.thunderbird.net/ and allows a limited browsing (no back button and address bar) of that website. The rendering of the website sort of implies that I view it thru fully-featured (or limited) web browser. Given Thunderbird is a sister project to Firefox and having a similar architecture, I can come to conclusion what this Thunderbird component is Mozilla Gecko. Could someone please positively (or negatively) confirm that? And maybe add some explanation on the "internal browser's" capabilities and limitations. Unfortunately, Thunderbird is very poorly documented, even developer's article on that subject has not been written yet.
So far this question is purely theoretical, but if it is really fully functional Gecko there could be some uses for it, eg. viewing PDF attachments via built-in pdf.js or even submitting basic subscribe/unsubscribe web-forms. But this is rather broad topic, let it be the separate discussion.

A: Yes, Thunderbird contains Gecko.  Gecko isn't actually a browser, it's much of the engine on which a browser is built.  It's in all Mozilla products that relate to web browsing and email (and a number of third party products).  For a better understanding of what Gecko is and does, see https://developer.mozilla.org/en-US/docs/Gecko/FAQ.
It's listed in the Thunderbird user agent (see this list, and for example, this parsing).  It is used as the layout engine for rendering messages and as part of the Thunderbird user interface.  As far as browsing the web, Thunderbird uses it to a very limited extent to view a designated collection of pages such as the add-on related stuff.  That is a very controlled range of content.
But Thunderbird has no provision for you to specify an arbitrary URL for it to render, and doesn't contain the supporting infrastructure to handle the range of content you can encounter on the web in general.  Any links contained in messages are opened by the default browser as specified in your OS settings.  See this link and this link.  Some step-by-step instructions for setting a Thunderbird-specific browser here.
There are also some add-ons that let you select a different browser to open a link, but you can't specify Thunderbird, itself.  The same applies to rendering any other type of attachment.
There used to be an add-on called ThunderBrowse (and perhaps others?), that allowed you to view web links in Thunderbird.  But that is no longer compatible with the recent versions of Thunderbird, and I don't know how it worked (i.e., built on top of the internal Gecko engine or just a lightweight browser that got integrated).
The documentation on Gecko is, indeed, a bit hit-or-miss.  Many of the available links haven't been well maintained.  There's a good general discussion on Wikipedia.

A: Yes, Thunderbird is built exactly like Firefox – it uses Gecko to render both the "contents" (email messages themselves) and the "chrome" (the whole Thunderbird UI).
(Don't forget that the original "Mozilla" browser, as well as its Netscape predecesor, had the web browser and the mail client in a single program, and Thunderbird is essentially just the mail component split out.)
Though you'll notice that the email preview windows are severely restricted (e.g. no JavaScript, hardly functional forms, all links forced to open in a new window), but that is deliberately done for security reasons because we just can't have nice things – the whole email message is still rendered using Gecko. (And if you use Thunderbird as an Atom/RSS feed reader, it will show the linked webpage.)
There were indeed plans to use pdf.js inside Thunderbird, and apparently there is a "Conversations" addon which can also provide this feature.


text:
Q: rake assets:precompile throws Sass::SyntaxError: Invalid CSS after "*/" I hope this isn't a duplicate problem; I've tried other solutions on SO with no effect
When pushing my app to Heroku, the push has failed because application.css has not been able to compile.
My terminal output:
Running: rake assets:precompile
rake aborted!
Sass::SyntaxError: Invalid CSS after " */": expected selector, was "@font-face"
(in /tmp/build_17e92975-ae8d-446f-8678-110eeeccfb64/app/assets/stylesheets/adminsite/application.css)
(sass):1845

Attempts at solution
I've searched and deleted every instance of "*/" that comes before an @font-face inside the ../stylesheets/adminsite/ directory. Same issue and result.
I've tried setting:
  config.assets.compile = true

...Same issue
Edit
Here is my application.css (not the app level one, but the one failing in the adminsite directory)
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the top of the
 * compiled file, but it's generally better to create a new file per style scope.
 *
 *= require jquery.ui.all
 *= require_self
 *= require normalize
 *= require ./global/plugins/bootstrap/css/bootstrap
 *= require ./global/plugins/uniform/css/uniform.default
 *= require ./global/plugins/bootstrap-switch/css/bootstrap-switch
 *= require ./global/css/components
 *= require ./global/css/plugins
 *= require ./global/plugins/simple-line-icons/simple-line-icons
 *= require ./admin/layout/css/layout
 *= require ./admin/layout/css/themes/light2
 *= require ./admin/layout/css/custom
 */

By removing and recompliling, I found that
*= require ./global/plugins/font-awesome/scss/font-awesome

that was 3 from the bottom of that list, was causing it to fail. I can now locally run
rake assets:precompile --trace RAILS_ENV=production

but I can't push to heroku using
git push herokunb newbeta:master

SOLVED:
It was the font awesome CSS. Removing that from require fixed it. The issue appeared unsolved only due to my own mistakes with git.

A: Even though you found your way to fix it, I'm gonna share my solution too, because I was facing the same issue and it was kinda hard to debug it.
You're probably using rails 3.2, sass-rails 3.2 and font-awesome-sass 4.1.
It turns out that the rails 3.2 uses sass-rails 3.2.6, which depends on sass >= 3.1. However, It looks like sass 3.1 is not compatible with font-awesome 4.1, so I explicitely set the sass gem to use version 3.2 on my Gemfile.
gem 'sass-rails', '~> 3.2.6'
gem 'sass', '~> 3.2.0'

Hope this helps someone! ;)

A: I ran into a similar issue as well and stumbled upon this thread.  Turned out for me, I left a } off of the end of one of my CSS statements.  Added it in and I was back up within minutes.

A: Another way to solve this is to explicitly tell the asset-pipeline to use the css version of the asset over the scss one. For example, if you're importing a .scss file in your application.scss like this:
@import "angular-material";      # this will use scss version of the asset

You can alternatively tell it to use the css version like so:
@import "angular-material.css";  # this will use the css version

Most vendors provide scss and css versions, so it is useful to rely on css versions of assets especially when using vendor assets. Remember everything will be precompiled and uglified in the end, so wither you use scss or css they all end up the same.

A: SOLUTION
The file that was breaking things was the font awesome CSS. Removing that from application.css's "require" lines allowed the precompilation to work.
The way to do this was to first delete all of the precompilation require fields, showing that it would compile, and then to slowly add the require fields back to see where it broke.
(Thanks for all those who helped figure this out.)

A: For me, I forgot to add # in front of the class sign-in.
It should be
#sign-in
  (your code)

A: I'm a newbie to rails and was having a similar issue when pushing to heroku. A friend looked at my application.css file and noticed that I had
*= require bootstrap
and
*= require bootstrap-datetimepicker
below the */
Removing them allowed me to push successfully.


text:
Q: prove continuity of additive function of integer group under topology $T=\{ \mathbb Z,\emptyset \} \cup\{[n,\infty), n \in \mathbb Z\}$ Assume that $(\mathbb Z,+)$ be group which has been armed by  topology
$T=\{ \mathbb Z,\emptyset \} \cup\{[n,\infty), n \in \mathbb Z\}$
How to show that additive function($(a,b)\to_f a+b)$ is is continuous under defined topology and inverse function(  $a\to_ga^{-1})$ is not continuous
since pull back of open set $[n,\infty)$   under $g$is not open then  $g$ is no not continuous
I tried to use $\epsilon, \delta $ definition to prove continuity of $f$
$$\forall  \quad U_{a+b} : \exists \quad U_a,U_b  \quad\text{s.t}\quad U_a+U_b\subset  U_{a+b} $$
 since all open set in  T has form of $[n,\infty)$ or$[m,n)$ enough to show that
 above statement for all for every all possible open set  but I think its rough way for this problem.    Does the easy solution??

A: For $n\in\Bbb Z$ let $U_n=[n,\to)$. Then
$$f^{-1}[U_n]=\{\langle k,\ell\rangle\in\Bbb Z\times\Bbb Z:k+\ell\ge n\}\;,$$
so you need to show that this set is open for any $n\in\Bbb Z$.
HINT: Given $\langle k,\ell\rangle\in f^{-1}[U_n]$, consider the set $U_k\times U_\ell$. Sketching $\Bbb Z\times\Bbb Z$ and $U_n$ might help.


text:
Q: Route to get a member of a model by a value other than :id I have Students, each of which has a standard :id but they also have a :student_number which is unique. I would like to be able to find a view a student given only their :student_number
Here's the route I have now:
resources :students do
    collection do
        get 'find_by_num'
    end
end

This works, but it feels a little strange, creating a 'collection' for what I know will be a single result--that is, a 'member'. At the same time, members expect :id and I don't have one.
What would be the accepted, RESTful way of doing this?
I searched for an existing answer and found this question, but I'm interested in the route itself.
Thanks for any help!

A: Ok I hope I understood correctly your question and you want something like
http://myapp.com/users/student_number to get you to the specific student.
If that is the case, you don't need to do anything with the routing, just in the Users Controller
def show
  @user = User.find_by(student_number: params[:id])
end

Then in your views, to link to the student you will have:
= link_to user.name, user_path(user.student_number)


text:
Q: React: How to use received json data from firebase to make list of array? I want to make a list of user details by filling the form with name, email, designation, phone & image input field, I've saved the form data in an object and sent the form data to it's parent using props addedUser(userData);, I'm using this addedUser prop in the parent component to send the data to the firebase and then use the same fetched data to make a list of users in array.
I've made loadedData empty array simply wanna push the data into it but the responseData.json() doesn't give me anything, the data is being saved to firebase perfectly but I'm facing problems using it.
Please check the code here and also the <Users /> component code where I'm trying to make the list:
Parent:-
function App() {
    const [userData, setUserData] = useState([]);

    const fetchData = useCallback(async () => {
        try {
            const responseData = await fetch(
                "https://react-users-db-default-rtdb.asia-southeast1.firebasedatabase.app/users.json"
            );

            const data = responseData.json();
            console.log(data);

            const loadedData = [];

            for (const key in data) {
                loadedData.push({
                    key: key,
                    userName: data[key].userName,
                    userEmail: data[key].userEmail,
                    userDesignation: data[key].userDesignation,
                    usePhone: data[key].usePhone,
                    userImage: data[key].userImage,
                });
            }

            console.log(loadedData);

            setUserData(loadedData);
        } catch (err) {
            console.log(err);
        }
    }, []);

    useEffect(() => {
        fetchData();
    }, [fetchData]);

    async function recieveUserData(users) {
        const responseData = await fetch(
            "https://react-users-db-default-rtdb.asia-southeast1.firebasedatabase.app/users.json",
            {
                method: "POST",
                body: JSON.stringify(users),
                headers: {
                    "Content-Type": "application/json",
                },
            }
        );
        const data = await responseData.json();
        console.log(data);
    }

    return (

                <AddUserForm addedUser={recieveUserData} />

                {userData.length > 0 ? (
                    <Users newUser={userData} />
                ) : (

No user found

                )}

    );
}

Users Component:
export default function Users({ newUser }) {
    console.log(newUser);
    return (

            {newUser.map((el, i) => {
                return (
                    <UserCard
                        key={i}
                        name={el.userName}
                        email={el.userEmail}
                        designation={el.userDesignation}
                        phone={el.userPhone}
                        image={el.userImage}
                    />
                );
            })}

    );
}

Data is going to firebase:-

But responseData.json() is giving me this, I can't see my user object to access:-

A: In your fetchData function you need to await responseData.json().
 const data = await responseData.json();


text:
Q: Any example for gantt chart using d3.js in react.js either with d3.js or react.js approach? I want to build gantt chart using d3.js in my react.js app. But both manipulate DOM. So,there are 3 ways https://frontendcharts.com/react-d3-integrate/ to go with this. I will like to go with first approach i.e D3 approach. It'll be highly appreciated if I get a basic example implemented as I have to showcase it to my senior.
I tried below code but it gives error 'gantt' is not exported from 'd3' (imported as 'd3'). One thing more is that how to add this gantt chart to SVG.
import React, { Component } from 'react';
import * as d3 from 'd3';

let tasks = [
    { "startDate": new Date("Sun Dec 09 01:36:45 EST 2012"), "endDate": new Date("Sun Dec 09 02:36:45 EST 2012"), "taskName": "E Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 04:56:32 EST 2012"), "endDate": new Date("Sun Dec 09 06:35:47 EST 2012"), "taskName": "A Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 06:29:53 EST 2012"), "endDate": new Date("Sun Dec 09 06:34:04 EST 2012"), "taskName": "D Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 05:35:21 EST 2012"), "endDate": new Date("Sun Dec 09 06:21:22 EST 2012"), "taskName": "P Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 05:00:06 EST 2012"), "endDate": new Date("Sun Dec 09 05:05:07 EST 2012"), "taskName": "D Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 03:46:59 EST 2012"), "endDate": new Date("Sun Dec 09 04:54:19 EST 2012"), "taskName": "P Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 04:02:45 EST 2012"), "endDate": new Date("Sun Dec 09 04:48:56 EST 2012"), "taskName": "N Job", "status": "RUNNING" },
    { "startDate": new Date("Sun Dec 09 03:27:35 EST 2012"), "endDate": new Date("Sun Dec 09 03:58:43 EST 2012"), "taskName": "E Job", "status": "SUCCEEDED" },
    { "startDate": new Date("Sun Dec 09 01:40:11 EST 2012"), "endDate": new Date("Sun Dec 09 03:26:35 EST 2012"), "taskName": "A Job", "status": "SUCCEEDED" }
];

let taskStatus = {
    "SUCCEEDED" : "bar",
    "FAILED" : "bar-failed",
    "RUNNING" : "bar-running",
    "KILLED" : "bar-killed"
};

let taskNames = [ "D Job", "P Job", "E Job", "A Job", "N Job" ];

class Chart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tasks: tasks,
            taskStatus: taskStatus,
            taskNames: taskNames,
            format: "%H:%M",
        }
    }

    drawChart = () => {
        let gantt = d3.gantt().taskTypes(this.state.taskNames).taskStatus(this.state.taskStatus).tickFormat(this.state.format);
        return gantt(this.state.tasks);
    }

    render() {
        return (
            <div>
                {this.drawChart()}
                {/* <svg width={this.props.width} height={this.props.height} ref={e1 => this.svgE1 = e1}></svg> */}
            </div>
        )
    }
}

export default Chart;

I just want a basic example of gantt chart using d3.js in react.js

A: Apparently d3.gantt() is an external library called Gantt-Chart, so in addition to d3 library it needs to be imported as well.
And last but no least, make sure to install d3 version V3, for example: npm i d3@3.5.12 since d3-gantt-chart is compatible with v3 version.
Once d3 and d3-gantt-chart packages are installed, the chart component could be implemented like this:
import React, { Component } from "react";
import * as d3 from "d3";
import "d3-gantt-chart";

class GanttChart extends Component {

  componentDidMount() {
    this.drawChart();
  }

  drawChart() {
    const { tasks, taskTypes, taskStatus, tickFormat } = this.props;
    var gantt = window.d3
      .gantt()
      .taskTypes(taskTypes)
      .taskStatus(taskStatus)
      .tickFormat(tickFormat);
    gantt(tasks);
  }

  render() {
    return null;
  }
}

export default GanttChart;

Here is a demo for your reference (adapted from this original example)


text:
Q: Why is firewalld allowing public traffic to my non-public ports, bound to Docker containers? I'm trying to implement a pretty simple firewall in Fedora, where the public internet can access SSH, HTTP, HTTPS and Cockpit, but nothing else. Meanwhile, the servers run microservices via Docker that can talk to each other on ports 8000-8999.

I set this up on a fresh Fedora Server install with the following commands:
firewall-cmd --zone=public --add-service=cockpit
firewall-cmd --zone=public --add-service=http
firewall-cmd --zone=public --add-service=https

firewall-cmd --zone=internal --add-source=192.168.1.65
firewall-cmd --zone=internal --add-source=192.168.1.66

firewall-cmd --zone=internal --add-port=8000-8999/tcp

firewall-cmd --runtime-to-permanent

When I check my config with --list-all, everything looks correct:
> firewall-cmd --list-all --zone=internal
internal (active)
  target: default
  icmp-block-inversion: no
  interfaces:
  sources: 192.168.1.65 192.168.1.66
  services: dhcpv6-client ssh
  ports: 8000-8999/tcp
  protocols:
  forward: no
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

> firewall-cmd --list-all --zone=public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: enp2s0
  sources:
  services: cockpit dhcpv6-client http https ssh
  ports:
  protocols:
  forward: no
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

However, when I test this, I'm able to hit http://192.168.1.65:8080. I can hit it from a machine on the same internal network (192.168.128.128), as well as a public request from an external machine. Since neither was listed in internal's sources, I assumed that firewalld would not allow the requests through.
I have an auto-configured docker zone with the docker0 interface, but removing that doesn't seem to change my ability to hit the internal port.
Why am I able to successfully request :8080 from sources that are not listed on internal?

A: Well, it turns out that the problem stems from the fact that I'm using Docker for my internal ports. In order to simplify the process of getting containers to talk to the world and each other, Docker made the choice to take a large amount of control over your firewalls/networking. This means that if you don't want your containers to be publicly accessible AND you need to control public access via the firewall on the same machine as your Docker daemon, you need to configure your firewalls slightly differently. Docker has some official documentation on how to do this. Basically, you have the following options:

*

*Set up a separate machine just for your firewall. This would probably be the easiest, since Docker and your firewall wouldn't have to share resources.

*Add your iptables rules to the DOCKER-USER chain (this is more of an answer for iptables users; I'm not sure how to get firewalld to replicate this approach)

*Disable the whole thing by setting iptables=false in your Docker service config. (this blog post discusses this option)

I also found a post that I thought was a nice variation on the DOCKER-USER chain option. Basically, you create an iptables.conf file that you can load without a flush using iptables-restore -n. Unfortunately, it's an iptables solution, not a firewalld solution.
One of the hard parts of diagnosing this issue was that I would run a script to modify the firewall to match what I wanted, and that would work until I restarted the machine or started up the Docker daemon. Docker overwrites the iptables config when it starts up.


text:
Q: esp32-idf ble mesh save/delete network saved parameters I have a question that I can not find my answer to.
I know that to save the BLE Mesh parameters and network configuration, I can check the Store BLE Mesh configuration in the "MenuConfig".
(*) Store BLE Mesh configuration persistently
so After resetting the ESP32 it's restored automatically and my node is still joined to the network.
and in the MenuConfig there's a feature -> "Use a specific NVS partition for BLE Mesh" and "Name of the NVS partition for BLE Mesh" but I can not find a way to access this.
my question is, How can I delete the saved configuration and again save this configuration for a node?
I mean when my node joined the network and that config saved the network parameter to NVS flash how can I read that data and erase or rewrite it again?
Is there any function to manage it?
Does anyone know?
Regards.


text:
Q: Avoid concurrent accessible for piece of code in server I want to avoid concurrent accessible for piece of code in my server side business logic.
my business class is not a static class. Service layer is implemented in wcf .Any suggestion?

A: You need to use some kind of synchronization mechanism. The simplest is the lock statement:
class BusinessLogic
{
    // To avoid the possibility of a deadlock, prevent external code from
    // ever acquiring this lock by making the lock target private.
    private readonly object lockTarget = new object();

    void Foo()
    {
        lock(lockTarget)
        {
            // your code here
        }
    }
}

Of course thread synchronization in general is a complex topic, and the correct or best solution can only be reached after considering the particular context. There are other synchronization primitives in the System.Threading namespace that you should also be aware of.

A: Question needs bit of editing to clearly mention where is business logic which you want to restrict concurrent access for, is it part of wcf side?
Also which concurrency mode of wcf you have configured your wcf for as of now?
I assume code which your want to control access for is part of wcf side, with that assumption, as your class is not static, then only way to restrict concurrent access is through various locking mechanism provided in .net.
check on locking in C# and see which one best suits for your locking needs (how much thread safety you need).
also can check this discussion, it will give you some directions on what you need basically:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/f82f9cd8-87d6-4a4e-9e03-5dd2d143c680/wcf-service-concurrency-lock-right-way-to-do


text:
Q: How to view any kind of document file in my view in laravel If i want to view pdf, docx, doc, zip rar and others document in same view page. what should i do?
description:
If user upload a pdf file its need to show pdf and if user upload a doc file its need to show doc.
any solution please.
My view
@if($status->type == 1)
      image_url }}">
         image_url)}}" class="img-responsive" style="width:100%;">

     @endif

A: You can use iframes to preview documents in your page. Simply provide the source of the document in the iframe src. You can use this method to preview pdf and document files. Now, Since browsers directly do not have integrated viewers for documents, you can use https://view.officeapps.live.com to preview Word, Excel, or PowerPoint document (as per the website). So, you can simply
 @if(upload is image)

 @elseif(upload is pdf)

 @elseif(upload is document)

 @else
   //manage things here
 @endif

If you want to preview zip and RAR files, check this out
In PHP is it possible to inspect the content of a Zip file without extracting its content first?
. I personally have not used this, but, yeah this might help.

A: You can see PDF or image files with the integrated viewer that has the web browsers, but you can't do this with all formats. Some formats, like zip, rar,... must be downloaded to the desktop, tablet or mobile phone and viewed with the corresponding program.

A:

*

*Offical office live helps to render files in iframe.

*Above is the example to render dummy doc file.

*Don't forget to use a live url for document instead of local

*Copy paste & you are good to go.


text:
Q: How to edit or add tag colors In Preview.app for macOS 10.13.3, how do I remove a tag from the drop-down menu and add additional colour tag, other than the few shown? I made a tag which I want to remove from the drop-down menu. Also, I wonder if it is possible to add custom colors to tags?

A: The tags shown when saving or modifying a file are Finder tags, not specific to Preview, etc. Therefore you are limited to the colours available for Finder tags.
Go to Finder → Preferences, then choose the Tags tab.

Click on a tag, then choose – to remove it.
Tag colours can be changed by right-clicking on a tag in the list and choosing a new colour for it.

Drag your favourite tags to the area below to make them available for quick use in Finder menus.


text:
Q: Assigning a list of numbers to a variable I have list of numbers in a file test.txt:
31
32
26
28
27
30
24
15
4
2
1
3

I want to assign this list to a variable in a script which can be used as loop variable for a FOR loop. The variable should be assigned like this:
LIST="31 32 26 28 27 30 24 15 4 2 1 3" (space separated).
This list should be assigned by the script dynamically.  How can I do this?

A: In Bash, you can use:
list=$(<test.txt)

This uses the notation for command substitution but avoids the overhead of executing an external program.  The non-Bash alternative is:
list=$(cat test.txt)

This also works in Bash, of course, but incurs the overhead of the separate cat process.
You can use back-quotes list=`cat test.txt` but you should generally use the $(…) notation instead.  It is much easier to deal with quoting and nesting using the $(…) notation than it is using back-quotes.

A: while read -r line; do
  echo "$line";
done < test.txt

or
for line in $(cat test.txt); do
  echo "$line"
done

A: LIST=`tr  '\n' ' '   < test.txt`
echo $LIST

A: var=`cat test.txt`

... that's all you need. You can then iterate over $var in a for loop.
If you specifically need a space-separated string, echo $var will give you that.

A: Several ways of doing this:
#!/bin/bash
LIST="$(tr -s '\n' ' ' <<< "$(<file)")"
#LIST="$(tr -s '\n' ' ' <<< "$(cat file)")"
#LIST="$(cat file |tr -s '\n' ' ')"
#LIST="$(echo "$(<file)" |tr -s '\n' ' ')"
#LIST="$(tr -s '\n' ' ' <file)"
LIST="${LIST/% /}" #trims the space at end
printf "%s" "$LIST"

The command tr -s '\n' ' ' replaces newline with a single space. A space is also added at end in $LIST which is omitted by LIST=${LIST/% /}
Another way:
LIST="$(echo $(<file))" # $(<file) must not be quoted here
printf "%s" $LIST  # Use quote as normal, $LIST without quote will lose spaces

Note: Use variables quoted (double quote), otherwise you may lose white spaces.


text:
Q: error when logging to application when logging to application i have error
tomcat 7 in win7 with java options
set JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1536m
-Xmx1536m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=512m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in startup.bat i have error:
java.lang.OutOfMemoryError: PermGen space
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
        at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2895)
        at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
        at com.documentum.thirdparty.javassist.bytecode.ClassFile.<init>(ClassFile.java:68)
        at com.documentum.thirdparty.javassist.CtNewClass.<init>(CtNewClass.java:38)
        at com.documentum.thirdparty.javassist.ClassPool.makeClass(ClassPool.java:621)
        at com.documentum.thirdparty.javassist.ClassPool.makeClass(ClassPool.java:605)
        at com.documentum.fc.impl.util.reflection.proxy.ProxyClassGenerator.newClass(ProxyClassGenerator.java:94)
        at com.documentum.fc.impl.util.reflection.proxy.ProxyClassGenerator.makeProxyByteCode(ProxyClassGenerator.java:54)
        at com.documentum.fc.impl.util.reflection.proxy.ProxyClassLoader.makeProxyClass(ProxyClassLoader.java:93)
        at com.documentum.fc.impl.util.reflection.proxy.ProxyClassLoader.loadProxyClass(ProxyClassLoader.java:47)
        at com.documentum.fc.impl.util.reflection.proxy.ProxyFactory.getProxyClass(ProxyFactory.java:74)
        at com.documentum.fc.impl.util.reflection.proxy.ProxyFactory.makeDoubleProxy(ProxyFactory.java:53)
        at com.documentum.fc.client.impl.bof.compoundclass.PObjectProxyFactory.newProxyInstance(PObjectProxyFactory.java:27)
        at com.documentum.fc.client.impl.bof.compoundclass.PObjectProxyFactory.newProxyInstance(PObjectProxyFactory.java:18)
        at com.documentum.fc.client.impl.bof.compoundclass.DynamicProxyMgr.newProxy(DynamicProxyMgr.java:44)
        at com.documentum.fc.client.impl.objectmanager.PObjectFactoryWithAspects.makeObject(PObjectFactoryWithAspects.java:52)
        at com.documentum.fc.client.impl.objectmanager.PersistentObjectManager.getObjectFromServer(PersistentObjectManager.java:356)
        at com.documentum.fc.client.impl.objectmanager.PersistentObjectManager.getObject(PersistentObjectManager.java:311)
        at com.documentum.fc.client.impl.session.Session.getObject(Session.java:834)
        at com.documentum.fc.client.impl.session.Session.getObjectByQualificationEx(Session.java:1015)
        at com.documentum.fc.client.impl.session.Session.getObjectByQualification(Session.java:993)
        at com.documentum.fc.client.impl.bof.util.DfModificationManager.doFetch(DfModificationManager.java:154)
        at com.documentum.fc.client.impl.bof.util.DfModificationManager.getChangeRecordObject(DfModificationManager.java:123)
        at com.documentum.fc.client.impl.bof.util.DfModificationManager.init(DfModificationManager.java:217)
        at com.documentum.fc.client.impl.bof.util.DfModificationManager.getInstance(DfModificationManager.java:36)
        at com.documentum.fc.client.impl.bof.cache.BofConsistencyChecker.makeConsistent(BofConsistencyChecker.java:35)

tried different options and still this error...

A: You have -XX:PermSize=512m and -XX:MaxPermSize=256m
You might want to start with swapping the sizes, so that the max value is higher than the initial: -XX:PermSize=256m and -XX:MaxPermSize=512m


text:
Q: PHP: not looping inside a foreach I have this array:
$flavours = array (
    0 => array(799390 => 'Banana',),
    1 => array(799391 => 'Chocolate',)
);

And now I inside a foreach looping a set from my database. I get 'Banana' from the database and I need the array to give me 799390.
I have tried:
array_search('Banana', $flavours);

but it  does not work unless I add:
array_search('Banana', $flavours[0]);

But I cannot add [0] as I won't be able to tell in which position 'Banana' flavour is in the array.
Any solution apart from looping again inside a foreach??
Thanks a ton

A: First, we can use array_walk_recursive() to flatten your array, which just gets rid of your nested arrays.
Next, we use array_flip() to swap the keys/values in the flattened array. This makes it easier to grab the ID for a specific term.
<?php

$flavours = [
    [799390 => 'Banana'],
    [799391 => 'Chocolate']
];

//flatten array
//Produces: Array ( [799390] => Banana [799391] => Chocolate )
array_walk_recursive($flavours,
    function($v, $k) use (&$temp) {
        $temp[$k] = $v;
    }
);

//flip array. Swaps keys with values.
//Produces: Array ( [Banana] => 799390 [Chocolate] => 799391 )
$flavours = array_flip($temp);

Now you can get the ID pretty easily, such as $flavours['Banana'].

If you have a very very large array, this method may become slow. However, I tested this with 100,000 values on my cheap webhost, and ran this method a few times (20-25 times). It is finishing consistently at around (usually under) 0.1 milliseconds, which is about 0.0014 seconds.

A: You can insert an if statement to set a condition for your loop as
foreach ($flavours as $key => $value) {
  if($key =  array_search('Banana', $value)){
   echo $key;
 }
}

Output
799390

A: If the word being searched for is a different case many of the usual array methods will not work when trying to find the match, using preg_grep however will allow matches to be found in a case-insensitive manner.
function findflavour( $search, $haystack ){
    foreach( $haystack as $index => $arr ){
        $res=preg_grep( sprintf( '@%s@i', $search ), $arr );
        if( !empty( $res ) ) return array_search( array_values( $res )[0], $arr );
    }
    return false;
}

$search='BaNanA';
$flavours=array(
    array( 799390 => 'Banana' ),
    array( 799391 => 'Chocolate' ),
    array( 729361 => 'Chilli' ),
    array( 879695 => 'Apple' ),
    array( 995323 => 'Avacado' ),
    array( 528362 => 'Orange' ),
    array( 723371 => 'Cherry' ),
);

printf( 'Key:%s', findflavour( $search, $flavours ) );

If there might be multiple elements in the source array with the same value but different IDs a slightly different version of the findflavour function
function findflavour( $search, $haystack, $multiple=false ){
    $keys=[];
    foreach( $haystack as $index => $arr ){
        $res=preg_grep( sprintf( '@%s@i', $search ), $arr );
        if( !empty( $res ) ) {
            $key=array_search( array_values( $res )[0], $arr );
            if( $multiple )$keys[]=$key;
            else return $key;
        }
    }
    return $multiple ? $keys : false;
}

$multiple=true;
$search='AVacAdo';
$flavours=array(
    array( 799390 => 'Banana' ),
    array( 799391 => 'Chocolate' ),
    array( 291333 => 'Avacado' ),
    array( 729361 => 'Chilli' ),
    array( 879695 => 'Apple' ),
    array( 995323 => 'Avacado' ),
    array( 528362 => 'Orange' ),
    array( 723371 => 'Cherry' ),
);

printf( 'Key(s): %s', print_r( findflavour( $search, $flavours, $multiple ), true ) );


text:
Q: Why doesn't my exported csv file contain list contents? I'm somewhat new to python and trying to write a program using Spotipy to first get Spotify song IDs from a playlist and then grab info on their sonic characteristics. I'm able to grab a list of dicts containing the song IDs using a while loop, but if I understand correctly the list stays in the while loop.
In that case the next step would be to either save to a variable outside the loop or just export that info to a csv or other file. I'm opting to export for now, though my exported csv files seem to contain just the header "song_id" and not the actual song IDs themselves. I'm sure this is a simple error but I can't seem to spot what it is. Does anyone have any ideas?
import pandas as pd
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
from pprint import pprint
import csv

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

#get songs from the Pop Connoisseur Playlist
pl_id = 'spotify:playlist:5AvWMqi0lbzSPvDR6WWesu'
offset = 0

while True:
    response = sp.playlist_tracks(pl_id, offset=offset, fields='items.track.id,total')
    pc_tracks = [x['track']['id'] for x in response['items']]
    print(pc_tracks)
    offset = offset + len(response['items'])
    print(offset, "/", response['total'])
    s = 0
    with open('popconn.csv', 'w', newline='') as csvfile:
        fieldnames = ['song_id']
        thewriter = csv.DictWriter(csvfile, fieldnames = fieldnames)
        thewriter.writeheader()
        for song in pc_tracks:
            s += 1
            thewriter.writerow({'song_id': song})

    if len(response['items']) == 0:
        break

A: Your code is writing to the same file each time it goes around the while True loop. This would overwrite anything you have already written. As your last loop probably has no items, this will leave you with a file containing just the header.
To avoid this, you only need to open your output file once before you start your loop. This would also just write the header once.
For example:
import pandas as pd
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
from pprint import pprint
import csv

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

#get songs from the Pop Connoisseur Playlist
pl_id = 'spotify:playlist:5AvWMqi0lbzSPvDR6WWesu'
offset = 0

with open('popconn.csv', 'w', newline='') as csvfile:
    fieldnames = ['song_id']
    thewriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
    thewriter.writeheader()

    while True:
        response = sp.playlist_tracks(pl_id, offset=offset, fields='items.track.id,total')
        pc_tracks = [x['track']['id'] for x in response['items']]
        print(pc_tracks)
        offset = offset + len(response['items'])
        print(offset, "/", response['total'])
        s = 0

        for song in pc_tracks:
            s += 1
            thewriter.writerow({'song_id': song})

        if len(response['items']) == 0:
            break


text:
Q: Understanding Haskell code which applies the `tails` function to an infinite list within a list comprehension After submitting my solution to Project Euler's problem 50 earlier today, I was scrolling through the problem's forums, taking a look at other folks' solutions/execution times.
After a while, I started to feel quite proud of my code which solved it in ~3 seconds (my code used the Primes library and was compiled with O2)...
...and then I came across the code below which solved it in ~0.05 seconds...in interpreted mode (i.e., ghci).
Can someone explain how/why the code below solves this particular problem?
The mind-twisting part is the application of the tails function to the infinite list of primes (primes) within a list comprehension.  I'm having a hard time understanding how we guarantee that we look at all possible sublists of consecutive primes and not just those generated by tails.
(My usual strategy of trying bits and pieces of code in ghci doesn't work in this situation because primes is infinite...)
The problem: We're asked to find the largest prime number below 1,000,000 which is the result of summing consecutive prime numbers.  For example, the largest prime number below 100 which is the sum of consecutive primes is 41 (2 + 3 + 5 + 7 + 11 + 13).
import Data.List (tails)
import Data.Numbers.Primes

under n xs = takeWhile (< n) xs

takeUntil p xs = foldr (\x r-> if p x then [x] else x:r) [] xs

res :: [((Int, Int), (Int, Int))]
-- ((top_length, sums_to), (total_length, starting_prime))

res = [(r,(length s,x)) | (x:xs) <- tails primes
                        , let s = zip [1..]
                                $ under 100
                                $ scanl (+) x xs
                        , let r = ...]

main = mapM_ print $ takeUntil ...

A: To work around the infinite list problem, just define:
primesUpTo100 = takeWhile (< 100) primes

and use primesUpTo100 in the definition of res in place of primes.
Next, change the definition of res to return different values so you can see what is going on, e.g.:
res = do
  (x:xs) <- tails primesUpTo100
  let s = zip [1..] $ under 100 $ scanl (+) x xs
  let r = last  $ filter (isPrime.snd) s
  return (x, take 10 xs, s)

Now you can see what s is and how it is related to x and the first 10 elements of xs.
If the list res is too long just evaluate take 10 res. Another tip is to define a helper function:
import Control.Monad
pp xs = forM_ xs print

This will print out a list which each element on a new line which should make things easier to read. E.g.:
pp (take 10 res)

Using all of these ideas I bet you can figure it out. It's actually a brute-force search for the longest sequence, but the use of scanl might avoid the recalculation of sums.

A: In general, there's no problem with taking tails of primes, because Haskell is lazy (the evaluation is on-demand).
Here specifically there's even less problem because each sublist is trimmed with under 100 = takeWhile (< 100) - only a finite prefix is taken.
(x:xs) <- tails primes just goes through all suffixes of primes - i.e. primes starting from x=2; then primes starting from x=3, then 5,7,11, .... The pattern only demands the  head element x, and the tail xs of the primes list, and even their values aren't immediately requested, only the so-called "spine" of primes list is forced, 1 notch at a time (of course making sure primes starts with at least one element x will automatically compute the actual value of x, but that's another matter).
So (x:xs) <- tails primes operates on consecutive suffixes of the primes list. Try tails [1..10] to see what's going on there.

When you type
GHCi> primes

at the GHCi prompt, you're actually requesting all the elements of primes list to be printed as the output. But
GHCi> under 100 primes

will only request those below 100, and not more than one element after that. It uses the built-in takeWhile that examines elements in primes, one after another, until one is found that fails the predicate (in this case, is bigger than 100). The terminating element is not included in the result.
The user-defined takeUntil differs from that only in that it also includes the terminating element in its result (and the meaning of predicate is flipped - it signals when to stop).
The scanl (+) is the usual way to calculate the sequence of partial sums of a sequence:
Prelude> scanl (+) 1 [2..10]
[1,3,6,10,15,21,28,36,45,55]

The code
 [ (r,(length s,x)) | (x:xs) <- tails primes
                    , let s = zip [1..]
                            $ under 100
                            $ scanl (+) x xs
                    , let r = last $ filter (isPrime.snd) s]

means:
for each suffix of primes        -- [[2,3,5,7...],[3,5,7,11...],...]
  let
    x  = head suffix             -- for all primes from x
    xs = tail suffix             --   i.e. xs
    t1 = scanl (+) x xs          -- calculate partial sums
    t2 = under 100 t1            -- stopping when the sum reaches 100
    s  = zip [1..] t2            -- index each sum by the length of subsequence,
    t3 = filter (isPrime.snd) s  -- keep only such that summed to a prime,
    r  = last t3                 -- and take the one created from the
  in                             --    longest subsequence, starting from x
    emit (r,(length s,x))        -- and collect the data

So we get the list of entries ((top_length, sums_to), (total_length, starting_prime)) for each consecutive prime number, starting_prime = 2,3,5,7,11, ... .
The takeUntil expression in main determines when it's okay to stop, as there's no possibility of improving the result anymore.


text:
Q: Xamarin Android - Will my AlertDialog extension leak memory? I created a simple extension on Activity to show Alert Dialogs. I know from other sources that you need to call the Dispose() method after showing a dialog to prevent memory leaks. Since I don't have a reference to "alert", I cannot call Dispose(). However, I placed my code in a Using statement, but I am not sure if this will work. As a side note, I'm not sure if "EventHandler)null" might cause problems as well.
So, the question is, will this code leak memory? And if so, can you advice me a proper way to write this extension?
using DB = System.Diagnostics.Debug;

public static class AndroidExtensions
{
    public static void ShowAlert(this Activity activity, string title, string message, string cancelButtonTitle) {
        if (activity == null) {
            DB.WriteLine("ShowAlert() : Failure showing alert; activity is null");
            return;
        }

        try {
            using (var builder = new AlertDialog.Builder (activity)) {
                if (cancelButtonTitle != "") {
                    builder.SetNegativeButton (cancelButtonTitle, (EventHandler<DialogClickEventArgs>)null);
                }

                using (var alert = builder.Create ()) {
                    if (title != "") {
                        alert.SetTitle (title);
                    }

                    alert.SetMessage (message);
                    activity.RunOnUiThread(()=> {
                        alert.Show ();
                    });
                }
            }
        } catch(Exception ex) {
            DB.WriteLine ("ShowAlert() : Couldn't create alert : " + ex.Message);
        }
    }
}


text:
Q: MySQL - Retrieve data from database by joining 3 tables and display one column value with comma I have three tables, named location and Hospital and hospital location. These are the fields and data of both table
Table : location
id | location_name
1  | location1
2  | location2

Table : hospital
id | hospital_name
1  | Hospital1
2  | Hospital2

Table : hospital_location
id | hospital_id | location_id
1  | 1          |   1
2  | 1          |   2

I need to create a query in mysql to display all the data from hospital table. The location_name column has multiple values, separated by a comma.
id | hospital_name | location_name
1  | Hospital1     | location1, location2

A: What you need is the GROUP_CONCAT mysql function
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
SELECT h.hospital_name, GROUP_CONCAT(l.location_name) as location_name
FROM hospital h
LEFT JOIN hospital_location hl ON hl.hospital_id = h.id
LEFT JOIN location.l ON hl.location_id = l.id
GROUP BY h.id


text:
Q: Delete operation not working in ajax I tried to make a delete operation work in my CRUD operation but when I clicked on the delete button nothing seemed to work: onclick event is not responding every time I clicked on the delete button.
I have tried everything but nothing seemed to work.
Below are the souce codes:
Html

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 Remove Member

Do you really want to delete this department ?

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="removeBtn"> Delete</button>

The PHP codes
retrieve.php
<?php
require_once('../../includes/config.php');
$output = array('data' => array());

$sql = "SELECT * FROM department order by id desc";
$query = $mysqli->query($sql);
$x = 1;
while ($row = $query->fetch_assoc()) {
    $actionButton = '

     ';

    $output['data'][] = array(
        $x,
        $row['dept_code'],
        $row['dept_name'],
        $actionButton
    );
    $x++;
}
// database connection close
$mysqli->close();
echo json_encode($output);

remove.php
<?php
require_once('../../includes/config.php');

$output = array('success' => false, 'messages' => array());
$memberId = $_POST['member_id'];

$sql = "DELETE FROM department WHERE id = {$memberId}";
$query = $mysqli->query($sql);
if($query === TRUE) {
    $output['success'] = true;
    $output['messages'] = 'Successfully Deleted';
} else {
    $output['success'] = false;
    $output['messages'] = 'Error while deleting the Department information';
}
// close database connection
$mysqli->close();
echo json_encode($output);
?>

And lastly, the jquery codes:
    function removeMember(id = null) {
        if(id) {
            // click on remove button
            $("#removeBtn").unbind('click').bind('click', function() {
                $.ajax({
                    url: 'dept/remove.php',
                    type: 'post',
                    data: {member_id : id},
                    dataType: 'json',
                    success:function(response) {
                        if(response.success == true) {
                            $(".removeMessages").html('
'+
                                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>'
'  '+response.messages+'
');
// refresh the table
                            manageDeptTable.ajax.reload(null, false);
                            // close the modal
                            $("#removeDeptModal").modal('hide');
                        } else {
                            $(".removeMessages").html('
'+
                                  '<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>'+ '  '+response.messages+
                                '
');
                        }
                    }
                });
            }); // click remove btn
        } else {
            alert('Error: Refresh the page again');
        }
    }

A: Problem lies in your DELETE sql,
$sql = "DELETE FROM department WHERE id = {$memberId}";

should be
$sql = "DELETE FROM department WHERE id = $memberId";

Also, I would suggest to use PreparedStatement instead, to avoid any SQL injection and syntax error.


text:
Q: Passing by reference to n-th element in C# In C, if we have an array, we can pass it by reference to a function. We can also use simple addition of (n-1) to pass the reference starting from n-th element of the array like this:
char *strArr[5];
char *str1 = "I want that!\n";
char *str2 = "I want this!\n";
char *str3 = "I want those!\n";
char *str4 = "I want these!\n";
char *str5 = "I want them!\n";
strArr[0] = str1;
strArr[1] = str2;
strArr[2] = str3;
strArr[3] = str4;
strArr[4] = str5;
printPartially(strArr + 1, 4); //we can pass like this to start printing from 2nd element

....

void printPartially(char** strArrPart, char size){
int i;
for (i = 0; i < size; ++i)
    printf(strArrPart[i]);
}

Resulting in these:
I want this!
I want those!
I want these!
I want them!

Process returned 0 (0x0)   execution time : 0.006 s
Press any key to continue.

In C#, we can also pass reference to an object by ref (or, out). The object includes array, which is the whole array (or at least, this is how I suppose it works). But how are we to pass by reference to the n-th element of the array such that internal to the function, there is only string[] whose elements are one less than the original string[] without the need to create new array?
Must we use unsafe? I am looking for a solution (if possible) without unsafe
Edit:
I understand that we could pass Array in C# without ref keyword. Perhaps my question sounds quite misleading by mentioning ref when we talk about Array. The point why I put ref there, I should rather put it this way: is the ref keyword can be used, say, to pass the reference to n-th element of the array as much as C does other than passing reference to any object (without mentioning the n-th element or something alike)? My apology for any misunderstanding occurs by my question's phrasing.

A: The "safe" approach would be to pass an ArraySegment struct instead.
You can of course pass a pointer to a character using unsafe c#, but then you need to worry about buffer overruns.
Incidentally, an Array in C# is (usually) allocated on the heap, so passing it normally (without ref) doesn't mean copying the array- it's still a reference that is passed (just a new one).

A: Edit:
You won't be able to do it as you do in C in safe code.
A C# array (i.e. string[]) is derived from abstract type Array.
It is not only a simple memory block as it is in C.
So you can't send one of it's element's reference and start iterate from there.

But there are some solutions which will give you the same taste of course (without unsafe):
Like:

*

*As @Chris mentioned you can use ArraySegment<T>.

*As Array is also an IEnumerable<T> you can use .Skip and send the returned value. (but this will give you an IEnumerable<T> instead of an Array). But it will allow you iterate.

*etc...

A: Your confusion is a very common one. The essential point is realizing that "reference types" and "passing by reference" (ref keyboard) are totally independent. In this specific case, since string[] is a reference type (as are all arrays), it means the object is not copied when you pass it around, hence you are always referring to the same object.
Modified Version of C# Code:
string[] strArr = new string[5];
strArr[0] = "I want that!\n";
strArr[1] = "I want this!\n";
strArr[2] = "I want those!\n";
strArr[3] = "I want these!\n";
strArr[4] = "I want them!\n";
printPartially(strArr.Skip(1).Take(4).ToArray());

void printPartially(string[] strArr)
{
    foreach (string str in strArr)
    {
        Console.WriteLine(str);
    }
}

A: If the method should only read from the array, you can use linq:
string[] strings = {"str1", "str2", "str3", ...."str10"};
print(strings.Skip(1).Take(4).ToArray());

A: Question is old, but maybe answer will be useful for someone.
As of C# 7.2 there are much more types to use in that case, ex. Span or Memory.
They allow exactly for the thing you mentioned in your question (and much more).
Here's great article about them
Currently, if you want to use them, remeber to add <LangVersion>7.2</LangVersion> in .csproj file of your project to use C# 7.2 features


text: Q: File.Move on SND: The process cannot access the file because it is being used by another process I have a file watcher windows service that moves a dropped file from folder A to folder B. File movement in this setup was successful, but when I shared the same folder and drop a file using the shared path, I always get an error indicating The process cannot access the file because it is being used by another process. Do note that I also tried accessing the shared path on the server itself and encountered the same error when dropping files. The event I use is FileSystemWatcher.Changed.


text:
Q: Can every measurable set (with positive measure) be represented as a countable union of non-measurable set? Let $A$ be a measurable set with positive measure. I know that you can always find a non-measurable subset $E\subset A$ using a construction similar to Vitali sets.
But I have a stronger question: can $A$ always be written as a countable union of non-measurable sets? I tried to use the old trick of using $\mathbb{R} /\mathbb{Q}$ but what I did didn't exactly work.
Any ideas?
NOTE: I'm talking only about lebesgue measure in $\mathbb{R}$.

A: Generalize the construction of a Bernstein set.
Enumerate $A=\{x_\xi:\xi<2^\omega\}$. Let $\mathscr{F}=\{F_\xi:\xi<2^\omega\}$ be the family of uncountable closed subsets of $A$. Recursively construct distinct $y_{\xi,n}\in A$ for $\langle\xi,n\rangle\in 2^\omega\times\omega$ as follows.
If $\eta<2^\omega$, and we have $y_{\xi,n}$ for each $\langle\xi,n\rangle\in\eta\times\omega$, let $Y_\eta=\{y_{\xi,n}:\langle\xi,n\rangle\in\eta\times\omega\}$, and let $X_\eta(0)=\{\xi<2^\omega:x_\xi\notin Y_\eta\}$. Recursively construct $\xi_n$ for $n\in\omega$ by setting
$$\xi_n=\min\{\xi\in X_\eta(n):x_\xi\in F_\eta\}$$
and $X_\eta(n+1)=X_\eta\setminus\{\xi_n\}$. In other words, the set $\{\xi_n:n\in\omega\}$ contains precisely the indices of the first $\omega$ members of $F_\eta$ (in the enumeration of $A$) that aren't in $Y_\eta$. Now let $y_{\eta,n}=x_{\xi_n}$ for each $n\in\omega$.
For $n\in\omega$ let $E_n=\{y_{\xi,n}:\xi<2^\omega\}$; each $E_n$ is a Bernstein set in $A$ and is therefore non-measurable, and the sets are certainly pairwise disjoint. Finally, the construction ensures that $A=\bigcup_{n\in\omega}E_n$, since each point of $A$ is in $2^\omega$ members of $\mathscr{F}$ and must therefore eventually be picked. (Alternatively, one could index $\mathscr{F}$ so that each member is listed $2^\omega$ times.)


text:
Q: Is it possible to create bundled products where Magento automatically Is it possible to create bundled products where Magento automatically gets the pictures for the simple products and shows in the gallery under the main picture?
If yes, how?


text:
Q: Extreme events in power law distribution After reading Difference between power law distribution and exponential decay, I wanted to know more about power law distributions. I stumbled across Nassim Nicholas Taleb's "Technical Incerto - The Statistical Consequences of Fat Tails", where (p.8) - in relation to subexponential distributions - he claims that
"[...] extreme events away from the centre of the distribution play a very large role. Black Swans are not "more frequent" (as it is commonly misinterpreted), they are more consequential."
This seems to conflict with other sources I found (e.g. https://science.sciencemag.org/content/sci/335/6069/665.full.pdf) and with my intuition. Why shouldn't an extreme event (say an event larger than 10SD) be more frequent in a power law distribution than in, for example, a normal distribution?

A: The first point is that all distributions with a finite standard deviation or variance satisfy Chebyshev's inequality $$\mathbb P(|X-\mu|\geq k\sigma) \leq \frac{1}{k^2}$$  so, to take your example, no more than $0.01$ i.e. $1\%$ of the distribution can be $10$ standard deviations or more from the mean.
But for most distributions this is a very loose bound:

*

*For a normal distribution $2\Phi(-10)\approx 1.5 \times 10^{-23}$ so that is the proportion of the distribution which is $10$ standard deviations or more from the mean, much much less than the Chebyshev bound.

*For an example of a power law distribution with a finite standard deviation, say a Pareto distribution with minimum $1$ and shape $3$, so with mean $\frac32$ and standard deviation $\frac{\sqrt{3}}{2}$,  the proportion of the distribution $10$ standard deviations or more from the mean is about $0.00095$, around a tenth of the Chebyshev bound.
So that seems to confirm your intuition.
But I think Taleb may be saying an extreme event should not be defined by how many standard deviations it is from the mean, but simply by how unlikely it (or something more extreme) is to occur.  In that sense there are as many extreme events with one continuous distribution as with another, and the difference between them is how far such extreme events are from the mean.
For example setting "extreme" as a probability of $10^{-6}$ and with the same mean $\frac32$ and s.d. $\frac{\sqrt{3}}{2}$,

*

*a normal distribution would have "extreme" values being those below $-2.74$ and above $5.74$

*a Pareto distribution with minimum $1$ and shape $3$ would have "extreme" values being those above $100$
and in this sense "extreme" values are more consequential in the Pareto case


text:
Q: Getting started with WSO2 Enterprise Integrator Our company(Enterprise) have planned to use WSO2(EI/ESB) products for our systems that connects with each other by P2P.
So we needed integration solution and chose WSO2.
I am asking that Is it good to use WSO2 for huge systems (Middlewares, Web services, Gateway etc).

*

*Is WSO2 OK if there are a tons of request to handle?

*Is there any WSO2 Training Course (On-Site and Online)

A: Yes, you could use WSO2 EI to achieve your need. Currently all WSO2 products are proven to build large scale platforms. You can visit [1] and find out large scale users and their stories.

*

*Is WSO2 OK if there are a tons of request to handle?

Yes, EI (ESB profile) capable of handling huge request load and it is proven for example in ebay "WSO2 ESB to Process More Than 1 Billion Transactions Per Day" and many more.

*Is there any WSO2 Training Course (On-Site and Online)

Of cource, WSO2 provide online certification, onsite/online product training and self learning materials. Please find more information at [2]
[1] https://wso2.com/about/customers/
[2] https://wso2.com/training
Thanks,
Milinda


text:
Q: VB.net COMExeption was unhandled I am creating a user login system using vb.net and MS access. I am unsure what is going wrong with my system and I receive the error message "Item cannot be found in the collection corresponding to the requested name or ordinal" The error is coming up in the section "User.Find(Username)" on the first line of the DO loop. Here is my code:
Public Class Login

Dim LoginError As String ' This will tell the user what is wrong with his login

Public Function Login()
    Dim DBConn As New ADODB.Connection ' This is how we tell visual studio
    'how to connect to our database

    Dim User As New ADODB.Recordset 'We pass our argument through our recordset

    Dim Username As String 'This will be our "Query"
    Dim strUserDB As String 'This get sets to the email field in our database.
    Dim strPassDB As String 'Same as above just for the password

    Dim blnUserFound As Boolean 'I will be using a "DO" loop so I will use
    'this as my condition

    DBConn.Open("Provider = Microsoft.Jet.OLEDB.4.0;" & _
                 "Data Source = '" & Application.StartupPath & "\UserDetails2000.mdb'")
    'The inverted comas in the dataOuce statement as itt keeps the location of your
    'file as one string.

    User.Open("tblUserDetails", DBConn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
    'This is my table           'This is my connection         'These are some settings

    blnUserFound = False
    Login = False
    Username = "User = '" & txtEmail.Text & "'" 'This tells the database to find the email field
    'Equivilent to what was entered in the textbox

    Do
        User.Find(Username) 'This is the full statement that sends my 'Query' to the record set
        If User.BOF = False And User.EOF = False Then
            'BOF = Begining of file, EOF = End of file, it tests whether the database has
            'reached its sentinal value, if it hasent then the username has been found, If it has,
            'the username has been found.

            strUserDB = User.Fields("Email").Value.ToString
            '"Email" is my table field. I am setting strUserDB to the username field of my table
            strPassDB = User.Fields("Password").Value.ToString

            If strUserDB <> txtEmail.Text Then
                User.MoveNext()
                'This IF statement handles different CASE usernames, Example, admin and AdMiN
                'We use this if statement to differentiate between different CASE letters
            Else
                blnUserFound = True
                If strPassDB = txtPassword.Text Then
                    User.Close()
                    DBConn.Close()
                    Return True
                Else
                    LoginError = "Invalid Password"
                    User.Close()
                    DBConn.Close()
                    Return False
                End If
            End If
        Else
            LoginError = "Invalid Username"
            User.Close()
            DBConn.Close()
            Return False

        End If
    Loop Until blnUserFound = True
    LoginError = "Invalid Username"
    User.Close()
    DBConn.Close()
    Return False

End Function

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
    If Login() = True Then
        MessageBox.Show("Login Succesful", "Login Status")
    Else
        MessageBox.Show(LoginError, "Login Status")
    End If
End Sub

End Class

A: Verify that tblUserDetails contains a column named User.
Maybe User is also a reserved keyword in Access so try setting Username as:
Username = "[User] = '" & txtEmail.Text & "'"


text:
Q: Action in a short exact sequence Let $1 \mapsto A \mapsto B \mapsto C \mapsto 1$ be a short exact sequence of groups and assume that $B$ is finitely generated.
My question is whether the action of $C$ on $A$ (by conjugation) has finitely many orbits.
If $C$ is finitely presented, I think that it is true. Since $C$ is finitely presented, $A$ is finitely generated as a normal subgroup of $B$, in other words, the action of $C$ on $A$ has finitely many orbits.
Nevertheless, if we do not ask $C$ to be finitely presented (we just know that since $B$ is finitely generated, so is $C$), I do not know whether the following argument is correct:
The group $B$ is finitely generated and it is generated by $\langle A, \tilde{C} \rangle$, where $\tilde{C}$ is a lift of $C$ in $B$. Then, there are elements $a_1,\dots,a_k$ in $A$ and $\tilde{c_{1}},\dots,\tilde{c_{n}}$ in $\tilde{C}$ such that $B=\langle a_1,\dots,a_k,\tilde{c_{1}},\dots,\tilde{c_{n}}\rangle$. Hence, $A$ is generated by $a_1,\dots,a_k$ and their conjugates by words in $\{\tilde{c_1},\dots,\tilde{c_{k}}\}$. In particular, the action of $C$ on $A$ has finitely many orbits because $$A=\bigcup_{i\in \{1,\dots,k\}} C \cdot a_i.$$


text:
Q: Telethon Telegram message filter I would like to get all the messages from a chat that have been sent today.
import sys,datetime
from telethon import TelegramClient
api_id = 1234567
api_hash = "0986asdgshjfag"
client = TelegramClient('session_name', api_id, api_hash)
client.start()

dialogs = client.get_dialogs()
chat = client.get_input_entity('username')

filter = InputMessagesFilterEmpty()
result = client(SearchRequest(
    peer=chat,  # On which chat/conversation
    q='',  # What to search for
    filter=filter,  # Filter to use (maybe filter for media)
    min_date=datetime.date.today(),  # Minimum date
    max_date=None,  # Maximum date
    offset_id=0,  # ID of the message to use as offset
    add_offset=0,  # Additional offset
    limit=5,  # How many results
    max_id=0,  # Maximum message ID
    min_id=0,  # Minimum message ID
    from_id=None,  # Who must have sent the message (peer)
    hash=0  # Special number to return nothing on no-change
))

for message in client.iter_messages(chat,filter=result):
    print(message.message)

The filter doesn't work at all, I can see more than 5 messages (the whole chat) and it doesn't care about the time.
Why?

A: You can use 'message.date'.
If you want to get the message from today you need to check the sent day. and this would be like :
if datetime.datetime.now().strftime('%Y-%m-%d') == message.date.strftime('%Y-%m-%d')


text:
Q: EFCore: How to detect which of the newly added entity's properties have changed since the dbContext Attach or Add happened? (trying to make my query clearer and not to confuse you):
In a WinForm app that makes use of EFCore, C# and SQLite,
What I am trying to achieve is this: I have a WinForm called AddNewVisitForm. I use it to Add a New Visit each time. Visit is a model of several properties. The form itself, contains many textboxes, one for each Visit's property.
When the form Loads, a new Visit entity is created
var newVisit = new Visit();
_dbContext.Add<Visit>(newVisit);

having the default value for each of its properties) and these new Visit's properties values are passed to all these textboxes initializing their contents.
Then the user starts entering new values to these textboxes altering their contents.
Then, at some point let's say, the user changes his mind and wants to cancel the AddNewVisit form and presses the Cancel button.
What I would like to do is, the form should be able to check (via dbContext detect changes probably) to see if any modifications to the newVisit entity have been made, warning the user that "Some modifications are made!!!. Really, you want to cancel?".
So, the user has to be informed of thesse changes made either by mistake or intentianally and then make his final decision!
Hope this makes clear why I need to know details of the entity changes apart from entity.Added state. Is there a way to be informed of changes made to the entity's properties before I call SaveChanges or simply discard all of them and close the form?
Thanx indeed for your time!!I would appreciate for your help
What I have tried so far is
 if (dbContext.ChangeTracker.HasChanges())
 {
        dbContext.ChangeTracker.DetectChanges();
      Debug.WriteLine(_dbContext.ChangeTracker.DebugView.LongView);
}

or
 EntityEntry<TFlatVisit> entry = _dbContext.Entry(newVisit);
    entry.DetectChanges();
    var modified = entry.Members.Where(m => m.IsModified).ToList();
    var modified2 = entry.Properties.Where(m => m.CurrentValue != m.OriginalValue).ToList();
    var modified3 = entry.Properties.Where(m => m.CurrentValue == m.OriginalValue).ToList();

None of them seems to work as expeted!!
PS: the exchange of data between the controls and the entity is being done via VisitBindingSource (eg. in the Load event I put  VisitBindingSource.DataSource = newVisit; and after the user presses the Cancel button I put VisitBindingSource.EndEdit();
Is there a way to accomplish this task?
I would appreciate if you could help me with this. Thanx a lot

A: You can use EntityEntry.Members:

Provides access to change tracking information and operations for all properties and navigation properties of this entity.

var modified = ctx.Entry(message).Members
   .Where(m => m.IsModified)
   .ToList();

UPD

None of them seems to work as expeted!!

No, they work pretty much as expected according to the goals of the change tracking and the docs:

For each tracked entity, Entity Framework Core (EF Core) keeps track of:

*

*...

*The "original values" of properties, when this information is available. Original values are the property values that existed when entity was queried from the database.

*...

Since the entity is a newly created one there are no "original" values to track.
And I would argue that EF Core change tracker is not a right tool for you in this case - you should handle the stuff on the form itself and/or in the cancel key handler by analyzing the passed values and compare them to some "original"/"default" ones.


text:
Q: Does anyone know how to get Google+ user's home/work address(not email) from Google API? Currently we retrive user's profile by people.get API, and scopes are profile email https://www.googleapis.com/auth/plus.login.
But no matter user sets their home/work address as public, we still can't get address from reponse.
Did I use the wrong API or scopes?

A: As documented for scopes.

*

*email gives access to "the user's Google account email address."

*https://www.googleapis.com/auth/plus.profile.emails.read gives access to "the user's Google account email address, as well as any public, verified email addresses in the user's Google+ profile."