text:
Q: How do I mention my own products in answers? Twice now I've seen questions on Stack Overflow where one of my company's products might provide an answer to the question.
One was a slightly vague connection about object-relational mapping, but the other was a specific question about workshop/event management where we have a product which is almost an exact match for the questioner's needs.
Of course the questioner should take a pinch of salt with anything I say about it, but it might be useful to have the product brought to his attention as one possible solution.
What are the rules and guidelines about answering with something I worked on?

A: As long as your answer is informative and has a disclosure about your affiliation, I think it would be appropriate to mention your product.

A: If you wanted to demonstrate your objectivity then you would mention how your product solves the problem and also mention your competitors' products that may also solve the problem.

A: I wouldn't have a problem with you mentioning it, but I think full disclosure is important.  You absolutely need to say, in that post, that you work for the company that sells this product.

A: I wouldn't think that it should be a problem.  If you have a product that you believe in you should be able to mention it regardless of the company that it came from (yours or someone elses).  Now creating questions and then using it to promote your product I would say that is an entirely different story. :)

A: If it will help answer the question why would it be bad etiquette to mention your own product?
You could make note of it to be polite, but in the end the question's author will take the best advice provided, if that happens to be a product you shepherd/produce, then all the better.

A: As long as you aren't spamming your own product and only mention it where it's appropriate, I don't see a problem. However, you might want to say that it's your product in the answer.

A: If your product is helpful your answer should get voted up and/or accepted, if not, it will be voted down. I don't see this as being an issue.

A: It's not but I do have a seminar on web-etiquette that should be perfect for you!

A: If it's a reasonable answer to someone else's question, then yes. Being a shill should see the crowd reward you appropriately ...
If you do mention your own product or site, I would suggest you cite your own affiliation clearly.

A:
What are the rules and guidelines about answering with something I worked on?

If you just worked on a product for a company you don't have shares in then I think you should be able to write whatever you like about it. In my experience, employees are often more negative about products they work on than the general public so I would personally rate an employee saying positive things very highly.
If you own your own company and cite your own products (as I do) then I think you must provide some relevant and useful information in your answer and state your affiliation.

A: Not at all.


text:
Q: passing data(Id) with redircetToAction to url using ViewModel hello I'm trying to pass the new posted value to a different view with the new value id at the url using RedirectToAction but I'm getting the wrong Url .
Just like here in SO ,that you get redirect to your Q. after submit.
the Url I'm suppose to get is  http://localhost:1914/en/evntes/index/60
MyCode(Controler= VoosUp)
public ActionResult Create()
    {
        var viewModel = new LectureFormViewModel
        {
            Genres = _context.Genres.ToList(),

        };
        return View("Gigform", viewModel);
    }

    [Authorize, HttpPost]
    public ActionResult Create(LectureFormViewModel viewModel)
    {
        if (!ModelState.IsValid)
        {
            viewModel.Genres = _context.Genres.ToList();

            return View("Gigform", viewModel);
        }

        var lectureGig = new LectureGig
        {
             //Prametrest
        };

        _context.LectureGigs.Add(lectureGig);
        _context.SaveChanges();

        // return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id)); //Compiler Error
        return RedirectToAction("index", "Events", new { id = lectureGig.Id });//Ok Id 60
    }

Events/Index
public ActionResult Index(int id)//OK id=60
    {
        var lecturegig = _context.LectureGigs.Include(g => g.Artist)
           .Include(g => g.Genre)
           .SingleOrDefault(g => g.Id == id);
        if (lecturegig == null)
            return HttpNotFound();
        var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };

        return View("index", viewmodel);
    }

Url i'm getting :http://localhost:1914/en/VoosUp/Create
and the view is correct

redpajama_set_name: RedPajamaStackExchange


text:
Q: Timezone confusion with Ruby's Time class It's worth noting I am using Ruby 2.1.2, and so the Time class uses a signed 63 bit integer. The integer is used when it can represent a number of nanoseconds since the Epoch; otherwise, bignum or rational is used, according to the documentation.
When I use ::new without arguments, it gives me the current time using my local time zone (not UTC):
> Time.new
 => 2015-06-30 18:29:08 -0400

It's correct. It's 6:29pm on the East coast of the US. Now I want to check the local time in two timezones to the east of EDT:
> t = Time.new(2015,6,30,18,29,8,"+02:00")
=> 2015-06-30 18:29:08 +0200

This is where my confusion comes in. When I specify two timezones to the east of me, I expect there to be two additional hours because each timezone is 15 degrees longitude and each is represented by 1 hour.
Why did it give me the same time as my local time, instead of two hours later?

A: What you think is happening isn't what's happening.  What you've done is give that time an offset of GMT +2 as opposed to two hours out from your current timezone.
If you want to see the time at the offset of two hours ahead of where you are, then you want to create the instance of Time, get your local time, and shift that by the GMT offset.
Time.now.getlocal("-02:00")

If you want to compute this, you have to look at your local time's utc_offset first, then either add or subtract the product of 3600 and however many timezones you want to move.  Note that this only moves timezones in whole number increments and will break in cases where a timezone that requires a different precision is needed (i.e. Newfoundland).
t = Time.now
t.getlocal(t.utc_offset + (3600 * 2))


text:
Q: how can i connect to my database sql in a java class method and called it in another class? i'm trying to create a desktop application using corba and java swing for graphical interface.
As you know , in CORBA we have to make the principal methods like: connecting to the database ,calculations... in the server ,so i have created a method in a server class for connecting to the database.
The java class method is the one shown bellow:
public  void connect_db(){
    // TODO Auto-generated method stub

    JTextField txtUsername = FrameLogin.txtUsername;
     JPasswordField pwd= FrameLogin.pwd;
    JLabel lblLoginMessage= FrameLogin.lblLoginMessage;

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root", "Mrayhana123");
        Statement stm = conn.createStatement();
        String sql="select * from etudiant where username='"+txtUsername+"' and pwd='"+pwd+"'";
        ResultSet result = stm.executeQuery(sql);
        if(result.next()){
            lblLoginMessage.setText("you are connected");
            lblLoginMessage.setForeground(Color.GREEN);

        }
        else {
            lblLoginMessage.setText("Incorrect username or password!");
            lblLoginMessage.setForeground(Color.RED);
        }

    } catch(Exception e){
        //System.out.println("not connected to database");
        e.printStackTrace();
}
}

And i have called it in the client class which contain the graphical interface by the following way:
public static JTextField txtUsername;
   public static JPasswordField pwd;
   public static JLabel lblLoginMessage = new JLabel("");

 pnlBtnlogin.addMouseListener(new MouseAdapter() {
            @Override

                  String username = txtUsername.getText();
                    String pwd= pwd.getText();

                    try {

                        SraCorbaImpl sci = new SraCorbaImpl();
                        sci.connect_db();

                    } catch(Exception e1){
                        //System.out.println("not connected to database");
                        e1.printStackTrace();
                        }

But the result always shows me Incorrect username or password! even though I type a username and a password which are in the database.
THANK YOU FOR HELPING ME

A: According to your comment, I understand that you are successfully connecting to the database but your query is not returning any rows.
If the code in your question is your actual code, then you are passing a JTextField to your [SQL] query and not the text of the JTextField. Likewise with the password. You are passing the JPasswordField and not the actual password.
Try the below code.
public  void connect_db(){
    JTextField txtUsername = FrameLogin.txtUsername;
    JPasswordField pwd= FrameLogin.pwd;
    JLabel lblLoginMessage= FrameLogin.lblLoginMessage;
    try {
//        Class.forName("com.mysql.cj.jdbc.Driver"); <- not required
        Connection conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/utilisateurs","root", "Mrayhana123");
        Statement stm = conn.createStatement();
        String sql="select * from etudiant where username='"+txtUsername.getText()+"' and pwd='"+pwd.getText()+"'";  // Change here.
        ResultSet result = stm.executeQuery(sql);
        if(result.next()){
            lblLoginMessage.setText("you are connected");
            lblLoginMessage.setForeground(Color.GREEN);
        }
        else {
            lblLoginMessage.setText("Incorrect username or password!");
            lblLoginMessage.setForeground(Color.RED);
        }
    } catch(Exception e){
        //System.out.println("not connected to database");
        e.printStackTrace();
}

Because you are using string concatenation, the toString of JTextField is being inserted into your SQL string.
Consider using a PreparedStatement instead.
String sql="select * from etudiant where username=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, txtUsername.getText());
ps.setString(2, pwd.getText());

In that case, if you omit the .getText(), the code will not compile.


text:
Q: How to Find IMEI Number from Windows 7? The Thinkpad X1 Carbon has built-in 4G which takes a Micro-SIM card. After getting a Micro-SIM, I was told to call in to activate it. The network operator though requires an IMEI number and refuses to make the Micro-SIM active without it.
There is no IMEI number anywhere on my laptop, its box or the documentation. How can I query Windows 7 to return IMEI. Tried to look in the Device Manager and the output from IPCONFIG but I cannot find it. I have the MAC addresses which were also on the box but no IMEI.

A: Assuming all of your drivers are installed run from CMD as admin:

netsh mbn show interface

Device ID is the IMEI
Alternatively you can use either the software that came with lenovo - I think the earlier version was called access connections or use some of the 3rd party software pacakges avalaible - like this one

A: Some models of Lenovo laptops have a sim card slot but do NOT have an internal card which interfaces the sim to the motherboard.  In this case you will get an error saying There is no Broadband interface when you try to show the IMEI without the card.
Specifically the Lenovo X1 Carbon 5th Gen has the sim card slot but no internal network card for the sim.  However, the Lenovo X1 Carbon 6th Gen DOES have an internal sim card.  Make sure you get the right laptop!


text:
Q: Overflow: Hidden doesn't work I'm trying to use the Masonry jQuery package to make an image gallery and want to have an effect where the picture you hover over enlarges. I've gotten all of this to work, but my problem lies in the fact that I can't get the overflow:hidden to work. My images just expand past where I'd like them to get cut off.
Any useful tips would be welcome. Here's some of my code:
HTML:

CSS:
.container_gallery {
  margin-top: 5%;
}

/* ---- Gallery ---- */
* {
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}

body { font-family: sans-serif; }

/* ---- grid ---- */

.grid {
  max-width: 1200px;
  max-height: 800px;
}

/* clearfix */
.grid:after {
  content: '';
  display: block;
  clear: both;
}

/* ---- grid-item ---- */

.grid-item {
  width: 160px;
  height: 120px;
  float: left;
  border: 1px solid black;
  border-color: hsla(0, 0%, 0%, 0.5);
  border-radius: 0px;
}

/*
.grid-item:hover {
  opacity: 0.3; filter: alpha(opacity=30);
}
*/

.grid-item--width2 { width: 320px; }
.grid-item--width3 { width: 480px; }
.grid-item--width4 { width: 640px; }

.grid-item--height2 { height: 200px; }
.grid-item--height3 { height: 260px; }
.grid-item--height4 { height: 360px; }

 /* ---- Gallery End ---- */

.grow .pic_float_w1h2 img {
  height: 200px;
  width: 160px;

  -webkit-transition: all 1s ease;
     -moz-transition: all 1s ease;
       -o-transition: all 1s ease;
      -ms-transition: all 1s ease;
          transition: all 1s ease;
}

.grow img:hover {
  height: 300px;
  width: 260px;
}

A: You are looking for somethings like this
  .grow img:hover {
     height: 300px;
     width: 260px;
     max-height: 300px;
     max-width: 260px;
   }


text:
Q: sqlite error step 19 iOS what is wrong here?
I need use sqlite bind, because I want add HTML tags to sqlite database.
sqlite3_stmt *stmt;

    const char *sql = "INSERT INTO News (id,title,description,date,removed) VALUES (?,?,\"asd\",1,0);";

    if (sqlite3_prepare_v2(database, sql, -1, &stmt, NULL) == SQLITE_OK) {
        sqlite3_bind_int(stmt, 0, 2);
        sqlite3_bind_text(stmt, 1, [@"test_binf" UTF8String], -1, SQLITE_TRANSIENT);

        if (sqlite3_step(stmt) == SQLITE_DONE) {

        }
        else {
            NSLog(@"Error on step: %i",sqlite3_errcode(database));
        }

        sqlite3_reset(stmt);
        sqlite3_finalize(stmt);

    }
    else {
        NSLog(@"Error on prepare: %i",sqlite3_errcode(database));
    }

I got sqlite error: "Error on step: 19".
Please help me.

A: The documentation says:

The leftmost SQL parameter has an index of 1.

You must use indexes 1 and 2.


text:
Q: Renaming of classes in MDriven Inspired by the "Making sense of a legacy db" am I trying to use the "autoforms feature" to make sense of a db having more than 8000 tables. Now have I reduced the number to 800 classes. All classes have gotten the table name, a typical four letter abbreviation. But I have managed to get a list of "good" names from business. I need this to get the names correct in order to move on and use autoforms.... The question is how can rename the classes via an ocl expression (for the Class.Name)? Tried in model debugger but I do not get access to "TableWithNewClassNames" (holding the mapping of the old and new class names) ?

A: The current name of the class is stored in the Name attribute.
If you have reversed the table, you can freely change the class name without disturbing the table name used to access the table in the database.
The extra information for mapping the class to the underlying table are stored in tagged values linked to the class model object.
In the image below, you see the tagged values providing this info
Note the tab "TaggedValuesAndAttributes". Click it and click "load" to see the editor.
So, you can rename classes freely using the Name value of the class.

Then, if you want to write EAL to do the changes, read this wiki article for help: https://wiki.mdriven.net/index.php/How_to_rename_a_class_in_your_model_%E2%80%93_using_the_model_debugger
Hope this helps!


text:
Q: Calculating Days With Equivalent String Value Using Datediff Computed Column Specification Formula I'm using SQL Server 2008 and I made a computed column on my table which is ResidencyStatus. Using datediff in ResidencyStatus I want to know the difference between the current date (now date) and my other date column ResidencyDate.

*

*Now, if the result is less than or equal to 183 days(less than or equal to 6 months) then I want to put the string 'Transient' in ResidencyStatus.

*If the result is greater than or equal to 184 days(greater than or equal to 6 months and 1 day) AND less than or equal to 1825 days(less than or equal to 4 years and 364 days) then the value will be 'Migrant'.

*If the result is greater than or equal to 1826 days(greater than or equal to 5 years) then the value will be 'Resident'.
I tried using this formula in the computed column:
(case when (datediff(day,[ResidencyDate],getdate()))<=183 then 'Transient' elseif (datediff(day,[ResidencyDate],getdate())>=184 and <=1825 then 'Migrant' elseif (datediff(day,[ResidencyDate],getdate())>=1826 then 'Resident' end

...but this error occurs "Error validating the formula for column ResidencyStatus." Can you give me an idea on how to make this formula work or maybe an alternative solution?

A: Try this.
  select
  ....
  CASE
     WHEN ( Datediff(day, [ResidencyDate], Getdate()) ) <= 183 THEN 'Transient'
     WHEN Datediff(day, [ResidencyDate], Getdate()) >= 184
          AND Datediff(day, [ResidencyDate], Getdate()) <= 1825 THEN 'Migrant'
     ELSE 'Resident'
   END
  .....
  .....

OR use Between
  select
  ....
  CASE
     WHEN ( Datediff(day, [ResidencyDate], Getdate()) ) <= 183 THEN 'Transient'
     WHEN Datediff(day, [ResidencyDate], Getdate()) Between 184 and 1825 THEN 'Migrant'
     ELSE 'Resident'
   END
  .....
  .....

A: There is no such thing as elseif in a case statement.  The case statement takes a series of when clauses, and these are evaluated in order.  So, you can express what you want as:
(case when datediff(day, [ResidencyDate], getdate()) <= 183 then 'Transient'
      when datediff(day, [ResidencyDate], getdate()) <= 1825 then 'Migrant'
      else 'Resident'
 end)

Okay, this does have a slight difference from your logic.  The else will include NULL values.  This is easy enough to fix:
(case when datediff(day, [ResidencyDate], getdate()) <= 183 then 'Transient'
      when datediff(day, [ResidencyDate], getdate()) <= 1825 then 'Migrant'
      when datediff(day, [ResidencyDate], getdate()) > 1825 then 'Resident'
 end)

This will return NULL in those cases.


text:
Q: upgrading node for electron I am creating an app using electron framework but when I'm trying to use async functions it gives me an error.
Because my electron uses node version 6.5.0 but node in this version doesn't support async functions.
So I am trying to upgrade my electron's node but I don't know how to create a branch or stuff like that since https://electronjs.org/docs/development/upgrading-node is the only link I found to explain this matter but I can't understand it. Can I upgrade node in my electron framework in another way?

A:
Can I upgrade node in my electron framework in another way

No, you cannot. Electron links a specific version of node with chromium in its build time, so each version of electron have a fixed version of node.js and cannot be replaced dynamically.
Either use a higher version of the electron have higher node.js version, try to manually build electron yourself is the only way to go.


text:
Q: org-mode: Agenda View doesn't show any items when I press c-c a a agenda view doesnt list any items, but when i press c-c a n agenda view lists week and todo items.
I have already added the org files to front.
Am I using the agenda view wrong?


text:
Q: my app consume high CPU My app is composed by four tab : a webview, and three view with some text/edittext, ...
The problem is my app consume a lot of CPU and I don't understand why, and one of the main problem is when the app is onPause (the user use the home button), my app still use CPU (arround 20%, or even more !) and is battery consuming.
I don't understand what use so much CPU, so I have two questions :

*

*How can I know exactly (with eclipse) the process (method, activity...) which use too much CPU ?

*How can I "freeze" with 0 CPU consumption my app when the user press the home button (I suppose is in the onPause method, I try with a finish(), it's work but when the user go back to my app, he get a FC).

Thanks a lot !
EDIT :
Seems my webview consume the CPU. How can i do to stop this webview during onPause without destroy the webview object ?

A: I find the solution :
THe javascript content in the webview was the problem. To solve that :
@Override
public void onPause() {
    super.onPause();
    /* pause timer of the webview, if not, high CPU during on pause */
    page.pauseTimers();
}

and on Resume,
public void onResume() {
    /* reactive timer */
    super.onResume();
    page.resumeTimers();
}


text:
Q: is it correct to say "Start to looking"? The first verse of the song "All that meat and no potatoes" by Louis Armstrong says:
A man works hard then comes on home,
Expects to find stew with that fine ham bone.
He opens the door, then start to looking,
Says, Woman, what's this stuff you're cooking?

"Start to looking" sounds wrong to me.
Of course he needs to rhyme with "cooking" so he could have used "starts looking" but then the sentence would be too short for the tempo.
So my question is: Is it actually correct to say "start to looking" or definitely not?

A: Start to VERBing, start in to VERBing, get to VERBing, get started to VERBing, and get started in to VERBing were all common in the dialect around me when I was young in East Alabama; it doesn't surprise me that one such construction should show up 350 miles to the southwest.
To in these constructions is a preposition, not an infinitive marker.

A: In terms of traditional grammar of standard English it is wrong, of course. Meaning: a school teacher would count it as a mistake, or two.
However, there are ways to interpret this by means of rhethoric figures, and as it is a song text, i.e. something like a poem, why not?
So, if you want to avoid stating that Armstrong made grammar mistakes, you may resort to interpreting this as an (extreme) form of ellipsis:

He opens the door, then [there is a] start to [the action of him] looking

Okay, I admit, on a scale between far-fetched and absurd, this is more to the latter, but, well... to save Amstrong's grammar reputation... ?


text:
Q: Set field based on sum(value) Apologies for ambiguous title
Given the following data..
  +------+------------+--------+
  |  ID  |  value     | used   |
  +------+------------+--------+
  | 1001 |    1       |   0    |
  +------+------------+--------+
  | 1002 |    1       |   0    |
  +------+------------+--------+
  | 1003 |    2       |   0    |
  +------+------------+--------+
  | 1004 |    4       |   0    |
  +------+------------+--------+
  | 1005 |    1       |   0    |
  +------+------------+--------+
  | 1006 |    1       |   0    |
  +------+------------+--------+
  | 1007 |    1       |   0    |
  +------+------------+--------+
  | 1008 |    6       |   0    |
  +------+------------+--------+

I would like to set the sum value of say 8, so the result would be ....
  +------+------------+--------+
  |  ID  |  value     | used   |
  +------+------------+--------+
  | 1001 |    1       |   1    |
  +------+------------+--------+
  | 1002 |    1       |   1    |
  +------+------------+--------+
  | 1003 |    2       |   1    |
  +------+------------+--------+
  | 1004 |    4       |   1    |
  +------+------------+--------+
  | 1005 |    1       |   0    |
  +------+------------+--------+
  | 1006 |    1       |   0    |
  +------+------------+--------+
  | 1007 |    1       |   0    |
  +------+------------+--------+
  | 1008 |    6       |   0    |
  +------+------------+--------+

I would do this my going through each item adding it to a total value, similar to this
  $goal = 8;
  $select = "SELECT ID, value FROM table WHERE !used";
  $result = mysql_query($select);
  while ($row = mysql_fetch_array($result))
     {
     $total = $total + $row['value'];
     if ($total => $goal)
         {
         $over = $goal - $total
         if ($over)
            {
            $id = $row['id'];
            mysql_query("INSERT INTO table(value,used) VALUES('$over',0)");
            mysql_query("update table SET used = 1 WHERE id = '$id'")
            }
          break;
         }
     $id = $row['id'];
     mysql_query("update table SET used = 1 WHERE id = '$id'")
     }

So, pretty ugly. suggestions of a better method?

A: Give this a whirl:
      $goal = 8;
      $used = Array()
      $select = "SELECT ID, value FROM table WHERE !used";
      $result = mysql_query($select);
      while ($row = mysql_fetch_array($result))
         {
         $total = $total + $row['value'];
         $used[] = $row['ID'];
         // Check for exact march
         if ($total == $goal) {
             // Loop through all used ID's to get an exact match
             foreach($used as $usedId) {
                mysql_query("update table SET used = 1 WHERE id = " . $usedId);
             }
             break;
         } elseif ($total > $goal) { // If over then insert as a new record
             $leftOver = $total - $goal;
             mysql_query("INSERT INTO table(value,used) VALUES($leftOver, 0)");
             break;
         }
      }

What this doesn't answer is if the total is less than your goal - what happens then?

A: Try this query -
SELECT t1.ID, t1.value, IF(SUM(t2.value) > 8, 0, 1) used FROM used t1
  JOIN used t2
    ON t1.ID >= t2.ID
  GROUP BY t1.ID

A: First of all you should not use old and deprecated mysql_* functions. Use MySQLi or PDO instead.
$goal=13;
$cache=0;
$idCache=0;
$result=$mysqli->query("SELECT id,value FROM [table] WHERE used=0 ORDER BY id ASC");
while($row=$result->fetch_assoc())
{
    $idCache=intval($row["id"]);
    $cache+=intval($row["value"]);
    if($cache>=$goal) break;
}
$result->free();
$stmt=$mysqli->prepare("UPDATE [table] SET used=1 WHERE used=0 AND id<=?");
$stmt->bind_param("i",$idCache);
$stmt->execute();
$stmt->close();
if($cache>$goal)
{
    $stmt=$mysqli->prepare("INSERT INTO [table] (value,used) VALUES (?,0)";
    $cache=$goal-$cache;
    $stmt->bind_param("i",$cache);
    $stmt->execute();
    $stmt->close();
}

Explanation:

*

*From your demo data I assumed that you want to fetch your data sorted by id ascending, so I query them all with an ORDER BY clause;
(the $mysqli->query part)

*Sum the result into $cache until it gets not less than $goal;
(the while part)

*Since we get the value in id-ascending order, we can safely mark all IDs not greater than the last row we get to be "used";
(the $mysqli->prepare before if block)

*If the sum is greater than goal, we added the "overflowed" value back into the table, with used marked as 0, as you hinted in your code.
(the if block)
Note that the above code does not take the "what if not enough value to sum up $goal" situation into account. You'll have to deal with that if it can be a real case.


text:
Q: Django 3.1 Best way to Conditionally load statics I'm new to django and currently trying to find an effective way to load css files in the django templating language depending on the current page. The url pattern is :
path('invoices/', views.list, name='invoice_list'),
path('invoices/new/', views.create, name='create_invoice'),
path('invoices/<int:pk>/', views.edit, name='edit_invoice'),
path('invoices/<int:pk>/lines/new', views.create_line, name='create_line'),
path('invoices/<int:pk>/lines/<int:fk>', views.update_line, name='update_line'),

In the base.html, this is what i'm doing:
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'invoice/css/common.css' %}">
    {% if request.path == '/invoices/'%}
       <link rel="stylesheet" href="{% static 'invoice/css/invoice_list.css' %}">
    {% endif %}
    {% if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path %}
       <link rel="stylesheet" href="{% static 'invoice/css/edit_invoice.css' %}">
    {% endif %}
    <title>My invoices </title>
  </head>

the  {% if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path %} is not great at all and would like to know if there's a nicer way to do it regexp style maybe?
Thanks in advance.

A: You should not put such logic in the template. Instead you should use the block and extends template tag for this purpose. See Template inheritance [Django docs]:
In base.html:
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'invoice/css/common.css' %}">
    {% block extra_css %}
    {% endblock extra_css %}
    <title>My invoices </title>
  </head>

Now in the template which is rendered when if request.path == '/invoices/' is true, you will fill this block as:
{% extends "base.html" %}
...
{% block extra_css %}
    <link rel="stylesheet" href="{% static 'invoice/css/invoice_list.css' %}">
{% endblock extra_css %}

Similarly In the template which is rendered when if '/invoices/' in request.path and request.path != '/invoices/' and '/line/' not in request.path is true you you will fill the block as:
{% extends "base.html" %}
...
{% block extra_css %}
    <link rel="stylesheet" href="{% static 'invoice/css/edit_invoice.css' %}">
{% endblock extra_css %}


text:
Q: How to add more to Biopython's chromosome drawings? I am trying to draw a karyotype/ideogram figure using Biopython's BasicChromosome library. I am able to draw my chromosome and make annotations inside the chromosome like in the tutorial; however, my boss prefers the annotations on the outside of the chromosome along with various symbols.
How can I expand on this great simple ideogram drawing tool? I noticed it uses reportlab and I am guessing I would have to customize the source code? For example, would I make a copy of the Module Bio.Graphics.BasicChromosome and edit the portion that pertains to drawing annotations then explicitly import my version? And for adding symbols I would have to learn reportlab's other features?

A: Yes, you would need to learn a bit more about ReportLab and then try modifying https://github.com/biopython/biopython/blob/master/Bio/Graphics/BasicChromosome.py
(I'm not quite sure what changes you want to make, an annotated image might help, so I can't give you any more specific hints)


text:
Q: Enable landscape orientation in didFinish function WKWebView I'm a big noob when it comes to swift and iOS app implementation.
So what Im trying to do and not sure if possible.
So I created a WKWebView and added UIImage and ProgressView to my viewDidLoad() function. Once the webiste finishes loading I remove both views in didFinish function. So I would like once the didFinish is called to be able to enable the screen to rotate, Not force it enable it. So if a user is in landscape the website only can be used in landscape.
In general I created a loader screen for my WKWebView and I want it to always be in portrait mode but once site is loaded to be flexible to change from portrait to landscape as normal.
Thanks in advance

A: In the function "supportedInterfaceOrientations", you can return the required orientation after checking whether your webview is loading or not. Then, after webview finished loading and your device is in landscape, you should change the orientation programmatically (How do I programmatically set device orientation in iOS7?)


text:
Q: How to use external SVG elements in IE 9-10-11 ( tag) I have the following:
<svg viewBox="0 0 20 20" class="icon">
     <use xlink:href="/img/svg/road.svg#Laag_1"></use>
</svg>

My doctype is correct. The SVG is shown when I add it in a general <img> tag. The reason why I can't do that is I can't do any animation (eg: fill: #fff;) onto it so this is the only solution.
The icons are properly displayed in all other browsers. Any ideas here?

A: (Found the answer through the comment of Robert Longson)
The problem here is the external use of the use-tag. One way to fix it is to use the svg4everybody library created by Jonathan.
Github:
https://github.com/jonathantneal/svg4everybody
CDN:
https://cdnjs.com/libraries/svg4everybody
Just implement it in the footer, call the function svg4everybody(); and it does the job. Note that you need the specific markup of the SVG file in order for it to work.
Markup of the SVG image has slightly changed:
<svg title="Tower" role="img" class="icon">
    <use xlink:href="/img/svg/_svg-icons.svg#tower"/>
</svg>

The "viewbox" is now specified in the general _svg-icons.svg file (and the title and role specified for readability)


text:
Q: How to schedule user-defined jobs with APscheduler in a Django view The idea is to allow users to submit a time/date to the server to have a job scheduled to execute at the user-specified time.
My first choice was to do this in the view, where the data from the frontend is posted to. However, apscheduler returns a value error.
Below is a snippet from the view I wish to use for user-scheduled jobs and just a small test.
class SchedulePolicyDeployView(APIView):
 def post(self, request, version):

    def test_job():
        print("cron job test")

    scheduler.start()
    scheduler.add_job(test_job, "cron", id="test_job", day="*", minute="*/1")

    return Response("job scheduled successfully")

The error message returned is:
ValueError: This Job cannot be serialized since the reference to its callable (<function SchedulePolicyDeployView.post.<locals>.test_job at 0x05694C00>) could not be determined. Consider giving a textual reference (module:function name) instead.

A: So I did fix this issue in my code; but it's changed quite a bit since I did asked this question. I've tried to bring it all in here though:
*assuming the scheduler object has already been initialised
scheduler.py
def schedule_job(arg1, arg2, arg3, time, job_id):
    scheduler.add_job(deploy_policy, 'date', args=[arg1, arg2, arg3], run_date=datetime(int(date['year']), int(date['month']), int(date['day']), int(time['hour']), int(time['minute']), 0))
    return Response({"message": "scheduled!"})

views.py
from scheduler import schedule_job
class SchedulePolicyDeployView(APIView):
    def post(self, request, version):
        schedule_job(apic, username, password, policy_url_and_payload_result, date_dict, time_dict, payload["job_id"])
        return Response({"result": "success"})


text:
Q: Load back a textfile into a List I'm currently stuck with a small problem.
My program currently outputs a return value and puts it in a listbox with this method:
        public override string ToString()
    {
        CheckKamer();
        if (IsKamerBezet == true)
        {
            return $"Kamer: {Nummer} is bezet";
        }
        else
        {
            return $"Kamer: {Nummer} is vrij";
        }
    }

after that my program saves the return values provided by the method in a .txt file with this method:
private void ReserveringText()
    {
        using (System.IO.StreamWriter file =
        new System.IO.StreamWriter(filepath, true))
            file.WriteLine(reserveringLB.Items.ToString());
        System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(filepath);
        foreach (var item in reserveringLB.Items)
        {
            SaveFile.WriteLine(item.ToString());
        }
    }

Now when I restart my program it reads the lines put in the .txt file and sets it back in the listbox, with another simple method:
        private void LaadItems()
    {
        var lines = File.ReadAllLines(filepath);
        reserveringLB.DataSource = lines;
    }

But whenever I try to add a new guest to my hotel, it says the object reference isnt set to an instance of the object, because it loads it from the .txt file and not from the class list I used to load it from.
My guest is added to the class here:
private void reserveerBtn_Click(object sender, EventArgs e)
{
    Gast gast = new Gast(tbNaam1.Text, cbOntbijt1.Checked, cbDiner1.Checked, (Model.Enum.Geslacht)cbGeslacht1.SelectedValue);
    Reservering reservering = new Reservering(vrijekamer, dateTimePicker1.Value, dateTimePicker2.Value, gast);
                    gast.Reservering = reservering;
    admin.VoegGastToe(gast);
     admin.VoegReserveringToe(reservering);
}

Could anyone help me out and tell me how I'd be able to let the program load the .txt file, and put that back into the List so I can actually add a guest to the program.
If anything is unclear please let me know, I'll be looking at this post alot so I can immediatly change it / add something if u guys need anything.


text:
Q: Opposite of required_if in laravel using multiple value evaluation How to validate must null if another field has specific value or not null
In my case it is the opposite of required_if with multiple values
$rule = array(
  'selection' => 'required',
  'stext' => 'required_if:selection,2|required_if:selection,3',// stext should be null if selection is 2 or 3
);

And if needed how to perform own validation?

A: So in your example you can do something like this:
$rule = array(
  'selection' => 'required',
  'stext' => 'required'
);

// override the rule
if(in_array(request('selection'), [2, 3]))
{
  $rule['stext'] = 'nullable';
}

This means if the selection is 2 the field will be required and if the selection field has any other value the stext field will be required.
I am not sure if I understood your question correctly. In any case the opposite of required_if is required_without so you can use that one if you want this field to be required even if the selection is empty.
With custom rule your passes method should look like this:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CustomRule implements Rule
{

    protected $selection;

    public __construct($selection)
    {
        $this->selection = $selection;
    }

    public function passes($attribute, $value)
    {
        return $value === null && in_array($this->selection, [2, 3]);
    }
}

You use it like this:
$rule['stext'] = [ new CustomRule(request('selection') ]

A: I try to extend the validation rule. put the following in AppServiceProvider:
Validator::extend('null_if', function ($attribute, $value, $parameters, $validator) {
    $other = $parameters[0];
    $other_value = array_get(request()->toArray(), $other);
    if ($parameters[1] == $other_value) {
        return empty($value);
    }
    return true;
});

Tell me if it's work or what error given to you.


text:
Q: Do Grillers have a set amount of Smallfry? In the Griller wave of Salmon Run, a bunch of Smallfry run underneath the Griller enemy itself.
Is there a set amount of Smallfry that come with the Griller, or are more Smallfry generated by the Griller as it moves around? I want to know if it is possible to defeat all the Smallfry so that I don't have to worry about them while fighting the Griller.

A: When a Griller enemy spawns, a group of Smallfry will spawn with it. During a Griller wave, Smallfry will constantly spawn, around 1 every 2-3 seconds.


text:
Q: Jquery - Add hyperlink to datatables Using the DataTable plugin I am able to generate a table just fine but I want a custom hyperlink on one of the columns that links to another page but taking information from the rest of the row...for example in row 1 I want a hyperlink: http://url/?data['imdata'][i]['faultInst']["attributes"]["code"] or something like that. I've seen a lot of complicated examples from other forms but couldn't get it to work. Looking for the simplest solution as this is a side project and I need it to be completed.
$(document).ready(function(){

        $.getJSON('/static/faults.json', function (data) {

            var test = $('#table5').DataTable({
            });

            var tr;
            for (var i = 0; i < data["totalCount"]; i++) {
              test.row.add([
                  data['imdata'][i]['faultInst']["attributes"]["code"],
                  data['imdata'][i]['faultInst']["attributes"]["cause"],
                  data['imdata'][i]['faultInst']["attributes"]["descr"],
                  data['imdata'][i]['faultInst']["attributes"]["created"],
                  data['imdata'][i]['faultInst']["attributes"]["changeSet"],
                  data['imdata'][i]['faultInst']["attributes"]["childAction"],
                  data['imdata'][i]['faultInst']["attributes"]["dn"],
                  data['imdata'][i]['faultInst']["attributes"]["domain"],
                  data['imdata'][i]['faultInst']["attributes"]["highestSeverity"],
                  data['imdata'][i]['faultInst']["attributes"]["lastTransition"],
                  data['imdata'][i]['faultInst']["attributes"]["lc"],
                  data['imdata'][i]['faultInst']["attributes"]["occur"],
                  data['imdata'][i]['faultInst']["attributes"]["origSeverity"],
                  data['imdata'][i]['faultInst']["attributes"]["prevSeverity"],
                  data['imdata'][i]['faultInst']["attributes"]["rule"],
                  "test",
                  //data['imdata'][i]['faultInst']["attributes"]["Severity"],
                  data['imdata'][i]['faultInst']["attributes"]["subject"],
                  data['imdata'][i]['faultInst']["attributes"]["type"],
                  //data['imdata'][i]['faultInst']['attributes']["ack"]
                  "test",
                  "test"
              ])
            }

            test.draw();
        });
    });

A: When you have a setup like this, just avoid to define data, by that you get the proper value you can turn into a link. dataTables know which data it should pass to the render function by the targets value. Example :
var table = $('#example').DataTable({
    columnDefs : [
      { targets : [0],
        render : function(data) {
          return ''+data+''
        }
      }
    ]
})

table.row.add(['https://example.com', 'david', 'programmer']).draw()

demo -> http://jsfiddle.net/47k7nhkb/


text:
Q: Delphi DLL Dynamic Error raise to many consecutive exception I found this source code from a Delphi sample codes, and
I am adding a control or component inside a Delphi dynamic DLL, I can't figure it out,
library DLLEntryLib;

uses
  SysUtils,
  Windows,
  Dialogs,
  Classes,
  msHTML,
  SHDocVw;

type
TMyWeb = class(TWebBrowser)
constructor create(Aowner: TComponent); override;
end;

var
web: TMyWeb;

// Initialize properties here
constructor TMyWeb.Create(AOwner: TComponent);
begin
inherited Create(Self);
end;

procedure getweb;
begin
    web := TmyWeb.create(nil);
    web.Navigate('http://mywebsite.com');
end;

procedure xDLLEntryPoint(dwReason: DWord);
begin
  case dwReason of
    DLL_PROCESS_ATTACH:
    begin
    getweb; //I THINK THE ERROR IS HERE, HOW TO WORK THIS OUT?
    ShowMessage('Attaching to process');
    end;
    DLL_PROCESS_DETACH: ShowMessage('Detaching from process');
    DLL_THREAD_ATTACH:  MessageBeep(0);
    DLL_THREAD_DETACH:  MessageBeep(0);
  end;
end;

begin
  { First, assign the procedure to the DLLProc variable }
  DllProc := @xDLLEntryPoint;
  { Now invoke the procedure to reflect that the DLL is attaching to the
    process }
  xDLLEntryPoint(DLL_PROCESS_ATTACH);
end.

//IN MY APPLICATION FORM.
procedure TMainForm.btnLoadLibClick(Sender: TObject);
begin
if LibHandle = 0 then
begin
LibHandle := LoadLibrary('DLLENTRYLIB.DLL');
if LibHandle = 0 then
  raise Exception.Create('Unable to Load DLL');
end
else
MessageDlg('Library already loaded', mtWarning, [mbok], 0);
end;

How do I get rid of the error?
raise to many consicutive exception

A: When you write:
inherited Create(Self);

you should write
inherited Create(AOwner);

You are asking the control to own itself. That just cannot work. That quite possibly leads to a non-terminated recursion if the constructor fails.
The other big problem is that you are creating a web browser control inside DllMain. That's a very big no-no. You'll want to stop doing that. Move that code into a separate exported function. Do nothing in DllMain.
Presumably the caller has already initialized COM. If not, you will need to ensure that the caller does so. If the caller is a VCL forms app then COM will be initialized automatically.


text:
Q: Search results in multi page - page numbers should be shown on top & bottom Search results exceeding more than one page are shown in multi pages as shown below

But currently this is showing only at the bottom of the page. If user scroll from bottom to top this bar will not be there and user again has to scroll to the bottom of the page to switch to another page.
Thus the page number also displayed at the top.


text:
Q: Correct expression for checking leap years
Possible Duplicate:
how to find leap year?

What will be the exact definition of leap year? AFAIK "A year which is divisible by 4 is a leap year. But for century years' the years which are divisible by 400 is a leap year."
But that definition makes 100, 200, 300, 400.... upto 1700 NOT LEAP years! But in Gregorian calendar all of them are all leap year, check this out.
You can also try "call 1700" in Linux to verify.
So the correct algorithm for leap years would be:
if ( (year % 4 == 0) && ( year <= 1700 || year % 100 != 0 || year % 400 == 0 ))
    printf("%d is a leap year.\n", year);
 else
    printf("%d is not a leap year.\n", year);

But is this specific to Gregorian calendar? Even if that is the case why is it not mentioned here?
Regards,
PS:The history of Gregorian callender seems interesting check out the September month of 1752.

A: For one thing, your algorithm is a bit off.  It's more like:
if ( (year % 4 == 0) && ( year % 100 != 0 || year % 400 == 0 ))
    printf("%d is a leap year.\n", year);
 else
    printf("%d is not a leap year.\n", year);

Also, the Gregorian calendar was not adopted until 1582 or so.
Edit:
The Gregorian calendar was decreed in 1582, but adopted by various countries at various times, as late as 1926 in Turkey.

A: I think it's important to separate the idea of historical dates on the one hand and date calculation on the other.  Historical dates are subject to all kinds of political, social, and technological issues, and are thus not very suitable for a simple algorithm.  See this page for the wide disparity in the adoption of the modern Gregorian calendar.
The usual practice when calculating dates is to forget about history and just pretend that the existing system has always been in place and will always be in place.  (Unless you are an astronomer or certain other kinds of scientist, in which case you would use something even more accurate, and would be even less interested in historical dates.)  If your application is all about recorded historical dates, then you are going to need a way to map those dates (which depend on the country, the period in history, etc.) to a more calculation-friendly universal dating system anyway.

A: Have a look here. I'll copy some of the pseudo-code here for reference:
if (year modulo 4 is 0) and ((year modulo 100 is not 0) or (year modulo 400 is 0))
       then is_leap_year
else
       not_leap_year

A:
"But is this specific to Gregorian calendar"

Yes.
Please read this http://en.wikipedia.org/wiki/Leap_year
Because of the orbits of Earth (and Moon), we have a variety of calendars, each with complex rules for trying to get a rational match between days and years.
Please read this http://en.wikipedia.org/wiki/Gregorian_calendar
Please buy a copy of http://emr.cs.uiuc.edu/home/reingold/calendar-book/index.shtml

A: Read down the web page you linked to. The reason for the gap in September 1752 is that is when the UK converted from Julian to Gregorian calendars, it is not a gap in Gregorian calendar but the difference between the two.
The page you link to uses the Julian calendar up until that point. Therefore the algorithm you use for calculating leap years is different to the way the page (or the UK, or England, though neither existed in AD 100) calculated for years before 1752.

A: If your platform has a Date datatype, your first try would be to use whatever date expression and manipulation features it has. Usually these are sufficient, and you can save yourself the trouble of taking responsibility for supporting YA date-handling library.
So the answer to your question would be the equivalent of:
if(exists("02/29/yyyy".toDate)) ...


text:
Q: New installed Ubuntu 20.04 got no internet connection I installed a new Ubuntu 20.04, but got no internet connection. The PC is connected through Ethernet cable. What can I do?
What I checked so far:
Lights working on both computer and router
Other PC with the same cable works.
Double checked that everything is plugged in correctly.
Running dmesg -w results in a very long list. Idk what were searching for. Maybe this: "link is up - 1gbps/full - flow control off"?
I installed windows on the same PC, with the same cable and internet works.
Lspci says "Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 03)
I can't ping 8.8.8.8
When typing "id a" it tells me things that i don't understand, starting with "1: lo: <LOOPBACK, UP, LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000"

A: Try to check interface via ip command:
This command will list all network interfaces with associated IP-addresses:
ip addr show

Try to find out which one you need(by default enp3s0 or like that).
If there is no interfaces but loopback then check output of this command and find your network device:
sudo lshw -C network

If there is your device check config file(first command below). And use second command to apply changes(if there is any).
sudo nano /etc/netplan/01-netcfg.yaml
sudo netplan apply

Example netplan config:
network:
version: 2
renderer: networkd
ethernets:
    enp3s0:
        dhcp4: true

If the interface's state is down(find out from ip addr show output), try to UP it:
sudo ip link set enp3s0 up

Also check assigned IP address from ip addr show output. If no IP is assigned, try this to get network configurations form DHCP:
sudo dhclient enp3s0

P.S. Replace enp3s0 to your interface.


text:
Q: The vpc none does not exist. - AWS CloudFormation When I try to launch my AWS cloudformation stack in new region. Am getting error "The vpc none does not exist" when creating RDS service. Can anyone help me to fix this issue?
"dbsgdefault": {
    "Type": "AWS::RDS::DBSecurityGroup",
    "Properties": {
        "GroupDescription": "default"
    }
},

A: The DBSecurityGroup documentation suggests that EC2VpcId is required when creating a DBSecurityGroup in a VPC. It also suggests DBSecurityGroupIngress is required. Here is an example group using the two required fields:
 "DBSecurityGroup": {
       "Type": "AWS::RDS::DBSecurityGroup",
       "Properties": {
            "EC2VpcId" : { "Ref" : "VpcId" },
            "DBSecurityGroupIngress": [
                 {"EC2SecurityGroupName": { "Ref": "WebServerSecurityGroup"}}
            ],
            "GroupDescription": "Frontend Access"
       }
 }

If you are working outside of a VPC then you probably won't need EC2VpcId but you will definitely need a DBSecurityGroupIngress rule.
However, it does also say that DBSecurityGroup is not the recommended way to add security to DB instances and to use VPCSecurityGroups instead.

The Id of the VPC. Indicates which VPC this DB Security Group should
  belong to.
Important The EC2VpcId property exists only for backwards
  compatibility with older regions and is no longer recommended for
  providing security information to an RDS DB instance. Instead, use
  VPCSecurityGroups. Type: String
Required: Conditional. Must be specified to create a DB Security Group
  for a VPC; may not be specified otherwise.


text:
Q: How to get last executed SQL query by SqlConnection? I have a SqlConnection object accessible to my code. All other ADO.NET objects like SqlCommand, SqlParameter etc are not accessible to me. These other objects are consumed by Dapper Extensions ORM.
My application executes SQL queries using SqlConnection object and Dapper Extensions method. SQL query is auto generated by Dapper Extensions; generated query is not accessible to me. I want to log this SQL query.
I already have my logging module in place and the only thing I need is the last SQL query executed by connection object.
How to get last executed SQL query by SqlConnection?
Following does not work because SqlCommand is not accessible.
If I get underlying SqlCommand, I can build the query from it using the code below; unfortunately, it is not accessible to me.
public string GetCommandLogString(IDbCommand command)
{
    string outputText;
    if(command.Parameters.Count == 0)
    {
        outputText = command.CommandText;
    }
    else
    {
        StringBuilder output = new StringBuilder();
        output.Append(command.CommandText);
        output.Append("; ");

        IDataParameter objIDataParameter;
        int parameterCount = command.Parameters.Count;
        for(int i = 0; i < parameterCount; i++)
        {
            objIDataParameter = (IDataParameter)command.Parameters[i];
            output.Append(string.Format("{0} = '{1}'", objIDataParameter.ParameterName, objIDataParameter.Value));

            if(i + 1 < parameterCount)
            {
                output.Append(", ");
            }
        }
        outputText = output.ToString();
    }
    return outputText;
}

A: An approach that I've used in the past, when I didn't want to rely upon any external tools (or when the tools were lacking, like when working with MS Access) is to use database connection and command "wrapper" classes so that I can add logging to any of their methods or properties.
To use it, you pass whatever connection you want to use into the WrappedDbConnection's constructor as below:
using (var conn = new WrappedDbConnection(GetMyConnection()))
{
    // Do work using Dapper here against "conn"
}

(Note: When the WrappedDbConnection instance's Dispose method is called, that will be passed onto the underlying connection and so you don't need a using for the WrappedDbConnection and a separate using for your connection - you only need one using, as shown above).
The two classes that you need are defined below.
Note that there are Console.WriteLine calls in the methods ExecuteNonQuery, ExecuteReader, ExecuteReader and ExecuteScalar that will write out what query is about to be executed. You may want to change this for your requirements to write out the query after it's completed or you might want to use a different output that Console.Writeline but those should be simple enough changes to make.
public class WrappedDbConnection : IDbConnection
{
    private readonly IDbConnection _conn;
    public WrappedDbConnection(IDbConnection connection)
    {
        if (connection == null)
            throw new ArgumentNullException(nameof(connection));

        _conn = connection;
    }

    public string ConnectionString
    {
        get { return _conn.ConnectionString; }
        set { _conn.ConnectionString = value; }
    }

    public int ConnectionTimeout
    {
        get { return _conn.ConnectionTimeout; }
    }

    public string Database
    {
        get { return _conn.Database; }
    }

    public ConnectionState State
    {
        get { return _conn.State; }
    }

    public IDbTransaction BeginTransaction()
    {
        return _conn.BeginTransaction();
    }

    public IDbTransaction BeginTransaction(IsolationLevel il)
    {
        return _conn.BeginTransaction(il);
    }

    public void ChangeDatabase(string databaseName)
    {
        _conn.ChangeDatabase(databaseName);
    }

    public void Close()
    {
        _conn.Close();
    }

    public IDbCommand CreateCommand()
    {
        return new WrappedDbCommand(_conn.CreateCommand());
    }

    public void Dispose()
    {
        _conn.Dispose();
    }

    public void Open()
    {
        _conn.Open();
    }
}

public class WrappedDbCommand : IDbCommand
{
    private readonly IDbCommand _cmd;
    public WrappedDbCommand(IDbCommand command)
    {
        if (command == null)
            throw new ArgumentNullException(nameof(command));

        _cmd = command;
    }

    public string CommandText
    {
        get { return _cmd.CommandText; }
        set { _cmd.CommandText = value; }
    }

    public int CommandTimeout
    {
        get { return _cmd.CommandTimeout; }
        set { _cmd.CommandTimeout = value; }
    }

    public CommandType CommandType
    {
        get { return _cmd.CommandType; }
        set { _cmd.CommandType = value; }
    }

    public IDbConnection Connection
    {
        get { return _cmd.Connection; }
        set { _cmd.Connection = value; }
    }

    public IDataParameterCollection Parameters
    {
        get { return _cmd.Parameters; }
    }

    public IDbTransaction Transaction
    {
        get { return _cmd.Transaction; }
        set { _cmd.Transaction = value; }
    }

    public UpdateRowSource UpdatedRowSource
    {
        get { return _cmd.UpdatedRowSource; }
        set { _cmd.UpdatedRowSource = value; }
    }

    public void Cancel()
    {
        _cmd.Cancel();
    }

    public IDbDataParameter CreateParameter()
    {
        return _cmd.CreateParameter();
    }

    public void Dispose()
    {
        _cmd.Dispose();
    }

    public int ExecuteNonQuery()
    {
        Console.WriteLine($"[ExecuteNonQuery] {_cmd.CommandText}");
        return _cmd.ExecuteNonQuery();
    }

    public IDataReader ExecuteReader()
    {
        Console.WriteLine($"[ExecuteReader] {_cmd.CommandText}");
        return _cmd.ExecuteReader();
    }

    public IDataReader ExecuteReader(CommandBehavior behavior)
    {
        Console.WriteLine($"[ExecuteReader({behavior})] {_cmd.CommandText}");
        return _cmd.ExecuteReader();
    }

    public object ExecuteScalar()
    {
        Console.WriteLine($"[ExecuteScalar] {_cmd.CommandText}");
        return _cmd.ExecuteScalar();
    }

    public void Prepare()
    {
        _cmd.Prepare();
    }
}


text:
Q: How do I compile gcc-5 from source? It looks like gcc-5 was recently removed from Debian's unstable repository. I need gcc-5 to compile an older Linux kernel (3.19) and so I am looking to build it from source, through this is causing me a great deal of trouble. I have been following the instructions found here, but I find myself wondering what settings I need to set and more. Thus far, I have done the following.

*

*Downloaded and unpacked the source code.

*Configured gcc-5 by doing the following:

% mkdir objdir
% cd objdir
% ../gcc-5.4.0/configure (I included neither options nor target flags)

*Attempted to build using the following in my objdir directory:

% make BOOT_CFLAGS='-O' bootstrap

However, bootstrapping raised errors that prevented me from moving onto the install. After running for about 5 minutes, I encounter the following errors:
In file included from ../../../../gcc-5.4.0/libgcc/unwind-dw2.c:401:0:
./md-unwind-support.h: In function 'x86_fallback_frame_state':
./md-unwind-support.h:141:18: error: field 'uc' has incomplete type
struct ucontext uc;
                ^
make[5]: *** [../../../../gcc-5.4.0/libgcc/shared-object.mk:14: unwind-dw2.o] Error 1
make[5]: Leaving directory '/home/me/objdir/x86_64-unknown-linux-gnu/32/libgcc'
make[4]: *** [Makefile:1154: multi-do] Error 1
make[4]: Leaving directory '/home/me/objdir/x86_64-unknown-linux-gnu/libgcc'
make[3]: *** [Makefile:119: multi-do] Error 2
make[3]: Leaving directory '/home/me/objdir/x86_64-unknown-linux-gnu/libgcc'
make[2]: *** [Makefile:16510: all-stage1-target-libgcc] Error 2
make[2]: Leaving directory '/home/me/objdir'
make[1]: *** [Makefile:22461: stage1-bubble] Error 2
make[1]: Leaving directory '/home/me/objdir'
make: *** [Makefile:22798: bootstrap] Error 2

I am running Debian 10 (Buster) and have the necessary prerequisites installed as listed here.
Any help or guidance either in fixing the errors I have during bootstrapping or with building from source in general would be much appreciated! Thank you.

A: The reason is that there were changes in glibc, which broke compatibility with old compilers. There exists a patch for those compilers. The patch replaces struct ucontext with ucontext_t in libgcc/config/<arch>/linux-unwind.h files, where <arch> is i386, aarch64, alpha etc.
There is a similar question on stackoverflow.
I addition to these fixes, I also needed to apply fixes for sanitizers code from here (some of them were enough) and here.
After that the GCC has been finally built.


text:
Q: How to create template and generate pdf using template and database data iText C# I want to do below task using iText7.

*

*create template using HTML or ..(some fields can be able to hide
    according to user input)

*Fill the template with the database data

*generate accessible pdf

How can I do this?

A: As far as I understand, you want to have an HTML template where you will fill in data based on user input as well as data coming from your database. This is possible in iText in general, however you would need to do a lot of work, especially if you want to have a template for the PDFs that you are going to generate (as well as the template for the HTML form for capturing data).
It would be nice to have a tool where we design the HTML form and the form with which the output PDF is going to be generated interactively and maybe even using the same resources, sub-forms, sub-templates etc. Then the only thing the technical person would do is to bind the actual data to the form elements. The template will have the logic to show/hid elements or any other conditions that you might come up with. It would simplify the workflow a lot.
iText is working on a product called Dito which was announced in GIDS 2018 in Bangalore, India and a demo session was given. Dito is going to do exactly what you want and what I describe above. You can find the presentation here: http://www.developermarch.com/developersummit/downloadPDF/Dito.pdf
You can find also document workflow here: https://itextpdf.com/sites/default/files/attachments/LL_iText_Infographic_Flyer_A4-pdf.pdf


text:
Q: Creating repetitions of list with mapcan freezes? I have two lists: (1 2 3) and (a b) and I need to create something like this (1 2 3 1 2 3).  The result is a concatenation of the first list as many times as there are elements in the second. I should use some of the functions (maplist/mapcar/mapcon, etc.). This is exactly what I need, although I need to pass first list as argument:
(mapcan #'(lambda (x) (list 1 2 3)) (list 'a 'b))
;=> (1 2 3 1 2 3)

When I try to abstract it into a function, though, Allegro freezes:
(defun foo (a b)
  (mapcan #'(lambda (x) a) b))

(foo (list 1 2 3) (list 'a 'b))
; <freeze>

Why doesn't this definition work?

A: There's already an accepted answer, but I think some more explanation about what's going wrong in the original code is in order.  mapcan applies a function to each element of a list to generate a bunch of lists which are destructively concatenated together.  If you destructively concatenate a list with itself, you get a circular list.  E.g.,
(let ((x (list 1 2 3)))
  (nconc x x))
;=> (1 2 3 1 2 3 1 2 3 ...)

Now, if you have more concatenations than one, you can't finish, because to concatenate something to the end of a list requires walking to the end of the list.  So
(let ((x (list 1 2 3)))
  (nconc (nconc x x) x))
;        -----------      (a)
; ---------------------   (b)

(a) terminates, and returns the list (1 2 3 1 2 3 1 2 3 ...), but (b) can't terminate since we can't get to the end of (1 2 3 1 2 3 ...) in order to add things to the end.
Now  that leaves the question of why
(defun foo (a b)
  (mapcan #'(lambda (x) a) b))

(foo (list 1 2 3) '(a b))

leads to a freeze.  Since there are only two elements in (a b), this amounts to:
(let ((x (list 1 2 3)))
  (nconc x x))

That should terminate and return an infinite list (1 2 3 1 2 3 1 2 3 ...).  In fact, it does.  The problem is that printing that list in the REPL will hang.  For instance, in SBCL:
CL-USER> (let ((x (list 1 2 3)))
           (nconc x x))
; <I manually stopped this, because it hung.

CL-USER> (let ((x (list 1 2 3)))
           (nconc x x)            ; terminates
           nil)                   ; return nil, which is easy to print
NIL

If you set *print-circle* to true, you can see the result from the first form, though:
CL-USER> (setf *print-circle* t)
T
CL-USER> (let ((x (list 1 2 3)))
           (nconc x x))
#1=(1 2 3 . #1#)                  ; special notation for reading and
                                  ; writing circular structures

The simplest way (i.e., fewest number of changes) to adjust your code to remove the problematic behavior is to use copy-list in the lambda function:
(defun foo (a b)
  (mapcan #'(lambda (x)
              (copy-list a))
          b))

This also has an advantage over a (reduce 'append (mapcar ...) :from-end t) solution in that it doesn't necessarily allocate an intermediate list of results.

A: You could
(defun f (lst1 lst2)
  (reduce #'append (mapcar (lambda (e) lst1) lst2)))

then
? (f '(1 2 3) '(a b))
(1 2 3 1 2 3)

A: Rule of thumb is to make sure the function supplied to mapcan (and destructive friends) creates the list or else you'll make a loop. The same applies to arguments supplied to other destructive functions. Usually it's best if the function has made them which makes it only a linear update.
This will work:
(defun foo (a b)
  (mapcan #'(lambda (x) (copy-list a)) b))

Here is some alternatives:
(defun foo (a b)
  ;; NB! apply sets restrictions on the length of b. Stack might blow
  (apply #'append (mapcar #'(lambda (x) a) b))

(defun foo (a b)
   ;; uses loop macro
   (loop for i in b
         append a))

I really don't understand why b cannot be a number? You're really using it as church numbers so I think I would have done this instead:
(defun x (list multiplier)
   ;; uses loop
   (loop for i from 1 to multiplier
         append list))

(x '(a b c) 0) ; ==> nil
(x '(a b c) 1) ; ==> (a b c)
(x '(a b c) 2) ; ==> (a b c a b c)

;; you can still do the same:
(x '(1 2 3) (length '(a b))) ; ==> (1 2 3 1 2 3)


text:
Q: How to make the label appear on the window? I have the following code and I want the label ("Correct answer to appear on the window.") I am getting 'window is not defined error'. How do I resolve it.
    class Game:
        def __init__(self, window):

            self.label = Label(window, text="Welcome to the game", font=("arial 35 bold"))
            self.label.place(x=0, y=0)

            # question goes here
            self.qn1 = Label(window, text=q, font=('arial 20 bold'))
            self.qn1.place(x=50, y=70)

            # entry
            self.ans = StringVar()
            self.qnent1 = Entry(window, width=25, textvariable=self.ans)
            self.qnent1.place(x=150, y=120)

            self.btn1 = Button(window, text="Next", width=20, height=2, bg='steelblue', command=self.check)
            self.btn1.place(x=150, y=150)

        def check(self):
            game = (self.qnent1.get())
            if game.lower() == ans:
                print("Correct answer")
                label = Label(window, text="Correct Answer", font=('arial 20 bold'), fg='green')
                label.pack()

            else:
                print(self.ans.get())
                print("Wrong answer")

    start = Tk()
    c = Game(start)
    start.geometry("640x320+0+0")
    start.mainloop()

A: Add self.window = window after the def __init__(self, window): line and replace all window's inside both functions with self.window
It should solve your problem.
Your code with corrections:
class Game:
    def __init__(self, window):
        self.window = window

        self.label = Label(self.window, text="Welcome to the game", font="arial 35 bold")
        self.label.place(x=0, y=0)

        # question goes here
        self.qn1 = Label(self.window, text=q, font='arial 20 bold')
        self.qn1.place(x=50, y=70)

        # entry
        self.ans = StringVar()
        self.qnent1 = Entry(self.window, width=25, textvariable=self.ans)
        self.qnent1.place(x=150, y=120)

        self.btn1 = Button(self.window, text="Next", width=20, height=2, bg='steelblue', command=self.check)
        self.btn1.place(x=150, y=150)

    def check(self):
        game = (self.qnent1.get())
        if game.lower() == ans:
            print("Correct answer")
            label = Label(self.window, text="Correct Answer", font='arial 20 bold', fg='green')
            label.pack()

        else:
            print(self.ans.get())
            print("Wrong answer")

start = Tk()
c = Game(start)
start.geometry("640x320+0+0")
start.mainloop()


text:
Q: How do I read a string into a list of dictionaries? I'm trying to turn a some strings into a list.
I have have various strings called elementX, which I want to turn into a list with the same structure as Options.
#turn string into list
element1 = {'label': '26', 'value': '26'}
element2 = {'label': '28', 'value': '28'}
element3 = {'label': '29', 'value': '29'}
type(element1)

options=[
        {'label': '26', 'value': '26'},
        {'label': '28', 'value': '28'},
        {'label': '29', 'value': '29'},
     ]

Goal is it to offer the labels of the string as Options in a Dropdown.dcc from Dash.

A: @zacha2, what is wrong with [element1, element2, element3]?
Keep in mind that until 3.6 or 3.7, dictionaries are unordered so when you print them, the 'label' and 'value' tuples might be transposed but this doesn't affect the functionality of the dictionaries.
Or do you have an arbitrary number of dictionaries called elementNNN and you want to collect them all at runtime? First I would reconsider your design so that you have instead something like elements[] instead. But if you really need to do this for an arbitrary number of elementN variables, you can use:
[v for (k,v) in locals().items if k.startswith('element')]

The locals() function will return a dictionary of local variables and their associated values.


text:
Q: Looping through returned rows of dataset in VB.NET I have an application written in VB.Net which shows data from a table in a gridview.
 Dim DbaseDataSet As DreamApp.DbaseDataSet = CType(Me.FindResource("DbaseDataSet"), DreamApp.DbaseDataSet)
    Dim DbaseDataSetDevicesTableAdapter As DreamApp.DbaseDataSetTableAdapters.DevicesTableAdapter = New DreamApp.DbaseDataSetTableAdapters.DevicesTableAdapter()
    DbaseDataSetDevicesTableAdapter.Fill(DbaseDataSet.Devices)
    Dim DevicesViewSource1 As System.Windows.Data.CollectionViewSource = CType(Me.FindResource("DevicesViewSource1"), System.Windows.Data.CollectionViewSource)
    DevicesViewSource1.View.MoveCurrentToFirst()

Query which returns values is:
SELECT [Name], [Username], [Password], [IP], [Type], [Curr] FROM [Devices]

My table is filled with correct data.
How would i iterate through rows that are returned to make for each loop, and to run a piece of code for each returned row using returned values from a query above.

A: Just loop over Rows property
For each drRow as Datarow in DbaseDataSet.Devices.Rows

....
'DrRow("colname") = something

Next


text:
Q: ng-click inside ng-repeat doesnt work I have html which looks like one below, I have 2x ng-click in whole code in both situation I call same function. Both functions are in same controller.

{{pos.name}}

            <button type="button" class="btn btn-success" ng-click="listCtrl.chosenPositions(789456)">Add</button>

controller looks like:
myApp.controller('ListCtrl', ['$scope', '$cookies', '$http', function ($scope, $cookies, $http) {

    var listCtrl = {
        candidates: [],
        positions: [],
        chosenPositions: [],

        init: function () {
            listCtrl.getCandidates();
            listCtrl.getPositions();
        },
        getCandidates: function () {
            $http.get('candidates.json').then(function (res) {
                listCtrl.candidates = res.data;
            });
        },
        getPositions: function () {
            $http.get('positions.json').then(function (res) {
                listCtrl.positions = res.data;
            });
        },
        choosePosition: function (position) {
           console.log(position);
        }

    };

    listCtrl.init();
    $scope.listCtrl = listCtrl;
}]);

I double check for missspells and make sure its not because of function (I create a new one with simple console log).
Problem is that button click correctly call function but ng-repeat
 doesnt do anything. I read in angular documentation that ng-repeat create new scope but this should be still okey in my opinion as soon as I use reference to object listCtrlchoosePosition()
Can someone tell me what I am doing wrong?
Thanks
EDIT: Plunker example:
http://plnkr.co/edit/ooUQA2n1Vyj8RZtsQ1Pj?p=preview

A: ng-blur is doing something weird, so I'm going to suggest you to change the $scope.focus value from the ListCtrl instead of using the ng-blur.
html file

<input class="tagselect__input" placeholder="Position" ng-focus="focus=true" ng-model="query">

{{pos.name}}

js file
// more code goes here.
choosePosition: function (position) {
  //alert('Going to choosen position');
  //$scope.query = position.name;
  $scope.focus = false; // Hide div options from here.
  // rest of your code.
},
// more code goes here.

Working in this  plunkr


text:
Q: Generate all combination of dictionaries containing ranges In julia I have a dictionary that can contains other dictionaries, lists of strings/numbers, lists of dictionaries, strings/numbers, and ranges.
I need a list containing all the possible combination of dictionaries for every range (like StepRange, FloatRange, UnitRange) it's contained in it.
Example:
Dict{}("A" => Dict{}("B" => 1:1:3, "C" => 2), "B" => [Dict{}( "S" => 1:1.1:2.1)])

=>
[
Dict{}("A" => Dict{}("B" => 1, "C" => 2), "B" => [Dict{}( "S" => 1.1)]),
Dict{}("A" => Dict{}("B" => 2, "C" => 2), "B" => [Dict{}( "S" => 1.1)]),
Dict{}("A" => Dict{}("B" => 3, "C" => 2), "B" => [Dict{}( "S" => 1.1)]),
Dict{}("A" => Dict{}("B" => 1, "C" => 2), "B" => [Dict{}( "S" => 2.1)]),
Dict{}("A" => Dict{}("B" => 2, "C" => 2), "B" => [Dict{}( "S" => 2.1)]),
Dict{}("A" => Dict{}("B" => 3, "C" => 2), "B" => [Dict{}( "S" => 2.1)])
]

Right now, I'm overloading a recursive function like this, but have no idea on how to continue.
function iterate(generic, nets::Array)
    return (generic, false)
end

function iterate(range::Union{StepRange,FloatRange,UnitRange}, nets::Array)
    return (collect(range), true)
end

function iterate(array::Array, nets::Array)
    for (n, v) in enumerate(array)
        res = iterate(v, nets)
        if res[2]
            ## We found a range! Return it
            return res
        end
    end
    return (array, false)
end

function iterate(dict::Dict, nets::Array)
    for (k, v) in dict
        res = iterate(v, nets)
        if res[2]
            return (dict, true)
        end
    end
    return (dict, false)
end

(I have already done this in python, but working on piece of text, using regex to find custom-defined ranges (like "[1,2,0.1]") and after generating the text code parsing it.)

A: The following snippet reproduces the output in the example, and it could serve as a basis for other variants which treat the recursion differently (there are many options, as I noticed when trying this out). It using Iterators.jl which is installed with Pkg.add("Iterators").
using Iterators

function findranges{K}(sd::Dict{K})
  ranges = Vector{Vector}()
  for v in values(sd)
    if isa(v,Range)
      push!(ranges,collect(v))
    elseif isa(v,Dict)
      push!(ranges,recdictcollect(v))
    elseif isa(v,Vector)
      push!(ranges,map(x->vcat(x...),collect(product(map(recdictcollect,v)...))))
    end
  end
  ranges
end

function recdictcollect{K}(sd::Dict{K})
  ranges = findranges(sd)
  if length(ranges)==0
    cases = [()]
  else
    cases = product(ranges...) |> collect
  end
  outv = Vector{Dict{K,Any}}()
  for c in cases
    newd = Dict{K,Any}()
    i = 1
    for (k,v) in sd
      if any([isa(v,t) for t in [Range,Dict,Vector]])
        newd[k] = c[i]
        i += 1
      else
        newd[k] = v
      end
    end
    push!(outv,newd)
  end
  return outv
end

And the example:
julia> example = Dict{}("A" => Dict{}("B" => 1:1:3, "C" => 2), "B" => [Dict{}( "S" => 1:1.1:2.1)])
Dict{ASCIIString,Any} with 2 entries:
  "B" => [Dict("S"=>1.0:1.1:2.1)]
  "A" => Dict{ASCIIString,Any}("B"=>1:1:3,"C"=>2)

julia> recdictcollect(example)
6-element Array{Dict{ASCIIString,Any},1}:
 Dict{ASCIIString,Any}("B"=>[Dict{ASCIIString,Any}("S"=>1.0)],"A"=>Dict{ASCIIString,Any}("B"=>1,"C"=>2))
 Dict{ASCIIString,Any}("B"=>[Dict{ASCIIString,Any}("S"=>2.1)],"A"=>Dict{ASCIIString,Any}("B"=>1,"C"=>2))
 Dict{ASCIIString,Any}("B"=>[Dict{ASCIIString,Any}("S"=>1.0)],"A"=>Dict{ASCIIString,Any}("B"=>2,"C"=>2))
 Dict{ASCIIString,Any}("B"=>[Dict{ASCIIString,Any}("S"=>2.1)],"A"=>Dict{ASCIIString,Any}("B"=>2,"C"=>2))
 Dict{ASCIIString,Any}("B"=>[Dict{ASCIIString,Any}("S"=>1.0)],"A"=>Dict{ASCIIString,Any}("B"=>3,"C"=>2))
 Dict{ASCIIString,Any}("B"=>[Dict{ASCIIString,Any}("S"=>2.1)],"A"=>Dict{ASCIIString,Any}("B"=>3,"C"=>2))


text:
Q: While-loop with XML package in R for variable length query I have the following problem, I am scraping some data from the Basketballreference website, in it I will make several queries in the player season finder part of the website, each query gives back multiple pages. I have been able to scrape it using the XML package of R:
library(XML)

URL="http://www.basketball-reference.com/play-index/psl_finder.cgi?request=1&match=single&type=per_poss&per_minute_base=36&per_poss_base=100&lg_id=NBA&is_playoffs=N&year_min=1980&year_max=&franch_id=&season_start=1&season_end=-1&age_min=0&age_max=99&shoot_hand=&height_min=0&height_max=99&birth_country_is=Y&birth_country=&birth_state=&college_id=&draft_year=&is_active=&debut_yr_aba_start=&debut_yr_aba_end=&debut_yr_nba_start=&debut_yr_nba_end=&is_hof=&is_as=&as_comp=gt&as_val=&award=&pos_is_g=Y&pos_is_gf=Y&pos_is_f=Y&pos_is_fg=Y&pos_is_fc=Y&pos_is_c=Y&pos_is_cf=Y&qual=&c1stat=&c1comp=&c1val=&c2stat=&c2comp=&c2val=&c3stat=&c3comp=&c3val=&c4stat=&c4comp=&c4val=&c5stat=&c5comp=&c6mult=1.0&c6stat=&order_by=ws&order_by_asc=&offset="

numerals <- seq(from = 0, to = 7200, by = 100)
NBAlist <- list()
for(i in 1:73)
{
  URL1 <- paste(URL, numerals[i], sep = "")
  tablefromURL <- readHTMLTable(URL1)
  NBAlist[[i]] = tablefromURL[[1]]
}

NS = do.call(rbind, NBAlist)

To get the number 73 I will go and find the last page that still has players manually, which for one query is not much, but I intend to do many queries.
I thought that I could do a While loop and stop when it retrieves an empty table doing something like this:
while (NBAlist[[i]] !is.na()){...}

However when I did this as a test with offset 100000:
URL <- "http://www.basketball-reference.com/play-index/psl_finder.cgi?request=1&match=single&type=per_poss&per_minute_base=36&per_poss_base=100&lg_id=NBA&is_playoffs=N&year_min=1980&year_max=&franch_id=&season_start=1&season_end=-1&age_min=0&age_max=99&shoot_hand=&height_min=0&height_max=99&birth_country_is=Y&birth_country=&birth_state=&college_id=&draft_year=&is_active=&debut_yr_aba_start=&debut_yr_aba_end=&debut_yr_nba_start=&debut_yr_nba_end=&is_hof=&is_as=&as_comp=gt&as_val=&award=&pos_is_g=Y&pos_is_gf=Y&pos_is_f=Y&pos_is_fg=Y&pos_is_fc=Y&pos_is_c=Y&pos_is_cf=Y&qual=&c1stat=&c1comp=&c1val=&c2stat=&c2comp=&c2val=&c3stat=&c3comp=&c3val=&c4stat=&c4comp=&c4val=&c5stat=&c5comp=&c6mult=1.0&c6stat=&order_by=ws&order_by_asc=&offset=100000"

tablefromURL <- readHTMLTable(URL)

I do get a Named list(), and if I go further down the loop and do:
NBAlist[[1]] <- tablefromURL[[1]]

I get the following error: Error in tablefromURL[[1]] : subscript out of bounds.
I don't know how to proceed further, any help would be greatly appreciated


text:
Q: hiding collections and sub collections in DSpace? I'm using the dspace 5.5 in my repository. And I did a content restriction by restriction policy for some items to anonymous users. But when I do a search, it is displayed collections and sub-collections of restricted items. But when I access these collections the content is hidden. But I wanted you to hide all both the collections and sub-collections and bitstreams for anonymous users. Could someone suggest me some kind of setup?

A: I'm going to  assume you use Discovery for search, it's the default in DSpace 5.
What are the authorisation policies of the collections/communities that hold hidden items? If you make the collections/communities non-public (=no READ permission for the ANONYMOUS group), I believe this will be reflected in the search results when Access rights awareness is turned on (which is the default). That is, they will be shown in search results when you're logged in as a user with READ access to the collections, but not otherwise.
You could also switch off having collections/communities included in search results altogether. There's a commented-out example in the Discovery config file (link goes to 5.x version on github) that allows you to do that, see also the DSpace documentation on Discovery:
<property name="defaultFilterQueries">
  <list>
    <!--Only find items-->
    <value>search.resourcetype:2</value>
  </list>
</property>

A: If you restrict a collection or community, DSpace will continue to provide a link to the collection or community.  When a user attempts to access the collection/community, they will asked to authenticate.
If you are using XMLUI, you can restrict the listing in your stylesheet.
<xsl:template
    match="dri:reference[@url='/metadata/handle/10822/xxxxxx/mets.xml']"
    mode="summaryList"/>

It is not elegant, but it works.


text:
Q: Laptop autoshutdown problem? My notebook goes off randomly after some time without displaying any warning, error or blue screen.
I have re-installed my Vista couple of times, but while re-installing this problem occurs most of
the time.
I tried Ubuntu on same machine but it didn't shut off.   Any one knew the reason?

A: Try monitoring your system with RealTemp or SpeedFan and see if you're having a temperature problem.

A: When I first saw the question title and first bit, I thought heat... but after reading what you wrote, I don't want to scare you, but, my first guess would be either hardware failure or just a driver issue.
It is worth a try making sure that all the vents are clear as @techie007 said just to rule out heat.... if your machine ever crashes in Ubuntu, then, this is the most likely reason.
Firstly drivers:
It is possible that you have a piece of hardware that is incompatible with the driver on the Windows installation media. If you are installing from a source that did not come with your machine, you may want to try another disk in case it was a restricted disk without (or with a invalid) storage controller, or similar that is causing a blue screen.
However, that being said, I have seen very similar issues a few times.
Most hardware have a few ways that they can be used. Firstly is "just working" and secondly is "full-feature rich". An example of this is a graphics card - with a generic driver (such as "Generic SVGA Driver") will work fine for displaying a picture, but, give it the full graphics driver and performance will go through the roof!
To expand further, on a laptop I had about 3-4 years ago with the dreaded Nvidia bug, it simply would blue screen and crash with the Nvidia driver, but, by uninstalling it and using the standard generic SVGA driver, it would work fine - and - just like you, I was able to use Linux just fine as the build I had did not have a good graphics driver.
Without seeing the laptop, it is hard to guess, but, based on my past experience and what you said, this is what I think the problem is.

A: This does sound like it could be a overheating problem.
Try having a good clean out of the insides and check that the fan/s are working. Does it shut off after the same duration of being on each time?


text:
Q: Redirecting an entire directory excluding one particular url string Greets:
I have an old piece of code in a /work directory that I have to keep there. I'd like to redirect all requests to the /work directory to the site root, *except for url's that look like this:
/work/index.php?option=com_career&view=career &
/work/administrator
How would I go about doing this in .htaccess?
Thanks in advance.
Chris

A: Try adding these rules to the htaccess file in your document root:
RewriteEngine On

# pass through this URL unchanged
RewriteCond %{QUERY_STRING} ^option=com_career&view=career
RewriteRule ^work/index\.php$ - [L]

# pass through this URL unchanged
RewriteRule ^work/administrator - [L]

# redirect everything else
RewriteRule ^work/ / [L,R=301]


text:
Q: Select Json Object as nvarchar(max) in JSON_VALUE I do not know how to extract a path of JSON as nvarchar(max). It always returns null.
I do not want to specify the fields to get because I have no idea the field names. So the idea here is select it as a string and process them later.
DECLARE @json nvarchar(max) =
'{
    "firstName": "John",
    "lastName" : "doe",
    "address"  : {
        "streetAddress": "naist street",
        "city"         : "Nara",
        "postalCode"   : "630-0192"
    }
}'

SELECT [Type]
FROM OPENJSON( @json, '$.address' )
WITH ([Type] NVARCHAR(max) '$');

The expected result is that the Type column contains the whole JSON object of address as string
{ "streetAddress": "naist street", "city": "Nara", "postalCode" : "630-0192" }

A: You need to execute the statement in a different way. Note, that when you use OPENJSON() with explicit schema you need to use AS JSON to specify that the referenced property contains an inner JSON object or array. Of course, you may use JSON_QUERY() to get the same result:
JSON:
DECLARE @json nvarchar(max) =
'{
    "firstName": "John",
    "lastName" : "doe",
    "address"  : {
        "streetAddress": "naist street",
        "city"         : "Nara",
        "postalCode"   : "630-0192"
    }
}'

Statement (using OPENJSON()):
SELECT *
FROM OPENJSON(@json)
WITH ([Type] NVARCHAR(max) '$.address' AS JSON);

Statement (using JSON_QUERY())
SELECT JSON_QUERY(@json, '$.address') AS [Type]

Result:
Type
{
        "streetAddress": "naist street",
        "city"         : "Nara",
        "postalCode"   : "630-0192"
    }


text:
Q: couldnt render json object got from api using ember data I am building an ember app which should send request to servlet and get the json response and display it. I tried it with ember data and the request is sent also the servlet is sending the right json response which I verified by printing in the console yet the ember couldnt render it.. it says router_js.js:1277 Uncaught (in promise) Error: More context objects were passed than there are dynamic segments for the route: error*
the json data that is received from the servlet
My: Array(7)
0: {CAPACITY: '2', PRICE: '1579', RTYPE: 'villa', ID: '5'}
1: {CAPACITY: '1', PRICE: '1526', RTYPE: 'villa', ID: '1'}
2: {CAPACITY: '4', PRICE: '1241', RTYPE: 'villa', ID: '6'}
3: {CAPACITY: '6', PRICE: '1500', RTYPE: 'villa', ID: '13'}

my route code
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class PostsRoute extends Route {
  @service store;
  model() {
    console.log(this.store.findAll('My'));
    return this.store.findAll('My');
  }
}

my model code
import Model from '@ember-data/model';
import DS from 'ember-data';
const { attr } = DS;
export default Model.extend({
  CAPACITY: attr('string'),
  RTYPE: attr('string'),
});

my adapter code:
import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host: 'http://localhost:8080/hotelres',

  pathForType() {
    return 'My';
  },
});

and my handlebar code
inside My

{{outlet}}

{{#each this.model as |my|}}
    <h1>{{my.CAPACITY}}</h1>
{{/each}}

my serializer code
import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  normalizeResponse(store, primaryModelClass, payload, id, requestType) {
    console.log('control at serializer->post->normalize');
    payload = { My: payload };
    console.log(payload)
    return this._super(store, primaryModelClass, payload, id, requestType);
  },
});

A: It seems that ember is  expecting an 'id' field in every json that it returns and since my json has only 'ID' and not 'id' it pops this error and also i found that after ember 3.6 there is a bug in ember that shows wrong error of 'more context should be passed' instead of the actual error. When i changed from 'ID' to 'id' it worked

A:
router_js.js:1277 Uncaught (in promise) Error: More context objects were passed than there are dynamic segments for the route: error*

This error indicates you are passing objects to the <LinkTo /> component but your route does not include a dynamic segment or does not contain as many dynamic segments as objects you are passing.
Further, the default behavior of routes is to attempt to serialize your model into something usable for the url. It does this by looking at any dynamic param segment names and checking for properties of the same on the objects returned by the model hook or passed to the LinkTo component.
The error here honestly has nothing to do with EmberData or normalization. Likely what occurred was by not normalizing your data correctly you were passing something to a route that did not conform to the route handler's specification.

I think a key thing the ember-data docs need to focus on is serialization for custom formats, like what you have. always room to improve tho

The docs honestly can't be any clearer than they are, they give you the exact spec for what you need to transform to: https://api.emberjs.com/ember-data/4.6/classes/MinimumSerializerInterface/methods/normalizeResponse?anchor=normalizeResponse


text:
Q: Ajax Call on End of Scroll Down of div I have a div with scroll.what i want to do is call a function when the scroll down of that div end or reached over there.how can i do that?Please help me.your suggestion might be helpful.
thanks in advance


text:
Q: Preload Image in html gives warning message Preloaded the image to be used in the page using link preload
<link rel="preload" href="http://shmdhussain.github.io/WebTest/test_img/blue.png"
crossorigin="anonymous" as="image">

but in the browser getting warning as

preload for 'https://shmdhussain.github.io/WebTest/test_img/blue.png' is found, but is not used because the request credentials mode does not match. Consider taking a look at crossorigin attribute.

I expect it to work but I am seeing two downloads for the same resource(image)
see this demo https://hussain-test.glitch.me/ , open console to see the warning , thanks in advance for any help.

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
  <title>HTML BolierPlate</title>
  <link rel="preload" href="https://shmdhussain.github.io/WebTest/test_img/blue.png" crossorigin="anonymous" as="image">

  Welcome to BoilerPlate!!!

A: There is no need to user crossorigin when you preload an image! Images do not need CORS
Just remove crossorigin
WITH crossorigin your will see one failing preload and one successful load


text:
Q: print JSON value in table which come through ajax response using jQuery I am not able to print the value getting from this JSON response. I am using jQuery and Ajax.
In success response, I am using for-each function for print all the data,
In my JSON response, there are multiple trees.
When I print single data it working by using this code.
console.log(response.saleOrderDTO.billingAddress.name) //for fetching name

but I am trying to append all data available in billingAddress as in my attachment file, when I used this below code it says undifined not working.

$.ajax({
  type: "POST",
  cache: false,
  timeout: 10000,
  success: function (response) {
    var response = $.parseJSON(response);
    $.each(response.saleOrderDTO.billingAddress, function(i, item) {
         $("table#table2").append(`

${item.name}

          `)
    });
  }
})

Please help - JsFiddle


text:
Q: Use XPath to select all values on a page and replace content I want to replace every instance of the word "Specialization" with "Profession." This is the XPath code I have so far:

My thanks to @Mateen for their help with my original question for writing the above line for me in the first place.

A: Not sure why you need an XPath solution, but if you want to stick with the standard DOM API, here's a simple solution.

document.querySelectorAll("div").forEach(function(d){
  if(d.textContent.includes("Foo")){
    d.textContent = d.textContent.replace("Foo","FooBar");
    d.classList.add("match");
  }
});
.match { color:#f00; }

Foo is cool

Bar is not

Foo is cool

Bar is not

Foo is cool

Bar is not

Foo is cool

Bar is not

Foo is cool

Bar is not

Foo is cool

Bar is not


text:
Q: Lightning Quick Action Error on IPad Only... Works on Phone and Desktop I have a lightning component in a quick action that works fine on IOS for phone and Desktop but fails to open from the IPad. The error thrown is the following:
Action failed: forceChatter:lightningComponent$controller$doInit [Unable to evaluate code at: components/c/OrderHistoryLightningComponent.js]
quickActionHandlerHelper.js failed to create component - forceChatter:lightningComponent

I am not using Chatter at all in this component, maybe the API is used on mobile to render components, I am not sure. Again, this component works fine on IPhone and desktop. My SF1 is up to date on the IPad also.
Any suggestions are greatly appreciated!


text:
Q: tmux on startup and ssh-agent forwarding issue I've added the following lines (taken from here) to my .bashrc to automatically start a tmux session on login:
if [ "$PS1" != "" -a "${STARTED_TMUX:-x}" = x -a "${SSH_TTY:-x}" != x ]
then
        STARTED_TMUX=1; export STARTED_TMUX
        sleep 1
        ( (tmux has-session -t remote && tmux attach-session -t remote) || (tmux new-session -s remote) ) && exit 0
        echo "tmux failed to start"
fi

However, this seems to breaks ssh agent forwarding on subsequent logins. Is there a way around this?

A: You can use this pattern to solve your problem: https://superuser.com/questions/180148/how-do-you-get-screen-to-automatically-connect-to-the-current-ssh-agent-when-re
That allows you to have the SSH agent connection dynamically updated to reflect each connection; I think it uses screen, but tmux should be very much the same pattern.
The principal is to use a symlink to the SSH agent socket, which can change, inside tmux - and then update that symlink when you connect in a new SSH session.


text:
Q: panic: SetUint using value obtained using unexported field From byte buffer received server, I want to copy struct.
The format of buffer is fixed size bytes as below.
00000000  83 27 48 12 6c 00 00 00  01 02 00 00 01 01 00 02  |.'H.l...........|
00000010  10 01 d2 02 96 49 00 00  00 00 87 d6 12 00 00 00  |.....I..........|
00000020  00 00 01 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000030  00 02 01 02 3c 01 01 00  00 00 01 01 01 01 18 10  |....<...........|
00000040  2c 01 90 01 01 6c 07 03  c8 02 01 02 03 9c 0a 0b  |,....l..........|
00000050  0c 00 00 00 01 01 00 00  00 00 00 00 00 01 01 01  |................|
00000060  01 01 01 01 01 01 01 01  01 00 01 01 01 00 00 00  |................|

My struct is below.
type HeaderT struct {
    magicValue [8]byte
    bodyLength [4]byte
    bodyVersion [1]byte
    ...
}

My implementation is at below.
func onMessageReceived(client MQTT.Client, message MQTT.Message) {
    payload := message.Payload()
    fmt.Printf("Received message on topic: %s\nMessage: \n%s\n", message.Topic(), hex.Dump(payload))

    header := HeaderT {}
    err := binary.Read(bytes.NewBuffer(payload[:]), binary.LittleEndian, &header)  // <-- error occurred at this line
    ...
}

My code make panic as below.

panic: reflect: reflect.Value.SetUint using value obtained using
  unexported field
goroutine 38 [running]: reflect.flag.mustBeAssignable(0x1a8)
          /usr/local/go/src/reflect/value.go:231 +0x1ee reflect.Value.SetUint(0x12540e0, 0xc0001a2000, 0x1a8, 0x83)
          /usr/local/go/src/reflect/value.go:1551 +0x2f encoding/binary.(*decoder).value(0xc000148d88, 0x12540e0,
  0xc0001a2000, 0x1a8)
          /usr/local/go/src/encoding/binary/binary.go:548 +0x7c6 encoding/binary.(*decoder).value(0xc000148d88, 0x125cfc0,
  0xc0001a2000, 0x1b1)
          /usr/local/go/src/encoding/binary/binary.go:510 +0x104 encoding/binary.(*decoder).value(0xc000148d88, 0x129fa00,
  0xc0001a2000, 0x199)
          /usr/local/go/src/encoding/binary/binary.go:523 +0x2c5 encoding/binary.Read(0x12fcf80, 0xc00018a150, 0x1300c60, 0x14d76d0,
  0x1248040, 0xc0001a2000, 0x0, 0x0)
          /usr/local/go/src/encoding/binary/binary.go:248 +0x342 main.onMessageReceived(0x13012a0, 0xc000140000, 0x1300c00,
  0xc000192000)

A: The issue is that none of HeaderT's fields are "public".
Notice that all the fields start with a lowercase letter - that means the fields are unreachable to any code outside of your package.
From the spec:

Exported identifiers
An identifier may be exported to permit access to it from another package. An identifier is exported if both:

*

*the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and

*the identifier is declared in the package block or it is a field name or method name.

  All other identifiers are not exported.

Try Exporting them by capitalizing their names:
type HeaderT struct {
    MagicValue [8]byte
    BodyLength [4]byte
    BodyVersion [1]byte
    ...
}