text:
Q: Add specific capacity constraint on arcs for routing optimization with Or-Tools Is it possible with Or-Tools Routing to create capacity constraints on arcs?
Let me explain:
I have implemented the following example.
The problem is that during some rounds there are routes where the capacity of the truck is limited (for example a bridge where the capacity of the truck must not exceed 6 units).
Is it possible to add specific capacity constraints between two nodes i and j so that :
capacity(i) - capacity(j) <= allowed capacity between the two steps, if so how?
The constraint must be on the arc and I can't find how to do it using Java.

An example:
I have a truck loaded with 3 units at point i, it must go to point j and encounter a bridge where the maximum load allowed on the bridge is 2 units. Therefore, it cannot cross the bridge. In other words, the round must be run in another way.
Thank you very much in advance

A: I share with you my solution if it can help someone else.
The following constraint must be added: the result of subtracting the load (capacity) of step j - step i must be smaller than the maximum load allowed for step ij.
With Java, we get the following code:
Capacity matrix:

long[][] maxLoad = {
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1,-1,-1,-1},
            };

Constraint declaration:

Solver solver = routing.solver();
RoutingDimension capacite_dim = routing.getDimensionOrDie("Capacity");

for (int i = 0; i < secteur.getMaxLoad().length; i++) {
  for (int j = 0; j < secteur.getMaxLoad()[0].length; j++) {
    //if there is a load constraint in matrix
    if (secteur.getMaxLoad()[i][j] >= 0) {
      long beforeIndex = manager.nodeToIndex(i);
      long afterIndex = manager.nodeToIndex(j);
      //add constraint
      solver.addConstraint(solver.makeLessOrEqual(solver.makeDifference(capacite_dim.cumulVar(afterIndex),capacite_dim.cumulVar(beforeIndex)),secteur.getMaxLoad()[i][j]));
    }
  }
}

The constraint ensures that the load flowing on the arc between two steps is less than the maximum allowed load for this step.


text:
Q: fluent-ffmpeg performance - Taking screenshot for a huge amount of file on a network drive I'm trying to scan all the videos inside a specific folder and create a thumbnail for each of them.
Here is the relevant code:
public async scan(): Promise<string[]> {

    const files = await this.readFile(this._directoryPath);

    const result: string[] = [];

    for await (const file of files) {
        result.push(file);
        try {
            ffmpeg(file)
                .on("error", (err, stdout, stderr) => {
                    console.log(err.message);
                })
                .screenshots({
                    timestamps: [5],
                    filename: basename(file) + ".png",
                    folder: this._thumbnailPath,
                });
        } catch (e: any) {
            logger.error("Failed taking screenshot for " + file + " with error " + e.message);
        }
    }

    return result;
}

It is running fine a for small amount of video, but when I tried on a network path (\\Servername\some_folder) containing 2000 video files, my pc died after a moment. It manages to scan ~800 videos then everything crashed.
Is there a way to make that a background process ? I don't need to wait for it to be over. Or is it possible to run this chunk by chunk from one API call ?
I'm completely new to node.js so any help is appreciated.

A: Your problem seems to be that the code is trying to process all input files at once in parallel. As a result, you experience resource allocation issues.
From the usage of await, I assume that you are trying to handle this situation.
But the problem is that the ffmpeg(..).on(...).screenshots(..) code sequence returns immediately, without waiting for the screenshots to be created first. So, await is not working the way you want it to.
So, you need to wait for each video file to finish, then move on to the next file.
A solution would be to place the thumbnail generation inside a promise:
async function processFile(file) {
    return new Promise((resolve, reject) => {
        ffmpeg(file)
            .screenshots(...YOUR_OPTIONS_HERE...)
            .on("error", ...USE_REJECT_HERE.....)
            .on("end", function() {
                resolve(file);
            });
    })
}

And then, instead of doing:
result.push(file)
try {
    ffmpeg(file)....

to do something like:
try {
    result.push(await processFile(file));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send Data from Jquery Dialog and MVC I have a Jquery modal dialog, My question is what is the best way to send this data to the controller, and to display a message back to the dialog. I can not seem to find and good examples of this.

A: With JQuery, you can get the Form plugin, and submit your form easily with Ajax like this:
 $('#myform').ajaxForm({
      url: '/mycontroller/myaction/myid',
      datatype: 'json',
      success: function(responseJson) {
                    alert ('success! response was:' + responseJson);
               }
   });

A: $.post('site/controller/action', $('#myForm').serialize(), function (data) {
    alert('form submitted');
}, 'json');

A: Put data collection controls within a form like so:

    <form id="AddTaskForm" method="post" action="">
    <%= Html.Hidden("AddTaskProjectId") %>
    <%= Html.Hidden("AddTaskTemplateName") %>
        <fieldset>

Task ID

                Level:
                <%= Html.TextBox("AddTaskLevel", "", new{@maxlength= "3", @size="3"})%>
                <%= Html.ValidationMessage("AddTaskLevel", "*")%>

                Major ID:
                <%= Html.TextBox("AddTaskMajorLevel", "", new { @maxlength = "3", @size = "3" })%>
                <%= Html.ValidationMessage("AddTaskMajorLevel", "*")%>

                Minor ID:
                <%= Html.TextBox("AddTaskMinorLevel", "", new { @maxlength = "3", @size = "3" })%>
                <%= Html.ValidationMessage("AddTaskMinorLevel", "*")%>

                Description:
                <%= Html.TextBox("AddTaskDescription", "", new { @maxlength = "32", @size = "32" })%>
                <%= Html.ValidationMessage("AddTaskDescription", "*")%>

                ResponsibleRole:
                <%= Html.TextBox("AddTaskResponsibleRole")%>
                <%= Html.ValidationMessage("AddTaskResponsibleRole", "*")%>

                DurationInDays:
                <%= Html.TextBox("AddTaskDurationInDays", "", new { @maxlength = "3", @size = "3" })%>
                <%= Html.ValidationMessage("AddTaskDurationInDays", "*")%>

                Task Type:
                <%= Html.DropDownList("AddTaskType", (SelectList)ViewData["TaskTypes"])%>

        </fieldset>
    </form>

Next add the following Javascript: Note Open function Add has a Serialize. This assembles the Json data. Now go down and look at the DTO then the controller.

Create a DTO: Note property names ar identical to form control names:
public class TaskDto
{
    public string AddTaskProjectId { get; set; }
    public string AddTaskDescription { get; set; }
    public string AddTaskDurationInDays { get; set; }
    public string AddTaskLevel { get; set; }
    public string AddTaskTemplateId { get; set; }
    public string AddTaskTemplateName { get; set; }
    public string AddTaskMajorLevel { get; set; }
    public string AddTaskMinorLevel { get; set; }
    public string AddTaskResponsibleRole { get; set; }
    public string AddTaskActive { get; set; }
    public string AddTaskType { get; set; }
}

Your MVC controller:
public ActionResult AddTask(TaskDto taskDto)
{
    // Code here
}

And thats it.
So I place the dialog in my site master making it there all the time, ready. It initializes itself.
Then when I need it I call the open and then rest is done.


text:
Q: showDialog in flutter is not working in release version of iOS I am creating an app for iOS using Flutter.
For that Application, I am using dialogue in one screen.
For that dialogue, It is showing a grey layer on dialogue in the
release version of iOS but it is working as expected in the Simulator or debug version
There is a grey layer on dialogue I have added my code to anyone facing the same issue?
need help.
 static dynamic customPage(BuildContext context) {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return CustomDialog(
          insetPadding: const EdgeInsets.all(20),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(8)),
          ),
          child: Container(
            child: Stack(
              children: [
                Positioned(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Positioned(
                      right: 0.0,
                      child: GestureDetector(
                        onTap: () {
                          if (Navigator.canPop(context))
                            Navigator.pop(context, true);
                        },
                        child: Container(
                          color: Colors.transparent,
                          child: Icon(
                            Icons.close,
                            color: Colors.black,
                            size: 25,
                          ),
                        ),
                      ),
                    ),
                  ),
                  right: 1.0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      "images/bind_loader.gif",
                      height: 90.0,
                      width: 90.0,
                    ),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 80.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CustomDialougeUtil(),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      right: 12.0, bottom: 10.0, top: 120),
                  child: Text(
                    "Please wait while we are confirming your payment",
                    style: bindTheme.textTheme.headline3,
                    textAlign: TextAlign.center,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
// this is a Widget that is showDialog
class _CustomDialougeUtilState extends State<CustomDialougeUtil> {
  //State full widget that uses normal timer view to display on dialogue
}


text:
Q: extract string between double quotes I have requirement that i need to extract string using quotes. My string as follows.
"abcd efgh" "ijkl mnop" "qrst uvwxyz"

can you help me to get the string between second double quotes(ijkl mnop) using sed or grep command.
In other words if I say give me the string in first quotes I want the  first string; if I say second string it should give me string between second double quotes and similarly third one also.

A: I am not sure how you want to input the string. This has the effect you want to achieve, but it might need to be modified according to how the string is entered:
aa() { echo $3 ; } ; aa "abcd efgh" "ijkl mnop" "qrst uvwxyz"

Edit: So, if it is in variable (it has to be defined with quoted ") :
AA="\"abcd efgh\" \"ijkl mnop\" \"qrst uvwxyz\""
echo $AA

then:
FIRST=`echo $AA| awk -F \" '{print $2}'`
SECOND=`echo $AA| awk -F \" '{print $4}'`
THIRD=`echo $AA| awk -F \" '{print $6}'`
echo $FIRST : $SECOND : $THIRD

as jasonwryan pointed out above. You said, you wanted to use sed, but it makes it unnecessary complex :
FIRST=`echo $AA| sed 's/^\"\([^\"]*\)\".*/\1/'`
SECOND=`echo $AA| sed 's/^\"[^\"]*\" \"\([^\"]*\)\".*/\1/'`
THIRD=`echo $AA| sed 's/^\"[^\"]*\" \"[^\"]*\" \"\([^\"]*\)\".*/\1/'`

Edit2:
It is actually possible to achieve completely without sed,awk,perl,.. only with bash, using its "read" builtin function like this (echos are for debugging):
#!/bin/bash

aa() {
echo '$1'="$1"
IFS=\" read aaa FIRST bbb SECOND ccc THIRD ddd <<< "$1"
echo FIRST=$FIRST : SECOND=$SECOND : THIRD=$THIRD
}

AA="\"abcd efgh\" \"ijkl mnop\" \"qrst uvwxyz\""
echo '$AA'="$AA"
aa "$AA"

A: You said this in a comment:

above string is in variable. I need to extract each section(first,second,third) and store it different variables

So let's just split it.
IFS=\"                  #set the shell's field separator
set -f                  #don't try to glob
set -- $var             #split on $IFS
var1=$2 var2=$4 var3=$6 #yay
unset IFS               #restore something like a sane default

That won't handle strings which might contain backslash-escaped quotes, though. I hope that's not a problem, because I don't like doing those.

A: Building on (and somewhat simplifying) ludvik02's sed answer:
AA='"abcd efgh" "ijkl mnop" "qrst uvwxyz"'
AA1=$(echo "$AA" | sed -r 's/^([^"]*"){1}([^"]*).*/\2/')
AA2=$(echo "$AA" | sed -r 's/^([^"]*"){3}([^"]*).*/\2/')
AA3=$(echo "$AA" | sed -r 's/^([^"]*"){5}([^"]*).*/\2/')
(Note that                        this ↑                        is different on every line.)

The -r option to sed enables extended regular expressions.
We need that to use {n},
which means n occurrences of the preceding regex.
([^"]*") is a compound (group) regex that matches
any number of characters other than ", terminated by a ".
The example input string can match this regex up to six times
(because it has six " characters);
with ...s inserted to distinguish the gaps between the strings,
those occurrences are
"abcd efgh" ... "ijkl mnop" ... "qrst uvwxyz"
↑↑--------↑↑----↑↑--------↑↑----↑↑----------↑
1    2       3       4       5        6

Matching any odd number (e.g., three) of occurrences of that consumes
everything up through and including the nth
(e.g., third) " character, i.e., the " character at the beginning of
the ((n+1)/2)th (e.g., second) quoted string.
Then ([^"]*) matches (and groups) everything up to (but not including)
the (n+1)th " character,
i.e., the " character at the end of the second quoted string.
So this group (the second group) matches the second quoted string.
Finally, .* consumes the rest of the input string.
So then we replace the entire input line with \2, the value of the second group:
"abcd efgh" ... "ijkl mnop" ... "qrst uvwxyz"
↑↑--------↑↑----↑⇑=======⇑⇈≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡⇈
1    2       3
↑---------------↑⇑=======⇑⇈≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡⇈
        \1          \2          (unnamed)


text:
Q: Error Statement
No suitable method found for setDate(int,java.util.Date) method
  PreparedStatement.setDate(int,java.sql.Date,Calendar) is not
  applicable

public void update (Pasien dp) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
PreparedStatement statement = null;
try {
    statement =  connection.prepareStatement(update);

    statement.setString(1, dp.getId_pemeriksaan());
    statement.setString(2,dp.getNama());
    statement.setString(3,dp.getAlamat());
    statement.setString(4,dp.getUmur());
    statement.setString(5,dp.getJenis_kelamin());
    statement.setString(6,dp.getGolongan_darah());
    statement.setString(7,dp.getSpesimen());
    statement.setString(8,dp.getPengirim());
    statement.setString(9,dp.getPemeriksaan());
    statement.setDate(10, dp.getTanggal()df.format(getTanggal));
    statement.setString(11, dp.getNo_rekam_medik());
    statement.executeUpdate();

} catch (SQLException ex) {
    System.out.println("error karena" +ex.getMessage());
}finally{
    try {
        statement.close();
    } catch (SQLException ex) {
        System.out.println("error karena" +ex.getMessage());
    }
   }
  }

A: This line of code is suspicious:
statement.setDate(10, dp.getTanggal()df.format(getTanggal));

Should, perhaps, be: statement.setDate(10, df.parse(dp.getTanggal()));
(if dp.getTanggal() method is a String).

Obviously you haven't checked the PreparedStatement.setDate() method.
The method has the following signature:
void setDate(int parameterIndex, java.sql.Date x) throws SQLException;

It's not a java.util.Date but a java.sql.Date object.
If you want to use Calendar then:
void setDate(int parameterIndex, java.sql.Date x, Calendar cal) throws SQLException;

is the one to call. Obviously, this still requires java.sql.Date object.

To convert a java.util.Date to a java.sql.Date, you can do this:
java.util.Date date = df.parse(...);
java.sql.Date = new java.sql.Date(date.getTime());

A: The exception says the exact error.

No suitable method found for setDate(int,java.util.Date) method
  PreparedStatement.setDate(int,java.sql.Date,Calendar) is not
  applicable]

In your src the below line
dp.getTanggal()df.format(getTanggal)

is returning java.util.Date. But the PreparedStatement.setDate() method expects java.sql.Date

A: statement.setDate(10, dp.getTanggal()df.format(getTanggal));

you have forgot to put comma(,). :)
But the interesting part is DateFormat#format returns a formatted String representation of Date. Which need to pass it trough setString method.


text:
Q: Generate Dagger components using Annotation Processor I'm working on an Android App which follows the MVP architecture pattern. In all my fragments I'm injecting a Presenter. Therefore my Fragments (Views) need to have a Component in which I declare the injects. For example:
@ActivityScope
@Component(
        dependencies = AppComponent.class,
        modules = {
                PresenterModule.class,
                InteractorModule.class
        }
)
public interface ViewInjectorComponent {
    void inject(SelectEventOccurrenceFragment fragment);
    void inject(CreateOpponentFragment fragment);
    void inject(SelectOpponentFragment fragment);
    void inject(TeammatesInvitedFragment fragment);
    ...
}

Every new View that I add into my App (Fragment) needs to have its entry declared here. I was wondering if It's possible to generate this code automatically with some kind of annotation processor. The App has already several fragments, this component file has easily more than 300 entries. It'd be awesome if I could do something like:
@Injectable
public class MyNewFragment implements MyNewView {
...
}

And then automatically generate the entry in the ViewInjectorComponent file. It's possible? Where should I look at?

A: The situation you are experiencing may be a consequence of organising your Modules and Components in an unusual way. In particular, grouping laterally (one Component injects all the Presenters) rather than vertically (one component injects the functionality related to SelectOpponentActivity) is problematic.
A good example to follow is in the Google Android Architecture Blueprints GitHub repo. If you peruse the code there, you will see that they have organised functionality related to Tasks inside one Java package together with a separate Component, Module, Presenter etc. This has the nice advantage of being able to restrict accessibility of the constructors of the classes contained therein and fulfilling Effective Java Item 13: Minimize the accesibility of classes and members.
Likewise, you've grouped all your modules together into a Presenter Module and an Interactor Module. The advice from the Dagger 2 official documentation is to organise Modules first for testability and then along functional lines. Again, you can refer to the Blueprint example for how to do this.
Finally, note that there is unavoidably some boilerplate involved in using most DI frameworks like Dagger 2. In a sense, you are exchanging a bigger problem ("how do I deal with all of these constructors?") with much smaller and more manageable problems ("how do I group my Components" etc.).
Update
There is a library called Auto Dagger2 that can generate components for you. See this Github repo. Here is an example of an annotation:
@AutoComponent
@Singleton
public class ExampleApplication extends Application {
}

Which generates the following code:
@Component
@Singleton
public interface ExampleApplicationComponent {
}

Also check out Google Auto if you are interested in code generation tools.

A: I'm not entirely sure that what I'm going to say is appropriate for an answer, but I'll take a chance here.
Even if you find a way to do what you want, don't do this in production (it is fine if you just want to learn code generation techniques).
The benefits you get from such an approach are small (not writing several lines of trivial code), but consider the drawbacks:

*

*The logic for code generation needs to be written/debugged/maintained

*Such an approach will be a violation of "principle of least astonishment"

*Code generation is BAD

Note the third point - I really mean it. Usage of code generation always leads to maintenance overhead, therefore it should be used only as a last resort.
Dagger by itself uses code generation, but for a good reason - performance. However, performance is not an issue in your case.
To summarize: your idea is very interesting, but approaches like this should not be used for production applications (unless this functionality is added to Dagger natively).


text:
Q: How can I bypass Heroku's timeout when retrieving large amounts of data from S3? I am trying to write a Koa endpoint that retrieves and archives a large amount of data from AWS S3. Response times can take over a minute in some cases but performance is not a huge concern. However, when hosting on Heroku, the page always times out before the data can be processed and returned (apparently because Heroku has a limit of 30s on any single request). My (simplified) code to retrieve and return the data is:
router.get('/diagnostics/data', async (ctx) => {

  const archive = archiver('zip', { zlib: { level: 9 } })
  ctx.body = archive

  try {
    ctx.status = 200
    ctx.type = 'application/zip'
    ctx.attachment(`myS3Data.zip`)

    // on stream closed we can end the request
    archive.on('end', () => {
      log.info(util.format('Archive wrote %d bytes', archive.pointer()))
    })
    archive.on('error', (err) => {
      throw err
    })

    // This line does the actual retrievals from S3 and takes the most time, over 1min on large requests
    // myKeys here is just an example, a real request would have a lot more keys
    const myKeys = ['key1','key2','key3']

    const stream = new Stream.PassThrough()
    ctx.body = stream
    archive.pipe(stream)

    // retrieve and append one archive chunk at a time
    // theoretically this should push to the stream so the Heroku doesn't time out
    for (let i = 0; i < myKeys .length; i += 1) {
      const retrieval = s3Client.getObject(BUCKET_NAME, myKeys[i])

      await Promise.allSettled([retrieval]).then((data) => {
        const payload =
          data[0].status === 'fulfilled'
            ? data[0].value
            : data[0].value || `Failed to retrieve data with key ${myKeys [i]}! Status: ${data[0].status}`
        const keyFinal = data[0].status === 'fulfilled' ? myKeys [i] : `${myKeys [i]}_Failed.txt`
        archive.append(payload, { name: keyFinal })
      })
    }

  } catch (err) {
    ctx.status = 500
    ctx.body = `${err.message}`
  } finally {
    archive.finalize()
  }

  return ctx
})

When hosted locally (ie. with no timeout to worry about), the S3 retrievals take about a minute to process, then the client finally starts downloading the zip file. Is there a way to have the client immediately access the zip file but just download bit by bit as its being compiled from S3? This way the overall time to completion is not changed but the Heroku will not see it as a hung connection while the zip is being compiled on the server. Alternatively, maybe some dummy event or data can be sent back to the client while processing is still going just to let it know not to time out too early.
EDIT: EDIT: reorganised the code to stream an archive back, which according to a few sources should have solved the issue, but the endpoint still behaves exactly the same, with the archive just being returned in bulk after far too long after the timeout triggers.


text:
Q: Table partition on non date column How can I partition a table in oracle on non-date column (Say partition on Username)?
I have table partitioning on only date columns.Say:
CREATE TABLE X
(
Username Varchar2(10 Char),
Import_date Date
)
PARTITION BY RANGE ("IMPORT_DATE") INTERVAL (NUMTODSINTERVAL(1,'DAY'))
 (PARTITION "CL_REP_DEF"  VALUES LESS THAN
     (TO_DATE(' 2018-06-29 00:00:00', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN'))
)

Though I am not sure how to partition with username here.

A: Oracle offers three types of partitions:

*

*Range

*Hash

*List

You can use any of them.
Selection of partitioning type depends on the data stored in a table and values of partitioned column (columns). If the number of distinct values in a column (columns) is limited and known, then LIST type would be a better choice.
As to your case, I think HASH partition fits the most.
Here's an example of how you can partition your X table:
CREATE TABLE X
(
Username Varchar2(10 Char),
Import_date Date
) PARTITION BY HASH(Username) PARTITIONS 16; -- 16 is the number of partitions.

You can find more about partitioning in official Oracle documentation.


text:
Q: How to get Output of a Command Prompt Window line by line in Visual Basic? I am trying to get a command line output line by line till the end of the output but I am not able to do so. I am using it in my Form and this code executes on click of a button.
Can you tell me whats wrong with my code?
Dim proc As ProcessStartInfo = New ProcessStartInfo("cmd.exe")
    Dim pr As Process
    proc.CreateNoWindow = True
    proc.UseShellExecute = False
    proc.RedirectStandardInput = True
    proc.RedirectStandardOutput = True
    pr = Process.Start(proc)
    pr.StandardInput.WriteLine("cd C:\sdk\platform-tools\")
    pr.StandardInput.WriteLine("adb help")
    Dim helpArray(20) as String
    For i as Integer 1 To 7
    helpArray(i) = pr.StandardOutput.ReadLine()
    Next
    pr.StandardOutput.Close()

The program stops responding when this code is executed.

A: I've done some research. adb help writes output into STDERR. So you need something like:
    Dim proc As ProcessStartInfo = New ProcessStartInfo("cmd.exe")
    Dim pr As Process
    proc.CreateNoWindow = True
    proc.UseShellExecute = False
    proc.RedirectStandardInput = True
    proc.RedirectStandardOutput = True
    pr = Process.Start(proc)
    pr.StandardInput.WriteLine("C:\sdk\platform-tools")
    pr.StandardInput.WriteLine("adb help 2>&1")
    pr.StandardInput.Close()
    Console.WriteLine(pr.StandardOutput.ReadToEnd())
    pr.StandardOutput.Close()

to catch it.
You need no 2>&1 if you call ipconfig, for example.

A: Do not interate over the output and do not read it! Normally you don't know how long the output (same goes for error output too) would be, so you need to prepare for an unknown length. Since you are telling the Process class, that you want to handle the standard output and the standard error by yourself, you also need to bind to the events, in this case:

*

*OutputDataReceived

*ErrorDataReceived

or to block the current process and read the complete output at once like @Dmitry Kurilo does in his answer. I find the first approach better because I do not need to wait for the process to end to see it's output. The MSDN documentation of the ProcessStartInfo.RedirectstandardError property gives a good explanation of the different possibilities with a lot of examples.
If you want to take a specific line, there are a lot of possibilities. One would be to store each output (line) in the delegate and use it later, using a List(Of String) and output the specific line when the process is done (= all output lines are present).
A possible solution could look like this:
' store error output lines
dim lines = new List(of String)

dim executable = "c:\temp\android\sdk\platform-tools\adb.exe"
dim arguments = " help"
dim process = new Process()
process.StartInfo = createStartInfo(executable, arguments)
process.EnableRaisingEvents = true
addhandler process.Exited, Sub (ByVal sender As Object, ByVal e As System.EventArgs)
    Console.WriteLine(process.ExitTime)
    Console.WriteLine(". Processing done.")
    ' output line n when output is ready (= all lines are present)
    Console.WriteLine(lines(4))
end sub
' catch standard output
addhandler process.OutputDataReceived, Sub (ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
        if (not String.IsNullOrEmpty(e.Data))
            Console.WriteLine(String.Format("{0}> {1}", DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") ,e.Data))
        end if
end sub
' catch errors
addhandler process.ErrorDataReceived, Sub (ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
    'Console.WriteLine(String.Format("! {0}", e.Data))
    ' add every output line to the list of strings
    lines.Add(e.Data)
end sub
' start process
dim result = process.Start()
' and wait for output
process.BeginOutputReadLine()
' and wait for errors :-)
process.BeginErrorReadLine()

private function createStartInfo(byval executable as String, byval arguments as String) as ProcessStartInfo
    dim processStartInfo = new ProcessStartInfo(executable, arguments)
    processStartInfo.WorkingDirectory = Path.GetDirectoryName(executable)
    ' we want to read standard output
    processStartInfo.RedirectStandardOutput = true
    ' we want to read the standard error
    processStartInfo.RedirectStandardError = true
    processStartInfo.UseShellExecute = false
    processStartInfo.ErrorDialog = false
    processStartInfo.CreateNoWindow = true
    return processStartInfo
end function

Now even if the adb writes to the error output, you will be able to see it. It will also be complete.
The output in this case looks like this:
14.10.2014 12:49:10
. Processing done.
 -e                            - directs command to the only running emulator.

Another possibility would be to put everything into one string and after the process has finished split the single string on line endings (CRLF \r\n) and you will gain the lines you want to filter.


text:
Q: Bing Ads API: How to get total spent amount for given account using CURL/SOAP As I want how much amount have spent on that account for ads by using the bing ads api. I need to integrate that code in PHP.
My question is to get the total spent on given account by using the bing ads api
If any one has any idea, please share with me. I have already search a lot but not get the what I have expected.


text:
Q: Upgrading SASS in a way that I can downgrade if needed? I'm using a very old version of SASS (3.1.15) in the Compass framework, and I want to upgrade to 3.4.3, which is the latest. I'm researching the process of upgrading, and after reading the SASS changelog, I'd like to be able to upgrade, then if I see a lot of errors and whatnot, revert back to the old version since I currently have actual development work to do in parallel with this research. I want to avoid being blocked due to legacy code being incompatible with new SASS, but I also want to see what issues an upgrade would bring, if any. Is there a way to do this?

A: I believe it would be as simple as this to upgrade:
$ sudo gem uninstall sass

$ sudo gem install sass --version 3.4.3

Then if you want to switch back to the old version:
$ sudo gem uninstall sass

$ sudo gem install sass --version 3.1.15

A: Both Bundler and RVM allow you to specify gems in their own way. Bundler is project-based, while RVM uses gemsets.


text:
Q: Transition function of the generalized nondeterministic finite automata Why does the transition function of a GNFA map from two states to a regular expression
$$
\delta: (Q \setminus \{q_{start}\}) \times (Q \setminus \{q_{accept}\}) \to R $$
instead of mapping from the current state and the regular expression to the next state?

A: It seems to be part of a normalization for the sake of convenience.
The traditional definition would work as well.
Citing from [HanWood2004] "The Generalization of Generalized Automata:
Expression Automata"

Definition 2. An expression  automaton A is  specified  by  a  tuple
  $(Q, \Sigma, \delta, s, f )$ , where $Q$ is a finite set of states, $\Sigma$ is an input
  alphabet, $\delta \subseteq Q \times R_\Sigma \times Q$ is a finite set of expression transitions,
  where $R_\Sigma$ is the set of all regular expressions over $\Sigma$,
  $s \in Q$ is the
  start state and $f \in Q$ is the final state. (Note that we need only have
  one final state.) We require that, for every pair $p$ and $q$ of states,
  there is exactly one expression transition $(p, \alpha, q ) \in δ$ , where $\alpha$ is a regular expression over $\Sigma$ .

So this early GNFA definition starts with the traditional specification of the transition function as relation from state $p$ via regular expression $\alpha$ to state $q$.
The next paragraph in that paper is (boldface added by me):

We can also use the functional notation $\delta : Q × Q \to R_\Sigma$ that gives the equivalent representation.
  An expression transition $( p, α, q )$
  gives $\delta( p, q )= \alpha$ . Note that $\delta$ contains
  exactly $|Q|^2$
  transitions, one transition for each pair of states, and whenever
  $( p,\emptyset,q )$ is in $\delta$, for some $p$ and $q$ in $Q$ , $A$ cannot move from $p$ to $q$ directly.

We note that this functional notation ($\delta$ is a function, not a relation) only allows for one expression transition from $p$ to $q$ via the regular expression $\alpha$ simply because functions are single-valued.
Thus the requirement at the end of definition 2 above can be dropped.
This convenience might explain the use of the functional notation.
To cite [Sipser2006] p. 70:

For convenience we require that GNFAs always have a special form that meets the following conditions.

*

*The start state has transition arrows going to every other state but    no arrows coming in form any other state.

*There is only a single accept state, and it has arrows coming in from every other state but no arrows going to any other state.
  Furthermore, the accept state is not the same as the start state.

*Except for the start and accept states, one arrow goes from every state to every other state and also from each state to itself.

References:
[HanWood2004] Yo-Sub Han and Derick Wood. "The Generalization of Generalized Automata: Expression Automata." In: 9th International Conference on Implementation and Application of Automata, CIAA 2004, Kingston, Canada, July 22–24, 2004, Revised Selected Papers, LNCS 3317, pp. 156–166.
[Sipser2006] Michael Sipser. 2006. Introduction to the Theory of Computation (2nd ed.). International Thomson Publishing.


text:
Q: Prove that x{n} is convergent So I'm currently studying for my midterms and I found the following question from my practice set which I'm unable to solve:
Prove that the following sequence $(x_{n})$ is convergent. Let
$$x_{n} = \frac{\sin 1}{2} + \frac{\sin 2}{2^2} + \frac{\sin 3}{2^3} + ... + \frac{\sin n}{2^n}$$
This is the first time I've seen such a sequence, how does one go about proving such questions? Do I need to first prove that the sequence is monotonic?

A: The series converges absolutely and thus it converges, since
$$\left|\frac{\sin k}{2^k}\right|\le\frac1{2^k}$$
Apply now the comparison test and we're done.


text:
Q: StackOverflowError in GUI code Any idea why my code is not connected to the frame?
Frame:
import javax.swing.*;
import java.awt.*;

public class CourseGUI extends JFrame {
    public CourseGUI()
    {
        super("CourseGUI Frame");

        JPanel topPane = new TopPanel();
        JPanel topPanel = new JPanel();
        topPanel.setBackground(java.awt.Color.WHITE);
        Dimension d = new Dimension(800,600);

        topPanel.setPreferredSize(d);

        this.setLayout(new BorderLayout());

        this.add(topPanel, BorderLayout.NORTH);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(800,600);

        this.setVisible(true);
    }
    public static void main(String[] args)
    {
        new CourseGUI();
    }

}

Panel:
import javax.swing.*;
import java.awt.*;

public class TopPanel extends JPanel {

    public TopPanel() {
        TopPanel tp = new TopPanel();
        tp.add(new JLabel("Course Info"));
        tp.setSize(300,300);

        tp.setVisible(true);
    }

}

With the panel, I tried to get it where it will be on the NORTH of the Frame, sadly, it's not working. I am a beginner programmer, well In SCHOOL this year to actually learn this, Our teacher taught us this 4 days ago and I can not be anymore confused. Tried to get help several times on this, even from professor, with no avail, someone please help me out and explain. Thanks in advance.

A: public class TopPanel extends JPanel {

    public TopPanel() {
        TopPanel tp = new TopPanel();
        tp.add(new JLabel("Course Info"));
        tp.setSize(300,300);

        tp.setVisible(true);
    }

}

By creating a TopPanel object inside its own constructor you are causing near infinite recursion:

*

*your TopPanel constructor will create a new TopPanel object

*

*whose constructor will create a new TopPanel object

*

*whose constructor will create a new TopPanel object

*

*whose constructor will create a new TopPanel object whose constructor ,....

*

*... etc -- recursion until your memory runs out. Don't do this.

Instead, don't do this:
public class TopPanel extends JPanel {

    public TopPanel() {
        // get rid of the recursion
        // TopPanel tp = new TopPanel();

        // add the label to the current TopPanel object, the "this"
        add(new JLabel("Course Info"));

        // setSize(300,300); // generally not a good idea

        // tp.setVisible(true); // not needed
    }

    // this is an overly simplified method. You may wish to calculate what the
    // preferred size should be, or simply don't set it and let the components
    // size themselves.
    public Dimension getPreferredSize() {
       return new Dimension(300, 300);
    }

}

Edit
Also, while not in error, this:
   JPanel topPane = new TopPanel();
   JPanel topPanel = new JPanel();

is very confusing since the two JPanel variables are close enough in name to confuse us, and more importantly to confuse your future self. You will want to use more logical and distinct variable names.


text:
Q: How do I resize text inside a table using media queries? I have this html
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/newcss.css"/>

...

      General Inquiries:
      Email@email.com

      Phone:
      #########

      Mailing address:
      123 Some St. 123 456

and this css
table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
}

td {
    padding: 0px 10px;
}

@media (max-width: 730){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

However, when I resize the window to below 730, the font size does not change on any of the elements listed in the media query. Any Ideas?

A: You simply forgot to add the unit in your max-width statement! Just add px after the number and it will work (click the "View Fullscreen" link below the snippet in order to be able to see the change):

table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
    background: #666; /* added this for the snippet so we can see the text at all */
}

td {
    padding: 0px 10px;
}

@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

      General Inquiries:
      Email@email.com

      Phone:
      #########

      Mailing address:
      123 Some St. 123 456

A: I think you forgot the px after the 730, so try
@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

By the way, if possible, don't insert text inside the  directly, add a  or a
 to wrap the text inside.

A: you have a mistake in your media query
@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}


text:
Q: Strong stability of the wave equation with time depending potential It is well known that the wave equation with frictional damping
$$\eqalign{
  & {y_{tt}} = {y_{xx}} - a(t,x){y_t}{\text{  }}{\text{,(t}}{\text{,x)}} \in {\text{ }}(0,\infty ) \times (0,1)  \cr
  & y(t,0) = y(t,1) = 0 \cr} $$
is strongly stable in the energy space $H^1_0 \times L^2$ norm in the case $a(t,x)=a(x)$ if it is non zero everywhere ($a$ is in $L^\infty$).
What can we say about the case $a(t,x)$ ?. Clearly, we can not use the spectral theory here because of the time dpending of $a$. Is there any references or suggestions ?
Thank you.


text:
Q: In Posix how is type dev_t getting used? What I am after is the meaning of such type and what interface can use it.
It is explained in Posix spec that dev_t is used for device IDs. However, what device id means for any object described by a path, which can be a file, a directy, a fifo or a physical device?
For example, calling stat() shall give you a struct including a member of such type; and you can stat any kinds of object in your file system. The device id should have different meanings for different file types then.

A: Actually, there are two dev_t-typed fields in struct stat:

*

*st_dev is the "[d]evice ID of device containing file", so if two files have the same st_dev, they're on the same filesystem.

*st_rdev is the device ID of the device denoted by a character or block special file, i.e. the files commonly encountered in /dev. It has no meaning for other types of files.

A: Within the kernel, the dev_t type who is defined in  is used to hold device numbers (major/minor). dev_t is a 32-bit quantity with 12 bits set aside for the major number and 20 for the minor number.

A: The only use of dev_t in the vast majority of programs (ones which are portable and not connected to a single OS) is to determine that two file names or file descriptors refer to the same underlying file. This is true if and only if the st_ino and st_dev entries for the two files' stat structures match one another.
Basically, st_dev tells which "device" (e.g. mounted partition, network share, etc.) the file resides on, and st_ino is a unique identifier of the file within the context of a single device.

A:
NOT an answer to the question, just update some info about st_dev

dev_t in current glibc (2.35) is 64-bit, with 32-bit major and minor numbers. glibc's default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major number and m is a hex digit of the minor number. This is backward compatible with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also backward compatible with the Linux kernel, which for some architectures uses 32-bit dev_t, encoded as mmmM MMmm.
One can use major(3) and minor(3) to decompose a dev_t:
$ cat main.c
#include <assert.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <stdio.h>

int main(void)
{
        struct stat buf;
        assert(0 == stat(".", &buf));

        printf("Major device ID: %d\n", major(buf.st_dev));
        printf("Minor device ID: %d\n", minor(buf.st_dev));
}

$ gccs main.c && ./a.out
Major device ID: 0
Minor device ID: 39


text:
Q: Linux/gcc and kill() I'm compiling a piece of C code that references/calls kill(pid,SIGNAL).
The code includes:
#include <sys/types.h>
#include <signal.h>

When I compile using gcc, I get:
"warning: implicit declaration of function 'kill' "
When I compile using g++, no complaints.
Why?


text:
Q: Change map language in GoogleMaps instance When I create instance of GoogleMaps from google_maps_flutter package, the Google Maps widget language of English (all the cities and street names are presented in English).
How do I change this language to Hebrew or any other language?

A: It's depending on the device language


text:
Q: Show query results for keys not found [MySQL] IF I am comparing 2 tables users [user_id, username] and user_comments [user_id, comment] where user_id are the keys in both tables. If I create a simple query to find the usernames for all users that made a comment. Is it possible if there is a user_id within user_comments that doesn't link to a user_id with users can we generate default response within the query where the unknown user_id is given a result of anonymous?
Basically I have 5 user_id 4 of which I can find in both users and user_comments however the last user_id. Can I create a query that will show the 5 results between the 2 columns however for the unknown user_id it gives a result of unknown?

A: I think you want a left join:
select coalesce(cast(uc.user_id as varchar(255)), 'unknown') as user_id,
       uc.comment
from user_comments uc left join
     users u
     on u.user_id = uc.user_id;

You do need to be careful about the type of user_id.  Assuming it is not a string, you need to cast it to be compatible with 'unknown'.  Otherwise, NULL is a fine non-matching value.


text:
Q: input element generates x and y coordinates of mouse click I have a need to submit page, and i have chosen to use  element to do so with and image that zooms a bit on hover.
Due to the weird nature of the question i found nothing of importance about this subject on google, as i could not formulate it in simple key words.
this is the php.( i know echo html elements is bad practice, but lets focus on problem at hand.)
echo '<form method="get">';
echo '<input type="hidden" name="v" value="30" />';
echo '
';
echo '
';
echo '
';
echo '<input type="image" name="submit" src="http://[img host]/image.jpg" border="0" alt="Submit"/>';
echo '
';
echo '
';
echo '
';
echo '</form>';

Now when i click on the image i pass in the GET value as it should , but it also passes the x,y location where the click occurred on the image like this
&submit.x=24&submit.y=34
how do i remove the extra two values so that  the URL looks nice and tidy like this
http://localhost/vlp/?v=5

instead of this
http://localhost/vlp/?v=5&submit.x=24&submit.y=34

If i change the <input> element to  element then there are no extra GET values, but i need to submit and reload the page with new values and have the image that zooms on hover.
Can this be done without Javascript?

A: I will just use <button> instead to fix the extra GET values in URL


text:
Q: ZF2 Dependency Injection - Injecting tables into classes Please note: This was ZF beta 1. I doubt this is the same for current release
I was just attempting to inject dependencies into some of my classes. I thought I had this down as I was already managing it with quite a few things like injecting database configurations, DB adapters and auth adapters into my UserMapper class.
I was trying to do the same with some other classes of mine and couldn't work out at all why it just wasn't working like my UserMapper class was. Now I see that the UserMapper class is being injected into a controller which has an alias set for it at the top of the config file.
So I guess without having it first injected by using a controller... how am I supposed to be injecting stuff into my Models? I'm using the standard ZF2 Skeleton by EvanDotPro
My Models are in:
Application\Model\
Application\Model\DbTable

My config currently looks something like:
<?php
return array(
'bootstrap_class' => 'Application\Bootstrap',
'layout'          => 'layouts/layout.phtml',
'di'              => array(
    'instance' => array(
        'alias' => array(
            'index'             => 'Application\Controller\IndexController',
            'view'              => 'Zend\View\PhpRenderer'
        ),

        'Zend\View\HelperLoader' => array(
            'parameters' => array(
                'map' => array(
                    'url' => 'Application\View\Helper\Url',
                ),
            ),
        ),

        'Zend\View\HelperBroker' => array(
            'parameters' => array(
                'loader' => 'Zend\View\HelperLoader',
            ),
        ),

        'Application\Controller\IndexController' => array(
            'parameters' => array(
                'userMapper' => 'Application\Model\UserMapper',
                'flashMessenger' => 'Zend\Mvc\Controller\Plugin\FlashMessenger'
            )
        ),

        'Application\Model\UserMapper' => array(
            'parameters' => array(
                'db' => 'Zend\Db\Adapter\PdoMysql',
                'authAdapter' => 'Zend\Authentication\Adapter\DbTable',
                'userTable' => 'Application\Model\DbTable\UserTable'
            )
        ),

        'Application\Model\DbTable\UserTable' => array(
            'parameters' => array(
                'config' => 'Zend\Db\Adapter\PdoMysql',
            )
        ),

            // Auth adapter

        'Zend\Authentication\Adapter\DbTable' => array(
            'parameters' => array(
                'zendDb' => 'Zend\Db\Adapter\PdoMysql',
                'tableName' => 'users',
                'identityColumn' => 'username',
                'credentialColumn' => 'password',
                'credentialTreatment' => 'MD5(CONCAT(?,"OSalTyr$"))'
            )
        ),

        // DB Adapter

        'Zend\Db\Adapter\PdoMysql' => array(
            'parameters' => array(
                'config' => array(
                    'host' => 'localhost',
                    'username' => 'root',
                    'password' => '',
                    'dbname' => 'blahblah',
                ),
            ),
        ),

        // View

        'Zend\View\PhpRenderer' => array(
            'parameters' => array(
                'resolver' => 'Zend\View\TemplatePathStack',
                'options'  => array(
                    'script_paths' => array(
                        'application' => __DIR__ . '/../views',
                    ),
                ),
                'broker' => 'Zend\View\HelperBroker',
            ),
        ),

    ),
),

'routes' => array(
    'default' => array(
        'type'    => 'Zend\Mvc\Router\Http\Regex',
        'options' => array(
            'regex'    => '/(?P<controller>[^/]+)(/(?P<action>[^/]+)?)?',
            'spec'     => '/%controller%/%action%',
            'defaults' => array(
                'controller' => 'error',
                'action'     => 'index',
            ),
        ),
    ),
    'home' => array(
        'type' => 'Zend\Mvc\Router\Http\Literal',
        'options' => array(
            'route'    => '/',
            'defaults' => array(
                'controller' => 'index',
                'action'     => 'index',
            ),
        ),
    ),
),
);

Thanks, Dominic

A: Ahah... I found out why this wasn't working.
Although the above config is correct and I'm defining what I want injecting into what... I wasn't actually using the injected instance of the object in question.
I thought when using 'new thingy();' that DI would magically pick up that it has dependencies and apply them when needed but this is not the case...
What I infact needed to do... was inject the thingy class into my UserMapper class like a chain and then use the injected instance instead of creating it a new instance of it without stuff injected into it.
Like:
RegisterController requires UserMapper so inject it in and use that instance
UserMapper requires Thingy so inject it in and use that instance


text:
Q: NSPopover Not Appearing I really wish I could be more specific, but unfortunately, I cannot. All appropriate objects are non-nil, and all appropriate method calls are going through (presumably) successfully, but my NSPopover just never shows up. None of the delegate methods get called, either.
// ivars
NSPopover *tagPopover;
NSViewController *tagPopoverViewController;

// in method to display popover
tagPopover = [[NSPopover alloc] init];
[tagPopover setBehavior: NSPopoverBehaviorApplicationDefined];
[tagPopover setDelegate: self];
tagPopoverViewController = [[MYViewController alloc] initWithNibName: @"MYViewController" bundle: nil];
[tagPopover setContentViewController: tagPopoverViewController];
[tagPopover setContentSize: tagPopoverViewController.view.frame.size];

[tagPopover showRelativeToRect: NSMakeRect(700, 400, 5, 5) // Screen coordinates
                        ofView: [[NSApp keyWindow] contentView]
                 preferredEdge: NSMinYEdge];

A: Turns out the coordinate system was wrong:
NSRect theRect = [[NSApp keyWindow] convertRectFromScreen: NSMakeRect(700, 400, 5, 5)];
[tagPopover showRelativeToRect: theRect // Window Coordinates
                        ofView: [[NSApp keyWindow] contentView]
                 preferredEdge: NSMinYEdge];

Needed to convert it to the window's coordinate system first.

A: I suspect that tagPopoverViewController.view.frame is NSZeroRect, since frames are set to that before they start to go onscreen (e.g. they are meaningless as they come out of xibs/storyboards). Are you sure you need that line? The documentation mentions that the contentSize is bound to the content-view's size anyway.


text:
Q: Error in Selenium webdriver on clicking on button I've error in Python Selenium. I'm trying to download all songs with Selenium, but there is some error. Here is code:
from selenium import webdriver
import time

driver = webdriver.Chrome('/home/tigran/Documents/chromedriver/chromedriver')

url = 'https://sefon.pro/genres/shanson/top/'

driver.get(url)
songs = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[3]/div/div[3]/div[2]/a')

for song in songs:
    song.click()
    time.sleep(5)
    driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/div[2]/div/div[3]/div[1]/a[2]').click()
    time.sleep(8)
    driver.get(url)
    time.sleep(5)

And here is error:
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    song.click()
  File "/home/tigran/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "/home/tigran/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "/home/tigran/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/tigran/.local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=90.0.4430.72)

Any ideas why error comes?

A: Before your loop try to add try:
Sometimes the document is not attached, so it gives an error

A: Here's link selenium while loop not working. You need to locate elements in loop.
Final code:
from selenium import webdriver
import time

driver = webdriver.Chrome('/home/tigran/Documents/chromedriver/chromedriver')

url = 'https://sefon.pro/genres/shanson/top/'

driver.get(url)
size = len(driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[3]/div/div[3]/div[2]/a'))

for i in range(0, size):
    songs = driver.find_elements_by_xpath('/html/body/div[2]/div[2]/div[1]/div[3]/div/div[3]/div[2]/a')
    songs[i].click()
    time.sleep(5)
    driver.find_element_by_xpath('/html/body/div[2]/div[2]/div[1]/div[1]/div[2]/div/div[3]/div[1]/a[2]').click()
    time.sleep(8)
    driver.execute_script("window.history.go(-1)")
    time.sleep(5)


text:
Q: where does ILDASM show the .JPG, .XML, .txt files apart from the assembly and type metadata Could anyone please guide me as to where does the ILDASM show the .JPG, .XML, .txt files (that are added to the project) apart from the assembly and type metadata
Regards


text: Q: How to add more containers I have been struggling to add more independent rows that have columns and have their own container. I have managed to build the first container which containers horizontal scrollable avatars


text:
Q: Different results between nslookup and Java's InetAddress getHostName I'm trying to write a simple java program that will return the dns names of ip addresses which I do using the following code:
InetAddress host = InetAddress.getByName(ip);
String dnsName = host.getHostName();

When a dns name is registered getHostName() returns this name and when there is no existent dns name the ip address is returned.
For many addresses the above code doesn't return any while the nslookup command returns.
For example, for the address 82.117.193.169 nslookup returns peer-AS31042.sbb.rs while getHostName() returns only the address. This doesn't happen for all the addresses but for a large number of cases.

A: Your computer may not be configured to use DNS by default, even if it is available on demand.
I would try
ping 82.117.193.169

and see whether it resolves the IP address into a hostname.

A: It is due to the "A" record check - Java wants that IP number you're looking up, was listed there. They call it "XXX" and I understand why:
private static String getHostFromNameService(InetAddress addr, boolean check) {
String host = null;
for (NameService nameService : nameServices) {
    try {
        // first lookup the hostname
        host = nameService.getHostByAddr(addr.getAddress());

        /* check to see if calling code is allowed to know
         * the hostname for this IP address, ie, connect to the host
         */
        if (check) {
            SecurityManager sec = System.getSecurityManager();
            if (sec != null) {
                sec.checkConnect(host, -1);
            }
        }

        /* now get all the IP addresses for this hostname,
         * and make sure one of them matches the original IP
         * address. We do this to try and prevent spoofing.
         */

        InetAddress[] arr = InetAddress.getAllByName0(host, check);
        boolean ok = false;

        if(arr != null) {
            for(int i = 0; !ok && i < arr.length; i++) {
                ok = addr.equals(arr[i]);
            }
        }

        //XXX: if it looks a spoof just return the address?
        if (!ok) {
            host = addr.getHostAddress();
            return host;
        }

        break;


text:
Q: How do I add month number to a hard coded column value in SQL? I have a hard coded value in my SQL database and I'd like to add the month number to the value.  Here's what it looks like now:
SELECT 'Campaign_Reviews' as [Campaign Name]

And what I would like is for the value to include the month number: i.e.
Select 'Campaign_Reviews_MONTH(GETDATE())' as [Campaign Name]

Is there any way to accomplish this?

A: I would do this as:
Select 'Campaign_Reviews_' + right('00' + cast(month(GETDATE()) as varchar(255)), 2) as [Campaign Name]

This zero pads the number, so you get "01" rather than just "1".  The values will sort correctly.

A: If 2012+, you can use concat()
Example
Select concat('Campaign_Reviews_',month(GetDate())) as [Campaign Name]

A: You just need to concatenate that value:
SELECT 'Campaign_Reviews_' + CAST(DATEPART(MONTH,GETDATE()) AS VARCHAR(2)) [Campaign Name];


text:
Q: Octave: Save a table inside a table I am trying to save an array inside a table and i get this error: nonconformant arguments (op1 is 1x1, op2 is 1x4)
I have a function running which produces an array of 1 row and 4 columns. For example:
W =   0.32574   0.21354   0.10639   0.35433
What I am trying to do is save all the results that are being generated from the loops. What I am doing is this (for N=4):
for m=1:15
  W(m)=weights(N) # N=the number of columns it is going to generate
endfor

My function looks like this: (e.g criteria=4)
function W=weights(criteria)

W=zeros(1,criteria); #fill the table with zeros
x=rand(1,criteria); #Random numbers are generated, range=[0,1]
sumx=sum(x); #Sum of all random numbers
factorsumx=1/sumx; #calculate the factor
W=x.*factorsumx; #Random numbers are multiplied with 1/sumx
finalsum=sum(W); #FinalSum is to confirm that the sum of weights is always equal to 1

endfunction

A: as op2 is 1x4 you need op1 of same size
N=4;
w=zeros(15,N);

for m=1:15
  W(m,1:N)=weights(N) # N=the number of columns it is going to generate
endfor


text:
Q: Infinite loop when loading Linked List from Text File and printing I'm having trouble reading from a file into a linked list. I have a (probably extremely inefficient way) of reading the file and loading each node into the linked list, however if I read and attempt to print more than 1 line then I get an infinite loop when printing.
Load Code
void readFile()
{
    string text;
    string temp; // Added this line
    node* newNode = new node;

    ifstream file;
    file.open("example.txt");

    for (int i = 0; i < 1; i++)
    {
        getline(file, temp);
        text = temp;

        string input = text;
        istringstream ss(input);
        string token;

        int counter = 0;

        while (getline(ss, token, ','))
        {
            cout << token << '\n';
            newNode->rented = token;
            counter++;

            if (counter == 0)
            {
                newNode->rented = token;
            }
            else if (counter == 1)
            {
                std::istringstream ss(token);
                ss >> newNode->maxload;
            }
            else if (counter == 2)
            {
                std::istringstream ss(token);
                ss >> newNode->passengers;
            }
            else if (counter == 3)
            {
                std::istringstream ss(token);
                ss >> newNode->doors;
            }
            else if (counter == 4)
            {
                newNode->registration = token;
            }
            else if (counter == 5)
            {
                std::istringstream ss(token);
                ss >> newNode->engine;
            }
            else if (counter == 6)
            {
                newNode->model = token;
            }
            else if (counter == 7)
            {
                newNode->make = token;
            }
        }
        system("pause");
        list.insertNode(newNode);
    }
    file.close();
}

Insert Node
void linkedList::insertNode(node* newNode)
{
    newNode->nextNode = head;
    head = newNode;
}

Print Code
void linkedList::displayList()
{

    node* thisNode = head;

    if (head == NULL)
    {
        cout << "The list is empty\n";
        return;
    }
    else
        cout << "---------------------------------------------------------\n";
        cout << "\tMake\tReg Number\tRented\n";
        cout << "---------------------------------------------------------\n";
        cout << "\t";

    do
    {
        cout << setw(8) << left << thisNode->make;
        cout << setw(16) << left << thisNode->registration;
        cout << setw(10) << left << thisNode->rented;
        cout << "\n\t";
        thisNode = thisNode->nextNode;

    } while (thisNode != NULL);
    {
        cout << "\n\n";
    }
}

Text File
car,Ferarri,12.0,aa,3,1,0,true
car,Mercedes,12.0,bb,5,4,0,false
car,Ford,1.6,cc,5,4,0,false

If I set the for loop in the load code to just 1 iteration it outputs the correct display of:
0 aa true

However if I set the for loop to iterate more than 1 time the print code will infinitely print whatever the last line read was (ignoring all lines before it)?
0 bb false
0 bb false
0 bb false
...

Can anyone see any reason why this is doing this?

A: You are just allocating one node. Move the following line to the start of the for loop:
node* newNode = new node;

Otherwise you overwrite everything in the node everytime and then add it repeatedly to your list, creating a circular reference.


text:
Q: Ubuntu server not responding after upgrade I upgraded from Ubuntu 8.x to the latest version via the command-line. The installation appeared to work fine, no errors, but now I can't log on to the server through SSH and my website no longer resolves. I just get timeout errors.
I do have access to a very basic web form that allows me to execute commands on the server, but it is limited. I also have access to a process manager.
I attempted to start / stop sshd and also rebooted the server. When attempting to update through this web based console I get the following errors:
Err http://archive.ubuntu.com lucid Release.gpg
Temporary failure resolving 'archive.ubuntu.com'
Err archive.ubuntu.com lucid-updates Release.gpg
Temporary failure resolving 'archive.ubuntu.com'
Err archive.ubuntu.com lucid-security Release.gpg
Temporary failure resolving 'archive.ubuntu.com'
Reading package lists...

Any help would be appreciated.

A: Try this:
echo nameserver 8.8.8.8 > /etc/resolv.conf

Then restart SSH again.  Your inability to connect to SSH might be caused by it trying to do a reverse lookup on your IP when you connect.  If you don't have a valid DNS server set, this would take a very long time to timeout.
If not, check your logfiles:
tail /var/log/messages; tail /var/log/secure


text:
Q: add column of listed keywords(strings) based on text column If i have a dataframe with the following column:
df$text <- c("This string is not that long", "This string is a bit longer but still not that long", "This one just helps with the example")

and strings like so:
keywords <- c("not that long", "This string", "example", "helps")

I am trying to add a column to my dataframe with a list of the keywords that exist in the text for each row:
df$keywords:
1 c("This string","not that long")
2 c("This string","not that long")
3 c("helps","example")

Though i'm unsure how to 1) extract the matching words from the text column and 2) how to then list them matching words in each row in the new column

A: Maybe like this:
df = data.frame(text=c("This string is not that long", "This string is a bit longer but still not that long", "This one just helps with the example"))
keywords <- c("not that long", "This string", "example", "helps")

df$keywords = lapply(df$text, function(x) {keywords[sapply(keywords,grepl,x)]})

Output:
                                                 text                   keywords
1                        This string is not that long not that long, This string
2 This string is a bit longer but still not that long not that long, This string
3                This one just helps with the example             example, helps

The outer lapply loops over df$text, and the inner lapply checks for each element of keywords if it is in the element of df$text. So a slightly longer but perhaps easier to read equivalent would be:
df$keywords = lapply(df$text, function(x) {keywords[sapply(keywords, function(y){grepl(y,x)})]})

Hope this helps!

A: We can extract with str_extract from stringr
library(stringr)
df$keywords <- str_extract_all(df$text, paste(keywords, collapse = "|"))
df
#                                                text                   keywords
#1                        This string is not that long This string, not that long
#2 This string is a bit longer but still not that long This string, not that long
#3                This one just helps with the example             helps, example

Or in a chain
library(dplyr)
df %>%
   mutate(keywords = str_extract_all(text, paste(keywords, collapse = "|")))


text:
Q: Freezing intermediate layers in ALBERT I want to freeze intermediate sub-layers in ALBERT. Unlike BERT,
ALBERT's encoder looks like this
(encoder): AlbertTransformer(
      (embedding_hidden_mapping_in): Linear(in_features=128, out_features=768, bias=True)
      (albert_layer_groups): ModuleList(
        (0): AlbertLayerGroup(
          (albert_layers): ModuleList(
            (0): AlbertLayer(
              (full_layer_layer_norm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
              (attention): AlbertAttention(
                (query): Linear(in_features=768, out_features=768, bias=True)
                (key): Linear(in_features=768, out_features=768, bias=True)
                (value): Linear(in_features=768, out_features=768, bias=True)
                (dropout): Dropout(p=0, inplace=False)
                (dense): Linear(in_features=768, out_features=768, bias=True)
                (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
              )
              (ffn): Linear(in_features=768, out_features=3072, bias=True)
              (ffn_output): Linear(in_features=3072, out_features=768, bias=True)
            )
          )
        )
      )
    )

So inside the modulelist, we can easily choose which sublayers to freeze. But here, we have one module. The documentation says that there are 12 repeating layers. Is there any good way to freeze intermediate layers in ALBERT?

A: By default, the config sets inner_group_num to 1. It can be modified by the user to obtain required number of modules in ModuleList.
config = AutoConfig.from_pretrained(
    model_args.config_name if model_args.config_name else model_args.model_name_or_path,
    num_labels=num_labels,
    finetuning_task=data_args.task_name,
    cache_dir=model_args.cache_dir,
)

config.inner_group_num = 6

model = AutoModelForSequenceClassification.from_pretrained(
    model_args.model_name_or_path,
    config=config,
    cache_dir=model_args.cache_dir,
)


text:
Q: Google Maps context menu - Pearman code I am trying to implement a pop-up context menu in GoogleMaps.  The best of the Google search results I found was this 2012 StackOverflow post
Google Map V3 context menu
(of four examples given at top, two URLs no longer work - but some additional options are given in later comments)
I investigated four code options mentioned there, deciding that the Pearman code, as referenced in
http://googlemapsmania.blogspot.com/2012/04/create-google-maps-context-menu.html
would be best for my case.  However, when I implemented it I discovered a problem - which I then determined also occurs in his original example
http://code.martinpearman.co.uk/googlemapsapi/contextmenu/1.0/examples/advanced_example.htm
when one knows what to look for. (This also occurs for a later fork of the original code that I found).  All works as expected so long as the map is not moved, with the pop-up menu position being altered by the location of the mouse click such that the entire menu is always visible within the map area.  BUT if the map is moved, then the popup can be cutoff, per the bottom left corner in the example below (in which I first moved Norwich into the corner, then right-clicked on it)

Looking into the code, I see it uses GoogleMaps Overlay.  Reading up a bit on that, I get the impression that "something" needs to be done/updated when an overlay is moved.  But I am beyond my knowledge level and ability to fully understand what I am reading, so am hoping to find some help/insight here.  Hoping to figure out a general solution to also help others who implement Pearman's code.

A: SOLUTION FOUND
Lots of searching and testing and false turns while working on this, but finally got a solution - of course it seems "obvious" after one finally sorts out what is going on.
Short answer: values returned by GM Overlay "fromLatLngToDivPixel" function represent the "GM DIV" and hence location on the GM map whereas "fromLatLngToContainerDiv" values represent the "map_canvas DIV" and hence the observed map boundary.  So the actual placing of the menu must be based upon values returned by "fromLatLngToDivPixel" but testing its visibility within the map_canvas DIV must be based upon values from "fromLatLngToContainerDiv".  Sometimes values returned by the different functions are identical but sometimes not - the former seems to occur when the map is static whereas the latter can occur when the map is moved/dragged.
Long answer:
The relevant part of the original Pearman code is, where "left" and "top" are later used in CSS styling of the menu, to set its position:
var mousePosition=this.getProjection().fromLatLngToDivPixel(this.position_);
var left=mousePosition.x;
var top=mousePosition.y;
if(mousePosition.x>mapSize.width-menuSize.width-this.pixelOffset.x){
  left=left-menuSize.width-this.pixelOffset.x;
} else {
  left+=this.pixelOffset.x;
}
if(mousePosition.y>mapSize.height-menuSize.height-this.pixelOffset.y){
  top=top-menuSize.height-this.pixelOffset.y;
} else{
 top+=this.pixelOffset.y;
}

I found the following helpful comments regarding "fromLatLngToContainerPixel" in How to call fromLatLngToDivPixel in Google Maps API V3? , which led me to my fix

... This works perfectly for me initially, but if I pan the map the
  pixel positions are not updated.  ...
  ... using fromLatLngToContainerPixel instead of fromLatLngToDivPixel
  solved my issue with pixel positions not updating after panning the map.
  Roger Ertesvag

Looking at values returned by "fromLatLngToDivPixel", they were sometimes not valid for the map_canvas DIV containing the map (i.e. were sometime larger than the size of that DIV), whereas "fromLatLngToContainerPixel" DID produce apparently valid values.  But the seemingly obvious "fix" of simply replacing "fromLatLngToDivPixel" with "fromLatLngToContainerPixel" often produced much weirdness, with the menu not appearing.
I now gather that the "mousePosition" values returned by "fromLatLngToDivPixel" are valid for the location within the "GoogleMaps DIV" (still unclear exactly what that is) but are not appropriate for the map_canvas DIV.  Thus my "fix" was to use values from "fromLatLngToDivPixel" for the "base" menu location but use values from "fromLatLngToContainerPixel" to test and alter its display within the map_canvas DIV.
Specifically, instead of the original I'm now using the following code and it is working successfully.
var mousePosition=this.getProjection().fromLatLngToDivPixel(this.position_);
var left=mousePosition.x;
var top=mousePosition.y;
// my fix below, adjusting location based on nearness of map area boundary
var containerPosition=this.getProjection().fromLatLngToContainerPixel(this.position_);
if(containerPosition.x>mapSize.width-menuSize.width-this.pixelOffset.x){
  left=left-menuSize.width-this.pixelOffset.x;
} else {
  left+=this.pixelOffset.x;
}
if(containerPosition.y>mapSize.height-menuSize.height-this.pixelOffset.y){
  top=top-menuSize.height-this.pixelOffset.y;
} else {
  top+=this.pixelOffset.y;
}

A: PS: as a note to someone wanting to use the Pearman code for their context menus, I am actually using code (now altered) from a fork based upon it
https://github.com/knezmilos13/google-maps-api-contextmenu
The fork adds the ability to have global class names for the menu items, but that is not why I'm using it.  For me, the original Pearman code sometimes produced a "sticky" menu, i.e.  the menu remained displayed after it should be closed, especially on first usage of a menu, but that behaviour did not occur using the forked code.  Don't know the reason for the difference, did not investigate further.


text:
Q: How to close ffplay when video is over? To get the duration time with ffprobe.
ffprobe test.mp3 2>&1 | awk -F'[ ,]' '/Duration/{print $4}'
00:03:51.05

To set duration time with -t argument.
ffplay  -t '231'  test.mp3

The ffplay command can't stop when test.mp3 is over.
How to close ffplay when video is over?

A: Add -autoexit i.e.
ffplay -autoexit -t '231'  test.mp3


text:
Q: Why are some variables not defined? This is what I have to do:
Look up and print the student GPA
Add a new student to the class
Change the GPA of a student
Change the expected grade of a student
Print the data of all the students in a tabular format
Quit the program
    import student
    import pickle

    lookup = 1
    change = 2
    add = 3
    delete = 4
    QUIT = 0
    FILENAME = 'student.dat'

    def main():

        students_info = load_students()
        choice = 0
        load_students()
        #add(students_info)
        change_grade(students_info)
        change_GPA(students_info)
        #get_menu_choice()
        look_up(students_info)
        while choice != QUIT:
            choice = get_menu_choice()
            if choice == lookup:
                look_up(students_info)
            elif choice == add:
                add(students_info)
            elif choice == change:
                change(students_info)
            elif choice == delete:
                delete(students_info)
        save_students(students_info)

    def load_students():
        try:
            input_file = open(FILENAME, 'rb')
            students_dict = pickle.load(input_file)
            input_file.close()
        except IOError:
            students_dict = {}
        print(students_dict)
        return students_dict

    def get_menu_choice():
        print()
        print('Menu')
        print("-------------------")
        print('1. Look up ID')
        print('2.....')
        choice = int(input("Enter your choice:"))

        return choice

    def look_up(students_info):
        ID = input('Enter ID:')
        print(student_info.get(ID, "Not found!"))
    ##    try:
    ##        print(students_info[ID])
    ##    except KeyError:
    ##        print("Not found!")

    def change_GPA(students_info):
        ID = input("ID:")
        if ID in students_info:
            GPA= float(input("New GPA:"))
            students=student.Student(ID,GPA,grade,work)
            students_info[ID] = students
            print ("This",students_info[ID])
        else:
            print("Not found!")
    def change_grade(students_info):
        ID = input("ID:")
        if ID in students_info:
            New_grade = input("Enter new grade:")
            students=student.Student(ID,GPA,grade,work)
            students_info[ID] = students
            #new_grade = students_info[name]
        else:
            print("Not found!")

    def add(students_info):
        name = input("Enter the student name:")
        ID= input("Enter student's ID:")
        GPA= float(input("Enter GPA:"))
        grade= input("Enter student's expected grade:")
        work = input("Does the student work part time or full time?")
        students=student.Student(name,ID,GPA,grade,work)
        print(students_info['ID'])
    def save_students(students_info):
        output_file = open(FILENAME, 'wb')
        pickle.dump(students_info, output_file)
        output_file.close()
    main()

Whenever I tried to change the GPA or grade it's not defined. How could I change one value from the dictionary studens_info?

A: As gus42 has commented, the errors you are getting are from the lines:
students=student.Student(ID,GPA,grade,work)

You've not defined grade or work in either of the places you do this (nor GPA in change_grade), so it should not be surprising that you're getting an error.
I think there are two ways to fix the issue:
The simplest way is to change your logic from creating a new Student object to modifying the one that already exists. I don't know exactly what the attribute names are in your Student class, but here's a reasonable guess at a solution:
def change_GPA(students_info):
    ID = input("ID:")
    if ID in students_info:
        GPA= float(input("New GPA:"))
        students_info[ID].GPA = GPA  # assign new GPA to old student object

    else:
        print("Not found!")

def change_grade(students_info):
    ID = input("ID:")
    if ID in students_info:
        grade = input("Enter new grade:")
        students_info[ID].grade = grade  # assign new grade to existing student object
    else:
        print("Not found!")

The other option is to replace the existing Student object with a new one with some different values. This is close to what your current code, but it only really makes sense if your Student objects are immutable (perhaps because you made the type with namedtuple?). To make it work (where your current code does not), you'll have to load the old values from the old Student object before making the new object:
def change_GPA(students_info):
    ID = input("ID:")
    if ID in students_info:
        new_GPA = float(input("New GPA:"))
        old_grade = students_info[ID].grade  # load old values
        old_work = students_info[ID].work
        new_student = students.Student(ID, new_GPA, old_grade, old_work)
        students_info[ID] = new_student  # replace the old student with a new object
    else:
        print("Not found!")

def change_grade(students_info):
    ID = input("ID:")
    if ID in students_info:
        new_grade = input("Enter new grade:")
        old_GPA = students_info[ID].GPA
        old_work = students_info[ID].work
        new_student = students.Student(ID, old_GPA, new_grade, old_work)
        students_info[ID] = new_student
    else:
        print("Not found!")


text:
Q: How to add custom script to the particular Product Category page I am trying to add the script to the particular Product Category page, but the code is not adding it to the category.
Page (working):
function wpb_hook_faq_javascript() {
  if (is_single ('8') || is_page ('8')) {
    ?>
    <script type="application/ld+json">

    </script>

 <?php }
}
add_action('wp_footer', 'wpb_hook_faq_javascript');

Product Category (not working):
function wpb_hook_faqtocategory_javascript() {
  if ( in_category( 'category-name' )) {
    ?>
    <script type="application/ld+json">

    </script>

 <?php }
}
add_action('wp_footer', 'wpb_hook_faqtocategory_javascript');

But the above code is not working.
Product Category URL:
wp-admin/term.php?taxonomy=product_cat&tag_ID=9&post_type=product

A: in_category() should be used inside The Loop (unless if you pass a post ID as the second parameter like in_category( 1, 1 )) and only for the default/built-in category taxonomy.
For custom taxonomies like the product_cat in your case, you should use has_term(); however, if you're checking if the current request/page is a taxonomy archive page, you should instead use is_tax():
function wpb_hook_faqtocategory_javascript() {
    if ( is_tax( 'product_cat', 9 ) ) { // 9 is the term ID, but you can use the slug/name
        ?>
        <script type="application/ld+json">

        </script>
        <?php
    }
}

Or in WooCommerce (you're using WooCommerce, right?), you can use is_product_category(), but you'll need to know the term slug:
function wpb_hook_faqtocategory_javascript() {
    if ( is_product_category( 'term-slug' ) ) {
        // ... your code here ...
    }
}


text:
Q: batch if loop not able to execute iam trying to put if loops in batch script but not getting desired result, please look into code ans suggest where iam wrong in if loop
 IF  %banned% == 1  echo "vvvvv" it not comparing properly
even 1==1 and 1==0 is same for batch script?
    call E:\utility\batfiles\DBAEnvProd.cmd
set dbname=UMRdb

set proc=UMRdb.[dbo].[maintenancemode]
call %osqlExeLocation% -E -d%dbname% -S%svr% -w%w% -b -Q"exec %proc%" -o%pathout%%Maintmode.txt

@echo on
set "usrname=Y"
set "banfile=E:\utility\sysout\Maintmode.txt"
find /i "%usrname%" "%banfile%" >nul 2>&1&&set /a banned=1 || set /a banned=0
echo %banned%
echo comparing maintenance

IF  %banned% == 1  echo "vvvvv"
(

here banned is 1 then i dont want to execute rest of code it shd
go to endgood
)
else
normal code should be executed
@echo on
REM ********************************************************************************
REM JOB: TCMP_DBA_M_MNT_UMR_ESSENTIAL
REM
REM ********************************************************************************

set job=TCMP_DBA_M_MNT_UMR_ESSENTIAL
set RetCode=0
time /T & date /T

erase %pathout%%job%*.suc > nul
erase %patherr%%job%*.err > nul

REM ********************************************************************************
REM to display date and time
for /F "tokens=1-3 delims=:. " %%A in ('time/T') do set var=%%A%%B%%C%
set timestamp=%date:~4,2%%date:~7,2%%date:~10,4%
set timestamp1=%timestamp%%var%
REM
REM ********************************************************************************

:main

echo --- DB Growth Info
set proc=UMRdb.[dbo].[spCollectDBSpaceInfo]
call %osqlExeLocation% -E -d%dbname% -S%svr% -w%w% -b -Q"exec %proc%" -o%pathout%%job%_spCollectDBSpaceInfo.txt
if errorlevel 1 (
    set RetCode=1
    goto endbad
)

echo --- Cleanup of output files older than 30 days in sysout folder
call forfiles -p E:\utility\sysout /D -30 /M *.txt /C "cmd /c del @file"

:ENDGOOD
set RetCode=0
ECHO SUCCESS!!! %svr% %job% %proc%
echo %ErrMsg% > %pathout%%job%.SUC

GOTO END

:ENDBAD
set RetCode=1
ECHO ERROR!!! %svr% %job% %proc%
echo  SEE %pathout%%job%_%proc%.txt FOR ERRORS > %patherr%%job%.ERR

:END
time /T & date /T
echo %RetCode%

%pathexe%cc.exe %RetCode%

REM EXIT

A: this is problematic
IF  %banned% == 1  echo "vvvvv"

if == performs a string comparision and i'm seeing lots of spaces. if %banned% is 1 here you are comparing " 1" == "1 ". As you set/a banned=1, it would be better do a numeric comparision
IF %banned% EQU 1

or quoted string comparision
If "%banned%" == "1"


text:
Q: Can we here derive general expressions for Mean Squared Error and $R^2$? Suppose we have the linear relationship
$$ y= \beta _1 X_1+\beta _2 X_2+\beta _3 X_3 + \cdots + \beta _n X_n $$
and we have an estimate of  $y$ given by
$$ \hat{y}= \hat{\beta }_1 X_1+\hat{\beta }_2 X_2+\hat{\beta }_3 X_3 + \cdots + \hat{\beta }_n X_n $$
where  $X_1 ... X_n$ are all standard normal distributions.
Can we derive exact formulas for the mean squared error of $\hat{y}$ and for $R^2$, and is there an exact relationship between the two?


text:
Q: Bootstrap Collapsed menu dissappears when click The menu drop downs for a brief second and then goes back up. Can anyone please help in fixing it? If someone could suggest me a code to make it work then that would be even better.
This is the code:

       RESOLUTION ACCOUNTING

HOME

ABOUT US

             SERVICES

Bookkeeping

Accounting

CFO Oversight

Equity Raises

TESTIMONIALS

CONTACT US

A: You are using Bootstrap version 2.3.2 CSS with Bootstrap version 3.3.6 Javascript. They are not compatible with each other.  You need to use the same version of Bootstrap for both CSS and Javascript to get the correct behavior.
(It would have been helpful if you had included the URL to the site you need help with.)

A: Here you go with a solution https://jsfiddle.net/wqy986bt/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

       RESOLUTION ACCOUNTING

HOME

ABOUT US

             SERVICES

Bookkeeping

Accounting

CFO Oversight

Equity Raises

TESTIMONIALS

CONTACT US

There are few things:

*

*You have an extra closing div at the end of your code

*Check the ordering of the library file

*

*bootstrap CSS

*jQuery

*bootstrap JS

I've used bootstrap v3.3.7 and jQuery v2.1.1 (in snippet) and jQuery v2.2.4 (in jsfiddle)
Hope this will help you.


text:
Q: Is there something method like indexof() in jquery? Or how to do that? Look at the code below:
$(".head img").hover(function(){
    var id = $(this).attr('id');
    $(this).attr("src","images/"+id+"_hover.gif");
},function(){
    var id = $(this).attr('id');
    $(this).attr("src","images/"+id+".gif");
})

If I do not use the "id",just use "this.indexof()" something like this.
the code below is wrong, but i want you to know what i mean:
$(".head .fl_r img").hover(function(){
    $(this).attr("src","images/"+this.indexof(in array())+"_hover.gif");
},function(){
    $(this).attr("src","images/"+this.indexof(in array())+".gif");
})

How can i do that in jquery?

A: Yes, it's the .index() method:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Use it as $(this).attr("src","images/" + $(this).index() + "_hover.gif");

A: I'd look into the jQuery .each method, as it provides an index.
$(".head img").each(function(index, element) {
    element.hover(
        function() {
            $(this).attr("src","images/"+index+"_hover.gif");
        },
        function() {
            $(this).attr("src","images/"+index+".gif");
        }
    );
});

A: indexOf() is available for string objects.
If you want to use it on a attr via jquery, you should try this:
$(this).attr("src").indexOf("needle");

More info:
JavaScript indexOf()
jQuery attr()


text:
Q: inverse image of function and cardinality of resulting set Given the set of natural numbers f : $N^{2}$->$N$ and the set of all ordered pairs (a, b) where a and b are natural numbers.
Given a function defined as: f((a,b)) = a + b
find inverse image and cardinality of resulting sets:
part 1: |$f^{-1}$(8)|
part 2: |$f^{-1}$({0,1,2,...,8})|
So for example we have:
$f^{-1}$(3) = {(0,3),(1,2)}
|$f^{-1}$(3)| = 2
Here was my attempt, and it was marked wrong with no feedback.  Any help is appreciated. I wonder if I'm not understanding what is being asked.
Part 1 answer:
$f^{-1}$(8) = {(0,8), (1,7), (2,6), (3,5), (4,4)}
|$f^{-1}$(8)| = 5
Part 2 answer:
|$f^{-1}$({0, 1, 2, …, 8})| = 25
Shown by the following steps:
$f^{-1}$(0) = {(0,0)}
$f^{-1}$(1) = {(0,1)}
$f^{-1}$(2) = {(0,2), (1,1)}
$f^{-1}$(3) = {(0,3), (1,2)}
$f^{-1}$(4) = {(0,4), (1,3), (2,2)}
$f^{-1}$(5) = {(0,5), (1,4), (2,3)}
$f^{-1}$(6) = {(0,6), (1,5), (2,4), (3,3)}
$f^{-1}$(7) = {(0,7), (1,6), (2,5), (3,4)}
$f^{-1}$(8) = {(0,8), (1,7), (2,6), (3,5), (4,4)}
The cardinalities of $f^{-1}$(0) through $f^{-1}$(8) summed are: 1+1+2+2+3+3+4+4+5 = 25.

A: When you found the inverse images, you missed those ordered pairs $(a, b) \in \mathbb{N} \times \mathbb{N}$ in which $a > b$.
For instance, $f^{-1}(3) = \{(0, 3), (1, 2), (2, 1), (3, 0)\}$, so $|f^{-1}(3)| = 4$.
More generally, $|f^{-1}(k)| = k + 1$ since $a$ can vary from $0$ to $k$ over the nonnegative integers.  Thus, the number of elements in $f^{-1}(\{0, 1, 2, 3, 4, 5, 6, 7, 8\})$ is
$$\sum_{k = 0}^{8} |f^{-1}(k)| = \sum_{k = 0}^{8} (k + 1) = \sum_{j = 1}^{9} j = \frac{9 \cdot 10}{2} = 45$$
where I have used the formula that
$$\sum_{j = 1}^{n} j = \frac{n(n + 1)}{2}$$
in the preceding calculation.


text:
Q: getBoolean(String str) and valueOf(String str) of Boolean class gives different output I am surprised to know that getBoolean() and valueOf() method returns different results for the same input string.
I have tried to pass the "true" to both the methods. But getBoolean() gives me false output whereas valueOf() gives me right output that is true. Why?

A:                                      The API-documentation is your friend.

*

*Boolean.getBoolean probably doesn't do what you think it does:

Returns true if and only if the system property named by the argument exists and is equal to the string "true".

*

*Boolean.valueOf is probably what you're looking for:

The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

A: The javadoc of getBoolean clearly state that it searches the System Properties. The value that you pass to it is the name of the system property, not a "true" or "false" string.
E.g., `var b = Boolean.getBoolean("some.property");

A: Boolean.getBoolean must be the worst placed method in java. One of the big WTF.
Why wasn't it placed in System or Properties or whatever?
So to answer your question - yes, it is a very confusing thing and you can just click on the method in your IDE to see the code or read the javadoc.
Here's the source code:
 public static boolean getBoolean(String name) {
        boolean result = false;
        try {
            result = toBoolean(System.getProperty(name));
        } catch (IllegalArgumentException e) {
        } catch (NullPointerException e) {
        }
        return result;
    }

A: I too found this issue recently when using Boolean.getBoolean() . In addition if you want to have a null check you can use Boolean.parseBoolean which will return false in case of nulls

A: class Boo1
{
    public static void main(String[] args)
    {
       System.setProperty("true","true");
       System.setProperty("false","true");

       boolean d=Boolean.getBoolean("true");

       System.out.println(d);
   }
}


text:
Q: My transition is not working on one of my elements I'm trying to make a simple set up with some cartoon characters, and it seems like whatever I try to do with my transition code to the 'tom' element it wont affect it. My transitions work on one of two elements, but i can't get it to work on the last one. I'm realtive new to coding, so dont be too harsh on my coding.
Short story, I just want to add some transition to the element 'tom'.
I've tried to change up the transition property, duration, timing function and delay, to different values.

#container {
  margin: auto;
  position: relative;
  width: 1000px;
  height: 650px;
  border: 2px solid rgb(0, 150, 150);
  background-color: rgb(0, 180, 200);
  overflow: hidden;
}

#jerry {
  position: absolute;
  width: 150px;
  left: -20px;
  bottom: 0px;
  transform: scaleX(-1);
  transition-timing-function: linear;
  transition-property: left;
  transition-delay: 0s;
  transition-duration: 1s;
}

#tom {
  position: absolute;
  height: 150px;
  bottom: 0px;
  right: -150px;
  transition-property: left;
  transition-duration: 1s;
  transition-timing-function: linear;
  transition-delay: 0s;
}

#container:hover #tom {
  right: 300px;
}

#container:active #jerry {
  left: -150px;
}

A: You have to replace the below css code with your css.
#container {
    margin: auto;
    position: relative;
    width: 1000px;
    height: 650px;
    border: 2px solid rgb(0, 150, 150);
    background-color: rgb(0, 180, 200);
    overflow: hidden;
}

#jerry{
    position: absolute;
    width: 150px;
    left: -20px;
    bottom: 0px;
    transform: scaleX(-1);
    transition-timing-function: linear;
    transition-property: left;
    transition-delay: 0s;
    transition-duration: 1s;
}
#tom{
    position: absolute;
    width: 150px;
    bottom: 0px;
    right: -20px;
  transform: scaleX(-1);
    transition-property: right;
    transition-duration: 1s;
    transition-timing-function: linear;
    transition-delay: 0s;
}
#container:hover #tom{
    right: -150px;
}
#container:hover #jerry{
    left: -150px;
}

A: You've set tom's transition-property to left, while changing its right property. Set the transition-property to right:

#container {
  margin: auto;
  position: relative;
  width: 1000px;
  height: 650px;
  border: 2px solid rgb(0, 150, 150);
  background-color: rgb(0, 180, 200);
  overflow: hidden;
}

#jerry {
  position: absolute;
  width: 150px;
  left: -20px;
  bottom: 0px;
  transform: scaleX(-1);
  transition-timing-function: linear;
  transition-property: left;
  transition-delay: 0s;
  transition-duration: 1s;
}

#tom {
  position: absolute;
  height: 150px;
  bottom: 0px;
  right: -150px;
  transition-property: right;
  transition-duration: 1s;
  transition-timing-function: linear;
  transition-delay: 0s;
}

#container:hover #tom {
  right: 300px;
}

#container:active #jerry {
  left: -150px;
}