text:
Q: Tensorflow error: "two variables have the same name: OptimizeLoss/beta1_power" Working on a project a coworker wrote; don't understand what he did and he's out of town for a bit.  My guess would be that two of the optimizers are trying to use the same copie of "OptimizeLoss/beta1_power," but that doesn't make sense because the code was working before and how could any CNN work if this were an issue?
We're developing a CNN model in a Jupyter Notebook for use in an app.
ValueError                                Traceback (most recent call last)
<ipython-input-8-0a28e84925b8> in <module>()
      6 train_model(X_train,            y_train,            X_val,            y_val,            vgg_model,            max_steps=10000,            optimizer_type="adam",            lr=0.001,            batch_size=128,            checkpoint_dir=checkpoint_dir,            augment_data=False,

----> 8             reg_lambda=0.01)

     10 # evaluate model

<ipython-input-4-5353196dc790> in train_model(X_train, y_train, X_val, y_val, model, max_steps, optimizer_type, lr, batch_size, augment_data, reg_lambda, steps_per_train_summary, steps_per_checkpoint, steps_per_val, checkpoint_dir)
105
106     # define saver
--> 107     saver = tf.train.Saver()
108
109     step = 0

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/training/saver.py in __init__(self, var_list, reshape, sharded, max_to_keep, keep_checkpoint_every_n_hours, name, restore_sequentially, saver_def, builder, defer_build, allow_empty, write_version, pad_step_number, save_relative_paths, filename)
1237     self._filename = filename
1238     if not defer_build and context.in_graph_mode():
->  1239       self.build()
1240     if self.saver_def:
1241       self._check_saver_def()

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/training/saver.py in build(self)
1246     if context.in_eager_mode():
1247       raise RuntimeError("Use save/restore instead of build in eager mode.")
->  1248     self._build(self._filename, build_save=True, build_restore=True)
1249
1250   def _build_eager(self, checkpoint_path, build_save, build_restore):

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/training/saver.py in _build(self, checkpoint_path, build_save, build_restore)
1282           restore_sequentially=self._restore_sequentially,
1283           filename=checkpoint_path,
->  1284           build_save=build_save, build_restore=build_restore)
1285     elif self.saver_def and self._name:
1286       # Since self._name is used as a name_scope by builder(), we are

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/training/saver.py in _build_internal(self, names_to_saveables, reshape, sharded, max_to_keep, keep_checkpoint_every_n_hours, name, restore_sequentially, filename, build_save, build_restore)
741       raise ValueError("Graph mode needs to build save and restore together.")
742
--> 743     saveables = self._ValidateAndSliceInputs(names_to_saveables)
744     if max_to_keep is None:
745       max_to_keep = 0

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/training/saver.py in _ValidateAndSliceInputs(self, names_to_saveables)
594     """
595     if not isinstance(names_to_saveables, dict):
--> 596       names_to_saveables = BaseSaverBuilder.OpListToDict(names_to_saveables)
597
598     saveables = []

~/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/training/saver.py in OpListToDict(op_list, convert_variable_to_tensor)
559           if name in names_to_saveables:
560             raise ValueError("At least two variables have the same name: %s" %
--> 561                              name)
562           names_to_saveables[name] = var
563         else:

ValueError: At least two variables have the same name: OptimizeLoss/beta1_power

A: I fixed this problem by calling
tf.reset_default_graph()


text:
Q: PHP error Failed to open stream: No such file or directory enter image description here
I have this error in php that does not let me show the products of a table but I have no idea why if I already tried everything with the address and it does not show me and the same error keeps appearing
This is my code

Datos del producto

            ID
            Nombre
            Tipo
            Precio
            Cantidad
            ID Vendedor
            Imagen
            Descripcion
            <?php include ("/Modelo/S_Mostrar.php") ?>

enter image description here

A: Your include_path is missing . for the current directory. You should adjust your php.ini config to include . for the current directory. Alternatively, use absolute paths such as through __DIR__ rather than relative paths and you should be able to find your files.
Note also a leading forward slash won't start at the web root. It would start at your system's root, which would be D: in your case.
You should add __DIR__ in front like so:
<?php include __DIR__ . '/Modelo/S_Mostrar.php' ?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't figure out what causes the segmentation fault | from HW I have the following data types:
formation.h
typedef struct formation_t {
    Player players[FORMATION_NUM_PLAYERS];
    int numPlayers;                /* How many players are in the above array */
    int timesPlayed;
    int timesWon;
}* Formation;

team.h
typedef struct team_t {
    char* name;
    char* coachName;
    Formation* formations;
    int currFormations;
    int maxFormations;
}* Team;

And the following functions:

Team teamCreate(char* name, char* coach, int maxFormations)
{
    //Check if parameters make sense.
    if (name == NULL || coach == NULL || maxFormations < 1)
    {
        return NULL;
    }

    //Try allocating memory for name.
    char* teamName = malloc(strlen(name) + 1);
    if (teamName == NULL)
    {
        return NULL;
    }
    strcpy(teamName, name);

    //Try allocating memory for coachName.
    char* coachName = malloc(strlen(coach) + 1);
    if (coachName == NULL)
    {
        free(teamName);
        return NULL;
    }
    strcpy(coachName, coach);

    //Try allocating memory for formations.
    Formation* formations = malloc(sizeof(Formation) * maxFormations);
    if (formations == NULL)
    {
        free(teamName);
        free(coachName);
        return NULL;
    }

    //Try allocating memory for team.
    Team newTeam = malloc(sizeof(struct team_t));
    if (newTeam == NULL)
    {
        free(teamName);
        free(coachName);
        free(formations);
        return NULL;
    }

    //Initialize newly created team.
    newTeam->name = teamName;
    newTeam->coachName = coachName;
    newTeam->maxFormations = maxFormations;
    newTeam->currFormations = 0;

    //Return created team.
    return newTeam;
}

TeamResult teamAddFormation(Team team, Formation formation)
{
    //Check for TEAM_NULL_ARGUMENT.
    if (team == NULL | formation == NULL)
    {
        return TEAM_NULL_ARGUMENT;
    }

    //Check for TEAM_IS_FULL.
    if (team->currFormations == team->maxFormations)
    {
        return TEAM_IS_FULL;
    }

    //Add formation.
    printf("\n -about to clone- \n");
    team->formations[team->currFormations] = formationClone(formation);
    printf("\n -clone completed- \n");
    team->currFormations = team->currFormations + 1;

    return TEAM_SUCCESS;
}

Formation formationClone(Formation formation)
{
    if (formation == NULL)
    {
        return NULL;
    }

    Formation newFormation = malloc(sizeof(struct formation_t));
    if (newFormation == NULL)
    {
        return NULL;
    }

    *newFormation = *formation;

    return newFormation;
}

When I try to test my work using the following code, I get a segmentation fault right after "about to clone".
Team team = teamCreate("Ac Milan", "Carletto", 2);

Formation formation1 = formationCreate();
ASSERT_NULL_ARGUMENT(teamAddFormation(NULL, formation1));
ASSERT_SUCCESS(teamAddFormation(team, formation1));

A: In teamCreate() you never set your formations local variable into your Team structure after allocating it.
This is first:
//Try allocating memory for formations.
Formation* formations = malloc(sizeof(Formation) * maxFormations);
if (formations == NULL)
{
    free(teamName);
    free(coachName);
    return NULL;
}

then you do this after allocation the host-object:
//Initialize newly created team.
newTeam->name = teamName;
newTeam->coachName = coachName;
newTeam->maxFormations = maxFormations;
newTeam->currFormations = 0;

//Return created team.
return newTeam;

You never save the formation pointer to the structure member, so that pointer member is indeterminate and using it is invoking undefined behavior.
Add this to the bottom of that stack of assignments:
newTeam->formations = formations;

A: //Try allocating memory for name.
char* teamName = malloc(strlen(name) + 1);
if (teamName == NULL)
{
    return NULL;
}
strcpy(teamName, name);

teamName is pointing to an alocated char array. This array never deleted. This lead to a memory leak.


text:
Q: Unable to parse JSON from file using Python3 I'm trying to get the value of ["pooled_metrics"]["vmaf"]["harmonic_mean"] from a JSON file I want to parse using python. This is the current state of my code:
for crf in crf_ranges:
    vmaf_output_crf_list_log = job['config']['output_dir'] + '/' + build_name(stream) + f'/vmaf_{crf}.json'
    # read the vmaf_output_crf_list_log file and get value from ["pooled_metrics"]["vmaf"]["harmonic_mean"]
    with open(vmaf_output_crf_list_log, 'r') as json_vmaf_file:
        # load the json_string["pooled_metrics"] into a python dictionary
        vm = json.loads(json_vmaf_file.read())
        vmaf_values.append((crf, vm["pooled_metrics"]["vmaf"]["harmonic_mean"]))

This will give me back the following error:
AttributeError: 'dict' object has no attribute 'loads'
I always get back the same AttributeError not matter if I use "load" or  "loads".
I validated the contents of the JSON, which is valid using various online validators, but still, I am not able to load the JSON for further parsing operations.
I expect that I can load a file that contains valid JSON data. The content of the file looks like this:
{
  "frames": [
    {
      "frameNum": 0,
      "metrics": {
        "integer_vif_scale2": 0.997330,
      }
    },
  ],
  "pooled_metrics": {
    "vmaf": {
      "min": 89.617207,
      "harmonic_mean": 99.868023
    }
  },
  "aggregate_metrics": {
  }
}

Can somebody provide me some advice onto this behavior, what does it seem so absolutely impossible to load this JSON file?

A: loads is a method for the json library as the docs say https://docs.python.org/3/library/json.html#json.loads. In this case you are having a AttributeError this means that probably you have created another variable named "json" and when you call json.loads is calling that variable hence it won't have a loads method.


text:
Q: Textarea text overlaps the popup content in IE I struggle with IE trying to fix the following issue. IE renders textarea text over popup div with my configuration, the input text has no such effect. Chrome renders well the both.

html, body, body > div {
  height: 100%;
}

input, textarea {
 width: 300px;
  color: tomato;
}

.item {
  padding: 10px;
}

.dropdown {
 position: relative;
}

.dropdown-menu {
 position: absolute;
 padding: 10px;
 background-color: whitesmoke;
 border: 1px solid grey;
}

option

option

option

option

option

option

    <input value="very long long long long long long  long long long long long long text">

    <textarea rows="4">very long long long long long long  long long long long long long text</textarea>

*

*IE 11 screenshot

*Chrome screenshot
Does anybody face the same issue? How could I fix it?


text:
Q: SQL Statement for Oracle Reports Builder Break Group Oracle Reports Builder Break Group
Can any one explain how the example break group could be translated into an equivalent SQL statement?
Since some of you are unable to view the image, below is an ASCII diagram of the example:
     ----
     |Q_1|
     ----
      |
      |
----------------
|G_DEPARTMENT_ID|
----------------
| DEPARTMENT_ID |
| JOB_ID        |
----------------
      |
      |
---------------
|G_EMPLOYEE_ID|
---------------
| EMPLOYEE_ID |
| FIRST_NAME  |
| LAST_NAME   |
| SALARY      |
---------------

A: It is an ordinary query:
select
  -- fields that make G_DEPARTMENT_ID group
  department_id,
  job_id,
  -- fields that make G_EMPLOYEE_ID group
  employee_id,
  first_name,
  last_name,
  salary
from some_table
where ...

If you use Wizard to create a report (which is preferable way of doing it), it asks you what type of a report you want - that layout would be one of "Group" layouts (above or left, doesn't matter). Then you'd select which fields should belong to the "Group above" (department_id and job_id). Wizard will also create layout that supports such a model and everything will work just fine.
If you're doing it manually, no problem as far as Data Model Layout is concerned: by default, everything (all fields) will be in the same group. Then drag DEPARTMENT_ID out of existing group and put it in between QUERY and G_EMPLOYEE_ID group - it'll automatically create a new group. Then move JOB_ID in there.
However, creating a Paper Layout is much more difficult, as you'll have to create new frames, fields, take care that everything is correctly contained in appropriate frame etc. Even if you know what you're doing, it is not straightforward job; perhaps it is easier to delete existing layout and let Wizard create it from scratch.


text: Q: Deleting specific observations from a data frame. Those specific observations are stored in another data frame in R I have a big data frame with 6 million observation. From the column ID (that may have lots of duplicated values because I only have approximately 400k unique ID) I want to remove all ID that I have stored in a column in another data frame (around 50).


text:
Q: Fill @Html.EditorFor from model using JSON on change @Html.DropDownListFor I want to fill EditorFor fields that contain information about a room and save data if it has changed. For choosing a particular room in the list, data in fields changed.
My view:
@Html.DropDownListFor(model => model.Id, ViewBag.roomlist as SelectList, "Select room",new { @id = "ddlRoom"})

    @using (Html.BeginForm("EditRoom", "Admin", new { id = 0 }, FormMethod.Post))
    {
        @Html.ValidationSummary(true)

Number room:

        @Html.EditorFor(model => model.NumberRoom)

Category:

        @Html.DropDownListFor(model => model.Categoryid, ViewBag.catlist as SelectList, "Select Category")

Cost per night

        @Html.EditorFor(model => model.CostPerNight)

Number of seats

        @Html.EditorFor(model => model.NumberOfSeats)

        <input type="submit" value="Save" class="icon save" />
    }

JSON in view:

Controller:
public JsonResult EditRoomResult(int id)
{
    var distinct = _roomService.GetRoom(id);
    return Json( distinct, JsonRequestBehavior.AllowGet);
}

Service:
public IQueryable<Room> GetRoom(int id)
{
    var tmp=_context.Room.Where(m => m.Id == id);
    return tmp;
}

How to get the value field CostPerNight from var distinct in controller or data in JSON?

A: Your usage of $("#CostPerNight").val('data.CostPerNight'); is setting the value of the input to the string "data.CostPerNight". Assuming CostPerNight is a property of the model you are returning, then it needs to be
$('#ddlRoom').change(function () {
    $.getJSON('/Admin/EditRoomResult/' + $('#ddlRoom').val(),function (data) {
        $("#CostPerNight").val(data.CostPerNight); // no quotes
    });
});

Side note: I recommend you use the following format to ensure your url is correctly constructed (using @Url.Action()) and avoid unnecessarily traversing the DOM again (by using $(this).val())
$.getJSON('@Url.Action("EditRoomResult", "Admin")', { id: $(this).val() }, function (data) {


text:
Q: Cron task not running I've configure a cron task for running a NodeJS script everyday.
crontab -l
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
55 23 * * * /usr/bin/node /getGames/.

But my script is never executed (the script write data on a file, and the last modification time of this file is never updated.) When I run the script manually, it's working.
I've no idea why it's not working

A: Jobs run through cron, or at, or batch, aren't run in the same runtime environment that you have on your desktop. None of your PATH changes, or other environment  variable settings are automatically propagated to  your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).
One can set environment variables for all one's cron jobs in the crontab file
Read man 5 crontab.
Look at the results of  echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.
Since the command part of the crontab line is, by default,  interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script  (executable, mounted, starts with #!/bin/bash) which sets up the environment,  then calls the desired program.


text:
Q: Issue installing exchange server 2013 I was installing exchange server 2013 on windows server 2012 until, in finalizing installation my PC froze and I reset it.  After that I tried to install it again, but I see this happened:
http://i59.tinypic.com/1t7bf9.png
Looks like next button is disabled what must I do to go forward?


text:
Q: Как выглядит реализация? "Шаблон шаблона параметризируется шаблоном шаблона" Как выглядит реализация следующего предложения на языке с++ и вообще в каких случаях может потребоваться так делать?

Шаблон шаблона параметризируется шаблоном шаблона.

A: Вот, что удалось придумать (не делайте так на практике):
Предположим, нужно получить пару списочных объектов, которые сами имеют разные типы, но всегда хранят объекты одного типа (например, vector<int> и list<int>) (см. ListPair ниже). Для этого нужно передавать шаблонный шаблонный параметр и конкретизировать его шаблонным параметром. При это в main std::vector является шаблоном, ListPair - шаблоном шаблона, ListPair<std::vector, std::list, int> - конкретизацией шаблона шаблона.
Далее, если нужно получить подобным образом пару таких пар, сам ListPair будет передаваться как шаблонный шаблонный параметр, и конкретизироваться шаблонными шаблонными параметрами (см. ListPairPair). Тогда в main ListPairPair является шаблоном шаблона, ListPair является шаблоном шаблона, получается, что шаблон шаблона конкретизируется шаблоном шаблона (и еще шаблоном (vector и list) и не шаблонным типом double)
#include <iostream>
#include <iterator>
#include <tuple>
#include <list>
template<template<class...> class List1,
template<class...> class List2,
class Arg>
struct ListPair{
    List1<Arg> list1;
    List2<Arg> list2;
};

template<
    template<template<class...>class,
             template<class...>class,
             class> class Pair,
    template<class...>class List1,
    template<class...>class List2,
    class T>
struct ListPairPair{
    Pair<List1, List2, T> pair1;
    Pair<List2, List1, T> pair2; // Типы List1 и List2 меняются местами
};

int main(){
   ListPair<std::vector, std::list, int> listPair;
   listPair.list1 = {4, 7, 1, 6}; // std::vector
   listPair.list2 = {1, 3, 5}; //  std::list
....
   ListPairPair<ListPair, std::vector, std::list, double> listPairPair;
   listPairPair.pair1 = listPair; // {std::vector, std::list}
   listPairPair.pair2.list1 = {1, 3, 6}; //  std::list
   listPairPair.pair2.list2 = {6, 3, 1, 18}; // std::vector
....
}

Реального примера с ходу придумать не могу, предположительно, может применяться при работе с кортежами (внутри библиотек). Можно попробовать поискать в исходниках boost::hana.


text:
Q: can I automate integrating packages/frameworks in xcode? For implementing our unity3d project into iOS, we need to manually select/tune a long list of tweaks in xcode build menu every time we build the project to test it (mainly to use appodeal framework).
Is there an easy way this task can be automated?
for example, in android builds, I reuse the same manifest file for the project and everything works just fine. Is there a similar way for xcode?

A: This is Andrew from Appodeal support. In the last release of Unity plugin (0.4.9) we have post build function which can help to resolve this issue.
You can download it here: Download_link


text:
Q: In Android 11, how is it possible, for an app to retain data after uninstallation, without SAF user interaction to pick a file/ folder location? Based on Is it possible to persisit a file after app uninstall with Android 11?
In Android 11, It seems like almost impossible to retain user data locally, after app uninstallation. Unless we are using SAF, which requires explicit user interaction, to select file/ dialog using this system UI

Or, by using android:hasFragileUserData="true" flag, which will pop up the following UI during uninstallation - https://www.xda-developers.com/android-10-manifest-flag-developers-retain-app-data-before-uninstalling/
However, to my suprise, I do notice a popular app in the market, which able to cleanly retain user multiple backup data, with 0 user interaction, and not using android:hasFragileUserData="true" flag method.
This is a video, to show how it is able to cleanly read the retained data, after re-installation (I have already did a clean uninstall, before capturing the video) - https://www.youtube.com/watch?v=UqG4n_0xmVI
Does anyone has any idea, how I can achieve such "magic"?


text:
Q: Storing data in UserDefaults I'm trying to save User details in UserDefaults using below method but it crashes on archiver.encode(assistantContact,forKey: "assistantContact").
I tried making AssistantContact as class instead of Struct but still it didn't worked.
How to archive AssistantContact too in order to save them in User ?
  struct AssistantContact {
    var firstName: String
    var lastName: String
    var email: [String]
}

struct User {
    var firstName: String
    var lastName: String
    var email: String
    var phoneNumber: String
    var company: String
    var assistantContact: AssistantContact
}

extension User {
    func encode() -> Data {
        let data = NSMutableData()
        let archiver = NSKeyedArchiver(forWritingWith: data)
        archiver.encode(firstName, forKey: "firstName")
        archiver.encode(lastName, forKey: "lastName")
        archiver.encode(email, forKey: "email")
        archiver.encode(phoneNumber, forKey: "phoneNumber")
        archiver.encode(company, forKey: "company")
        archiver.encode(assistantContact, forKey: "assistantContact")
        archiver.finishEncoding()
        return data as Data
    }

    init?(data: Data) {
        let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
        defer {
            unarchiver.finishDecoding()
        }
        guard let firstName = unarchiver.decodeObject(forKey: "firstName") as? String else { return nil }
        guard let lastName = unarchiver.decodeObject(forKey: "lastName") as? String else { return nil }
        guard let email = unarchiver.decodeObject(forKey: "email") as? String else { return nil }
        guard let phoneNumber = unarchiver.decodeObject(forKey: "phoneNumber") as? String else { return nil }
        guard let company = unarchiver.decodeObject(forKey: "company") as? String else { return nil }
        guard let assistantContact = unarchiver.decodeObject(forKey: "assistantContact") as? AssistantContact else { return nil }
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.phoneNumber = phoneNumber
        self.company = company
        self.assistantContact = assistantContact

    }
}

A: You can store the values in a NSObject and then use this method for archiving data.
Replace the archiver.encode(assistantContact, forKey: "assistantContact") with archiver.archivedData(withRootObject: assistantContact)
and use this for unarchive unarchiver.unarchiveObject(with: assistantContact)


text:
Q: find the maximum cost of removing all occurrences of substrings "he" and "lo" For given string S and integers P and Q, which denotes the cost of removal of substrings "he" and "lo" respectively from S, the task is to find the maximum cost of removing all occurrences of substrings "he" and "lo".
example if S = 'hellohellohellohellohello', P = 6, Q = 4, then cost to remove 'he' and 'lo' is 50

A: There was no example for where the OP was stuck, but you can use the re module for this.
This works:
import re

s = "hellohellohellohellohello"

x = re.findall('he', s)
y = re.findall('lo', s)

p = len(x) * 6
q = len(y) * 4

print(p+q)

result:
50


text:
Q: When I set Tests' setUp method, there is no Result When I override the test's setUp method and run php artisan test, it doesn't appear anything in my console:

But if I remove this method, my test result appears:

A: I found the answer!
I forgot to put the :void at the end of the method declaration.


text:
Q: How to disable onkeyup for a few seconds im creating a browser game and i have added keybinds so the player can use keys to move around the world.
If people use the buttons to move, these buttons are getting hidden for 5 seconds to allow an animation to end. Now i want to do this for the keybinds too.
For example: Player presses spacebar and a interval will run that lasts 5 seconds. Pressing space again will glitch out really bad running the same interval twice. So how do i disable a function for 5 seconds after it has been called so that it won't glitch out?
This is the code i use for the keys:
<script>
            document.body.onkeyup = function(e){
                if(e.keyCode == 32){
                    var cmd = "<?php echo $row['HEADING']; ?>";
                    if(cmd == "N") myMoveUp();
                    if(cmd == "E") myMoveRight();
                    if(cmd == "S") myMoveDown();
                    if(cmd == "W") myMoveLeft();
                }
                if(e.keyCode == 37){
                    ChangeHeadingKP("W");
                }
                if(e.keyCode == 38){
                    ChangeHeadingKP("N");
                }
                if(e.keyCode == 39){
                    ChangeHeadingKP("E");
                }
                if(e.keyCode == 40){
                    ChangeHeadingKP("S");
                }
            }
            </script>

Any help would be appreciated.

A: I wouldn't rely on timing (say, 5 seconds) because when you change them, you'll have to review your code.
Instead I'd rely on toggling a flag by calling specific methods, like this:
keymanager.suspend();
// play animation, cutscene or whatever
keymanager.resume();

Those two functions are easy to define, along with the keymanager, as follows:
var keymanager = {
  "active": true,
  "suspend": () => {
    keymanager.active = false;
  },
  "resume": () => {
    keymanager.active = true;
  }
};

All that remains is the key event handler bailing out when keys are deactivated:
document.body.onkeyup = function (e) {

  if (!keymanager.active)
  {
    return; // do not process any keys
  }

  // rest of your code...
}


text:
Q: Form not passing along iframe input I have recently been working on a web app that has a form. However, I've run into a roadblock. In this form, there is an iframe that has a photo upload. When submitted, the photo is uploaded and lets the user know. There is also a hidden input in a form on this page. In this hidden input, the URL of the image is stored. This is my script that is supposed to intercept the value of this input and pass it along in the form:
window.onload = function() {
    document.getElementById("photoFrame").contentDocument.forms[0].onsubmit = function () {
        document.getElementById("entry_862192515").setAttribute("value", document.getElementById("photoFrame").contentDocument.forms[0].getElementById("photoUrl").value);
    }
}

Here is my HTML:

photo-upload.php is just a simple form that uploads the image. Now here is upload.php, the PHP script that uploads the image from a POST request:
<?php

// Cloudinary init
require 'Cloudinary.php';
require 'Uploader.php';
require 'Api.php';
\Cloudinary::config(array(
  "cloud_name" => "(my name)",
  "api_key" => "(my key)",
  "api_secret" => "(my secret)"
));

// Uploads images to Cloudinary
$uploaded_file = \Cloudinary\Uploader::upload($_FILES["fileToUpload"]["tmp_name"]);

// Declares URL to variable
$url = $uploaded_file['secure_url'];

echo '<form><input type="hidden" id="photoUrl" value="'.$url.'" /></form>';
echo 'Success! Photo uploaded. Once you finish filling out the form, click the "Send" button.';

?>

What is wrong with this script? I don't see any errors in my console when I run it, and inside the iframe, the input contains the URL value. What am I doing wrong? Thanks so much.

A: <form>
  Hidden parent's input for photo URL:
  <input id="saveURL" />

</form>

iFrame.html contains the form:
<form>
  <input id="photoUrl" style="width:60%" readonly="readonly" value="http://somedomain.com/somefile.jpg" />
</form>

Demo: http://plnkr.co/edit/auqk8tQrCYYEIFjJUmPC?p=preview

A: The photo-upload.php file expects a file data to be posted so that is can be retrieved from $_FILES. But when the iframe gets loaded, how come the file data will be posted? I guess it will throw error in php.


text:
Q: Output data from current month? I have this table and i want to ge the data from current month.
This is the table:
CREATE TABLE [dbo].[CSEReduxResponses](
        [response_id] [int] IDENTITY(1,1) NOT NULL,
        [submitterdept] [int] NOT NULL,
        [commentdate] [datetime] NOT NULL,
        [status] [int] NOT NULL,
        [approvedby] [int] NULL,
        [approveddate] [datetime] NULL,
            [execoffice_approvedby] [int] NULL,

     CONSTRAINT [PK_CSE_Responses] PRIMARY KEY CLUSTERED
    (

I want to get the data where
status=1 and execoffice_status=0 and the current date.I want to use the approveddata column to get the date.
Right now I have
select * from CSEReduxResponses WHERE STATUS=1 AND EXECOFFICE_STATUS=0;

I have Microsoft sql server 2008
Microsoft SQL Server Management Studio   10.0.2531.0

A: Add AND MONTH([approveddate]) = MONTH(GETDATE()) AND YEAR([approveddate]) = YEAR(GETDATE()) to your where clause, assuming [approveddate] is the date you're interested in.

A: It is simple:
SELECT *
FROM   CSEReduxResponses
WHERE  STATUS = 1
AND    EXECOFFICE_STATUS = 0;
AND    MONTH(commentdate) = MONTH(GETDATE())
AND    YEAR(commentdate) = YEAR(GETDATE())


text:
Q: Using QueryByAttribute cannot retrieve null values I am new to CRM Development. I would like to update the custom field values in addtion to its existing values in the CRM 2011 from my C# application. If the field has some values then it is working fine, but if it null then i am receiving "The given key was not present in the dictionary." error.
The code below is what i am trying to achieve.
IOrganizationService service = (IOrganizationService)serviceProxy;
QueryByAttribute querybyattribute = new QueryByAttribute("salesorder");
querybyattribute.ColumnSet = new ColumnSet(new String[] {
  "salesorderid", "new_customefield" });

querybyattribute.Attributes.AddRange("ordernumber");
querybyattribute.Values.AddRange(ordernumber);
EntityCollection retrieved = service.RetrieveMultiple(querybyattribute);

foreach (var c in retrieved.Entities)
{
  OrderID = new Guid(c.Attributes["salesorderid"].ToString());
  CustomFieldValue = c.Attributes["new_customefield"].ToString();
}

A: The error occurs because a field with no entered value won't get returned in the context object not the image. Or to put it graspably - you need to check whether a field is amongst the attributes.
It's not sufficient to have declared it and requested it via ColumnSet. It's confusing and annoying (been there myself).
Just of the top of my head, I can think of the following code snippet to manage the issue (without having to set an if clause for every read but also avoiding a bunch of methods - one for each variable type).
private Generic GetEntityValue<Generic>(
  Entity entity, String field, Generic substitute = default(Generic))
{
  if (entity.Contains(field))
    return (Generic)entity[field];
  return substitute;
}

edit: Or as an extension method
public static T GetAttributeValue<T> (this Entity e, string propertyName, T defaultValue = default(T))
{
    if (e.Contains(propertyName))
    {
        return (T)e[propertyName];
    }
    else
    {
        return defaultValue;
    }
}


text:
Q: Javascript passing a function different sets of parameters So I have a function with quite a few parameters, for example
function myFunction(height, width, name, surname, time){
...
}

The trouble is I want to use this function to send different sets of parameters.
So sometimes it would be...
  function myFunction(height, width, depth, name, surname, time){
    ...
    }

The function is used for many tasks and I don't want a long list of parameters in the function coupled with lots of spaces in the values list when the function is called.
I need something more dynamic, ideally an associative array would be passed to the function and variables created from that.

A: Because JavaScript doesn't have named arguments people usually use object as "Interfaces"
You can accept a single argument that is an object and have all those arguments as keys.
function myFunction(options){
   //access to options.height and more...

}

Pass arguments packed in an object to the function
myFunction({
  height: 100,
  widht: 300,
  ...
});

A: my last post was wrong. I had something different in mind. sorry for that.
you can write a function with the long lsit of paramters but you don't have to use all of them when you execute a function.
Function
function foo(a, b, c) {
    //body;
};

May be executed like this:
foo(a);
foo(a,b);
foo(a,b,c);

Inside the function check if parameters are not null and if they ar set a defaut value
function foo(a, b, c) {
    a = a !== 'null' ? a : defaultValue;
    b = b !== 'null' ? b : defaultValue;
    c = c !== 'null' ? c : defaultValue;
};


text:
Q: Renaming files in Rails model with multiple Paperclip attachments I have a Rails model that has 4 Paperclip attachment types (top_graphic, intro_graphic, bg_audio, and thumbnail), each of which needs to have its file renamed according to different logic upon upload. How can I check which of the 4 attachments is currently being updated in the post-processor in order to do so?
before_post_process :file_rename

def file_rename
  # e.g., if top_graphic file is being uploaded, rename file to "top_graphic.jpg"
  # e.g., if intro_graphic file is being uploaded, rename file to "intro_graphic.jpg"
end

** Please note that I do know that I could create 4 new models for each of the attachment types and attach them that way. I wish to avoid doing this as it seems like unnecessary filesystem and database clutter.
Thanks.


text:
Q: Handle Logrus and Cobra CLI in Golang I am relatively new to the packages Cobra and Logrus in Golang and there is one little thing I would to ask for help when it comes to integrating them. I am working on a new Golang Cobra CLI which contains several commands/sub-commands. I'd like to use Logrus for logging inside my subcommands but I cannot find a good way to add new fields to the logger and pass them all to my subcommands.
This is what I have so far (I simplified my code for better explanation of my purpose):
├──pkg/
    ├──logger/
    |  ├──logger.go
├──cmd/
    ├── root.go
    ├──scmd/
    |  ├──scmd.go

// root.go

package cmd

func ExecuteRoot() {
    rootCmd := getRootCmd()
    err := rootCmd.Execute()
    if err != nil {
        os.Exit(1)
    }
}

func getRootCmd() *cobra.Command {
    rootCmd := &cobra.Command{
        Use:   "mycli",
        PersistentPreRun: enableLogs,
    }

    rootCmd.AddCommand(scmd.Getscmd())

    return rootCmd
}

func enableLogs(cmd *cobra.Command, args []string) {
    logger.ConfigureLogger(cmd.Flag("log-level").Value.String())
}

// logger.go
package logger

import (
    "github.com/sirupsen/logrus"
)

var MyCli *logrus.Entry

func ConfigureLogger(d string) {
    lv, err := logrus.ParseLevel(d)
    if err != nil {
        logrus.Fatal(err)
    }
    logrus.SetLevel(lv)

    logrus.SetFormatter(&logrus.TextFormatter{
        DisableQuote: true,
        ForceColors:  true,
    })

    MyCli = logrus.WithFields(logrus.Fields{"foo1": "bar1", "foo2": "bar2"})
}

// scmd.go

package scmd

import (
   "pkg/logger"
   "github.com/spf13/cobra"
)

func Getscmd() *cobra.Command {
    serviceUpdateCmd := &cobra.Command{
        Use:   "scmd",
        Run:   runServiceUpdateCmd,
    }

    return serviceUpdateCmd
}

func runServiceUpdateCmd(cmd *cobra.Command, args []string) {
    logger.MyCli.Info("start scmd")

    // here what the command does ...
}

If I run it, I get what I am expecting: My subcommands (in this case scmd) logs at the level I set my flag log-level and the fields defined in my package logger are passed ("foo1": "bar1", "foo2": "bar2"). However, I feel it is not the right way and could become problematic when creating unit test as I am using the global variable var MyCli from my logger package. Moreover, I should import it and use it as logger.MyCli in every Info, error, warn, etc line I want to log.
My question is whether there is a better approach to pass fields in Logrus on all subcommands I create or the way I explained above is my only option.
Any help or idea to improve my code is really welcome.
Thanks!


text:
Q: Demonstration of the trace of a matrix Can you correct the following demonstration of the trace of a matrix: If $A\in M_{m\times n}(\mathbb{R}), B\in M_{n\times k}(\mathbb{R})$ and $C\in M_{k\times m}(\mathbb{R})$, then $tr(ABC)=tr(BCA)=tr(CAB)$.
$A=a_{ij}$ with $1\leq i\leq m, 1\leq j\leq n$
$B=b_{qs}$ with $1\leq q\leq n, 1\leq s\leq k$
$C=c_{tv}$with $1\leq t\leq k, 1\leq v\leq m$
$AB=ab_{is}$ with $1\leq i\leq m, 1\leq s\leq k, ab_{ij}=\sum^{i}_{w=1}a_{iw}\cdot b_{ws}$
$ABC=abc_{iv}$ with $1\leq i\leq m, 1\leq v\leq m, abc_{iv}=\sum^{k}_{z=1}ab_{iz}\cdot c_{zv}$
$abc_{iv}=\sum^{k}_{z=1}\left( \sum^{j}_{w=1}a_{iw}\cdot b_{wz}\right)\cdot c_{zv}=\sum^{k}_{z=1}\sum^{j}_{w=1}a_{iw}b_{wz}c_{zv}$
$abc_{ii}=\sum^{k}_{z=1}\sum^{j}_{w=1}a_{iw}b_{wz}c_{zi}\rightarrow tr(ABC)=\sum^{m}_{f=1}abc_{ff}=\sum^{m}_{f=1}\sum^{k}_{z=1}\sum^{j}_{w=1}a_{fw}b_{wz}c_{zf}$
$BCA=(BC)A$
$BC=bc_{qv}$ with $1\leq q\leq n, 1\leq v\leq m: bc_{qv}=\sum^{k}_{z=1}b_{qz}c_{zv}$
$BCA=bca_{qj}$ with $1\leq q\leq n, 1\leq j\leq n: bca_{qj}=\sum^{m}_{f=1}bc_{qf}a_{fj}=\sum^{m}_{f=1}\left( \sum^{k}_{z=1}b_{qz}c_{zf}\right)\cdot a_{fj}=\sum^{k}_{z=1}\sum^{m}_{f=1}a_{fj}b_{qz}c_{zf}$
$bca_{jj}=\sum^{k}_{z=1}\sum^{m}_{f=1}a_{fj}b_{jz}c_{zf}\rightarrow tr(BCA)=\sum^{j}_{w=1}bca_{ww}=\sum^{j}_{w=1}\sum^{k}_{z=1}\sum^{m}_{f=1}a_{fw}b_{wz}c_{zf}$
$CAB=(CA)B$
$CA=ca_{tj}$ with $1\leq t\leq k, 1\leq j\leq n: ca_{tj}=\sum^{k}_{z=1}c_{tz}a_{zj}$
$CAB=cab_{ts}$ with $1\leq t\leq k, 1\leq s\leq k: cab_{ts}=\sum^{m}_{f=1}ca_{tf}b_{fs}=\sum^{m}_{f=1}\left( \sum^{k}_{z=1}c_{tz}a_{zf}\right)\cdot b_{fs}=\sum^{k}_{z=1}\sum^{m}_{f=1}b_{fs}c_{tz}a_{zf}=\sum^{k}_{z=1}\sum^{m}_{f=1}a_{zf}b_{fs}c_{tz}$
$cab_{ss}=\sum^{k}_{z=1}\sum^{m}_{f=1}a_{zf}b_{fs}c_{sz}\rightarrow tr(CAB)=\sum^{j}_{w=1}cab_{ww}=\sum^{j}_{w=1}\sum^{k}_{z=1}\sum^{m}_{f=1}a_{fw}b_{wz}c_{zf}$
I also wanted to ask to you: In the case $m=n=k$ it is complied with that $tr(ABC)=tr(BAC)$?


text:
Q: How to dynamically modify an existing SVG in react? I'm currently using state-machine-cat to generate dynamic state machine diagrams as SVG images for a reactJS application.  This library generates the SVGs as strings, so I am able to integrate them into the react application using
.
I'm trying to do some "post-processing" of these images in order to add some additional SVG elements and attach onClick event handlers to specific nodes in the SVG.
If this was in plain HTML, I'd do something like the following:
div.querySelectorAll("g.node").forEach((node) =>
{
    const icon = document.createElementNS("http://www.w3.org/2000/svg", "image");
    icon.setAttribute("x", calcX(node));
    icon.setAttribute("y", calcY(node));
    icon.setAttribute("height", "16");
    icon.setAttribute("width", "16");
    icon.setAttribute("src", "/badge.png");
    icon.addEventListener('click', clickHandler(node));
    node.appendChild(icon);
});

However, ReactElements are in the virtual DOM, so they don't support querySelectorAll, etc.  All of the examples I can find on manipulating an SVG in React involve creating it in React, while this is created externally and I need to manipulate it after-the-fact.
What is the best way to accomplish this?

A: I ended up replacing the
 line with html-react-parser and then using the options.replace callback to do processing as it walks down the DOM.  It's reasonably fast and lets me do what I need to do.


text:
Q: Overriding parts of a webapp's web.xml in Tomcat (eg manager application max file upload size) I am running the Tomcat manager application via a Debian package (tomcat8-admin), which deploys the webapp from /usr/share/tomcat8-admin/manager. We ran into a problem hitting the maximum upload size (configured as the multipart-config element in the HTMLManager servlet block). This is easy to fix if you're willing to edit Debian-packaged files, but this is incorrect: files in /usr/share are owned exclusively by dpkg. Is there a way to override this element from somewhere in tomcat's conf directory (which is symlinked to /etc/tomcat8 in Debian)?
Searching for this problem on the web only results in suggestions about editing web.xml directly (eg http://www.giantgeek.com/blog/?p=1000) or about different programming approaches using context parameters (if I understand correctly; I'm not especially familiar with the jargon).
If it's not possible to override this at the moment, then I'd be interested in suggestions about the best place to file a bug: is it that web.xml shouldn't contain site-specific options, as I have read - in which case does the fault lie with Tomcat? Or is the Debian packaging faulty, and should web.xml be made into a config file and symlinked from /etc?
Of course I could maintain a local version of the Debian package with this overriden, but for such an apparently-obvious piece of configuration that seems wrong too.

A: You can install tomcat without dpkg. Also which folder you want. Some googling can help. After that make multipart conf in web.xml.


text:
Q: Transactions work, but throw errors I have a use case in my application where I need to perform an update on two nodes in the database, where the the update being performed itself depends on data that is read from both of those nodes.  The code I wrote to do this does have the desired effect on the database, but the logs contain the error:
Error serializing return value: TypeError: Converting circular structure to JSON

Here is some minimal code needed to reproduce the error.  If the database initially has numerical entries at paths "b" and "c", and then a new value is written at "a", the below code will update b and c but will report the above error in the logs.
exports.bork = functions.database.ref("a").onWrite(event => {
  return Promise.all([
    admin.database().ref("b").once("value"),
    admin.database().ref("c").once("value")
]).then(snapshots => {
  var left = snapshots[0].val();
  var right = snapshots[1].val();
  var average = (left + right) / 2;
  return Promise.all([
    admin.database().ref("b").transaction(
      data => { return data + average; }
    ),
    admin.database().ref("c").transaction(
      data => { return data + average; }
    )
  ]);
});
}
);

I'm quite sure what is causing this.  It only seems to happen when I transact on a node after reading it, but I don't see why that should be a problem.  Is there a way of performing this update that avoids this error?
Edit:  As requested, I have stripped down my above example as much as possible.  It still produces the same error.
exports.bork = functions.database.ref("a").onWrite(event => {
  return admin.database().ref("b").once("value")
  .then(snapshots => {
    return admin.database().ref("b").transaction(
        data => { return data; }
      );
  });
});

On the other hand, the below code works fine in a web page.
Promise.all([
      database.ref("b").once("value"),
      database.ref("c").once("value")
    ]).then(snapshots => {
      console.log("Acquired snapshots.");
      var left = snapshots[0].val();
      var right = snapshots[1].val();
      var average = (left + right) / 2;
      return database.ref("b").transaction(
        data => { return data + average; }
      );
    }).then( result=>{console.log(result)}, error=>{console.log(error)} )


text:
Q: Find common values between two array of objects and store as array of objects I have two array of objects
    const oldArr = [
      {
        assetDetail_ID: 1,
        asset_Condition: "",
        asset_Condition_ID: 0,
        supplier_ID: 5,
      },
      {
        assetDetail_ID: 2,
        asset_Condition: "Good",
        asset_Condition_ID: 3,
        supplier_ID: 10,
      },
    ];

    const newArr = [
      {
        assetDetail_ID: 1,
        supplier_ID: 40,
      },
      {
        assetDetail_ID: 2,
        supplier_ID: 30,
      },
    ];

I am trying find common values by checking with object key and if they are the same, get key and value pair into a new array so my final result will be

   expectedResult = [
      {
        assetDetail_ID: 1,
        supplier_ID: 5,
      },
      {
        assetDetail_ID: 2,
        supplier_ID: 10,
      },
    ];

I have tried this but I am only getting values as [1, 5, 2, 10]and not objects , what am I doing wrong here ?

const oldArr = [{
    assetDetail_ID: 1,
    asset_Condition: "",
    asset_Condition_ID: 0,
    supplier_ID: 5,
  },
  {
    assetDetail_ID: 2,
    asset_Condition: "Good",
    asset_Condition_ID: 3,
    supplier_ID: 10,
  },
];

const newArr = [{
    assetDetail_ID: 1,
    supplier_ID: 40,
  },
  {
    assetDetail_ID: 2,
    supplier_ID: 30,
  },
];
const arr = []
oldArr.forEach((one, x) => {
  for (let i in one) {
    for (let j in newArr[x])
      if (i === j) {
        arr.push(one[i]); // If I change to arr.push(one);, it adds the whole object
      }
  }
});

console.log(arr)

A: if you want to do it your way,

const oldArr = [{
    assetDetail_ID: 1,
    asset_Condition: "",
    asset_Condition_ID: 0,
    supplier_ID: 5,
  },
  {
    assetDetail_ID: 2,
    asset_Condition: "Good",
    asset_Condition_ID: 3,
    supplier_ID: 10,
  },
];

const newArr = [{
    assetDetail_ID: 1,
    supplier_ID: 40,
  },
  {
    assetDetail_ID: 2,
    supplier_ID: 30,
  },
];

const arr = oldArr.map((one, index) => {
  const existingKeys = Object.keys(newArr[index]).filter(key => one.hasOwnProperty(key));
  let newObj = existingKeys.reduce((acc, curr) => {
      acc[curr] = one[curr];
      return acc;
  }, {});
  return newObj;
});

console.log(arr)

A: You could take a single loop approach for both arrays and collect all assetDetail_ID of newArr in an object and get a flat array from oldArr by returning either a new object or an empty array.

const
    oldArr = [{ assetDetail_ID: 1, asset_Condition: "", asset_Condition_ID: 0, supplier_ID: 5 }, { assetDetail_ID: 2, asset_Condition: "Good", asset_Condition_ID: 3, supplier_ID: 10 }],
    newArr = [{ assetDetail_ID: 1, supplier_ID: 40 }, { assetDetail_ID: 2, supplier_ID: 30 }],
    temp = Object.fromEntries(newArr.map(({ assetDetail_ID }) => [assetDetail_ID, true])),
    result = oldArr.flatMap(({ assetDetail_ID, supplier_ID }) => temp[assetDetail_ID]
        ? { assetDetail_ID, supplier_ID }
        : []
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: function doTheJob(oldArr, newArr){
let result = new Set();
for(let i = 0; i < oldArr.length; i++){
 for(let j = 0; j < newArr.length; j++){
     if(oldArr[i].assertDetail_ID === newArr[j].assertDetail_ID){
         result.add(newArr[j]);
     }
 }
}
return Array.from(result);
}

This can solve your problem!

A: What you need is classic JavaScript array function filter()
Here's an example -
//your array

const oldArr = [
      {
        assetDetail_ID: 1,
        asset_Condition: "",
        asset_Condition_ID: 0,
        supplier_ID: 5,
      },
      {
        assetDetail_ID: 2,
        asset_Condition: "Good",
        asset_Condition_ID: 3,
        supplier_ID: 10,
      },
    ];

The function -
function getArr(id){
    const newArr = oldArr.filter(obj => { return obj.assetDetail_ID === id})
    console.log(newArr);  //let id = 1; this will give you a sub-array where assetDetail_ID = 1
    return newArr;
}


text:
Q: ¿Cómo realizar una consulta en ADO.NET de un registro en especifico cuando no tiene llave primaria la tabla que deseo consultar? Estoy queriendo hacer una consulta para ver los datos específicos de un registro que esta en una tabla al que le doy clic, y este clic me tiene que aparecer  una ventana con todos los datos, sin embargo cuando le doy click a un registro especifico de la tabla me dice que el nombre de la columna 'acccj76fg' no es valido y para verificar si ese dato esta dentro de los registros de la tabla lo consulto en el server y efectivamente es el usuario que quiero ver sus datos pero no se por que no me devuelve los datos y me sale ese error,que estoy haciendo mal en mi consulta? no sé si estoy mal en mi where, lo único es que la tabla de donde saco los datos no tiene id, es decir, no tiene llave primaria.
No sé si eso tiene algo que ver, sin embargo estoy poniendo la primera columna de la tabla la cual es USUARIO, este es  mi consulta:
    void ConsultarUsuario(){
    sqlConnection conexion=new SqlConnection(ConfigurationManager.ConnectionStrings["ejerciciosConnectionString"].ConnectionString);

     sqlCommand mySqlCommand=conexion.CreateCommand();
     conexion.Open();
     mySqlCommand.CommandText="SELECT USUARIO,rfc,importecredito,localidad FROM registros WHERE (USUARIO="+USUARIO+")";

     SqldataReader mySqlDatareader1=mySqlCommand.Executereader();

     while(mySqlDataReader1.read()){

     this.txtusuario=mySqlDataReader1["USUARIO"].toString;
     this.txtrfc=mySqlDataReader1["rfc"].toString;
     this.txtimportecredito=mySqlDataReader1["importecredito"].toString;
     this.txtlocalidad=mySqlDataReader1["localidad"].toString;
     }
     mySqlDataReader1.close();
     conexion.close();
     }

Asi es como esta mi codigo tambien intente poner where USUARIO=USUARIO AND rfc=rfc; y no me arroja nada,espero me puedan orientar en que es lo que estoy haciendo mal,el USUARIO no es numerico es varchar  ejemplo acccj76fg, no se si eso influye en las comillas de la consulta que estoy haciendo.

A: Debes ser mas especifico a la hora de solicitarle la información al servidor ya que el servidor de base de datos te va a responder acorde a los criterios que tu le pongas.
En este caso al no haber una clave primaria deberás de colocar mas filtros(campos) para poder separar el registro de los demás similares quedandote asi un registro unico.
Aunque lo mas recomendable sera normalizar la base de datos.
Creo que deberías de implementar primero tus restricciones en tu base de datos para poder realizar tus querys o búsquedas ya que es algo muy ambiguo solicitar ahora que podrías realizar algo como SELECT * FROM T_USUARIOS WHERE EMAIL='cadena' and NOMBRE='NOMBRE'

A: Por lo que veo en tu query, si la variable USUARIO no es numérica, se debe encerrar entre comillas simples ('). Esto te permite localizar el registro, independientemente de que el dato de búsqueda no sea llave primaria.
Es decir, la línea en la que armas la consulta quedaría del siguiente modo:
mySqlCommand.CommandText="SELECT USUARIO,rfc,importecredito,localidad FROM registros WHERE (USUARIO='"+USUARIO+"')";

Dos sugerencias

*

*No es recomendable que las consultas se armen utilizando cadenas
concatenadas. Pueden hacer que tu aplicación sea susceptible a
ataques de inyección de SQL. En este caso, es mejor utilizar
Procedimientos almacenados o bien consultas parametrizadas.

*Es importante que las tablas de BD tengan una llave primaria. Esta
siempre será una buena práctica de diseño.

A: Despues de tantos intento di con la solucion para que me trajera todos los datos del registro seleccionado y fue por la comilla simple,asi es como me soluciono el problema que tenia
  where USUARIO='"+ USUARIO +"';


text:
Q: Laravel Excel validation i have installed the maatwebsite/excel package for laravel. It works fine. My problem is how to handle it after i check the file.
The upload() function in which i show to file forum and where i upload the file is here:
public function upload(Request $request) {

    $orientation = $request->get('orientation');
    if($request->file('file')) {
        $status = Excel::load(Input::file('file'), function ($reader) use ($orientation) {
            return self::upload_excel_files($reader, $orientation);
        });
        if($status) {
            Session::flash('status', "Excel data was imported successfully");
            return redirect(route('admin.exchange.upload'));
        }
        else {
            return redirect(route('admin.exchange.upload'))->withErrors('Invalid format. Please check the XLS template.');
        }
    }
    return view('admin.exchange.upload');

}

public function upload_excel_files($file, $orientation) {
    if(something) return true;
    else return false;
}

The upload_excel_files function checks if the file has the right format and if yes it handles it and must return a successful note. If the file does not match the require format it needs to give an error message.
Unfortunately i am not sure where to put the user messages. As in the example it always return a successful message. If the messages are in the upload_excel_files() function for some reason i don't get the message by the first redirect, i get it at the second redirect which is strange.
What would u guys recommend me to do ?

A: For checks if the file has the right format use laravel request
 public function rules()
    {
        return [
            'file' => 'required|mimeTypes:'.
                'application/vnd.ms-office,'.
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,'.
                'application/vnd.ms-excel',
        ];
    }

More mime-type:
https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
For errors message read this:
https://laravel.com/docs/5.4/validation#working-with-error-messages


text:
Q: Реализация типа-обёртки Помогите исправить код. Я пишу тип-обёртку в проекте для нейронных сетей и я хочу чтобы изменяя в этой структуре тип с double на float, ufloat, double, udouble, ulong или другой числовой, все функции приведения типов, конструкторы, неявные преобразования работали корректно. Пожалуйста, посмотрите и исправьте в коде некорректные реализации:
using System;
namespace Neuronet
{
    /// <summary>
    /// Тип параметров нейрона
    /// </summary>
    public struct NType : IComparable, IComparable<NType>, IConvertible, IEquatable<NType>, IFormattable
    {
        /// <summary>
        /// Значение, выражающее тип параметров нейрона
        /// Сейчас double, вы можете сменить тип, изменяя тип value, MinValue, MaxValue, Epsilon
        /// </summary>
        readonly double value;
        public const double MinValue = double.MinValue;
        public const double MaxValue = double.MaxValue;
        public const double Epsilon = double.Epsilon;

        #region ctors
        /// <summary>
        /// Конструктор от int
        /// </summary>
        /// <param name="val">Значение</param>
        public NType(int v)
        {
            value = v;
        }

        public NType(double v)
        {
            value = v;
        }

        public NType(float v)
        {
            value = v;
        }

        public NType(uint v)
        {
            value = v;
        }

        public NType(Int16 v)
        {
            value = v;
        }

        public NType(UInt16 v)
        {
            value = v;
        }

        public NType(Int64 v)
        {
            value = v;
        }

        public NType(UInt64 v)
        {
            value = v;
        }

        public NType(NType v)
        {
            value = v;
        }
        #endregion

        #region comparse
        public override bool Equals(object obj)
            => obj is NType check && Equals(check);

        public override int GetHashCode()
        {
            return value.GetHashCode();
        }

        public bool Equals(NType other)
        {
            return this.value == other.value;
        }

        public int CompareTo(object obj)
        {
            if (obj is NType other)
                return CompareTo(other);
            else
                return -1; /// Неприводимые объекты больше приводимых
        }
        #endregion

        #region converts
        public static NType ToNType(int v)
        {
            return new NType(v);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            return value.ToString(format, formatProvider);
        }

        public TypeCode GetTypeCode()
        {
            return value.GetTypeCode();
        }

        public bool ToBoolean(IFormatProvider provider)
        {
            return value == 0 ? false : true;
        }

        public char ToChar(IFormatProvider provider)
        {
            return (char)value;
        }

        public sbyte ToSByte(IFormatProvider provider)
        {
            return (sbyte)value;
        }

        public byte ToByte(IFormatProvider provider)
        {
            return (byte)value;
        }

        public short ToInt16(IFormatProvider provider)
        {
            return (Int16)value;
        }

        public ushort ToUInt16(IFormatProvider provider)
        {
            return (UInt16)value;
        }

        public int ToInt32(IFormatProvider provider)
        {
            return (Int32)value;
        }

        public uint ToUInt32(IFormatProvider provider)
        {
            return (UInt32)value;
        }

        public long ToInt64(IFormatProvider provider)
        {
            return (Int64)value;
        }

        public ulong ToUInt64(IFormatProvider provider)
        {
            return (UInt64)value;
        }

        public float ToSingle(IFormatProvider provider)
        {
            return (float)value;
        }

        public double ToDouble(IFormatProvider provider)
        {
            return (double)value;
        }

        public decimal ToDecimal(IFormatProvider provider)
        {
            return (decimal)value;
        }

        public DateTime ToDateTime(IFormatProvider provider)
        {
            return new DateTime((long)value);
        }

        public string ToString(IFormatProvider provider)
        {
            return value.ToString(provider);
        }

        public object ToType(Type conversionType, IFormatProvider provider)
        {

            return ((IConvertible)value).ToType(conversionType, provider);
        }

        public int CompareTo(NType other)
              => value.CompareTo(other.value);
        #endregion

        #region overloads
        public static bool operator ==(NType left, NType right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(NType left, NType right)
        {
            return !(left == right);
        }

        public static bool operator <(NType left, NType right)
        {
            return left.CompareTo(right) < 0;
        }

        public static bool operator <=(NType left, NType right)
        {
            return left.CompareTo(right) <= 0;
        }

        public static bool operator >(NType left, NType right)
        {
            return left.CompareTo(right) > 0;
        }

        public static bool operator >=(NType left, NType right)
        {
            return left.CompareTo(right) >= 0;
        }

        public static NType operator +(NType left, NType right)
        {
            return new NType(left.value + right.value);
        }

        public static NType Add(NType left, NType right)
        {
            return left + right;
        }

        public static NType operator -(NType left, NType right)
        {
            return new NType(left.value - right.value);
        }

        public static NType Subtract(NType left, NType right)
        {
            return left - right;
        }

        public static NType operator *(NType left, NType right)
        {
            return new NType(left.value * right.value);
        }

        public static NType Multiply(NType left, NType right)
        {
            return left * right;
        }

        public static NType operator /(NType left, NType right)
        {
            return new NType(left.value / right.value);
        }

        public static NType Divide(NType left, NType right)
        {
            return left / right;
        }

        public static NType operator %(NType left, NType right)
        {
            return new NType(left.value % right.value);
        }

        public static NType Mod(NType left, NType right)
        {
            return left % right;
        }

        public static NType Increment(NType item)
        {
            var val = item.value;
            return new NType(val++);
        }

        public static NType Decrement(NType item)
        {
            var val = item.value;
            return new NType(val--);
        }
        #endregion

        #region implicits
        ///// <summary>
        ///// Неявное приведение типа от int к NType
        ///// </summary>
        ///// <param name="v">Значение</param>
        public static implicit operator NType(int v)
        {
            return new NType(v);
        }

        public static implicit operator NType(double v)
        {
            return new NType(v);
        }

        public static implicit operator NType(float v)
        {
            return new NType(v);
        }

        public static implicit operator NType(uint v)
        {
            return new NType(v);
        }

        public static implicit operator NType(Int16 v)
        {
            return new NType(v);
        }

        public static implicit operator NType(UInt16 v)
        {
            return new NType(v);
        }

        public static implicit operator NType(Int64 v)
        {
            return new NType(v);
        }

        public static implicit operator NType(UInt64 v)
        {
            return new NType(v);
        }

        public static implicit operator double(NType v)
        {
            return (double)v.value;
        }

        public static implicit operator float(NType v)
        {
            return (float)v.value;
        }

        public static implicit operator int(NType v)
        {
            return (int)v.value;
        }

        public static implicit operator uint(NType v)
        {
            return (uint)v.value;
        }

        public static implicit operator Int16(NType v)
        {
            return (Int16)v.value;
        }

        public static implicit operator UInt16(NType v)
        {
            return (UInt16)v.value;
        }

        public static implicit operator Int64(NType v)
        {
            return (Int64)v.value;
        }

        public static implicit operator UInt64(NType v)
        {
            return (UInt64)v.value;
        }
        #endregion
    }
}

A: В общем, я так реализовал:
using System;
namespace Neuronet
{
    /// <summary>
    /// Тип параметров нейрона
    /// </summary>
    public struct NType : IComparable, IComparable<NType>, IConvertible, IEquatable<NType>, IFormattable
    {
        /// <summary>
        /// Значение, выражающее тип параметров нейрона
        /// Сейчас double, вы можете сменить тип, изменяя тип value,
        /// MinValue, MaxValue, Epsilon и изменив конструктор.
        /// </summary>
        readonly double value;
        public const double MinValue = double.MinValue;
        public const double MaxValue = double.MaxValue;
        public const double Epsilon = double.Epsilon;

        #region ctors
        /// <summary>
        /// Конструктор от object
        /// </summary>
        /// <param name="v">Значение</param>
        public NType(object v)
        {
            if (v == null) { throw new ArgumentException(Resources.Error_2); }
            value = Convert.ToDouble(v, System.Globalization.CultureInfo.InvariantCulture);
        }
        #endregion

        #region comparse
        public override bool Equals(object obj)
            => obj is NType check && Equals(check);

        public override int GetHashCode()
        {
            return value.GetHashCode();
        }

        public bool Equals(NType other)
        {
            return this.value == other.value;
        }

        public int CompareTo(object obj)
        {
            if (obj is NType other)
                return CompareTo(other);
            else
                return -1; /// Неприводимые объекты больше приводимых
        }
        #endregion

        #region converts
        public static NType ToNType(int v)
        {
            return new NType(v);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            return value.ToString(format, formatProvider);
        }

        public TypeCode GetTypeCode()
        {
            return value.GetTypeCode();
        }

        public bool ToBoolean(IFormatProvider provider)
        {
            return Convert.ToBoolean(value, provider);
        }

        public char ToChar(IFormatProvider provider)
        {
            return Convert.ToChar(value, provider);
        }

        public sbyte ToSByte(IFormatProvider provider)
        {
            return Convert.ToSByte(value, provider);
        }

        public byte ToByte(IFormatProvider provider)
        {
            return Convert.ToByte(value, provider);
        }

        public short ToInt16(IFormatProvider provider)
        {
            return Convert.ToInt16(value, provider);
        }

        public ushort ToUInt16(IFormatProvider provider)
        {
            return Convert.ToUInt16(value, provider);
        }

        public int ToInt32(IFormatProvider provider)
        {
            return Convert.ToInt32(value, provider);
        }

        public uint ToUInt32(IFormatProvider provider)
        {
            return Convert.ToUInt32(value, provider);
        }

        public long ToInt64(IFormatProvider provider)
        {
            return Convert.ToInt64(value, provider);
        }

        public ulong ToUInt64(IFormatProvider provider)
        {
            return Convert.ToUInt64(value, provider);
        }

        public float ToSingle(IFormatProvider provider)
        {
            return Convert.ToSingle(value, provider);
        }

        public double ToDouble(IFormatProvider provider)
        {
            return Convert.ToDouble(value, provider);
        }

        public decimal ToDecimal(IFormatProvider provider)
        {
            return Convert.ToDecimal(value, provider);
        }

        public DateTime ToDateTime(IFormatProvider provider)
        {
            return Convert.ToDateTime(value, provider);
        }

        public string ToString(IFormatProvider provider)
        {
            return Convert.ToString(value, provider);
        }

        public object ToType(Type conversionType, IFormatProvider provider)
        {
            return Convert.ChangeType(value, conversionType, provider);
        }

        public int CompareTo(NType other)
              => value.CompareTo(other.value);
        #endregion

        #region overloads
        public static bool operator ==(NType left, NType right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(NType left, NType right)
        {
            return !(left == right);
        }

        public static bool operator <(NType left, NType right)
        {
            return left.CompareTo(right) < 0;
        }

        public static bool operator <=(NType left, NType right)
        {
            return left.CompareTo(right) <= 0;
        }

        public static bool operator >(NType left, NType right)
        {
            return left.CompareTo(right) > 0;
        }

        public static bool operator >=(NType left, NType right)
        {
            return left.CompareTo(right) >= 0;
        }

        public static NType operator +(NType left, NType right)
        {
            return new NType(left.value + right.value);
        }

        public static NType Add(NType left, NType right)
        {
            return left + right;
        }

        public static NType operator -(NType left, NType right)
        {
            return new NType(left.value - right.value);
        }

        public static NType Subtract(NType left, NType right)
        {
            return left - right;
        }

        public static NType operator *(NType left, NType right)
        {
            return new NType(left.value * right.value);
        }

        public static NType Multiply(NType left, NType right)
        {
            return left * right;
        }

        public static NType operator /(NType left, NType right)
        {
            return new NType(left.value / right.value);
        }

        public static NType Divide(NType left, NType right)
        {
            return left / right;
        }

        public static NType operator %(NType left, NType right)
        {
            return new NType(left.value % right.value);
        }

        public static NType Mod(NType left, NType right)
        {
            return left % right;
        }

        public static NType Increment(NType item)
        {
            var val = item.value;
            return new NType(val++);
        }

        public static NType Decrement(NType item)
        {
            var val = item.value;
            return new NType(val--);
        }
        #endregion

        #region implicits
        ///// <summary>
        ///// Неявное приведение типа от int к NType
        ///// </summary>
        ///// <param name="v">Значение</param>
        public static implicit operator NType(int v)
        {
            return new NType(v);
        }

        public static implicit operator NType(double v)
        {
            return new NType(v);
        }

        public static implicit operator NType(float v)
        {
            return new NType(v);
        }

        public static implicit operator NType(uint v)
        {
            return new NType(v);
        }

        public static implicit operator NType(Int16 v)
        {
            return new NType(v);
        }

        public static implicit operator NType(UInt16 v)
        {
            return new NType(v);
        }

        public static implicit operator NType(Int64 v)
        {
            return new NType(v);
        }

        public static implicit operator NType(UInt64 v)
        {
            return new NType(v);
        }

        public static implicit operator double(NType v)
        {
            return (double)v.value;
        }

        public static implicit operator float(NType v)
        {
            return (float)v.value;
        }

        public static implicit operator int(NType v)
        {
            return (int)v.value;
        }

        public static implicit operator uint(NType v)
        {
            return (uint)v.value;
        }

        public static implicit operator Int16(NType v)
        {
            return (Int16)v.value;
        }

        public static implicit operator UInt16(NType v)
        {
            return (UInt16)v.value;
        }

        public static implicit operator Int64(NType v)
        {
            return (Int64)v.value;
        }

        public static implicit operator UInt64(NType v)
        {
            return (UInt64)v.value;
        }
        #endregion
    }
}


text:
Q: Swift API Call using dataTaskPublisher Had various success with using dataTaskPublisher and pulling data from APIs.
Issue I'm having is with nested JSON. I can fetch simple JSON but something like the Pokemon API where it has nested JSON is getting me.
Any advise would be great.
The onappear: // fetch completion is the part I'm hung up on.
import SwiftUI
import Combine

struct Pokemon: Codable {
    var cards: Card
}

struct Card: Codable {
    var id: String
    var name: String
}

struct ContentView: View {
    @State private var requests = Set<AnyCancellable>()
    @State var pokemon: Pokemon

    var body: some View {
        VStack {
            Text("card name here")
        }
        .onAppear {
            let url = URL(string: "https://api.pokemontcg.io/v1/cards")!

            self.fetch(url, defaultValue: [Pokemon]()) {
                self.pokemon = $0
            }
        }
    }

    func fetch<T: Decodable>(_ url: URL, defaultValue: T, completion: @escaping (T) -> Void) {

        let decoder = JSONDecoder()

        URLSession.shared.dataTaskPublisher(for: url)
            .retry(1)
            .map(\.data)
            .decode(type: T.self, decoder: decoder)
            .replaceError(with: defaultValue)
            .receive(on: DispatchQueue.main)
            .sink(receiveValue: completion)
            .store(in: &requests)
    }
}

A: The key "cards" is an object array so you need to update  Pokemon  to as follows
struct Pokemon: Codable {
    var cards : [Card]
}

As the root of the JSON is a dictionary not an array, update the .onAppear function to
 .onAppear {
        let url = URL(string: "https://api.pokemontcg.io/v1/cards")!

        self.fetch(url, defaultValue: Pokemon(cards: [Card(id: "default", name: "default")])) {
            self.pokemon = $0
        }
    }


text:
Q: How do I position the navbar inside the header? How do I position the navbar inside the header?  If I float the divs inside the header it works fine.  But when I remove the float the navbar positions below the header.  I dont understand it.  How do I fix it?

html{
    height:100%;

}
body{
    margin: 0px;
    padding: 0px;
    background-color: grey;
    height:100%;
    width:100%;

}
#container{
    height:90%;
    width:90%;
    margin-left: 5%;
    margin-right: 5%;
    border-style: solid;

}
#header{
   height:8%;
   width:100%;

}
.logo{
    height:80%;
    width:10%;
}
.nav{
    height:90%;
    width:75%;
    margin:auto;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>basic</title>
    <link rel="stylesheet" type="text/css" href="style.css">

A: bydefault div element are block label element that's it took 100% width.
you can change it's to 'inline' element using float, inline-block. >br/>
check updated snippet below

html {
    height:100%;
}
body{
    margin: 0px;
    padding: 0px;
    background-color: grey;
    height:100%;
    width:100%;
}
#container{
    height:90%;
    width:90%;
    margin-left: 5%;
    margin-right: 5%;
    border-style: solid;
}
#header{
    height:8%;
    width:100%;
}
.logo{
    height:80%;
    width:10%;
    display: inline-block;
}
.nav{
    height:90%;
    width:75%;
    display: inline-block;
}

logo

            Nav1
            Nav2
            Nav3
            Nav4

A: If u make the logo position:absolute it wont push down the navbar.
You do have to specify heigth and width since it will not compare to the parent div.
.logo{
  height:40px;
  width:100px;
  position: absolute;
}

An other way of fixing this is by giving a negavtive margin to the navbar.
This way you dont have to specify the width and heigth of the logo.
.nav{
  height:90%;
  width:75%;
  margin:-35px auto;
}


text:
Q: Is there any way to prevent the Dock from jumping to another display when I reach the bottom of the screen? When your mouse reaches the bottom of the screen then try to drag it a little bit lower, macOS automatically moves the Dock to that display. I trigger this unintentionally a few times a day, so I want to turn it off to keep the Dock on my main display. Is there a way for that?
I am not open for attaching the Dock to the side of the screen.

A: You have two choices.

*

*Attach it to the side of the screen - which you already said you don't want to do.

*Disable "Displays have separate Spaces" In Mission Control.
This will have the side effect of making all your Spaces move in 'pairs', both screens are now one larger Space, rather than two independent, smaller Spaces.
The dock, however, will then always remain on your primary display.
Personally, I've always used 2. I just prefer my screen layout that way.


text:
Q: Highest time spent by a user in a month ,for every month in an year using time session I am trying to find the user who spent highest time in a month , for every month of the year
I am using the following data
   uid             activity-time                status
   ...          ...................            ........
    1           2016-12-31 16:00:04            sign in
    1           2016-12-31 21:05:37            sign out
    2           2016-12-25 18:00:04            sign in
    2           2016-12-25 20:45:31            sign out
    7           2016-10-31 13:00:04            sign in
    7           2016-10-31 16:05:30            sign out
    1           2016-12-27 17:00:04            sign in
    1           2016-12-27 19:05:00            sign out
    2           2016-10-25 18:00:04            sign in
    2           2016-10-25 20:45:31            sign out
    4           2017-12-31 16:00:04            sign in
    4           2017-12-31 21:05:37            sign out
    3           2017-12-25 18:00:04            sign in
    3           2017-12-25 20:45:31            sign out
    7           2017-10-31 16:00:04            sign in
    7           2017-10-31 21:05:37            sign out
    3           2017-10-25 18:00:04            sign in
    3           2017-10-25 20:45:31            sign out

I am expecting the following output
uid        year  month      time-spent
......     ..... .....      ..........
1          2016   12        07:10:45
7          2016   10        03:05:34
4          2017   12        05:05:41
7          2017   10        05:05:41

I have tried following query but i have no idea how to specify the logged in and logged out conditions
SELECT ETS.*
FROM (SELECT year(activity-time),month(activity-time), uid, count(uid) as c,
ROW_NUMBER() OVER (PARTITION BY month(activity-time) ORDER BY COUNT(uid) DESC) as seq
FROM activity_table
GROUP BY month(activity-time),year(activity-time), uid
) ds
WHERE seq = 1
ORDER BY c DESC ;

A: You could use a nested query with lag to get the time difference between a sign-in and sign-out record.
I don't have hiveql, so I might be off on some of the specific date/time functions, but the idea is this:
select yr,
       mnth,
       uid,
       from_unixtime(spent, 'hh:mm:ss') spent
from (
        select year(activity_time) yr,
               month(activity_time) mnth,
               uid,
               sum(spent) spent,
               row_number() over (partition by year(activity_time), month(activity_time)
                                  order by     sum(spent) desc) rn
        from (
                select uid,
                       activity_time,
                       status,
                       unix_timestamp(activity_time)
                           - lag(unix_timestamp(activity_time))
                                 over (partition by uid order by activity_time) spent
                from   activity_table
             ) base
        where status = 'sign out'
        group by year(activity_time),
                 month(activity_time),
                 uid
      ) grouped
where rn = 1;

NB: I would suggest not to use hyphens in column names, but underscores (which I did in above SQL).

A: This is in SQL Server but should give you an idea. I first created a CTE that will calculate the total seconds from the time so i can use SUM - grouped by ID , MM-yyyy date and converted it to time format again after. Then a row_number to get the max for each date.
;WITH activity_table_seconds
     AS (SELECT [uid],
                [activity-time],
                ( Datepart(hour, [activity-time]) * 60 * 60 ) + (
                Datepart(minute, [activity-time]) * 60 ) +
                Datepart(second, [activity-time]) AS
                [activity-time-seconds],
                [status]
         FROM   @activity_table)
SELECT [uid],
       [date],
       [activity-time]
FROM   (SELECT *,
               Row_number ()
                 OVER (
                   partition BY [date]
                   ORDER BY [activity-time] DESC) rn
        FROM   (SELECT a.[uid],
                       Format(a.[activity-time], 'MM-yyyy') AS [date],
                       CONVERT(VARCHAR(8),
                       Dateadd(second, Sum(b.[activity-time-seconds] -
                                           a.[activity-time-seconds]), 0),
                               108) AS [activity-time]
                FROM   (SELECT *
                        FROM   activity_table_seconds
                        WHERE  [status] = 'sign in') a
                       INNER JOIN (SELECT *
                                   FROM   activity_table_seconds
                                   WHERE  [status] = 'sign out') b
                               ON a.[uid] = b.[uid]
                                  AND Cast(a.[activity-time] AS DATE) = Cast(
                                      b.[activity-time] AS DATE)
                GROUP  BY a.[uid],
                          Format(a.[activity-time], 'MM-yyyy')) a) b
WHERE  b.rn = 1


text:
Q: How to get promise value correctly? Consider the following code:
function toolsQueryResult(){
    const query = `query{......}`
    return request('http://...', query,).then(data =>  { return data })
}

   var toolsQueryResult= toolsQueryResult();
   var toolsNames      = [];

   toolsQueryResult.then(function(result){
   result['key'].forEach(function(item){
    toolsNames.push(item["name"])
  })
 })

console.log(toolsNames)

This returns and prints out empty list "[ ]" to me.Does any one know why?
But if I put "console.log()" between two final "})", it returns list of tools correctly.How should I work with this promise object to have list of tools correctly after second "})" at the end of code?

A: The reason is, your console.log statement is executed before the the promise toolsQueryResult is resolved. It would be really useful and helpful if you have debugger tools on and place breakpoints to see what i just said.
That said,having the console.log outside of the promise being resolved or rejected beats the whole purpose, meaning you are trying to output a statement before it could complete its execution, hence when you place the console.log statement inside of the then function it outputs result.
Fiddle with your code (modified the result to be a simple array) for you to debug and see : https://jsfiddle.net/jayas_godblessall/vz8mcteh/
or execute it here to see :

function toolsQueryResult() {
  const query = `query{......}`
  return request('http://...', query, ).then(data => {
    return data
  })
}

// just to emulate your api call
function request(foo) {
  return Promise.resolve(["item1", "item2"]);
}

var toolsQueryResult = toolsQueryResult();
var toolsNames = [];

toolsQueryResult.then(function(result) {
  result.forEach(function(item) {
    toolsNames.push(item)
  })
  console.log("am executed after you waited for promise to complete - in this case successfully, so you can see the tool sets")
  console.log(toolsNames)

})

console.log("am executed before you could resolve promise")
console.log(toolsNames)


text:
Q: I have this problem, I already researched and I could not solve it, I imagine it has something to do with database permissions, but I can not fix it: throw new SequelizeErrors.AccessDeniedError(err);
^
AccessDeniedError [SequelizeAccessDeniedError]: Access denied for user 'root'@'localhost' (using password: NO)
at ConnectionManager.connect (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:94:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async ConnectionManager._connect (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:220:24)
at async C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:174:32
at async ConnectionManager.getConnection (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:197:7)
at async C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\sequelize.js:304:26
at async MySQLQueryInterface.tableExists (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\dialects\abstract\query-interface.js:102:17)
at async Function.sync (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\model.js:939:21)
at async Sequelize.sync (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\sequelize\lib\sequelize.js:376:9)
at async Server. (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\EcommerceApp\app.js:19:5) {
parent: Error: Access denied for user 'root'@'localhost' (using password: NO)
at Packet.asError (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\packets\packet.js:728:17)
at ClientHandshake.execute (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\connection.js:456:32)
at PacketParser.onPacket (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\connection.js:85:12)
at PacketParser.executeStart (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket. (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\connection.js:92:25)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10) {
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'@'localhost' (using password: NO)",
sql: undefined
},
original: Error: Access denied for user 'root'@'localhost' (using password: NO)
at Packet.asError (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\packets\packet.js:728:17)
at ClientHandshake.execute (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\commands\command.js:29:26)
at Connection.handlePacket (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\connection.js:456:32)
at PacketParser.onPacket (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\connection.js:85:12)
at PacketParser.executeStart (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket. (C:\Users\ASUS\node_modules\node_modules\anotherfolder\22-aug-2022-mvc\newproject\node_modules\mysql2\lib\connection.js:92:25)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10) {
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'@'localhost' (using password: NO)",
sql: undefined
}
}


text:
Q: Sort Numbers with a Letter Suffix from an Access Database I am attempting to retrieve some information from an Access database using an OleDbConnection. I am trying to Order the results By a column that contains a set of numbers in string format.
I wanted the results in a natural order (e.g. 1, 2, 10, 20 versus 1, 10, 2, 20), so I converted the data in the column of interest to integers and sorted the results.
"SELECT Drawing, Sheet FROM TableName ORDER BY CINT(Sheet) ASC"

This works fine, except in some cases when the table data has values with a letter suffix (e.g. 1A, 2B, etc...). The command above obviously fails for theses cases.
I would like the results sorted like so: 1, 2, 2A, 2B, 3, 3A, and so on...
So, how to go about this? I've seen some examples that use REGEXP and some conditional statements, but apparently MS SQL doesn't support REGEXP. So I'm stuck. Ideas would be appreciated.

A: There is no way to use a regular expression in a query run from outside an Access session.  If the query is run inside an Access session, it could use a custom VBA function with RegExp.  But a regular expression approach seems like over-kill for this situation anyway.  You can get what you need simply with Val().
The Val Function will return a number from the digits in your string.  It will stop reading the string when it hits a letter.
Here's an example from the Immediate window.
? Val("2A")
 2

Use it in your query like this ...
SELECT Drawing, Sheet
FROM TableName
ORDER BY Val(Sheet), Sheet;


text:
Q: problem with Switch Case I am creating a UIView dynamically and adding a scrollview in it. What I want is to create mutiple scrollviews and add them by using SWITCH Case.
I am passing an integer value called num on IBAction of a button on UIView. and calling the function to create a scrollview.
-(IBAction) button1pressed{
    num = 1;
    NSLog(@"value %d",num);
}

I have 6 IBActions like this with different values of num from 1 to 6. I want to Switch the value of num.
-(void)add_scrollview{
    Switch(num) {
        Case:1 {
            NSLog(@"case 1 executed");
            break;
        }
        Case:2 {
            NSLog(@"case 2 executed");
            break;
        }
        Case :3 {
            NSLog(@"case 3 executed");
            break;
        }
        default:{
            break;
        }
    }
}

every time i click a button, it takes its respective "num" value and performs the switch. But, when i click the another button,it is not switching the value of num. It takes num's previous value.

A: case and switch should both be lower case. And the correct syntax is
case 1: {
}

not
case:1{
}

If it still doesnt work i would add an argument to your method with the num instead of having it as a property.
-(void)add_scrollviewWithId:(int) id;