text:
Q: How to delete control file in oracle 11g I am practicing the rman backup in oracle 11g.and how to dalete the control file. Please help.
rm -rf \oracle\app\oracle\oradata\xe\control.dbf
it did not work at hosting server.

A: RMAN is a oracle utility to backup, restore & recovery of database.
The following Steps will be demonstrated the configuration of oracle RMAN backup (for first time configuration)
Lets assume the database is in NOARCHIVELOG mode, by default the database is in NOARCHIVELOG mode, we need to change it to ARCHIVELOG mode for RMAN backup configuration.
We can configure RMAN backup with catalog/repository database as well as control file. It is strongly recommended & very good practice to configure RMAN backup with catalog/repository database.
Note: Be sure you have installed oracle 11g successfully in your environment.
I had asked to you about O.S environment. I didn't get any clue from you. So as a example i am writing the all RMAN backup steps in Windows O.S environment.
First open the command prompt and try to connect sql server as per your environment credential. for example
Step # 1: Connect to Target database(Target DB: The database on which Backup & Recovery to be performed) as sysdba.
C:\> set Oracle_sid=orcl
c:\> sqlplus / as sysdba

SQL*Plus: Release 11.2.0.1.0 Production on Wed Jul 26 10:17:22 2017

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to an idle instance.

Step # 2: Ensure the database has been configured with ARCHIVELOG mode or not?
SQL> select log_mode from v$database;
LOG_MODE
NOARCHIVELOG
Database is in NOARCHIVELOG mode.

Step # 3: If the database has been configured with ARCHIVELOG mode then skip the Step number 3 to 6, If not then Shutdown the database.
SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.

Step # 4: Startup the database in mount state.
SQL> startup mount;
ORACLE instance started.
Total System Global Area 308981760 bytes
Fixed Size 2212896 bytes
Variable Size 163580896 bytes
Database Buffers 138412032 bytes
Redo Buffers 4775936 bytes
Database mounted.

Step # 5: Configure database in ARCHIVELOG mode.
SQL> alter database archivelog;
Database altered.

Step # 6: Alter database to open state.
SQL> alter database open;
Database altered.

SQL> select open_mode from v$database;
OPEN_MODE
--------------------
READ WRITE

Step # 7: Ensure ARCHIVELOG destination.
SQL> archive log list;
Database log mode              Archive Mode
Automatic archival             Enabled
Archive destination            USE_DB_RECOVERY_FILE_DEST
Oldest online log sequence     330
Next log sequence to archive   332
Current log sequence           332

Step # 8: Ensure the flash/fast recovery area location.
SQL> show parameter db_recovery_file_dest;

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
db_recovery_file_dest                string      C:\app\xyz\flash_recove
                                                 ry_area
db_recovery_file_dest_size           big integer 3852M

Note : Here i did 'xyz' in C:\app\xxx\flash_recovery_area. due to security reason.

Step # 9: Connect to RMAN prompt with target database.
C:\>rman target/

Recovery Manager: Release 11.2.0.1.0 - Production on Sun Jul 30 12:32:57 2017

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: ORCL (DBID=1464491423)

Step # 10 : To show the all configuration of your RMAN through this command.
RMAN> show all;

using target database control file instead of recovery catalog
RMAN configuration parameters for database with db_unique_name ORCL are:
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 7 DAYS;
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT   '/backup/rman/full_%u_%s_%p';
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT' OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO 'C:\APP\xyz\PRODUCT\11.2.0\DBHOME_1\DATABASE\SNCFORCL.ORA'; # default

Note : -  As per this statement  'CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT   '/backup/rman/full_%u_%s_%p';' I hope you have created the folder '/backup/rman' in your c: drive.

Typically we'll use "BACKUP AS BACKUPSET" to backup a database. So, to take a full backup of the database without the archive logs, do the following.
RMAN> BACKUP AS BACKUPSET DATABASE

RMAN> backup as backupset database;

Starting backup at 30-JUL-17
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=75 device type=DISK
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00002 name=C:\APP\xyz\ORADATA\ORCL\SYSAUX01.DBF
input datafile file number=00001 name=C:\APP\xyz\ORADATA\ORCL\SYSTEM01.DBF
input datafile file number=00003 name=C:\APP\xyz\ORADATA\ORCL\UNDOTBS01.DBF
input datafile file number=00005 name=C:\APP\xyz\ORADATA\ORCL\EXAMPLE01.DBF
input datafile file number=00004 name=C:\APP\xyz\ORADATA\ORCL\USERS01.DBF
channel ORA_DISK_1: starting piece 1 at 30-JUL-17
channel ORA_DISK_1: finished piece 1 at 30-JUL-17
piece handle=C:\BACKUP\RMAN\FULL_11SAL7BV_33_1 tag=TAG20170730T125212 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:02:16
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
including current control file in backup set
including current SPFILE in backup set
channel ORA_DISK_1: starting piece 1 at 30-JUL-17
channel ORA_DISK_1: finished piece 1 at 30-JUL-17
piece handle=C:\BACKUP\RMAN\FULL_12SAL7G7_34_1 tag=TAG20170730T125212 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:02
Finished backup at 30-JUL-17

For further your ref Here and Here


text:
Q: Javascript Function Call Order I have an object that I am configuring over multiple steps and I am simply to trying to organize the code better. Here is an example:
  var myObj = {};

  function one(obj) {
      //Do a whole bunch of stuff;
      obj.count = 0;
  }

  function two(obj) {
      obj.count += 1;
  }

  one(myObj);
  two(myObj);

When function 2 is called, am I guaranteed that obj.count already exists (because function one was completely ran)? I understand there are other ways I could do this, but I am simply wondering about this case and what's happening. These are not async functions either such as a database call or file reader.

A: Yes, you are guaranteed that obj.count exists. JavaScript executes synchronously.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read command not working with Git aliases sp = "!echo name && read name"
I've added this to my aliases list. When I run it "name" is printed as expected and I can input something into read; but on carriage returning and trying echo $name, nothing's there.
It works fine when I directly run the command in the terminal and whatever I type in gets stored in $name.
I also have another problem which was the first one and I was trying to simplify it as much as I can to zone in on the issue above but here's the original:
sp = "!read branch\"?Branch Name: \""
Whenever I run this via git sp, I get the error
read branch"?Branch Name:": line 0: read: `branch?Branch Name:': not a valid identifier
Copy pasting the first bit of the error which is the command text into the terminal and directly running it works perfectly so it can't be some sort of invalid hidden character somewhere tho I can't be certain how git is replacing stuff.
I'm on macos monterey using terminal.app and zsh. Thank you.

A: [With the original desired alias, you get:]

read branch"?Branch Name:": line 0: read: `branch?Branch Name:': not a valid identifier

Git runs aliases by feeding them to /bin/sh.  The:
read var?"prompt string"

syntax is peculiar to the zsh read built in (see, e.g., https://zsh.sourceforge.io/Doc/Release/Shell-Builtin-Commands.html); in /bin/sh that's an attempt to read into a variable named var?prompt string, which is not a valid variable name because of the embedded question-mark and space.
To use a zsh script directly, make the script executable, place it in your $PATH, and name it git-sp.  Then:
git sp

will run your git-sp script.  Since your script will begin with #! /bin/zsh, you will get zsh and not plain sh, and you will have access to your desired read built-in.  Also, you won't have to deal with all the complications produced by wedging the entire command in as a single line alias:

When I run [a simplified version,] "name" is printed as expected and I can input something into read; but on carriage returning and trying echo $name, nothing's there.

Each command is run by a separate shell invocation.  Values read into variables persist until that shell invocation exits (or you override or unset them in that same invocation); then they evaporate.  To store something more permanently, use the file system.  Consider storing settings in the git config databases (--global and per-repository): you can make up your own names here.  You do run the risk that some future Git release (git version 3.1415?) might steal your name and use it for its own purposes, but depending on what namespace you choose, you can make that pretty unlikely.  For instance:
git config --global torek.user.setting1 value1
git config --global torek.user.setting2 value2

I'm only in trouble here if future-Git decides to use torek.* settings.  (Perhaps it's being worked on by a Slovenian on a Tuesday.)


text:
Q: How to insert a row in a nested table in Oracle with PreparedStatement I created 2 types as OBJECT and a type of table and a nested table in my Oracle database. I know how to inset a row in table in cmd but I have no idea that how I can insert a row in this table with PreparedStatement in Java.
This is my table and type:
 CREATE Or REPLACE TYPE item AS OBJECT
(
  id        number,
  counter   number
);/
CREATE Or REPLACE TYPE time AS OBJECT
(
  year        number,
  month number,
  second number
);
CREATE Or REPLACE TYPE Shoping_list AS TABLE OF item;
create table invoice(
id number NOT NULL PRIMARY KEY ,
list shoping_list,
dateIn date,
timeIn time,
totalCost number )
nested table list store as list_of_product;

I can insert with this code in cmd
insert into invoice(id,list,dateIn,timeIn,totalCost) values(seq_ID_invoice.nextval,
shoping_list(item(1,2),item(26,1)),TO_DATE('1396-04-11','YYYY-MM-DD'),time(11,25,40),7000);

and this my java code
preparedStatement = connection.prepareStatement("insert into invoice (id,list,dateIn,timeIn,totalCost) values ("+id+",?,?,?,?)");

A: seq_ID_invoice is Oracle Sequence. So oracle takes its value automatically. For rest you can use setInt, setString, setFloat, etc. methods available in PreparedStatement based on the types of columns defined inside your table.
Following sample code may help you.

PreparedStatement ps = connection.prepareStatement(
    "insert into invoice(id, list, dateIn, timeIn, totalCost)"+
    " values (seq_ID_invoice.nextval, shoping_list(item(?,?), item(?,?)), TO_DATE(?,'YYYY-MM-DD'), time(?, ?, ?), ?)");

ps.setInt(1, int_value_for_id_of_item_1);
ps.setInt(2, int_value_for_counter_of_item_1);
ps.setInt(3, int_value_for_id_of_item_2);
ps.setInt(4, int_value_for_counter_of_item_2);
ps.setString(5, string_value_for_date);
ps.setInt(6, int_value_for_year_of_time);
ps.setInt(7, int_value_for_month_of_time);
ps.setInt(8, int_value_for_second_of_time);
ps.setInt(9, int_bvalue_for_total_cost);

int rowCnt = ps.executeUpdate();
System.out.println(rowCnt+" rows affected.");

int_value_for_id_of_item_1, int_value_for_counter_of_item_1, ... these are java variables. You can defined variables of your choice or you can directly mention values in place of these variables.


text:
Q: testing 3 port bit values and Anding the values i am flashing an led, but if i detect that 3 port pins all have 0 on them, Anding the result all to zero, i wish the led to stop flashing. But why doesnt his work?
if (RB3 & RB4 & RB5 == 0){
        RB6  = RB6;
        }
        else
        RB6  = !RB6;

A: This is more of a C question than an EE question. Consider the operator precedence for comparison (==) which is 7 vs. bitwise AND (&) which is 8.
So you have RB3 & RB4 & (RB5 == 0). So it will be true if RB3 is 1, RB4 is 1 and RB5 is 0, probably not what you wanted.
Maybe (0 == (RB3 | RB4 | RB5))  is what you want.
Note that I prefer to avoid putting an Lvalue on the left side of a comparison expression. That's a style thing- if one of the = signs is omitted (a common error) then the compiler will emit an error message rather than (at best) a warning- since it's otherwise a valid assignment statement.


text:
Q: Postgres - Moving Data Folder I wanted to move my PostgreSQL data folder on my Ubuntu server and I was following this tutorial to move it.
I was able to move it, and update my conf file to point to the new location.
When I go to run Postgres, it starts, but when I try to connect via
sudo -u postgres psql

It gives me this error:
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Any ideas what happened? It says it's running.

A: After done moving PostgreSQL data directory. Don't forget to restart the PostgreSQL service.
Check the PostgreSQL status by command ps -ef  | grep postgres. -D parameter value should be new directory location.
ERROR /var/run/postgresql/.s.PGSQL.5432 that's mean your PostgreSQL service not starting up Properly or Failed to when starting up.


text:
Q: How to convert file separator in maven I have a property defined like this:
<properties>
    <main.basedir>${project.parent.basedir}</main.basedir>
</properties>

Since I use Windows as OS, it contains backslashes. I want to add this path to a glassfish domain as JVM option (using glassfish maven plugin). The problem is, that asadmin can consume only slash as separator, and all my backslashes keep on disappearing. How can I define a property with exactly the same content with slashes?

A: Just an update to Sean's answer, I have had to make some minor adjustments in order to adapt it to the latest groovy maven plugin version:
<plugin>
          <groupId>org.codehaus.gmaven</groupId>
          <artifactId>groovy-maven-plugin</artifactId>
          <dependencies>
            <dependency>
              <groupId>org.codehaus.groovy</groupId>
              <artifactId>groovy-all</artifactId>
              <version>2.0.1</version>
            </dependency>
          </dependencies>
          <executions>
                <execution>
                    <id>setproperty</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>execute</goal>
                    </goals>
                    <configuration>
                        <source>
        project.properties['basedir']=project.parent.basedir.absolutePath.replace('\\','/');
                        </source>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: I don't think there is a non-programmatical way to do that. So I suggest a groovy one-liner with the Maven GMaven plugin (GMaven is usually the simplest way to embed programmatic code into a pom):
<plugin>
    <groupId>org.codehaus.gmaven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <executions>
        <execution>
            <id>setproperty</id>
            <phase>validate</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <source>
pom.properties['main.basedir']=project.parent.basedir.absolutePath.replace('\\','/');
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>


text:
Q: "Flattening" a Date Array returned by AJAX call to a String for use in DataTables 1.09 I'm attempting to display a row in a data table with a bunch of date cells. The dates on the backend are represented as so:
org.joda.time LocalDate closeDt;
I'm making an AJAX call to GET a bunch of model objects that have multiple dates attached to them and feeding all of this data into a (legacy version 1.09) DataTable. The problem is, however, that closeDate is returned to me as an array of values that looks something like

Unfortunately, applying a serializer on the backend or doing any type of transformation of the model data or how it's being returned isn't an option due to the dependencies and issues around that migration.
I've tried the "mRender" function of DataTables like so:
{"mData": "closeDt", "sTitle": "Closed Date", "mRender": function(data, type, full) {
    var date = data[1] + "/" + data[2] + "/" + data[0];
    console.log("date is: ", date);
    return date;
  }},

But, even it hasn't been successful. Additionally, if I do identify a way to get "mRender" working I'd like to extract the function as there are five or six other dates that are being represented in the table in the same way.
How can I get the date array to be "compressed" into a single string, in "MM/dd/yyyy" format?

A: You could destructure the Date array:
var [year, month, day] = closeDt;
var dateStr = [month, day, year].join('/');

Fiddle: http://jsfiddle.net/p0aty3rf/

A: I ended up accomplishing what I needed by the following:
{"mData": "closeDt", "sTitle": "Closed Date", "mRender": function(data, type, full) {
    if(data !== null) {
      return new Date(data).toLocaleDateString({day: "2-digit", month: "2-digit"});
    } else {
      return "";
    }
  }},

I had to put the if/else in because if the data was null for a particular record, the Date() was being set to 12/31/1969... I guess that's a default for something when you call new Date(), but I didn't spend much time researching why or how. I also had to copy/paste this in the "mRender" of every column that had a date and I'd like to research pulling it out to not be in violation of DRY, but for now it gets the job done.


text:
Q: Racket: how check the size of list? i need help with racket
(define size1 (lambda (m)
               (printf "size is ~v" (length m))))

test it
>(size1 '(2 8 9 0 'uu 98 0))
size is 7

which is fine
,
but second test
> (size1 '((((7) 9 (11)))))
size is 1

it is give me that 1, cuz of the brocket, However
what i want to provide is 3
i need help with that

A: Note the following:
'((((7) 9 (11))))           ; list with one element --> '(((7) 9 (11)))
'(((7) 9 (11)))             ; list with one element --> '((7) 9 (11))
'((7) 9 (11))               ; list with 3 elements  --> '(7), 9 and '(11)

If you intended to write a list with three elements, then your list should be '((7) 9 (11)), and your function call becomes:
> (size1 '((7) 9 (11)))
size is 3

A: So you would like to count the elements that are not null and not pairs:
(define (count-atoms tree)
  (cond ((null? tree) 0)       ; an empty tree has 0 atoms
        ((not (pair? tree)) 1) ; an atom is exactly one atom
        (else ???)))           ; the sum of counting atoms in car and cdr

This is very similar to how length is made.


text:
Q: Define HTML check boxes from database values I have project with HTML PHP and SQL database. I designed HTML input form to collect data from user and put drop down menu using PHP. It collected data from SQL database using query and those data used to drop down list and user can select those data. I have using following codes in PHP section.
$query2 = "SELECT Name FROM class ORDER BY Name";
$results2 = mysqli_query($connection, $query2);

while($result = mysqli_fetch_array($results2))
{
    $Classes .= "<option value=\"{$result['Name']}\">{$result['Name']}</option>";
}

In my database there are several classes as Class_A, Class_B, Class_C and etc. (Admin can create new class or delete available class. Then when user select classes, showing classes can be different according to Admin's settings.)
In HTML form section I used following code to display Class names.

    Classes Are

    <select name="Classes[]" size="3" multiple >
    <?php echo $Classes ?>
    </select>

I tried to use this process through Check boxes (replace Drop down list from Check boxes) But I cant fix that. So, If someone can give proper way to do this it is highly appreciate.

A: Perhaps this is what you need to use checkboxes? The name assigned to the HTML input element uses an array type syntax with the name of from the db supplied
$sql = "select `name` from `class` order by `name`";
$res = $connection->query( $sql );
while( $rs = res->fetch_object() ) {
    $classes=sprintf(
        '%1$s:
            <input type="checkbox" value="%1$s" name="Classes[%1$s]" />
        ',
        $rs->name
    );
}

Then, to process the form submission once the user has selected one or more checkboxes you could do:
foreach( $_POST['Classes'] as $index => $value ){
    // do things...
}

You likely do not even need to add the name so perhaps simply Classes[] as the input name would suffice. Please clarify the issue you had when trying to use checkboxes rather than select menus.


text:
Q: Calculate risk between classes I am doing some exercises about logistic regression with SAS and I need to calculate and interpret odds.

For calculating the individual probabilities I use those formulas:

While later, the Professor, calculates odds for rent and own categories:

My question is, how is obtained the odd for rent of 0.3911 and the odd for own of 0.2610?
I don't understand from which calculations those numbers come from.
Moreover, in SAS I have class level information
How to interpret it in this context and to use if for estimating odds?

A: Your model is:
$$logit(\pi) = \beta_0 + \beta_1 x_{free} + \beta_2 x_{rent} $$
which becomes:
$$ log{\pi \over{1-\pi}} = \beta_0 + \beta_1 x_{free} + \beta_2 x_{rent} $$
$$ log{~O_{y|x}} = \beta_0 + \beta_1 x_{free} + \beta_2 x_{rent} $$
Solving for $\beta_0$ ("own" coefficient) you get:
$$ \beta_0 = log{~ O_{y|x_{own}}}$$
$$ O_{y|x_{own}} = exp(\beta_0)$$
$$ O_{y|x_{own}} = exp(-1.0414) = 0.3529602$$
NB: This works because $x_{own}$ is chosen as the reference level for $x$ and its effect is in the model only when $x_{rent}=x_{free}=0$.
Similarly, solving for $\beta_2$ ("rent" coefficient) gives you:
$$ \beta_2 = (\beta_0 + \beta_2) - \beta_0  $$
$$ ~~~~~~~~~~~~~\beta_2 = log{~O_{y|x_{rent}}} - log{~O_{y|x_{own}}}  $$
$$\beta_2 = log{~O_{y|x_{rent}} \over ~O_{y|x_{own}} } $$
Therefore:
$$ {~O_{y|x_{rent}} = exp(\beta_2) \times ~O_{y|x_{own}} } $$
$${~O_{y|x_{rent}}} = 0.35296 \times exp(0.5987) = 0.6422995 $$


text:
Q: Error: Unresolved reference 'selenium' What is the reason? # -*- coding: utf-8 -*-
from selenium import selenium
import unittest, time, re

class rc(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*chrome", "http://stackoverflow.com/")
        self.selenium.start()

    def test_rc(self):
        sel = self.selenium
        sel.open("/")
        sel.type("id=kw", "selenium")
        sel.click("id=container")
        sel.click("id=su")

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

This is recorded with selenium IDE, into selenium remote control code. In the IDE test is passed.

But in pycharm open, the first line (from selenium import selenium)
There will be an error: Unresolved reference 'selenium'
What is the reason?
My environment is

*

*python3.5

*selenium3.3.1

*selenium-server-standalone-3.3.1.jar


text:
Q: faye-websocket-rails and heroku dinamics chats i create this chat https://intense-depths-60434.herokuapp.com/
with ruby on rails and im follow this guide: heroku ruby websocket.
all i want to do is to create chats between a x number of user but separated from the other "chats":
https://intense-depths-60434.herokuapp.com/room2
this is my middleware code:
module ChatDemo
      class ChatBackend
        KEEPALIVE_TIME = 15 # in seconds

        def initialize(app)
          @app     = app
          @clients = []
          @clientNames = []
        end

         def call(env)
            if Faye::WebSocket.websocket?(env)
                ws = Faye::WebSocket.new(env, nil, {ping: KEEPALIVE_TIME })

                ws.on :open do |event|
                  p [:open, ws.object_id]
                  @clients << ws
                end

                ws.on :message do |event|
                  p [:message, event.data]
                  @clients.each {|client| client.send(event.data) }
                end

                ws.on :close do |event|
                  p [:close, ws.object_id, event.code, event.reason]
                  @clients.delete(ws)
                  ws = nil
                end

                # WebSockets logic goes here

                # Return async Rack response
                ws.rack_response
            else
             @app.call(env)
            end
        end

      end

     end

this is my method code:
class ChatsController < ApplicationController

   def room
   end

   def room2
   end

end

and this is my js code:

    var scheme   = "wss://";
    var uri      = scheme + window.document.location.host+ "/";
    var ws       = new WebSocket(uri);

    ws.onmessage = function(message) {
      var data = JSON.parse(message.data);
      $("#chat-text").append("

" + data.handle + "

" + data.text + "

");
      $("#chat-text").stop().animate({
        scrollTop: $('#chat-text')[0].scrollHeight
      }, 800);
    };

    $("#input-form").submit(function(event){
      event.preventDefault();
      var handle = $("#input-handle")[0].value;
      var text   = $("#input-text")[0].value;
      ws.send(JSON.stringify({ handle: handle, text: text }));
      $("#input-text")[0].value = "";
    });


text:
Q: How to sum specific columns based on dates The two data frames are given below:
df1
     Start Date  End Date
 0   20110706    20110803
 1   20110803    20110907

df2
     DATE       50      51      52      53      54
  0  20110706   3.51    2.51    1.51    0.51    0
  1  20110801   10.98   9.98    8.98    7.98    6.98
  2  20110808   9.45    8.45    7.45    6.45    5.45
  3  20110906   0       1       23.2    0       1.2

Based off of df1, How can I modify df2 so columns are summed based off the range the dates fall within df1 start date(left inclusive).
Modified df2 dates being left inclusive.(with start date and end date range included in the df)
       Start Date  End Date    50      51      52      53      54
  0    20110706    20110803   14.49   12.49   10.49   8.49    6.98
  1    20110803    20110907    9.45    9.45    30.65   6.45    6.65

How can this be accomplished?

A: Since dates are duplicated in Start Date and End Date it's not clear what do with dates in df2 which fall exactly on the start or end; is it left-inclusive or right-inclusive. Assuming it's left-inclusive you can do
df1['Start Date'] = pd.DatetimeIndex(df1['Start Date'])
df1.set_index('Start Date', inplace=True)

df2['DATE'] = pd.to_datetime(df2.DATE)
df2.set_index('DATE', inplace=True)

sums = df2.groupby(df1.index.asof).sum()
pd.concat([df1, sums], axis=1)


text:
Q: Change color of geom_line in faceted plot I want the lines for each country to be the same colour that I manually set. ie. Sweden = Red, USA = Blue, Canada = Green.
How best to do this?
library(tidyverse)

df <- tibble(
  date = rep(c(as.Date("1995-01-01"), as.Date("1995-01-01"), as.Date("1996-01-01"), as.Date("1996-01-01")), 3),
  decile = rep(c("d1", "d2"), 6),
  income = c(10, 30, 15, 35, 50, 60, 70, 80, 90, 100, 110, 120),
  country = c(rep("Sweden", 4), rep("Canada", 4), rep("USA", 4))
)

g <- ggplot(df, aes(x = date, y = income)) +
  geom_line(aes(colour = decile), size = 2) +
  scale_color_manual(values = c("red", "green", "blue", "black"))

g + facet_grid(~ country)

A: EDIT: removed mapping distinguishing deciles.
g <- ggplot(df, aes(x = date, y = income, group = decile, color = country)) +
  geom_line(size = 2) +
  scale_color_manual(values = c("Sweden" = "red", "Canada" = "green",
                                "USA" = "blue")) +
  facet_grid(~ country)
g


text:
Q: How to I move the current file to a folder? I want to move the current file to a folder and remove it from the one that it is in, based on a cell value change.  Here is what I have:
 function onEdit() {

var File = SpreadsheetApp.getActiveSpreadsheet();
var TransferComplete = File.getSheetByName("Sheet9").getRange("E24").getValue();

var ActiveFolder = DriveApp.getFolderById("a0lweiurnawoeiuranwv");
var ArchiveFolder = DriveApp.getFolderById("apsleriuoavwnoeiura");

  if (TransferComplete = "Yes" )
  {ArchiveFolder.addFile(File) && ActiveFolder.removeFile(File)};

}

The error says that it cant find "add file" method.

A:
To move a file, you must first get the file itself as a file and not as a spreadsheet.
You need to use DriveApp.getFileById() to retrieve a file object that you can then pass into ArchiveFolder.addFile().
Additionally you have some syntax errors with your code.

*

*You are using an assignment operator = instead of a comparative operator == or '===' to compare TransferComplete to "Yes"

*You don't need a statement seperator ; at the end of an if statement

*You are using && to separate two statements, you need to separate them like so
if(TransferComplete == "Yes" ){
      ArchiveFolder.addFile(File);
      ActiveFolder.removeFile(File);
  }
Corrected code:
function onEdit() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var file = DriveApp.getFileById(spreadsheet.getId());
  var transfeComplete = spreadsheet.getSheetByName("Sheet9").getRange("E24").getValue();

  var activeFolder = DriveApp.getFolderById("a0lweiurnawoeiuranwv");
  var archivefolder = DriveApp.getFolderById("apsleriuoavwnoeiura");

  if (transfeComplete === "Yes" ){
    archivefolder.addFile(file);
    activeFolder.removeFile(file);
  }
}


text:
Q: Cross Join in Spark SQL I use Spark SQL 2.4. We use series of chained Spark temporary views to perform the data transformations.
So, many a times, I run into scenarios where I need to apply a CROSS JOIN between a large table and other small tables. The small lookup tables/views barely has 1-10 records. However, I still run into performance issues nevertheless where the main table has (say) 10M records, while the small table has only 1 record.
My question is how to ameliorate performance of the query in such scenarios. Is there any way to speed-up the queries. I have tried the BROADCAST hint on the lookup tables but didn't get the expected performance improvement compared to without the hint.
Can anyone please share their experience and expertise on the best practices for these cases especially when we do a cross join with another small table based on ranges (Scenario I) below.
SCENARIO I: Cross Join based on range
create temporary view lkp_tbl as
select agegrpid, lowage, highage
from small_tbl;

select /*+ MAPJOIN(b) */
a.id, a.name, a.age, b.agegrpid
from big_tbl a
inner join lkp_tbl b
WHERE a.age between b.lowage and b.highage; -- cross join based on range

SCENARIO II:
create temporary view big_tbl as
select id, name, age
from employee
where id = '1001';

create temporary view lkp_tbl as -- contains only 1 record
select max(last_prcs_dt) as prcs_dt
from run_table;

select /*+ MAPJOIN(b) */
a.id, a.name, a.age, b.prcs_dt
from big_tbl a
cross join lkp_tbl;

Thanks. Any help is appreciated.

A: Broadcasting seems to be working fine.
The following discussion seems to shed some light on the topic -
Cross Join for calculation in Spark SQL


text:
Q: How do I compare two tables in different databases I have two databases, which are basically identical running on the same machine.
I would like to compare the records in a table on database A vs the same table in database B
I would like to know which records exist in the table on database A that do not exist in the same table on database B.
Database A = "RICSTOREV341"
Database B = "RICHOSTV341"
The table is "Price_Tab"
The columns I would like to pull are F01, F26, F27, F19, F38
Can this be accomplished?

A: Yes, this can be done.
You could use something like a three part identifier to identify the tables in different database. Kinda like this :
RICSTOREV341.dbo.Price_Tab

Then you can perform a join on the primary key and fetch the result.

A: Besides the solutions above - I can also suggest using some 3rd party tools for performing data comparison, and most of them have a fully functional free trial (like SQL data comparison tools from ApexSQL or Redgate).
These tools can help you save lots of time, as they can do data comparison and synchronization in just a couple of clicks.
Hope I helped.


text:
Q: How to split my project into modules to be used in multiple platforms? I have a college project that manages bookmarks, a CRUD with folder structure. The project uses swing and hibernate all in the client. Now I want to make both a web and an android application version, but I don't know how to split the modules. For example, I thought about creating a web application with websockets and hibernate, and connect the swing, web and android in the websocket server.
Is that a good choice? If not, what better options are there?
Please note that the project has to be synchronized between the platforms and
I wonder about the technologies that can be used also, and not just the pattern.
I can use Spring too if necessary.

A: just an opinion, the project module structure should look like this:

*

*android client (androidUI)

*web client (webUI)

*service part

*db

*integration tests


text:
Q: How to make my Forms always to be on top my main form? How to make my non-modal forms to always be on top of my main form?
I have tried:
procedure TForm3.CreateParams(var Params: TCreateParams);
begin
  inherited CreateParams(Params);
  Params.WndParent := Application.MainForm.Handle;
end;

Which seems to work fine. Is that correct way?

A: This is the Win32 concept of window ownership. An owned window always appears on top of its owner. The owner is specified in the call to CreateWindow and can then not be modified.
In the VCL you specify the owner by setting WndParent in CreateParams, and the framework then passes that on to CreateWindow. The VCL does this for you but in older versions the owner handling is, well, somewhat flaky. Modern versions are better and allow more control through the PopupMode and PopupParent properties.
Your code will therefore have the effect that you desire.


text:
Q: How to have wcf datacontract class to have a field of an object of another datacontract class I have a WCF DataContract class as follows:
[DataContract]
public class Breads
{
    public Breads() { }

    public Breads(int breadid, string breadname, int specieid)
    {
        breadId = breadid;
        breadName = breadname;
        specieId = specieid;
    }

    private int breadId;

    [DataMember]
    public int BreadId
    {
        get { return breadId; }
        set { breadId = value; }
    }

    private string breadName;

    [DataMember]
    public string BreadName
    {
        get { return breadName; }
        set { breadName = value; }
    }

    private int specieId;

    [DataMember]
    public int SpecieId
    {
        get { return specieId; }
        set { specieId = value; }
    }

    private Specie.Species specie;

    [DataMember]
    public Specie.Species Specie
    {
        get
        {
            if (specie == null)
            {
                BLL_HIS.Classes.Animals.Specie s = new BLL_HIS.Classes.Animals.Specie();
                s = s.SelectById(specieId);
                specie = new Specie.Species(s.SpecieId, s.SpecieName);
            }
            return specie;
        }
    }

}

as you can see there is a property named Specie which is an instance of another class that is describe as follows:
    [DataContract]
public class Species
{
    public Species() { }

    public Species(int specieid, string speciename)
    {
        specieId = specieid;
        specieName = speciename;
    }

    private int specieId;

    [DataMember]
    public int SpecieId
    {
        get { return specieId; }
        set { specieId = value; }
    }

    private string specieName;

    [DataMember]
    public string SpecieName
    {
        get { return specieName; }
        set { specieName = value; }
    }

}

when i leave out the property Specie the code work just fine. Although it compiles and runs with the property, when i invoke it, an error occurs. The error text is as follows:
Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
The error details is a follows:
*The underlying connection was closed: The connection was closed unexpectedly.
Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at IBread.SelectById(Int64 id)
   at BreadClient.SelectById(Int64 id)
Inner Exception:
The underlying connection was closed: The connection was closed unexpectedly.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)*

notes:
1- I tryed to fill the Specie manually to make sure that the problem is not with that method, and the "underlying connection" is not relate to sql connection.
2- I tried to use "KnownType(typeof(Species))" attribute for my Breads class.
By the way, Sorry for the length of the post.

A: [DataMember]
public Specie.Species Specie { get; }

Currently you only define a get property. It must also define a set operation to be deserialized.
"The connection was closed unexpectedly" is probably an unhandled exception from the deserializer on the service side. If you turn on WCF logging, you'd be able to see the error message.

A: I have two problems, the first one as was solved by ErnieL (All DataMembers must have both set and get operations)
and the other one which solve my problem was, apparently all the services have to be in the same namespace, I had some folders and each service with it's relevant stuff were in that folders, I removed those folders and place all services in one folders then it works!!


text:
Q: Understanding why extracted contours offset in QGIS? I am a beginner at QGIS, and I am trying to extract 1m contours from 5m DEM data. I have clipped a small area from the DEM data (roughly 1.2km by 1.2km). When I go to Raster - Extraction - Contour, it gives the correct contours, but they are offset on the map by about 1km to the west, and about 140m to the south. Any suggestions on how to fix this?

A: That definitely sounds as a coordinate reference system (CRS, projection) issue. Contours are created in different CRS than the grid is as ahmadhanb suggested.
There is important basic rule in QGIS - you always have to be aware of source CRS of datasets and project CRS (displayed map). Most if not all the tools in QGIS won't reproject on the fly as map window does.

*

*Double click on raster layer name and in General tab there is "Coordinate reference system". Make sure it is the right one you are supposed to use.

*If you double click on your contour file there should be the same CRS. If not, your contours are in wrong projection.

You can switch it there on the fly to the same projection as raster is to check that fix your issue. But be aware that is only changing the projection on the fly and not changing projection of the contour file.
If you want to set the new (correct) projection to contours you need to go to the menu Vector / Data Management Tools / Define Current Projection... choose the contour file and projection (might be needed to click on Choose button to get what you need).


text:
Q: systemd httpd stop very slow under Arch Linux When I perform a:
systemctl stop httpd

Apache often takes minutes to stop. The command:
apachectl gracefully-stop

always stops immediately. Anyone have any idea what might be causing this? The commands:
systemctl start httpd

and
apachectl start

both run very quickly. Somehow this is both systemd and stopping httpd related (and possibly Arch Linux related).

A: According to: https://bugzilla.redhat.com/show_bug.cgi?id=906321 there is an issue with the default systemd KillMode for Apache.
One temporary fix is to add KillMode=none to /usr/lib/systemd/system/httpd.service
Be sure to run sudo systemctl --system daemon-reload after you make the change.


text:
Q: Measure theory question: Show that for $1I am having trouble trying to prove this containement for lp spaces: $l^1(\mathbb N) \subset l^p(\mathbb N)$.
Initially, I was thinking of choosing some sequence from L1 and show it is in Lp but didn't how to proceed with the proof.

A: For $(a_n)\in l^1$, $|a_n|$ is clearly bounded, say the bound is $M$.
Then $\sum |a_n|^p \le M^{p-1}\sum|a_n| < \infty$
BTW, show you thought instead of just put the question next time.

A: Well $f\in l^1(\mathbb{N})$ means that $\int |f| d\mu= \sum_{n=1}^\infty
 |f(n)|<\infty$. Since the series converges then there exists $N$ such that $n\geq N$ implies that $|f(n)|\leq 1$. As $p\geq 1$, then for all $n\geq N$ we have that $|f(n)|^p\leq |f(n)|$. Hence $\sum_{n\geq N}|f(n)|^p\leq \sum_{n\geq N} |f(n)| < \infty
$. Clearly $|f(n)|<\infty$ for any $n$, so $\sum_{n=1}^N|f(n)|^p <\infty
$. It follows that $\sum_{n=1}^\infty
|f(n)|^p < \infty
$, hence $f\in l^p(\mathbb{N})$.

A: Take a converging series $(a_n)$. From some $n$ onwards the $|a_n| \leqq 1$, so by taking the $p$:th power the series converges even faster. Before that $n$ there are only finite number of elements, so they don't matter on the convergence issue.


text:
Q: Saving variable data from jQuery to PHP and getting it after page reload I'm new to PHP and trying to figure this out and still not understanding. I'm trying to take the value of a html text box in jQuery and turn it into a variable I can then store as a (variable or string?) and pull back again after a page refresh.
I want the user to hit a button that then executes the following:
$('.save').click(function () {
    // pulls the value from the textarea
    var file = $('#subtext').val();
    // send to php to hold text
    $.ajax({
        url: '/mininote/system/data.php',
        type: 'POST',
        data: { textbox: file },
        success: function(data) {
            alert('Saved data to php!');
            $(save).text('All changes saved.').show().delay(3000).fadeOut(800);
        }
    });

});

Then receives the post data and stores in the php until the user reloads the page where it pulls data (or checks if there is any) from the php like so and replaces the value of the textbox with the value from the php:
$.ajax({
    url: '/mininote/system/data.php',
    type: 'GET',
    data: { textbox: file },
    success: function(data) {
        // add text back to text box
        $("#subtext").val(data);
    }
});

Basically what I'm looking for is below:-

*

*a way to perform an ajax POST to insert the data grabbed from the textbox,

*add to PHP

*on a page reload use a GET request and replace textbox text with text from the PHP file.

What would I need to put into the PHP code? Or would it be easier to go in another direction? I've gotten this method to work in local storage. I also want browser compatibility for this work.
I don't need to set it up for a bunch of users. Any response that will increase my knowledge on this will help greatly.
EDIT: I'm really looking for something more server-side so it's usable across multiple platforms and devices.

A: You could use the following simple PHP script to accomplish your goal:
<?php
session_start();

if (isset($_POST['textbox'])) {
   $_SESSION['textbox'] = $_POST['textbox'];
} else {
   echo $_SESSION['textbox'];
}
?>

Another option would be to use HTTP Cookies. Just set the cookie with JavaScript using a plugin or something simple such as, document.cookie = "variable=value"; and access it in PHP with, $_COOKIE["variable"].
Hope this helps.

A: actually jquery-ajax works like below:-

*

*it takes request and

*it gives response.

For Your requirement You also need to follow this steps. so for this , You

*

*send request to PHP page then

*send response from php page

so replace Your above jquery-ajax code part with below:-
$('.save').click(function () {
    // pulls the value from the textarea
    var file = $('#subtext').val();
    // send to php to hold text
$.ajax({
    url: '/mininote/system/data.php',
    type: 'POST',
    data: { textbox: file },
    success: function(data) {
        alert('Saved data to php!');
        $('#subtext').val(data);
        $(save).text('All changes saved.').show().delay(3000).fadeOut(800);
    }
});

});

make sure in Your data.php page textbox value has made echo after inserting data to DB. This process would be something like below:-
data.php
<?php
     $textbox = $_POST["textbox"];
        /*
             perform Your DB inser part here
         */
      if(data inserted to db)
      {
            echo $textbox;
      }
?>

Hope this will help You.

A: In the PHP code you could use a PHP session variable like so:
$_SESSION['saveMe'] = $saveMe;

Then get it later, even after a refresh, by using the session variable in php as you would normally use any variable.
For more info see http://www.w3schools.com/php/php_sessions.asp

A: Use a session, like a temporary cookie, like the following.
session_start();
$_SESSION['sessionName'] = $sessionVar;

Then you can destroy the session with, session_destroy();
See more here.

A: Why you send it to PHP ?
Just saving in client-side with cookie is better and access in PHP with $_COOKIE
Download jQuery.cookie from :
carhartl/jquery-cookie
and do :
$('.save').click(function () {
// save data from textarea to cookie
var data = $.trim($('#subtext').val());
$.cookie('TEXTAREA_VALUE', data);
});

and go to read by PHP :
<?php
echo $_COOKIE['TEXTAREA_VALUE'];
?>

and to remove :
$.removeCookie('TEXTAREA_VALUE', { path: '/' });

Okay friend !

A: Ajax is mainly used for sending data without reloading the webpage - from client(js) to serverside(php) or from serverside(php) to client(js). Make sure that name-attribute is given in the textarea and that method is set to post in the form. If I understand your issue correctly you could do something like this:
<?php
session_start();

if (isset($_POST['subtext'])) {
    $_SESSION['subtext_value'] = $_POST['subtext'];
}
if (isset($_SESSION['subtext_value'])) {
    $subtextValue = $_SESSION['subtext_value'];
}
else {
    $subtextValue = '';
}
?>
<html>
<body>
<form action="/mininote/system/data.php" method="post">
<textarea id="subtext" name="subtext"><?php echo $subtextValue;?></textarea>
<input type="submit" value="ok" />
</form>
</body>
</html>


text:
Q: Assign number incrementally, reset when value changes declare @t table (scanCode varchar(6), dates datetime, flag varchar(1))

insert @t ( scanCode, dates, flag)
select '182086','01 Jul 2020','P' union all
select'182086','02 Jul 2020','P' union all
select'182086','03 Jul 2020','A' union all
select'182086','04 Jul 2020','A' union all
select'182086','06 Jul 2020','P' union all
select'182086','07 Jul 2020','P' union all
select'182086','08 Jul 2020','P' union all
select'182086','09 Jul 2020','P' union all
select'182086','10 Jul 2020','A' union all
select'182086','11 Jul 2020','A' union all
select'182086','13 Jul 2020','A' union all
select'182086','14 Jul 2020','A'

select scanCode
    , dates
    , flag
    , prn = row_number() over (partition by scanCode,flag order by scanCode, dates)
from @t t
order by t.dates

Currently the result is:
scanCode    dates   flag    prn
182086      2020/07/01  P   1
182086      2020/07/02  P   2
182086      2020/07/03  A   1
182086      2020/07/04  A   2
182086      2020/07/06  P   3
182086      2020/07/07  P   4
182086      2020/07/08  P   5
182086      2020/07/09  P   6
182086      2020/07/10  A   3
182086      2020/07/11  A   4
182086      2020/07/13  A   5
182086      2020/07/14  A   6

I want the result to be:
scanCode    dates   flag    prn
182086      2020/07/01  P   1
182086      2020/07/02  P   2
182086      2020/07/03  A   1
182086      2020/07/04  A   2
182086      2020/07/06  P   1
182086      2020/07/07  P   2
182086      2020/07/08  P   3
182086      2020/07/09  P   4
182086      2020/07/10  A   1
182086      2020/07/11  A   2
182086      2020/07/13  A   3
182086      2020/07/14  A   4

scancode, dates is primary key in my table.

A: SQL Server 2008R2 is pretty limited in its windowing functions, no lag/lead functionality, and ORDER BY can only be used with ROW_NUMBER().  So the usual techniques to solve this are not readily available.
I'm going to assume your primary key is (ScanCode,Dates), if it isn't this won't return consistent results.
SELECT
  curr.ScanCode
 ,curr.Dates
 ,curr.Flag
 ,prn = ROW_NUMBER() OVER (PARTITION BY curr.ScanCode, pr.Dates ORDER BY curr.Dates)
FROM
  @t curr
LEFT JOIN
  @t pr --Get maximum date prior to current date where Flag did not match
    ON pr.ScanCode = curr.ScanCode
        AND pr.Dates =
          (
            SELECT
              MAX(Dates)
            FROM
              @t
            WHERE
              ScanCode = curr.ScanCode
                AND Flag <> curr.Flag
                AND Dates < curr.Dates
          )

This works because the dates for a contiguous block of Flag will all have the same prior date value:
ScanCode    Dates       Flag    PriorDate
182086      2020-07-01  P       NULL
182086      2020-07-02  P       NULL
182086      2020-07-03  A       2020-07-02
182086      2020-07-04  A       2020-07-02
182086      2020-07-06  P       2020-07-04
182086      2020-07-07  P       2020-07-04
182086      2020-07-08  P       2020-07-04
182086      2020-07-09  P       2020-07-04
182086      2020-07-10  A       2020-07-09
182086      2020-07-11  A       2020-07-09
182086      2020-07-13  A       2020-07-09
182086      2020-07-14  A       2020-07-09

So if your clustered index is chosen properly, this is one table scan plus two seeks per row, and one sort for the PARTITION BY.  Not great, but even with LAG/LEAD you'd probably not create anything more efficient.
Other advice:

*

*Dates isn't a good column name as the column stores a single value, not plural.
Additionally, it's not very descriptive of what the column represents - is this a date of a certain event?  Entry date?  If you can rename it, do.  Also, if the values will always be dates, use the DATE datatype.

*The primary key in this instance really should be (ScanCode,Dates) if it isn't already.  Not only is this necessary to guarantee consistent results, but the join to get the prior value will be a seek on the clustered index.  To test, declare a primary key on your table variable and compare the execution plans with and without.

A: Another way to solve this is to think of it as a variation of the gaps and islands pattern:
SELECT *, diff = (N.rn1 - N.rn2)
FROM
(
    SELECT
        *,
        rn1 = ROW_NUMBER() OVER (
            PARTITION BY T.scanCode
            ORDER BY T.dates),
        rn2 = ROW_NUMBER() OVER (
            PARTITION BY T.scanCode
            ORDER BY T.flag, T.dates)
    FROM @t AS T
) AS N;

That output gives us a way to identify groups:

All that is left to do is number rows within each group. The full query is:
WITH
    N AS
    (
        -- Previous code
        SELECT
            *,
            rn1 = ROW_NUMBER() OVER (
                PARTITION BY T.scanCode
                ORDER BY T.dates),
            rn2 = ROW_NUMBER() OVER (
                PARTITION BY T.scanCode
                ORDER BY T.flag, T.dates)
        FROM @t AS T
    )
SELECT
    N.scanCode,
    N.dates,
    N.flag,
    prn = ROW_NUMBER() OVER (
        PARTITION BY N.scanCode, (N.rn1 - N.rn2)
        ORDER BY N.dates)
FROM N;

The output is:

Execution plan:

db<>fiddle online demo


text:
Q: Play audio during a phone call I saw many posts regarding this issue but all of them are from a few years ago.
Would like to ask again whether anything has changed? Is it possible today to play sound during a phone call?
What I want to do is to use android text-to-speech and play it during a phone call.
I tried to turn on the speaker and play it but the other side does not hear it.
Any suggestions?
Thanks.

A: You can not play in-call audio streaming. MediaPlayer api's are not allowing to do.
This is mentioned in MediaPlayer overview
Note: You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.


text:
Q: swift using filter to get the difference between two arrays I have an array of the following:
var cardsInHand = [1,2,3]

I want to be able to have two arrays of cardsInHand and cardsOnTable.  cardsOnTable can only be from cardsInHand. For example, if I play card 1, then cardsInHand will be [2,3] and cardsOnTable will be [1].  I can accomplish this using filter, but the value removed from cardsInHand is lost.  The inverse is true, if I card 1 backup, then cardsInHand will be [1,2,3] and cardsOnTable will be []
let cardsPlayed = 1

cardsInHand = cardsInHand.filter { $0 != cardsPlayed }

print(cardsInHand)

[2,3]

How can I get the cardsOnTable be the difference between cardsPlayed and cardsInHand?
Sorry if the heading is misleading, but I wasn't sure how to describe it.  I have a feeling that map, reduce or filter might be the easiest way to handle this.

A: You can simply use remove(at:) func for achieving your goal, like this
let cardsPlayed = 1
    if let index = cardsInHand.index(of: cardsPlayed)
    {
        cardsOnTable += [cardsInHand.remove(at: index)]
    }

In the case there are multiple cards which are dropped, like you have mentioned in comment, you can directly store them into an array cardsOntable and use like this
        cardsOnTable += [1,2]
    cardsInHand = cardsInHand.filter{!self.cardsOnTable.contains($0)}


text:
Q: Infer domains/ranges with OWL reasoners How can I infer OWL domains/ranges of a given data/object property with a reasoner?
For example, I have two classes Rat, Bird and a data property hasName. I want these classes to be the solely domains of hasName:
<Declaration><Class IRI="#Rat"/></Declaration>
<Declaration><Class IRI="#Bird"/></Declaration>
<Declaration><DataProperty IRI="#hasName"/></Declaration>
<DataPropertyDomain>
    <DataProperty IRI="#hasName"/>
    <ObjectUnionOf>
        <Class IRI="#Rat"/>
        <Class IRI="#Bird"/>
    </ObjectUnionOf>
</DataPropertyDomain>

When I used HermiT reasoner to infer domain, I got the owl:Thing class, and not Rat or Bird:
Set<OWLClass> inferedDomains = hermitReasoner
                            .getDataPropertyDomains(hasNameProperty, false)
                            .getFlattened();

I can manually extract the domains by using owl-api to read DataPropertyDomainAxioms of hasName, to get Rat, Bird classes. But then I'll unable to get other inferable classes (e.g. Rat has an equivalent class Mouse).
So I'd like to use inference engines to infer the result, such as:

*

*Reasoners: HermiT, FacT++,...

*SQWRL rule engines: Drools,...

Is there any approach to achieve such results?

A: The class you've defined as domain is an anonymous one (the union of two named classes), so it cannot be returned by an implementation of OWLReasoner.
To work around this limitation, you can search for subclasses of the asserted domains of your property - so, using OWLOntology::getDataPropertyDomainAxioms(OWLDataProperty) you will retrieve the union from the root ontology; with OWLReasoner::getSubClasses(OWLClassExpression, false) you will be able to retrieve all nodes that contain subclasses of the disjunction. Each node will contain a set of equivalent classes; in your case, I'd expect to see a node containing {Rat, Mouse} and a node containing {Bird}.
Edit: added example to answer comments.
OWLOntology o = ... //root ontology for the reasoner
OWLReasoner r = ...
OWLDataProperty p = ...
for (OWLDataPropertyDomainAxiom ax: o.getDataPropertyDomainAxioms(p)) {
    OWLClassExpression c = ax.getDomain();
    NodeSet<OWLClass> allSubClasses = r.getSubClasses(c, false);
    // allSubClasses contains all named subclasses of the domain
}

As suggested by @AKSW in the comments, the reason why OWLReasoner does not return anonymous expressions in any of its methods is due to the fact that anonymous expressions in these methods are infinite: for example, given any class, there are infinite anonymous subclasses of this class. The proof is too long to be replicated here but can be easily found in description logics articles and books.
So, when OWLReasoner was designed, the choice was between making the reasoning incomplete (by only returning a more or less arbitrary set of anonymous expressions), undecidable (by returning an infinite set) or restrict it to named classes only. The latter was judged the best solution.


text:
Q: ifndef include guard in Gnu Make breaks on nested conditional I'm trying to implement include guards in Gnu Make. In this Makefile, the first inclusion is OK, while the second one fails with an error.
ifndef INCLUDED
INCLUDED = 1
$(info Including)

define macro
ifneq ($(1),)
define inner_macro
macro content...
endef
else
define inner_macro
endef
endif
endef

endif

The same effect can be simulated by explicitly giving INCLUDED = 1 before the inclusion, e.g. on command line.
Gnu Make 4.1 under Gentoo says Makefile:14: *** missing separator.  Stop., while Gnu Make 3.81 under Debian Wheezy says Makefile:14: *** extraneous `endef'.  Stop.. On the first inclusion, they both say:
Including
make: *** No targets.  Stop.

If I try $(eval $(call macro,whatever)) after the first inclusion, it defines inner_macro as expected.
I used make INCLUDED=1 and make commands respectively to get the described behavior.
The same happens when I clear the environment and disable built-in rules and variables: env -i make -rR INCLUDE=1. When I use -p to dump the database, without INCLUDED=1, the macro is defined as it should be, but with INCLUDED=1, empty inner_macro is defined. This is consistent across both the versions of Make. This hints me that when the condition is false, Make parses the Makefile differently and thinks the else inside macro's definition belongs to the ifndef. Other condition types behave all the same.
If I remove both the definitions of inner_macro, the problem goes away.
I read the manual pages info make conditional\ syntax and info make multi-line (formerly defining), but I found no caveat there and I still think I am doing nothing wrong.

*

*Am I correct with my conclusions?

*Is this a bug in Make, or am I invoking undefined behavior?

*How should I implement include guards in Gnu Make?

A: That's a bug.  Report it on Savannah.
There's something wrong with the tracking of nested define/endef inside a not-taken ifdef/ifndef condition.  If you don't use nested define/endef then it works; for example (obviously you may not be able to do this in your environment):
ifndef INCLUDED
INCLUDED = 1
$(info Including)

define macro
ifneq ($(1),)
inner_macro = macro content...
else
inner_macro =
endif
endef

endif


text:
Q: Double Impreciso El programa es una Distribución Poisson, pero cuando el número es muy grande, el factorial es impreciso y agrega algunas milésimas.
¿Como podría hacer más precisión el double? ¿O existe un valor con mayor tamaño?
for (int x = 0; x <= 15; x++)
{
    Console.WriteLine("\n\nx:{0} -------------------------- ", x);
    double num1 = Math.Pow(e, -lambda);
    double num2 = Math.Pow(lambda, x);

    double num = num1 * num2;

    fact = 1;
    for (i = 1; i <= number; i++)
    {
        fact = fact * i;
    }
    //Factorial

    double fxres = 0;
    fxres = num / fact;
    Console.WriteLine("F(x): " + fxres);
    fx+= fxres;
    Console.WriteLine("\nSuma: " + fx);

    number++;

A: Si lo importante es la precisión, deberías usar el tipo Decimal. Si lo importante es la velocidad, usar double.
Decimal tampoco es 100% preciso ya que los decimales en informática son así ... finitos. Pero tiene más precisión que double.


text:
Q: Trying to read data with experimental feature from chrome (serial port) but code freeze on await data I'm trying to use serial port, experimental feature from google chrome with reactjs. I do the connection with a digital balance (https://www.toledobrasil.com/blob/products/5_image1566803343.jpg) but the function freeze when wait for any data.
await port.open({
      baudRate: 9600,
      dataBits: 7,
      stopBits: 1,
      parity: "none",
    });
const _reader = port.readable.getReader();
while (true) {
      const { value, done } = await _reader.read(); //the execution freeze here
      console.log({ value, done }); //this line never is executed because the await above never return
    }


text:
Q: Get more recent statuses for a list of userids with twitter4j Im using twitter4j in java
I got a Set idsSet with some twitter usersIds.
I'm trying to get the 20 most recent status with 'getUserTimeline' for each userID.
for(Long id : idsSet)
{
   statusMap.put(id,twitter.getUserTimeline(id));
}

The problem is that I only get the statuses for 180 users every 15 mins.
My question is
is there a way to get more users every 15 mins? like with the 'lookupUsers' thats holds up to 100 usersIds per request allowing 18k every 15 mins

A: The twitter API description for users specifies that you can get the information of 100 users for request. In the same way, you can use the attribute count to control how many tweets you get with one request (up to 200), this is specified here. Now, as twitter4j is a wrapper around these GET requests, you need to configure you call with a Paging object. It would be something like this:
Paging page = new Paging (1, 200);
twitter.getUserTimeline(id,page);


text:
Q: iOS Long String Stored in Keychain Gets Randomly Corrupted I am fighting a rather pesky and illusive bug in my app. I am storing a long random string ( > 3200 characters ) in the iOS keychain using the Keychain wrapper UYLPasswordManager. After what seems like a completely random period of time, that value stored in the Keychain returns as a string of date rather than the long string that was originally stored.
Now, I say that it returns a string of a date instead of the long string, however it could very well be returning any number of strings that are not correct - I was only able to reproduce it once with debugging to see the erroneous value coming back from the Keychain.
Things I have tried:

*

*A multitude of Keychain wrappers, each of which exhibits the issue eventually.

*Combing through each character of code that writes to the Keychain to ensure the value is not being overwritten.

Beyond that, due to the illusive nature of the bug, I have not been able to attack it from a different angle because I have no idea where else to look. I am storing other strings in the Keychain that are much shorter which never seem to have a problem. Is there a known issue or anyone else with a similar experience with storing long strings in the Keychain?
I am using Swift 1.2 (the problem pre-dates v1.2) and the latest Xcode (stable).
EDIT: I am attempting to split the string into smaller chunks and save those each in the keychain to see if there is corruption or loss of that data over time. I will post back here with results.
EDIT: Ever since I split up the string into many small parts, I have not seen the issue. I am going to wait another week before I confirm the issue as resolved using this method. Also, I plan on filing a bug report to Apple.

A: For anyone else having an issue storing a very long string, it appears breaking the string into many parts and storing smaller chunks has solved this issue. Hope it helps someone else!


text:
Q: Ruby / Redis gem: change default connection parameters How can I change the default connection parameters for redis gem?
For example, I want all instances of redis to connect to other host/port by default.

A: I've searched for the answer for a while and found, that Redis::Client::DEFAULTS hash is mutable.
So, you can put something like this
# list of options: http://www.rubydoc.info/gems/redis/3.1.0/Redis/Client
Redis::Client::DEFAULTS[:host] = 'mycoolapp.local'

to some initializer (i.e. config/initializers/redis.rb) in Rails or where you're doing initialization in your non-rails app.


text:
Q: Pipelines and git-ftp dirt repository error I am trying to use Pipelines with git-ftp to push files to my remote server.
Error message:

fatal: Dirty repository: Having uncommitted changes. Exiting...

YML file:
image: php:7.1.1

pipelines:
  default:
    - step:
        caches:
          - composer
        script:
          - apt-get update && apt-get install -y unzip
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - composer install
          - apt-get -qq install git-ftp
          - git ftp init --user USER --passwd PASSWORD ftp://user@mydomain.tld@ftp.mydomain.tld/

I also tried git ftp push but same thing.
There are no uncommitted changes, so what gives?

A: try to debug changes that made your repo dirty add line to your script graph:
- git status -uno --porcelain
If it returns you something this means, in virtual deploy server some changes happen. For example, some files was corrupted while sending to over server
png, jpeg, exe, jar, etc
in order to fix it add lines into .gitattributes
*.exe binary
*.jar binary
*.png binary
*.jpg binary
*.gif binary


text:
Q: VBA with multiple discounts & Problem of next without for & insert value in respective cell The problem here is we've got a promotion for fruits, herbs and vegetables. A vba code is needed under several discounts rules.

*

*Cauliflower, Guava and mango are on sale, with 30% off discount, will not be affected by the order quantity.

Fruits category:

*

*No discount for order quantity less than 5 cases.

*10% discount if order quantity from 5 to 15 cases.

*20% discount for more than 15 cases.

Herbs category:

*

*No discount for order quantity less than 10 cases.

*5% discount if order quantity from 10 to 15 cases.

*10% discount for more than 15 cases.

Vegetables category:

*

*Kale: 12% discount for 20 cases or more

*Others:  12% discount for 5 cases or more

However, I am facing the issue of "next without for"......and I could not see where is the lack...and secondly may I know how to insert the respective discount in column D (under percentage). Any suggestion and help are more than appreciated. Thx !!
Sub Task3()
    Dim i As Integer
    Dim FinalRow As Integer
    Dim thisCategory As String, thisProduct As String
    Dim thisQty As Integer
    Dim Sale As Boolean
    Dim discount As Single

    With Sheets("sheet1")
    FinalRow = Cells(Rows.Count, 1).End(xlUp).Row

    Range("D1").Value = "Discount"

    For i = 2 To FinalRow
        thisCategory = Cells(i, 1).Value
        thisProduct = Cells(i, 2).Value
        thisQty = Cells(i, 3).Value

        Select Case thisProduct
            Case "Cauliflower"
                Sale = thisProduct
            Case "Guava"
                Sale = thisProduct
            Case "Mango"
                Sale = thisProduct
        End Select

        If Sale Then
            discount = 0.3
        Else
            If thisCategory = "Fruits" Then
                Select Case thisQty
                    Case Is < 5
                        discount = 0
                    Case 5 To 15
                        discount = 0.1
                    Case Is > 15
                        discount = 0.2
                End Select

            ElseIf thisCategory = "Herbs" Then
                Select Case thisQty
                    Case Is < 10
                        discount = 0
                    Case 10 To 15
                        discount = 0.05
                    Case Is > 15
                        discount = 0.1
                End Select

            ElseIf thisCategory = "Vegetables" Then
                    If thisProduct = "Kale" And thisQty >= 20 Then
                        discount = 0.12
                    ElseIf thisProduct <> "Kale" And thisQty >= 5 Then
                        discount = 0.12
                    End If
        End If
        ' insert discount in column D

         If discount = 0.3 Then
            .Range(.Cells(i, 1), Cells(i, 4)).Interior.Color = vbYellow
         End If
    Next i
    End With

End Sub

A: I have reviewed your code, added some comments and the two lines need to set the discount. I hope it works for you.
Sub Task3()

    Dim i As Integer
    Dim FinalRow As Integer
    Dim thisCategory As String, thisProduct As String
    Dim thisQty As Integer
    Dim Sale As Boolean
    Dim discount As Single

    With Sheets("sheet1")
        ' use a leading period to identify each item that
        ' VBA should find in Sheets("sheet1") specified with "With"
        ' I marked every added period with *
        FinalRow = .Cells(.Rows.Count, 1).End(xlUp).Row     ' **

        .Range("D1").Value = "Discount"                     ' *

        For i = 2 To FinalRow
            thisCategory = .Cells(i, 1).Value               ' *
            thisProduct = .Cells(i, 2).Value                ' *
            thisQty = .Cells(i, 3).Value                    ' *

            Select Case thisProduct
                Case "Cauliflower"
                    Sale = thisProduct
                Case "Guava"
                    Sale = thisProduct
                Case "Mango"
                    Sale = thisProduct
            End Select

            If Sale Then
                discount = 0.3
            Else
                If thisCategory = "Fruits" Then
                    Select Case thisQty
                        Case Is < 5
                            discount = 0
                        Case 5 To 15
                            discount = 0.1
                        Case Is > 15
                            discount = 0.2
                    End Select

                ElseIf thisCategory = "Herbs" Then
                    Select Case thisQty
                        Case Is < 10
                            discount = 0
                        Case 10 To 15
                            discount = 0.05
                        Case Is > 15
                            discount = 0.1
                    End Select

                ElseIf thisCategory = "Vegetables" Then
                        If thisProduct = "Kale" And thisQty >= 20 Then
                            discount = 0.12
                        ElseIf thisProduct <> "Kale" And thisQty >= 5 Then
                            discount = 0.12
                        End If
            End If
            ' insert discount in column D

            With .Cells(i, 4)
                .Value = discount
                .NumberFormat = "0%"
                If discount = 0.3 Then
                    .Offset(0, -3).Resize(1, 4).Interior.Color = vbYellow   '*
                End If
            End With
        Next i
    End With
End Sub


text:
Q: Lifting of families of curves to characteristic 0 Let $k$ be a finite field, $X_0$ be a smooth affine variety over $k$ and $C\rightarrow X$ a smooth projective family of curves of genus $\geq 2$.
By a result of Elkik we can always lift $X_0$ to a smooth affine scheme over $W(k)$.
It seems that, up to replace $X_0$ with an open subset, one can always lift $C_0\rightarrow X_0$ to a smooth projective family of curves $C\rightarrow X$.
Does anyone have a reference for this fact?

A: I am just posting my comment as an answer.  This type of lifting is "classical".  In the article linked above with Chenyang Xu, we needed bounds on the lift, to deduce height bounds for some rational points.  So we worked out in detail the classical result.
The result that I called "Chow's Lemma for Stacks" is not actually Chow's Lemma for Stacks (sorry).  Rather, it is Théorème 6.3, p. 49 of the following.
MR1771927
Laumon, Gérard; Moret-Bailly, Laurent
Champs algébriques.
Ergebnisse der Mathematik und ihrer Grenzgebiete. 3. Folge, Volume 39.
Springer-Verlag, Berlin, 2000. xii+208 pp.
ISBN: 3-540-65761-4
For each field $k$ of finite characteristic $p$, denote by $W(k)$ a complete, local, Noetherian DVR with uniformizing element $p$ such that $W(k)/pW(k)$ equals $k$.  Let $\mathcal{M}$ be a smooth stack over $\text{Spec}\ W(k)$.  Let $X_0$ be a connected, smooth, quasi-projective $k$-scheme.  By hypothesis, there exists a locally closed immersion of $k$-schemes, $$i:X_0 \to \mathbb{P}^n_k.$$  Let $\zeta:X_0\to \mathcal{M}$ be a $1$-morphism over $\text{Spec}\ W(k)$.  By Théorème 6.3, up to replacing $X_0$ by a dense open subscheme, there exists a factorization of $\zeta$, $$X_0\xrightarrow{z} M \xrightarrow{\phi} \mathcal{M},$$ where $M$ is a smooth, quasi-projective $W(k)$-scheme, where $\phi$ is a smooth $1$-morphism over $W(k)$, and where $z$ is a $W(k)$-morphism.
So now we are reduced to lifting over $W(k)$ the locally closed subscheme $X_0$ in the closed fiber of the smooth, quasi-projective $W(k)$-scheme $$\mathbb{P}^n_{W(k)}\times_{\text{Spec}\ W(k)} M.$$  This is "classical".  Since $X_0$ is smooth, the locally closed immersion is a regular embedding.  Thus, up to shrinking $X_0$ further, this closed subscheme is an open subscheme of a complete intersection of degree $d$ ample hypersurfaces in $\mathbb{P}^n_{W(k)}\times_{\text{Spec}\ W(k)} M$ for all $d\geq d_0$. (You can spend a lot of time trying to optimize degrees in this argument, but the OP did not ask for an "optimal lifting", just some lifting.)  The defining equations of those hypersurfaces have coefficients that are elements of $k$.  By lifting those coefficients to $W(k)$, we can lift the hypersurfaces over $W(k)$.  This lifts the complete intersection over $W(k)$.
As the commenters note, this clashes with intuition that lifts should preserve intersection numbers and other notions that definitely are preserved for lifts of projective schemes.  However, this is a well-known "pathology" of lifts of affine schemes.  We can find projective models of these lifts, but then the closed fiber will be reducible.  Those properties suggested by our intuition typically do occur for the closed fiber of a projective model.  However, the property may hold for some irreducible component of the closed fiber different from the component containing $X_0$.


text:
Q: The element type 'Iterable' can't be assigned to the list type 'Widget' I am making an app using sqlite, and when I try to put the data into widget, I am having an error..
I am following a tutorial and it's giving me this error:
The element type 'Iterable' can't be assigned to the list type 'Widget'.
 FutureBuilder<List<Reminder>>(
          future: _reminders,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              _currentReminders = snapshot.data!;
              return ListView(children: [
                snapshot.data!.map<Widget>((reminder) {
                  return ReminderCard(
                      name: reminder.name, details: reminder.details);
                }).toList(),

*

*new error message:
the element type 'List' can't be assigned to the list type 'Widget'.dartlist_element_type_not_assignable

*

The element type 'List' can't be assigned to the list type 'Widget'.dartlist_element_type_not_assignable
Iterable map(T Function(Reminder) f)
dart:core
Returns a new lazy [Iterable] with elements that are created by calling f on each element of this Iterable in iteration order.
This method returns a view of the mapped elements. As long as the returned [Iterable] is not iterated over, the supplied function [f] will not be invoked. The transformed elements will not be cached. Iterating multiple times over the returned [Iterable] will invoke the supplied function [f] multiple times on the same element.
Methods on the returned iterable are allowed to omit calling f on any element where the result isn't needed. For example, [elementAt] may call f only once.
Reminder is the class for DB elements.
 Reminder(
      {this.id = 0,
      required this.name,
      required this.details,
      required this.save});

  factory Reminder.fromMap(Map<String, dynamic> json) => Reminder(
      id: json["id"],
      name: json["name"],
      details: json["details"],
      save: json["false"]);

  Map<String, dynamic> toMap() => {
        "id": id,
        "name": name,
        "details": details,
        "save": save,
      };
}

can you help me fix this?

A: *

*snapshot.data!.map<widget> - I do not expect that widget is a valid type, it should be Widget.

*If you want to use the .map function inside ListView children, you should convert map result - iterable - to list and use the spread operator to spread this list inside children:
ListView(children: [
  ...snapshot.data!.map<widget>((reminder) {
    return ReminderCard(
      name: reminder.name, details: reminder.details);
  }).toList(),


text:
Q: file request for: "0002-Add-uninstalled.pc.in-files.patch" from avahi for compiling for android I try to compile a Qt console project for Android that includes DNS services provided by avahi. As my shared libraries dns_sd.so are not compatible, I would try to compile avahi according to these links.
Utilize Avahi Libraries in Android for mDNS Discovering
Problems compiling avahi into Android NDK project
What I cannot find is the file "0002-Add-uninstalled.pc.in-files.patch" from Avahi. Please share it with me, if you still have it available. I also contacted avahi directly but did not receive a response yet. Thank you very much!

A: The files in the link below are accessible again.
Utilize Avahi Libraries in Android for mDNS Discovering


text:
Q: Open datepicker with certain date I'm having an input filled with a date in the past. All i want to do is open the datepicker of that input on current date.
Example: Input is filled with 10 nov 2011, onclick should open datepicker starting at 5 feb 2013
Html:
<input type="text" id="datepicker" data-today="5-2-2013" value="10-11-2011" />
Javascript:
var currentDate = $.datepicker.parseDate('dd-mm-yy', $('#datepicker').data('today'));
    $('#datepicker').datepicker({
        defaultDate: currentDate,
        dateformat: 'dd-mm-yy'
    });

With this codesample the datepicker still opens at november 2011

A: you can try setDate()

Sets the date for the datepicker. The new date may be a Date object or a string in the current date format (e.g., "01/26/2009"), a number of days from today (e.g., +7) or a string of values and periods ("y" for years, "m" for months, "w" for weeks, "d" for days, e.g., "+1m +7d"), or null to clear the selected date.

$( "#datepicker" ).datepicker( "setDate", currentDate );


text:
Q: Java deserialization: final variable value is not assigned I'm exploring Java Serialization and Deserialization but wonder how Deserialization works.
Here is my Serialization and Deserialization Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Testing{
    public static void main(String[] args){
        Serial obj = new Serial();
        Serial ObjNew = null;
        try{
           FileOutputStream fob= new FileOutputStream("file.src");
           ObjectOutputStream oob= new ObjectOutputStream(fob);
           oob.writeObject(obj);
           oob.close();
        }catch(Exception fnf){
            fnf.printStackTrace(System.out);
        }
        try{
            FileInputStream fis = new FileInputStream("file.src");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ObjNew=(Serial)ois.readObject();
        }
        catch(IOException | ClassNotFoundException fnf){
            fnf.printStackTrace(System.out);
        }
        System.out.println("OLD: "+obj);
        System.out.println("NEW: "+ObjNew);

    }
}

Here Serializable Class Code:
import java.io.Serializable;
public class Serial implements Serializable {
    private final String ok="DONE";
    @Override
    public String toString(){
        return ok;
    }
}

Everything is working fine with above code.
But When I try to Deserialize the Object with this code.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Testing{
    public static void main(String[] args){
        Serial ObjNew = null;
        try{
            FileInputStream fis = new FileInputStream("file.src");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ObjNew=(Serial)ois.readObject();
        }
        catch(IOException | ClassNotFoundException fnf){
            fnf.printStackTrace(System.out);
        }
        System.out.println("NEW: "+ObjNew);

    }
}

and I just changed the value of String ok="Do"; in Serializable Class Just to test Deserialize output.
But it just printing Do instead of the value DONE that stored in file.
Why it is printing just Do?
why it not reading the value from file?
Any Help?

A: A requirement of a Java class that is serializable is that it has access to a no-argument constructor in its first non-serializable superclass. Java serialization utilizes this no-arg constructor.  This is not exactly the same thing as stating that it creates a new class by this constructor, but certain aspects of the class's construction are carried out before the fields are set within the class.  One of these aspects is the setting of final constants, as they need to be set before the class can be considered "constructed".
You have a final field.  It cannot be set after class construction.  With such an item, the field is not serialized into the file on disk (at least I don't think it is) and even if it was and was read from disk it could not reset the field because then the field wouldn't honor the "final" keyword.  If you change it to non-final, you should expect different results.
Since you are effectively borrowing one class definition and populating it with a snapshot of what that definition was, you need a facility to identify when the definitions have drifted too far apart to be reconcilable.  This is the primary purpose of the serialVersionID member.

A: A final variable can only be assigned once.
Remove the final modifier, and try again.

A: It is depends on your final field modifier.
I have red the source code of ObjectInputStream and found this code
    Object obj;
    try {
        obj = desc.isInstantiable() ? desc.newInstance() : null; // here instance created
    } catch (Exception ex) {
        throw (IOException) new InvalidClassException(
            desc.forClass().getName(),
            "unable to create instance").initCause(ex);
    }

Once your instance created the value "DO" applied to the field, and since field is final it cannot be modified anymore


text:
Q: Add icons to options in select2 I am trying to put icons next to the options similar to the flags example in the GitHub: http://ivaynberg.github.io/select2/#templating, but need the icons to be based on the optgroup they're in. I end up with the same icon by every selection, instead of just in their optgroup.
JS
$(function() {
  function format(ade) {
    if (!ade.id)
      return ade.text; // optgroup
    return "" + ade.text;
  }
  function format(bob) {
    if (!bob.id)
      return bob.text; // optgroup
    return "" + bob.text;
  }
  function format(jive) {
    if (!jive.id)
      return jive.text; // optgroup
    return "" + jive.text;
  }
  $("#source").select2({
    placeholder: "Get Started...",
    allowClear: true,
    minimumInputLength: 2,
    formatResult: format,
    formatSelection: format,
    escapeMarkup: function(m) {
      return m;
    }
  });
});

HTML
<select id="source" class="search-box">
  <option></option>
  <optgroup label="Book of Business">
    <option value="bob">Jasper Beardly</option>
    <option value="bob">John Frink</option>
    <option value="bob">Elizabeth Hoover</option>
    <option value="bob">Edna Krabappel</option>
    <option value="bob">Otto Mann</option>
  </optgroup>
  <optgroup label="Dashboard Content" id="ade">
    <option value="ade">Additional time for Oklahoma customers to make payments</option>
    <option value="ade">Who to call when you have California policy questions</option>
    <option value="ade">Product Resource Center</option>
    <option value="ade">Quote Tracker</option>
  </optgroup>
  <optgroup label="Community Discussions" id="jive">
    <option value="jive">email account on Android phone</option>
    <option value="jive">Problems with changing</option>
    <option value="jive">Transfer discount for current client moving states </option>
    <option value="jive">Quoting auto on existing client.</option>
    <option value="jive">Where can I find sample ads/flyers/brochures for advertisement?</option>
  </optgroup>
</select>

A: Honestly it's a bit of a mess.
You have three functions with the same name, but with different parameter names.  That won't work.  Delete your three format functions and replace them with this:
function format(o) {
    if (!o.id)
      return o.text; // optgroup
    else if (o.id == 'bob')
        return "" + o.text;
    else if (o.id == 'ade')
        return "" + o.text;
    else
        return "" + o.text;
  }

Better yet, have your class names match your id names.  So
<option value="user">Jasper Beardly</option>

etc.
Then the format function simply becomes:
 function format(o) {
        if (!o.id)
          return o.text; // optgroup
        else
            return "" + o.text;
      }


text:
Q: Go lang - idiomatic default fallbacks I'm fairly new to go (about 9 months now full time using Go). However, I'm used to Python, typescript and PHP and I always find a short cut with these languages. However, I'm struggling to know what would be the most idiomatic way to achieve the following:
transit := gin.H{
    "rise": rs.Rise.String(),
    "set":  rs.Set.String(),
}

if rs.Rise.IsZero() {
    transit["rise"] = nil
}

if rs.Set.IsZero() {
    transit["set"] = nil
}

Essentially, I set a default struct, then if I need to change, I change ... but it just feels inefficient to me ... so I'm wondering if there are any tricks here that I could use?
I've chosen this specific real-world scenario, but I'm happy to have examples (rather than coding for me) ...

A: This is not inefficient in terms of execution. It may be a bit verbose compared to other languages. There are ways to shorten such repetitive code using anonymous functions. This can help shorten a lengthy repetitive section as you have without sacrificing readability.
type StringZeroable interface {
   fmt.Stringer
   IsZero() bool
}

checkZero:=func(in StringZeroable) interface{} {
   if in.IsZero() {
     return nil
   }
   return in.String()
}

transit := gin.H{
    "rise": checkZero(rs.Rise),
    "set":  checkZero(rs.Set)
}


text:
Q: How can i add a customized reading pane for my Add-In in Outlook with C# in Vsto? I am in the process of implementing an add-in for outlook. I am currently implementing all messages with the MessageBox. As this is not a nice solution, I would like to display the messages via a reading pane or something similar. How can I implement this in Vsto with C#? Or is there a better solution?

A: You may consider creating a form region in Outlook. See Create Outlook form regions for more information. Also you may find the Walkthrough: Design an Outlook form region helpful.
Another option is custom task panes in Outlook. Read more about that in the Walkthrough: Display custom task panes with email messages in Outlook article.

A: Task panes would be a good option for displaying any information in a non-modal fashion (see https://learn.microsoft.com/en-us/visualstudio/vsto/walkthrough-displaying-custom-task-panes-with-e-mail-messages-in-outlook?view=vs-2022).
Note that unlike Outlook form regions, task panes give you full control over when they are shown and hidden.


text:
Q: Code Coverage on AzureDevOps fails to generate coverage when referencing microsoft.CodeCoverage nuget When executing tests in a azure devops pipeline while using a datacollector uri="datacollector://microsoft/CodeCoverage/2.0" we are seeing errors in the generation of the coverage attachment file if a recent version of the Microsoft.CodeCoverage nuget package is referenced either directly or indirectly.
Reason is as follows:
The data collector adds the packages folder to its search path, the Microsoft.CodeCoverage assembly  gets loaded, and since the loading of the referenced Microsoft.CodeCoverage.Telemetry (which isn't in said nuget) fails, no data collector gets added and no coverage file written.
Any suggestions on how this can be prevented?
Every test project which references the current version of Microsoft.Net.Test.Sdk (17.5) has an indirect reference to the problematic package and causes this behavior.
Removing the reference or downgrading to a older version of the two nugets.