text:
Q: MIPs program to reverse a string using stack I'm getting errors when I'm running my program.
Here are the errors I'm getting.
I'm getting an exception error.
An error saying "Bad address in data/stack read"
An error saying "Instruction references undefined symbol"
In the console it says
"String to be reversed :
COSC 300 Exception 7 [Bad data address] occurred and ignored
The program
.data

str: .asciiz "String to be reversed : \n"
msg: .asciiz "COSC 300"
ans: .asciiz "The string reversed is : "

.text
.globl main

main:

la $a0, str            #print string
li $v0, 4
syscall

la $a0, msg            #print string
li $v0, 4
syscall

la $t0, msg            #load a string to be reversed

loop:
lb $t0, 0 ($t0)       #load char from msg
beqz $t0, stringEnd   # if null end loop
addi $sp, $sp -1      # reduce stack pointer
sb $t0, 0 ($sp)       # store t0 into stack
addi $t1, $t1, 1      # gets next char
j loop

stringEnd:
la $t1, msg1

storeLoop:
lb $t0, 0($t0)
beqz $t0, end
lb $t4, 0($sp)
sb $t4, 0 ($t0)
addi $t1, $t1, 1
addi $sp, $sp, 1
j storeLoop

end:
la $a0, ans
li $v0, 4
syscall

move $a0, $t4
li $v0, 4
syscall

li $v0, 10
syscall

A: One thing that looks a bit funny:
In both loop and storeLoop you are using $t0 as a pointer and also as the character to be loaded.  This means that the first time you load a byte you will be corrupting your pointer.

A: Pseudocode:
print(intro)
text = readString()

// find the end of the string
for (addr = text; *addr != NUL; addr++) { }

// now print it backward
while (--addr >= text) {
 printChar(*addr)
}

Registers:
addr => $t0, tmp => $t1, orig => $t2

    li      $v0, 4          # print(intro)
    la      $a0, intro
    syscall

    li      $v0, 8          # text = readString()
    la      $a0, text
    li      $a1, 256        # (size of input buffer)
    syscall

    la      $t0, text       # addr = text
    move    $t2, $t0        # orig = addr (backup of original address)
find:   lb      $t1, 0($t0)     # tmp = *addr
    beq     $t1, 0, print   # while(tmp != NUL)
    addi    $t0, $t0, 1     # addr++
    j       find            # (end loop)

print:  subi    $t0, $t0, 1     # --addr
    blt     $t0, $t2, end   # while (addr >= orig)
    li      $v0, 11         # printChar(
    lb      $a0, 0($t0)     #   *addr
    syscall                 # )
    j       print           # (end loop)

end:    li      $v0, 10         # exit cleanly
    syscall


text:
Q: Javascript regular expressions to remove character from a strings I would like to remove all occurrences of the words "hello" and "-hello" in a string, the "-" in "-hello" is a minus sign.
I am currently doing it as such

let regex = /hello/-hello/g

let word = "Hello, How are -hello you doing"

let newWord = word.replace(regex,'')

But this seems to throw an error, what is that correct way to do this?
thank you

A: Try this,

    let regex =  /-?hello/gi;

    let word = "Hello, How are -hello you doing"

    let newWord = word.replace(regex,'')

    console.log(newWord);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using linebreak and line options at the same time The documentation of linebreak says:

This option is not used when the 'wrap' option is off or 'list' is on.

I find this unsatisfactory. Is there a workaround to use certain listchars and linebreak?
My ideal .vimrc looks like this:
set linebreak
set list
set listchars=tab:▸–,trail:·,extends:»,precedes:«,nbsp:⍽

… so I'm not actually interested in eol:$, which is presumably the reason why list conflicts with linebreak (that's just my assumption but I see no other plausible reason for them to conflict).
There's a closely related question but in that the OP specifically wants the EOL mark, and the accepted answer addresses only this, so it's not useful for me.

A: I would guess (but do not know for sure) that the current implementation cannot deal with the change of the displayed width when a Tab character shrinks to ^I (assuming it has no value in 'listchars'). In any way, I think Vim could be enhanced to do just what you want, though it might not be easy to implement. It might be worth to raise this request on the vim_dev mailing list.
There are little good workarounds; one could theoretically use the new conceal feature to emulate certain things of :set list, but it interferes with syntax highlighting and there's only one choice for highlighting.


text:
Q: Create Table using DIV's I want to make a scalable 100% table using DIV's only. I don't want to use to display:table or display: table-cell since this doesnt work with IE7. The goal is to make this as cross browser compliant as possible.

1

2

3

4

5

6

If it's possible, I would like to make the cell width auto so if I add in more cells, it would fit into the row perfectly without pushing the cell to a second row. Been trying to figure this out. Any help would be awesome. Thanks

A: You can give your cells a width of 100/amount of cells %.
But if you want it automatically adjusted to the number of cells you will need javascript.
But I can't really get what advantage you see making a table out of divs.

A: I think it's not a nice idea to...reinvent tables (what about header, footer and groups?). You may use 100% width (so it'll works with 90% of browsers) and conditional include for IE7, patching them with a CSS workaround (anchors?) for that people that are still using IE7.

A: Something like:
http://linuxandfriends.com/2009/04/04/how-to-style-div-elements-as-tables/
But what for?

A: I recently did this as, even for tabular data, I wanted to challenge myself to present it using ul and li. You can emulate ul and li to act as your rows and columns.
Consider the following:

Cell #1

Cell #2

Cell #3

Cell #1

Cell #2

Cell #3

CSS
ul { list-style: none; }
  ul li { height: 20px; }
#column-one,
#column-two {
  float: left;
  position: relative;
  width: 50%;
}

If you need to emulate colspan:
.span-4 {
  clear: left;
  float: left;
  position: relative;
  width: 100%; /* if you have 4 UL elements */
}

You'll run into issues if the height of your cells is different. You could create "rowspan" classes which would increase the height.
It's totally up to you. I have always been a proponent for displaying tabular data within a
, but if you want to challenge yourself, please do so!


text:
Q: First law of thermodynamics, steady flow energy equation (SFEE) and $Vdp$ work Can first law of thermodynamics defined for a closed system be applied to the steady flow energy equation? Why?
I came across the derivation of $Vdp$ work and Every book applied the first law defined for closed system to steady flow energy equation.

Please clarify

A: OH , i get it now. You are right.We can't apply the first law if you don't consider the entire system and if the energy can leak in or out by other means ,say a more energetic fluid comes in. But in steady state flow ,no particular trait of a fluid changes with time.This means that the property of a fluid at a particular spatial point is constant in time(to be more mathematical,it's partial derivative with respect to time is zero).This means that the only way the energy of fluid can change in a constraint volume is by change in kinetic energy,change in potential energy or by work done.
For detailed explanantion,go to https://wiki.ucl.ac.uk/display/MechEngThermodyn/First+law+applied+to+flow+processes

A: It helps if you consider the first and second law expressed in terms of energy and entropy densities that depend explicitly on space and time, rather than differentials.
The first laws is:
$$\frac{\partial e}{\partial t} + \nabla\cdot(e\boldsymbol{v})
= \boldsymbol{T}:\nabla\boldsymbol{v}+\nabla\cdot\boldsymbol{q} - Q,$$
where $e$ is the energy density; $\boldsymbol{v}$ the velocity of the fluid or material; $\boldsymbol{T}$ is the stress, e.g. the pressure or viscosity in a fluid; $\boldsymbol{q}$ is the surface flux of heat, and $Q$ is the volume sink of heat. The term $\boldsymbol{T}:\nabla\boldsymbol{v}$ represent the work being done on the fluid or material, and reduces to $p\partial V/\partial t$ in the case of a fluid with no viscosity. If you integrate this equation over a control volume you get a formula that says, in words,
$$\frac{\mathrm{d}(\text{total internal energy within volume})}{\mathrm{d}t} + (\text{flux of energy through volume boundary}) = \text{power} + \text{heating}.$$
The "power" is the work done per unit time, and the "heating" is the heat transferred per unit time. The flux of energy through the boundary appears if the system is open, so matter that moves through the boundary is carrying its internal energy in or out.
The second law has a similar expression:
$$\frac{\partial s}{\partial t} + \nabla\cdot(s\boldsymbol{v})
\geqslant \nabla\cdot\left(\frac{\boldsymbol{q}}{T}\right) - \frac{Q}{T},$$
where $s$ is the entropy density and $T$ the temperature. Again, if you integrate over a control volume you obtain
$$\frac{\mathrm{d}(\text{total entropy within volume})}{\mathrm{d}t} + (\text{flux of entropy through volume boundary}) \geqslant \frac{\text{heating}}{\text{temperature}}.$$
The flux of entropy through the boundary appears if the system is open, so matter that moves through the boundary is carrying its entropy in or out.
I'm sorry if this looks complicated, but if you devote some time to it, even skipping the technical details, it can give you a better grasp of what the first and second laws say and how to use them in unfamiliar situations.
Check out C. A. Truesdell: Rational Thermodynamics (2nd ed., Springer 1984), or I. Samohýl & M. Pekař: The Thermodynamics of Linear Fluids and Fluid Mixtures (Springer 2014).


text:
Q: how could edit value of radio buttons in php In php form I get the data from radio button to database. It works well. But in edit page how do I get the checked value from the database?
my code is:

PCDC:

                <input type="radio" name="pcdc"  value="yes" style="vertical-align: middle; margin: 0px;">YES

                <input type="radio" name="pcdc"  value="no" style="vertical-align: middle; margin: 0px;">NO

A: Please try the code like that way ::
Suppose your variable name of radio button values is "$val" then use this $val variable like that way.
<input type="radio" name="pcdc" <?php if($val == 'yes') { echo "checked='checked'"; } ?>  value="yes" style="vertical-align: middle; margin: 0px;">YES
<input type="radio" name="pcdc"  <?php if($val == 'no') { echo "checked='checked'"; } ?> value="no" style="vertical-align: middle; margin: 0px;">NO

A: Can you try following code to
$('input[name="pcdc"][value="yes"]').prop('checked',true);

Above is a jQuery solution, advantage is when you have number of radio button, no need to check for each element.


text:
Q: Reordering Treenodes in C#.NET I have a Visual Studio 2005 C#.NET GUI application. I want to provide the flexibility to reorder the treenodes in the treeview just by dragging and dropping them wherever desired. Is that possible by using any property of the treeview class? Or do I have to do it the hard way by writing events for mouseup and then sensing the dragging of the node etc etc. Any help would be apreciated.
Thanks, Viren

A: There's better events than mouseup that make this kind of thing easy. This KB article should give you some idea. Read the documentation for the TreeView events that begin with drag for more info.


text:
Q: Is stream Reading can make and send Null to blob storage I use stream for file with: memory stream, stream readinng or file stream such as
byte[] buff = System.IO.File.ReadAllBytes(open.FileName);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buff);

and I want to send it to blob storage and at that point my blob is empty, is it because of reading file by stream or it refers to other problem such as miss configuration on blob or  CloudStorageAccount connection string.

A: Please ensure that your stream is positioned at 0 just before you start uploading to blob from that stream. As mentioned in the comments above, you could try the following:
ms.Position = 0

or
ms.Seek(0, SeekOrigin.Begin)

A: Just use the below code. No need to convert memory stream, You can pass stream to blob storage using Blob.UploadfromStream method.
StorageCredentials creds = new StorageCredentials(
                ConfigurationManager.AppSettings["accountName"],
                ConfigurationManager.AppSettings["accountKey"]
                );
            CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
            CloudBlobClient client = account.CreateCloudBlobClient();
            CloudBlobContainer contain = client.GetContainerReference("your container name");
            contain.CreateIfNotExists();
    CloudBlockBlob blob = contain.GetBlockBlobReference("your blob name");
    using (var stream = System.IO.File.OpenRead("your file"))
                    blob.UploadFromStream(stream);


text:
Q: Logging Custom Headers in IIS 7.5 - Cannot find Advanced Logging Module I wish to log a custom header in IIS logs for an application.
On my local machine (Windows 10, IIS 10.0) this is relatively easy:

On the target machine (Windows Server 2008 R2, IIS 7.5), however the option to add your own fields is not available (Apparently this is only available in IIS 8.5 and above).
I have read instead that you can achieve this same aim by using a module in IIS called Advanced Logging.
I cannot find this option though. In tutorials it appears to the left of the Authentication module in the IIS section (where the arrow below is pointing to).

Where can I find this? Is there somewhere that I need to install it. I had a look in the "Turn Windows Features On/Off" section but I couldn't find it there.

A: Plese try to use the Web Platform Installer to download the installer for this module, something like this:

Just download this via link:

Finally you will get this installer,:

Unfortunately I don't have such an environment to test with, so you'll need to try copying it to the target machine to see if you can install it. If that doesn't fix the issue either, I think you'll have to follow the official recommendation to use Enhanced Logging for IIS 8.5 or later versions.


text: Q: I can't see mysql.user table, I need to recover root password I logged to mysql server using mysql -ujohn -p. Then I executed show databases and I didn't see the mysql database so I can't execute use mysql. What I see are information_schema and test databases. Why can't I see the mysql database in order to list users table?


text:
Q: How to view php logs information with php docker container? I have a php-fpm docker container .  Php-fpm is run inside container, can i get php-fpm's log on host machine?  If i can,  how to do?

A: The common approach is that applications inside a container don't log to a file, but output logs on stdout / stderr. Anything that's printed to stdout / stderr by the container's main process is collected by the built-in logging facilities of docker, and can be viewed using docker logs <container-name>.
By default, the logs are stored per-container using the json-file logging driver, and will be deleted when the container itself is deleted, but there are other logging drivers available (see Configure logging drivers) that allow you to send those logs to (e.g.) syslog, journald, gelf.
Also see

*

*View a container's logs

*docker logs

A: The standard for Docker containers is to log to stdout/stderr. However this doesn't work well for some PHP runtimes, for example php-fpm, because of how logs get mangled in length and format.
Therefore, I switched my approach to write logs on a volume and using a sidecar container to get it into stderr and hence into Docker's log collection and/or your orchestrator.
Sample docker-compose.yml section:
cli:
    build: .
    volumes:
        - logs:/srv/annotations/var/logs
logger:
    image: busybox:1.27.2
    volumes:
        - logs:/logs
    # be careful, this will only tail alredy existing files
    command: tail -f /logs/all.json
    depends_on:
        - cli


text:
Q: Searching Model with Many to Many Polymorphic Relation Following the tags example in the Laravel docs, I've successfully implemented image tagging, and now I'm trying to search by said tags.
Pulling an image from a single tag works well, but I'm hitting a roadblock when trying to search for images containing multiple tags.
This is the closest I've gotten, and it works as expected but it is not what I desire.
/**
* $tag string, example: 'baseball'
* $tags array, example: ['baseball','stadium','new.york.yankees']
*/
Image::whereHas('tags', function($query) use ($tag,$tags) {
    if (count($tags)) {
        // Retrieves images tagged as 'baseball' OR 'stadium' OR 'new.york.yankees'
        // Instead, I want it to retrieve images that have all three tags
        $query->whereIn('tag', $tags);

        // The following returns no results, though there are images tagged correctly.
        // I presume this is an incorrect approach.
        foreach ($tags as $tag) {
            $query->where('tag', '=', $tag);
        }
    } else {
        // Retrieves images tagged as 'baseball'
        $query->where('tag', '=', $tag);
    }
})->orderBy('created_at', 'desc')
->paginate(config('app.images_per_page'))

I'm stumped, overtired, and getting nowhere while searching for similar examples. What am I missing? What is the correct terminology for what I am trying to achieve, so I can add it to my vocabulary for future endeavors?

A: I think this just needs to be a whereHas statement for each of the tags you are trying to filter by.  This would create an AND statement within the query.
if(!$count($tags)) $tags = [$tag]; //for simplicity lets always have an array

$imageQuery = Image::query();
foreach($tags as $tag){
    $imageQuery = $imageQuery->whereHas('tags', function($query) use ($tag) {
        $query->where('tag', '=', $tag);
    });
}
$results = $imageQuery->orderBy('created_at', 'desc')
    ->paginate(config('app.images_per_page'))->get();

Code is not tested but logically I think you need a where clause for each tag


text:
Q: Customizing the series data in pie charts with a dynamic json series (HighCharts) I am fairly new to Highcharts. I have a pie chart that is being rendered fine with dynamic data (JSON String) . But I want to customize certain slices to be Sliced: true and Selected: True. I am not sure how to do it. Please find my code as below,

var series = [];
var total = 0;
$.each(data, function(index, value) {
            series.push([value.statisticData+'_'+value.sizes,parseInt(value.sizes)]);
            console.log("statisticData",value.statisticData);
            console.log("value.sizes",value.sizes);
            total += parseInt(value.count);
        });

        var chartSessionStatus = new Highcharts.Chart({
            chart: {
                renderTo: $("#container_"+testSessionPageId).get(0),
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            exporting: {
                enabled: true,
                buttons: {
                    contextButton: {
                        menuItems: [{
                            text: 'Statistics',
                        }]
                    }}
                },

            tooltip: {
                formatter: function() {
                    return this.point.name.split('_')[0] + ': '+this.y+'';
                }
            },
            title: {
                text: '
Tenant Statistics
'
            },
            legend: {
                    labelFormatter: function() {
                        return this.name.split('_')[0] + ' (' + this.y+')';
               }
            },

            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        distance: 0,
                        useHTML: true,
                        formatter: function() {
                            if( this.y > 0)
                                return ''+this.point.name.split('_')[0] +'('+ this.y +')';
                        }
                    },
                    showInLegend: true,
                    size: 150
                }
            },
            series: [{
                type: 'pie',
                name: 'Tenant Statistics',
                data: series
            }]
        });

    });

Main point of concern, in the series , I have the option for data as "data : series" but I would like to customize certain slices in this series. But since the data is dynamic I am not sure how to use only certain parts of the json string
The Json that i receive is in the following format :
[{"statisticData":"Tests Created","sizes":"3"},{"statisticData":"Students","sizes":"2"},{"statisticData":"Users","sizes":"7"},{"statisticData":"Schools","sizes":"10"}]
Any Help is greatly appreciated !!! Thanks in advance.

A: After getting json, you can parse it / add slice parameter and then use in highcharts. So instead of pushing :series.push([value.statisticData+'_'+value.sizes,parseInt(value.sizes)]);
you can push something like:
series.push({
        name: value.statisticData+'_'+value.sizes,
        y: parseInt(value.sizes),
        sliced: true,
        selected: true
});


text:
Q: On OS X, difference between drag & drop install vs copying to /Applications I'm trying to automate the install of Xcode on an OS X machine. I've come across this question that got me most of the way.
The script given in the second answer gets the appropriate dmg mounted, and then uses installer to install the pkg. Except these days (e.g. version 7.3.1) Xcode is given as an app bundle inside the dmg, so there is no pkg to install. So I tried to simply copy it to /Applications via
cp -Rf /Volumes/Xcode/Xcode.app /Applications/

The resulting Xcode in my /Applications folder is 9.1 GB. But if I simply rename that bundle, manually open the dmg, and then drag & drop Xcode onto the Application shortcut, I end up with an Xcode that is 10.51 GB in size. Yet when I ask opendiff to compare the two, it tells me the contents are identical...
Does dragging & dropping from a dmg do something else under the hood, besides simply copying the app into /Applications? If so, is there a way to achieve the same via the command line?


text:
Q: Retrieve and parse JSON from multiple URLs and add to listview I started learning android a week ago and decided to write a simple android application for a website bhooka.in. I used koush/ion api to retrieve json data from the url.
Here's the problem - I have a single JSON file, containing multiple JSON URLs. Now I tried to retrieve all the JSONs in a for loop, but that doesn't seem to work. Here's the code:
Future<JsonObject> loading;

private void load() {
    // don't attempt to load more if a load is already in progress
    if (loading != null && !loading.isDone() && !loading.isCancelled())
        return;

    // load the tweets
    String url = "http://bhooka.in/web_services_json_helper.php?mode=fetch_locations&user_agent=in.bhooka.bhooka&city_id=4";
    loading = Ion.with(this)
            .load(url)
            .asJsonObject()
            .setCallback(new FutureCallback<JsonObject>() {
                @Override
                public void onCompleted(Exception e, JsonObject result) {
                    // this is called back onto the ui thread, no Activity.runOnUiThread or Handler.post necessary.
                    if (e != null) {
                        Toast.makeText(getView().getContext(), "Error loading information", Toast.LENGTH_LONG).show();
                        return;
                    }
                    JsonArray locationsList = result.getAsJsonArray("locations");
                    // add the tweets
                    for (int i = 0; i < locationsList.size(); i++) {
                        try {
                            JsonObject temp = Ion.with(getView().getContext())
                                    .load("http://bhooka.in/web_services_json_helper.php?mode=fetch_loc_info&user_agent=in.bhooka.bhooka&loc_id=" + locationsList.get(i).getAsJsonObject().get("post_id").getAsString())
                                    .asJsonObject().get();
                            placeArrayAdapter.add(temp.get("loc_info").getAsJsonObject());
                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }

                                /* tried this approach - but it doesn't work
                                .setCallback(new FutureCallback<JsonObject>() {
                                    @Override
                                    public void onCompleted(Exception e, JsonObject result) {
                                        // this is called back onto the ui thread, no Activity.runOnUiThread or Handler.post necessary.
                                        if (e != null) {
                                            Toast.makeText(getView().getContext(), "Error loading information", Toast.LENGTH_LONG).show();
                                            return;
                                        }
                                        placeArrayAdapter.add(result.get("loc_info").getAsJsonObject());
                                    }
                                });*/
                    }
                }
            });
}

The application opens up and then just freezes. I've also tried the asynchronous approach using callbacks, but it just shows up one or two entries in the listview and then it crashes. Could somebody please tell me what I'm doing wrong?
Thanks a lot.
EDIT: As suggested, here's the logcat:
07-14 17:02:11.851  20332-20332/? D/dalvikvm﹕ Late-enabling CheckJNI
07-14 17:02:11.867  20332-20338/? D/dalvikvm﹕ Debugger has detached; object registry had 1 entries
07-14 17:02:12.206  20332-20332/? I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LNX.LA.3.5.1_RB1.04.04.02.048.018_msm8610_LNX.LA.3.5.1_RB1__release_AU ()
    OpenGL ES Shader Compiler Version: E031.24.00.08
    Build Date: 03/07/14 Fri
    Local Branch:
    Remote Branch: quic/LNX.LA.3.5.1_RB1.1
    Local Patches: NONE
    Reconstruct Branch: AU_LINUX_ANDROID_LNX.LA.3.5.1_RB1.04.04.02.048.018 + f2fd134 +  NOTHING
07-14 17:02:12.244  20332-20332/? D/OpenGLRenderer﹕ Enabling debug mode 0
07-14 17:02:14.469  20332-20364/in.bhooka.bhooka D/dalvikvm﹕ Trying to load lib /data/app-lib/in.bhooka.bhooka-2/libgmscore.so 0x41d995f0
07-14 17:02:14.470  20332-20364/in.bhooka.bhooka E/dalvikvm﹕ dlopen("/data/app-lib/in.bhooka.bhooka-2/libgmscore.so") failed: dlopen failed: library "/data/app-lib/in.bhooka.bhooka-2/libgmscore.so" not found
07-14 17:02:14.470  20332-20364/in.bhooka.bhooka E/ProviderInstaller﹕ Unable to load native code from /data/app-lib/in.bhooka.bhooka-2/libgmscore.so
07-14 17:02:14.470  20332-20364/in.bhooka.bhooka D/dalvikvm﹕ Trying to load lib /data/app-lib/com.google.android.gms-2/libgmscore.so 0x41d995f0
07-14 17:02:14.472  20332-20364/in.bhooka.bhooka D/dalvikvm﹕ Added shared lib /data/app-lib/com.google.android.gms-2/libgmscore.so 0x41d995f0
07-14 17:02:14.472  20332-20364/in.bhooka.bhooka D/dalvikvm﹕ No JNI_OnLoad found in /data/app-lib/com.google.android.gms-2/libgmscore.so 0x41d995f0, skipping init
07-14 17:02:14.474  20332-20364/in.bhooka.bhooka E/ProviderInstaller﹕ libgmscore version mismatch (0 vs. 7574)
07-14 17:02:14.474  20332-20364/in.bhooka.bhooka W/IonConscrypt﹕ Conscrypt initialization failed.
07-14 17:02:44.955  20332-20364/in.bhooka.bhooka D/dalvikvm﹕ GC_FOR_ALLOC freed 3066K, 29% free 7930K/11072K, paused 37ms, total 47ms
07-14 17:02:45.008  20332-20332/in.bhooka.bhooka D/AndroidRuntime﹕ Shutting down VM
07-14 17:02:45.008  20332-20332/in.bhooka.bhooka W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415dad40)
07-14 17:02:45.010  20332-20332/in.bhooka.bhooka E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: in.bhooka.bhooka, PID: 20332
    java.lang.NullPointerException
            at in.bhooka.bhooka.MainActivity$1.onCompleted(MainActivity.java:73)
            at in.bhooka.bhooka.MainActivity$1.onCompleted(MainActivity.java:67)
            at com.koushikdutta.async.future.SimpleFuture.handleCallbackUnlocked(SimpleFuture.java:107)
            at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:141)
            at com.koushikdutta.async.future.SimpleFuture.setComplete(SimpleFuture.java:124)
            at com.koushikdutta.ion.IonRequestBuilder$1.run(IonRequestBuilder.java:244)
            at com.koushikdutta.async.AsyncServer$RunnableWrapper.run(AsyncServer.java:57)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

A: instead use retrofit and jackson converter to get the locations . It would really simply your code since code is really complex. These are the best combination to deal with urls

A: When you want to add items to an ListView/adapter, you have to do this in the main-thread.
You can use a Handler for that:
In your main-thread
Handler handler = new Handler();

And when you need to execute something on the main-thread
handler.post(new Runnable() {
    @Override
    public void run() {
        placeArrayAdapter.add(temp.get("loc_info").getAsJsonObject());
    }
}


text:
Q: vim could not load library python26.dll but i'm using python 2.7? Using vim and when I try use omnicomplete for python I get an error
Required vim compiled with +python.

When I try
:python print 'hello'

I get
E370: Could not load library python26.dll

Strangely I'm using python 2.7 anyway so how can I change what python vim should use or will I have to install python 2.6 to use this feature?

A: You have to have the same version of python installed that vim was compiled against.  That means you either need to install 2.6 or recompile vim against 2.7 (or find an existing binary that already is).


text:
Q: what is the best approach to creating 1-many relationship in dynamo db/ based on answer here for creating one-to-many (How to model one-to-one, one-to-many and many-to-many relationships in DynamoDB) . I understand we need to add a Global Secondary Index (GSI)  to the employee table below. what would be the GSI be here and as an example query, how does the query look like to find an employee with the highest salary , or youngest under a particular manager
Employee table:

Partition Key: eId

╔═══════╦═════════════╦════════╗════════
║  eId  ║ mgId ║  Age ║ salary ║  Name  ║
╠═══════╬═════════════╬════════╣════════
║ P1    ║ O1   ║  37  ║ 42000  ║ Jim    ║
║ P2    ║ O1   ║  38  ║ 40000  ║ Andy   ║
║ P3    ║ O2   ║  35  ║ 45000  ║ Angela ║
╚═══════╩═════════════╩════════╝════════
manager table:

Partition Key: mngrId

╔═════════╦════════╗
║ mgId    ║ Name   ║
╠═════════╬════════╣
║ O1      ║ Dwight ║
║ O2      ║ Micheal║
╚═════════╩════════╝


text:
Q: perl, starting more processes at the same time I am using Strawberry Perl on Windows XP to download multiple html pages, I want each in a variable.
Right now I am doing this, but as I see it, it gets one page at a time:
my $page = `curl -s http://mysite.com/page -m 2`;
my $page2 = `curl -s http://myothersite.com/page -m 2`;

I looked into Parallel::ForkManager, but couldnt get it to work.
Also tried to use the windows command start before curl but that doesn't get the page.
Is there a more simple way to do this?

A: The Parallel::ForkManager module should work for you, but because it uses fork instead of threads, the variables in the parent and each of the child processses is separate and they must communicate a different way.
This program uses the -o option of curl to save the pages in files. The file for, say, http://mysite.com/page is saved in file http\mysite.com\page and can be retrieved from there by the parent process.
use strict;
use warnings;

use Parallel::ForkManager;
use URI;
use File::Spec;
use File::Path 'make_path';

my $pm = Parallel::ForkManager->new(10);

foreach my $site (qw( http://mysite.com/page http://myothersite.com/page )) {
  my $pid = $pm->start;
  next if $pid;
  fetch($site);
  $pm->finish;
}

$pm->wait_all_children;

sub fetch {
  my ($url) = @_;

  my $uri = URI->new($url);
  my $filename = File::Spec->catfile($uri->scheme, $uri->host, $uri->path);
  my ($vol, $dir, $file) = File::Spec->splitpath($filename);

  make_path $dir;
  print `curl http://mysite.com/page -m 2 -o $filename`;
}

Update
Here is a version that uses threads with threads::shared to return each page into a hash shared between all the threads. The hash must be marked as shared, and locked before it is modified to prevent concurrent access.
use strict;
use warnings;

use threads;
use threads::shared;

my %pages;
my @threads;

share %pages;

foreach my $site (qw( http://mysite.com/page http://myothersite.com/page )) {
  my $thread = threads->new('fetch', $site);
  push @threads, $thread;
}

$_->join for @threads;

for (scalar keys %pages) {
  printf "%d %s fetched\n", $_, $_ == 1 ? 'page' : 'pages';
}

sub fetch {
  my ($url) = @_;
  my $page = `curl -s $url -m 2`;
  lock %pages;
  $pages{$url} = $page;
}


text:
Q: Ya hay un objeto llamado ##TablaTemporal en la base de datos Tengo el siguiente procedimiento almacenado, el cual permite generar un reporte en Excel. El caso es que cuando varios usuarios están generando el reporte, aparecen una serie de errores que indican ya hay un objeto llamado ##rpttabla en la base de datos.
Quisiera saber, ¿cómo puedo hacer para generar un nombre de tabla temporal aleatorio cada vez que se ejecuta el procedimiento?
IF @Opt = 0 BEGIN

    IF OBJECT_ID('tempdb..##RptMayorD')  IS NOT NULL
    BEGIN DROP TABLE ##RptMayorD END

    --** COMPROBANTE AUTOMATICOS **--
    SELECT
        Cuenta = D.Cuenta,
        Descripcion=CAST('' AS VARCHAR(250)),
        Folio=CAST(A.Folio AS VARCHAR(20)),
        Lote = CAST(A.IdLote AS VARCHAR(20)),
        Comprobante = C.Comprobante,
        FechaContable= CONVERT(CHAR(10),F.FechaContable,103),
        A.CodigoTransaccion,
        ReferenciaNegocio =  C.ReferenciaNegocio,
        OficinaTransaccion = D.OficinaContable,
        Nombre_Oficina=CAST('' AS VARCHAR(50)),
        MonedaTransaccion = c.MonedaTransaccion,
        Cotizacion  = D.Cotizacion ,
        ValorDebito = D.ValorDebito,
        ValorDebitoEquivalencia= D.valordebitoequivalencia,
        ValorCredito  =  D.ValorCredito,
        ValorCreditoEquivalencia= D.ValorCreditoEquivalencia,
        Concepto=C.Concepto,
        Observacion = CAST('' AS VARCHAR(150)),
        NroDocumento = CAST('' AS VARCHAR(15)),
        Cliente = CAST('' AS VARCHAR(250)) ,
        a.Origen,
        FechaTransaccion=CONVERT(CHAR(10),A.FechaTransaccion,103),
        Nombre = CAST('' AS VARCHAR(150)),
        NombreCliente = CAST('' AS VARCHAR(150)),
        a.IDFechaContable,
        A.IDLote,
        IDAsiento = C.IDAsiento,
        IDComprobante
        INTO  ##RptMayorD
    FROM Contabilidad..Comprobante A  WITH (NOLOCK)
    INNER JOIN Contabilidad..FechaContable F  WITH (NOLOCK) on F.IdFechaContable = A.IdFechaContable
    INNER JOIN GeneradorContableHistorico..Asientohistorico C  WITH (NOLOCK) on a.IdLote = c.LoteContable
    INNER JOIN GeneradorContableHistorico..AsientoDetalleHistorico D WITH (NOLOCK) on c.IdAsiento = d.IdAsiento
    WHERE A.EsMayorizado = 1 And A.EsCuadrado = 1 And A.EsVigente = 1 AND A.Origen <> 'MANUAL'  AND
          A.Folio LIKE @Fecha + '%'
          AND D.cuenta LIKE @Cuenta + '%'
          AND D.Moneda LIKE  @Moneda + '%'

    --** COMPROBANTE MANUALES **--
    INSERT INTO ##RptMayorD
    SELECT
        Cuenta = B.Cuenta,
        Descripcion=CAST('' AS VARCHAR(250)),
        Folio=CAST(A.Folio AS VARCHAR(20)),
        Lote = CAST(A.IdLote AS VARCHAR(20)),
        Comprobante = CAST('' AS VARCHAR(200)),
        FechaContable=CONVERT(CHAR(10),F.FechaContable,103),
        A.CodigoTransaccion,
        ReferenciaNegocio = CAST('' AS VARCHAR(250)),
        OficinaTransaccion = B.IDOficinaContable,
        Nombre_Oficina=CAST('' AS VARCHAR(50)),
        MonedaTransaccion = B.Moneda,
        Cotizacion  = B.ValorCotizacion ,
        ValorDebito =B.MontoDebito,
        ValorDebitoEquivalencia= B.MontoDebitoEquivalencia,
        ValorCredito  = B.MontoCredito,
        ValorCreditoEquivalencia = B.MontoCreditoEquivalencia,
        Concepto= CAST(A.Comentario.query(N'/Glosa/Comentario/text()') AS VARCHAR(8000)),
        Observacion = CAST('' AS VARCHAR(150)),
        NroDocumento = CAST('' AS VARCHAR(15)),
        Cliente = CAST('' AS VARCHAR(250)) ,
        a.Origen,  FechaTransaccion=CONVERT(CHAR(10),
        A.FechaTransaccion,103),
        Nombre = CAST('' AS VARCHAR(150)),
        NombreCliente = CAST('' AS VARCHAR(150)),
        A.IDFechaContable,
        IDLote,
        IDAsiento = 0,A.IDComprobante
    FROM Contabilidad..Comprobante A  WITH (NOLOCK)
    INNER JOIN Contabilidad..FechaContable F  WITH (NOLOCK) on F.IdFechaContable = A.IdFechaContable
    INNER JOIN Contabilidad..detallecomprobante B WITH (NOLOCK) on a.idcomprobante = b.idcomprobante
    WHERE A.EsMayorizado = 1 And A.EsCuadrado = 1 And A.EsVigente = 1 AND A.Origen = 'MANUAL'
            AND B.cuenta LIKE  @Cuenta + '%'
            AND A.Folio like @Fecha + '%'
            AND B.Moneda  LIKE  @Moneda + '%'

    --> Actualizar Nombre de Oficina
    UPDATE C SET Nombre_Oficina = trx.Nombre
    FROM ##RptMayorD C  WITH (NOLOCK)
    Join Configuracion..Oficina trx  WITH (NOLOCK) on trx.idoficina = c.OficinaTransaccion

    --> Actualizar Descripcion de la Cuenta
    UPDATE C SET Descripcion = trx.Descripcion
    FROM ##RptMayorD C  WITH (NOLOCK)
    Join contabilidad..catalogocuenta trx  WITH (NOLOCK) on trx.cuenta = c.cuenta

    --> Actualizar Nombre y Numero de Documento desde cuenta cliente
    UPDATE C SET NombreCliente=Nombres, NroDocumento = Documento, Cliente=Nombres
    FROM ##RptMayorD C  WITH (NOLOCK)
    Join Cuenta..CuentaCliente Cred  WITH (NOLOCK) On Cred.NumeroCuenta = c.ReferenciaNegocio
    Join Cliente..VW_Clientes Cli  WITH (NOLOCK) on Cred.IdCliente = Cli.IdCliente
    WHERE Origen <> 'MANUAL'

    -->Actualizar Nombre y Numero de Documento desde credito
    UPDATE C SET NombreCliente=Nombres, NroDocumento = Documento, Cliente=Nombres
    FROM ##RptMayorD C  WITH (NOLOCK)
    Join Credito..Credito Cred  WITH (NOLOCK) On Cred.NumeroCredito = c.ReferenciaNegocio
    Join Cliente..VW_Clientes Cli  WITH (NOLOCK) on Cred.IdCliente = Cli.IdCliente
    WHERE Origen <> 'MANUAL'  AND Cliente = ''

    --> Actualizar Nombres desde Transaccion
    UPDATE C SET Nombre=trx.Nombre, Observacion=trx.Observacion, NroDocumento = NumeroIdentificacion, Cliente = trx.Nombre
    FROM ##RptMayorD C  WITH (NOLOCK)
    Left  Join Caja..transaccion trx  WITH (NOLOCK) on trx.secuencial = c.ReferenciaNegocio
    WHERE Origen <> 'MANUAL'  AND Cliente = ''

    UPDATE ##RptMayorD SET Nombre='' WHERE Nombre IS NULL
    UPDATE ##RptMayorD SET Observacion='' WHERE Observacion IS NULL
    UPDATE ##RptMayorD SET NombreCliente='' WHERE NombreCliente IS NULL
    UPDATE ##RptMayorD SET NroDocumento='' WHERE NroDocumento IS NULL
    UPDATE ##RptMayorD SET Cliente='' WHERE Cliente IS NULL

    UPDATE A SET Concepto = Concepto_A
    FROM ##RptMayorD A
    JOIN (SELECT NumeroCuenta, ComprobanteCanal, B.IDCuentaCliente,
                 Concepto_A=Comentario + ' ' + ComentarioEstadoCuenta, FechaContable=CONVERT(CHAR(10),C.FEchaContable,103)
          FROM Cuenta..CuentaCliente B   WITH (NOLOCK)
          JOIN Cuenta..Transaccion C  WITH (NOLOCK) ON B.IDCuentaCliente = C.IDCuentaCliente  AND C.CodigoAtributo='ATRCRECASACOMER'
          ) D
    ON A.ReferenciaNegocio = D.NumeroCuenta AND A.CodigoTransaccion='TRANSCTA' AND A.FEchaContable = D.FEchaContable AND ComprobanteCAnal = Comprobante

    SELECT COUNT(*) N FROM ##RptMayorD

END

IF @Opt = 1 BEGIN
    SELECT Cuenta, Descripcion, Folio, Lote, Comprobante, FechaContable, CodigoTransaccion, ReferenciaNegocio,
           Cod_Oficina = OficinaTransaccion, Nombre_Oficina, Moneda = MonedaTransaccion, Cotizacion, ValorDebito,
           ValorDebitoEquivalencia, ValorCredito, ValorCreditoEquivalencia,
           Concepto, Observacion, NroDocumento, Cliente, Origen, FechaTransaccion
    FROM ##RptMayorD
    ORDER BY Folio
END

La versión que utilizo es la 2012 y la tabla sólo es utilizada en ese procedimiento almacenado.
Lo que ocurre es que no puedo usar tablas temporales locales porque cada parte del procedimiento almacenado utiliza una cadena de conexión diferente (como Davlio indica en un comentario). Las tablas temporales sólo se pueden utilizar en la conexión en la que el usuario las crea. Cuando la conexión termina la tabla temporal desaparece, cuando uso tablas temporales locales me sale el error "no se encontro el objeto ****"

A: Diferencia entre una tabla temporal global y local

#locales: Las tablas temporales locales tienen una # como primer carácter en su nombre y sólo se pueden utilizar en la conexión en la
  que el usuario las crea. Cuando la conexión termina la tabla temporal
  desaparece.
##globales: Las tablas temporales globales comienzan con ## y son visibles por cualquier usuario conectado al SQL Server. Y una cosa
  más, estás tablas desaparecen cuando ningún usuario está haciendo
  referencias a ellas, no cuando se desconecta el usuario que la creo.

El error que encuentras:

ya hay un objeto llamado ##rpttabla en la base de datos

Es debido a que todo los usuarios conectados encuentran redundancia en la existencia de la tabla temporal ##rpttabla, por ello podrías usar una tabla temporal de tipo local debido a que solo lo utilizas en un único procedimiento almacenado.

Podrías también considerar revisar:

*

*Diferencia entre variable de tabla y tabla temporal en SQL
Server

A: Ya lo Solucione Gracias.
declare @Cuenta Varchar(25),@Fecha Varchar(10),@Moneda Varchar(3),@User Varchar(20)
Declare @NomTabla Varchar(60)
    SET @User = 'CMARRUFO'
    SET @Cuenta ='190106010105'
    SET @Fecha ='20170812'
    SET @Moneda = 'SOL'
    SET @NomTabla = '##RptMayorDetalle' + @User

 EXEC ('IF OBJECT_ID(''tempdb..'+ @nomtabla + ''')  IS NOT NULL BEGIN DROP TABLE '+ @nomtabla + ' END')

    --** COMPROBANTE AUTOMATICOS **--
EXEC (' SELECT
            Cuenta = D.Cuenta,
            Descripcion=CAST('''' AS VARCHAR(250)),
            Folio=CAST(A.Folio AS VARCHAR(20)),
            Lote = CAST(A.IdLote AS VARCHAR(20)),
            Comprobante = C.Comprobante,
            FechaContable= CONVERT(CHAR(10),F.FechaContable,103),
            A.CodigoTransaccion,
            ReferenciaNegocio =  C.ReferenciaNegocio,
            OficinaTransaccion = D.OficinaContable,
            Nombre_Oficina=CAST('''' AS VARCHAR(50)),
            MonedaTransaccion = c.MonedaTransaccion,
            Cotizacion  = D.Cotizacion ,
            ValorDebito = D.ValorDebito,
            ValorCredito  =  D.ValorCredito,
            Concepto=C.Concepto,
            Observacion = CAST('''' AS VARCHAR(150)),
            NroDocumento = CAST('''' AS VARCHAR(15)),
            Cliente = CAST('''' AS VARCHAR(250)) ,
            a.Origen,
            FechaTransaccion=CONVERT(CHAR(10),A.FechaTransaccion,103),
            Nombre = CAST('''' AS VARCHAR(150)),
            NombreCliente = CAST('''' AS VARCHAR(150)),
            a.IDFechaContable,
            A.IDLote,
            IDAsiento = C.IDAsiento,
            IDComprobante
            INTO '+ @nomtabla +'
        FROM Contabilidad..Comprobante A  WITH (NOLOCK)
        INNER JOIN Contabilidad..FechaContable F  WITH (NOLOCK) on F.IdFechaContable = A.IdFechaContable
        INNER JOIN GeneradorContableHistorico..Asientohistorico C  WITH (NOLOCK) on a.IdLote = c.LoteContable
        INNER JOIN GeneradorContableHistorico..AsientoDetalleHistorico D WITH (NOLOCK) on c.IdAsiento = d.IdAsiento
        WHERE A.EsMayorizado = 1 And A.EsCuadrado = 1 And A.EsVigente = 1 AND A.Origen <> ''MANUAL''
        AND A.Folio LIKE'+ @Fecha +' + ''%''
              AND D.cuenta LIKE '+ @Cuenta +' + ''%''
              AND D.Moneda LIKE  '+ @Moneda +' + ''%''')


text:
Q: Como resolver o erro adb.exe start-server' failed -- run manually if necessary Estou tendo o erro:

Unable to run 'adb': null
  16:08 'C:\Users\Usuário\Desktop\PI\SDK\platform-tools\adb.exe
  start-server' failed -- run manually if necessary

Ao pressionar o botão run o Android Studio não mostra nenhum dispositivo, nem os AVDs que tenho.
Ele fica assim:

Pesquisei no Google e várias vezes encontrei que tem que fechar o processo adb.exe, vou lá e fecho e não resolve.
Vi também que abrir o cmd na pasta platform-tools e encerrar o server mas quando faço isso o cmd quebra a linha e o cursor só fica piscando e não faz nada.

A: Já resolvi o erro.
Havia um determinado serviço (traccar) que estava em execução no meu PC.
Só tive que reiniciá-lo e encerrar os processos adb.exe, e o Android Studio voltou a funcionar normalmente.
Outros dias, acontecia o mesmo, apenas tenho que reiniciar o serviço e encerrar os processos adb.exe.


text:
Q: Drawing TTF text in Slick2D at large sizes causes distortion Note: I am using Scala rather than Java but that should not make a difference.
I recently started using LWJGL and am currently trying to draw 2D strings using the TrueTypeFont Slick class, however when I draw a string using font.drawString(x, y, text, Color.white) at sizes larger than 48, the text gets distorted. Certain letters in the text become lines, and as I increase the size it becomes more extreme. Below is a comparison of font sizes 48 and 72 being drawn:

My code for creating the font is as follows:
val inputStream = ResourceLoader.getResourceAsStream("assets/font/" + file)
val font = new TrueTypeFont(Font.createFont(Font.TRUETYPE_FONT, inputStream).deriveFont(size.toFloat), true)

I have tried this with both built in fonts (Arial and Times New Roman) and custom fonts like the one above, Augustus and they all have the same problem. How can I render these fonts correctly at larger sizes?


text:
Q: Writing To and Reading From JSON File I am writing a script to check to see if a json file exists.  If it does, then it uses flask render_template function to use the data to load a web page.  If it does not, the script queries the database, puts the data in json format, and then creates and writes to the json file.  Here is some example code.
from flask import render_template
import json
import os

title = "Tests"
jsonFile = "tests.json"
if os.path.exists(jsonFile):
    return render_template('tests.html', title=title, data='tests')
else:
    data = '{"tests":[{"id":"1","ip_addy":"IP1","name":"name1"},
                      {"id":"2","ip_addy":"IP2","name":"name2"},
                      {"id":"3","ip_addy":"IP3","name":"name3"}
                     ]}'
    with open(jsonFile, "w+") as f:
        json.dump(data, f)
    f.close()
    return render_template('tests.html', title=title, data=data)

It writes to the test.json file just fine, but when I reload the tests.html page after creating test.json, the html says there are no records to display.  Did I create the json file incorrectly?

A: As @Simon Johansson mentions, it looks like the issue is that you are not reading the contents of the file.  Making just that change seems to work for me.
@app.route('/test')
def test():
    title = "Tests"
    jsonFile = "tests.json"
    if os.path.exists(jsonFile):
        file_data = ""
        try:
            with open(jsonFile) as f:
                file_data = f.read()
        except:
            file_data = "could not read file"
        return render_template('tests.html', title=title, data=file_data)
    else:
        data = {"tests":[{"id":"1","ip_addy":"IP1","name":"name1"},
                          {"id":"2","ip_addy":"IP2","name":"name2"},
                          {"id":"3","ip_addy":"IP3","name":"name3"}
                         ]}
        with open(jsonFile, "w+") as f:
            json.dump(data, f)
        f.close()
        return render_template('tests.html', title=title, data=data)

I tried modifying the file data once written and the changed data does show up correctly, indicating that the data is read from the file ok if present.
I used a simple templates\tests.html
<title>{{title}}</title>
Data:
{{data}}

A: This is the solution to the problem, thanks to Simon and J. Fay.  The data must be written and read as json.
@app.route('/test')
def test():
    title = "Tests"
    jsonFile = "tests.json"
    if os.path.exists(jsonFile):
        file_data = ""
        try:
            with open(jsonFile) as f:
                file_data = json.load(f)
            f.close()
        except:
            file_data = "could not read file"
        return render_template('tests.html', title=title, data=file_data)
    else:
        data = {"tests":[{"id":"1","ip_addy":"IP1","name":"name1"},
                         {"id":"2","ip_addy":"IP2","name":"name2"},
                         {"id":"3","ip_addy":"IP3","name":"name3"}
                         ]}
        with open(jsonFile, "w+") as f:
            json.dump(data, f)
        f.close()
        return render_template('tests.html', title=title, data=data)


text:
Q: Can I install different softwares into one Aws EC2 virtual machine? I want to ask a question as I'm new to AWS.
At one instance of Ubuntu EC2 I installed InfluxDB and it is running so I want to know if I can install Node.js on that same instance? Would my node.js installation affect InfluxDB?
Basically, I want to run a background nodejs script that will be live forever, to insert data to InfluxDB from a server.
Would I need to launch a separate virtual machine to run that script OR it will be on that same virtual machine?

A: Generally speaking, you can install and run any software in a single EC2 instance. The only limit is the underlying resource, meaning whether the instance has sufficient memory, CPU, disk I/O or network bandwidth to run all of them.
Practically, any decisions you make will have trade-offs and it's always good for you to be aware of them.
In your case, I can give you some pros and cons of the 2 approaches
Same-instance installation

*

*Pros: easy to configure as your script is in the same instance with your InfluxDB. Also , if your NodeJS script has a small resource footprint, then this approach is possibly cheaper as well.

*Cons: if you are running a cluster of multiple InfluxDB instances, having multiple copies of a NodeJS script in all of your InfluxDB instances will make it hard to maintain, deploy, update and monitor those instances.
This approach is only recommended if you are running single-node InfluxDB.

Dedicated installation

*

*Pros: easy to scale up. easy to manage, deploy and update. better availability.

You can have a dedicated cluster of InfluxDB and another much smaller cluster of your NodeJS scripts.
This separation provides you a more reliable cluster for InfluxDB, as the frequency that you update your NodeJS script is usually higher than you update your InfluxDB software. Having a dedicated NodeJS cluster gives you peace of mind that even if your script has a critical bug, your InfluxDB cluster is still running fine.

*

*Cons: harder to configure. You also need to deal with the distributed nature of your system, as your script is now hosted in different instances of your InfluxDB. Also, this approach is more expensive as well.

You should consider this approach if you are running InfluxDB cluster.


text:
Q: If P congruent to $-1 \bmod$ 8 then $2^{(p-1)/2} - 1$ divisible by $p$ I am trying to prove the following statement:

If $p$ congruent to $-1 \bmod 8$, then $$2^{\frac{p - 1}{2}} - 1$$ divisible by $p$.

I can assume $p$ is congruent to $-1 \bmod 8$, then I must prove
$2^{\frac{p - 1}{2}} - 1$ is divisible by $p$.
So $p + 1 = 8n$, but I'm confused how I can use this assumption to prove  $2^{\frac{p - 1}{2}} - 1$ divisible by $p$.

A: Let $p=8k-1$ and let $n=(p-1)/2 = 4k-1$.  Then note that
$$1\cdot 2\cdot 3\cdots n \equiv (-(p-1))\cdot 2 (-(p-3)) \cdot 4 (-(p-5)) \cdots (n-1)(-(p-n)) \pmod{p},$$
where we replaced each odd number $x$ by a congruent even number $-(p-x)$.
Now count the minus signs in the last product. Because $n$ is odd, there are $(n+1)/2 = 2k$ of them, so their product equals $1$.  So the congruence above becomes
$$n! \equiv (p-1)\cdot 2 (p-3) \cdot 4 (p-5) \cdots (n-1)(p-n) \pmod{p}.$$
Next, note that $2n = p-1$, $2(n-1) = p-3$, $2(n-2) = p-5, \ldots, n+1=4k =p-n,$ so we have
$$n! \equiv (2n)\cdot 2\cdot(2(n-1))\cdot 4 \cdots (n-1)\left(2\frac{n+1}{2}\right) \pmod{p}.  $$
Rearrange the right side to get
$$n! \equiv 2\cdot 4 \cdot 6 \cdots (n-1)(n+1)\cdots (2n) \equiv 2^n n!  \pmod{p}.$$
Cancel the $n!$ and you're done.

A: If you know Quadratic Reciprocity, then the Second Supplement says:

$2$ is a square mod $p$ iff $p \equiv \pm 1 \bmod 8$

Euler's criterion says:

$2$ is a square mod $p$ iff $2^{(p-1)/2} \equiv 1 \bmod p$

Therefore,
$$
p \equiv -1 \bmod 8
\implies
\text{$2$ is a square mod $p$}
\implies
2^{(p-1)/2} \equiv 1 \bmod p
$$


text:
Q: Laravel 5.2 debugbur exception I have debugbur exception when i'm trying to get record from DB
$news = \App\Models\News::findOrFail(1);

After this laravel throw exception
ErrorException in LaravelDebugbar.php line 291:
Missing argument 2 for Barryvdh\Debugbar\LaravelDebugbar::Barryvdh\Debugbar\{closure}()

my composer.json
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.2.*",
    "laravelcollective/html": "dev-master",
    "barryvdh/laravel-debugbar": "^2.1",
    "barryvdh/laravel-ide-helper": "^2.1"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "symfony/css-selector": "2.8.*|3.0.*",
    "symfony/dom-crawler": "2.8.*|3.0.*"
},

A: Looking at last changes in https://github.com/barryvdh/laravel-debugbar/commits/master it seems it should work now, so run in console:
composer update barryvdh/laravel-debugbar

to update this package


text:
Q: Настроить работу соединений пакета 'net' нужно чтобы клиент каждый раз не создавал и не убивал соединение на каждую итерацию, СЕРВЕР ТРОГАТЬ НЕЛЬЗЯ. Вкратце по коду: происходит перебор массива и на каждую итерацию создается соединение(у сервера максимум 2 соединения), и отправляется на сервер слово из массива, сервер обрабатывает запрос и отправляет клиенту ответ, клиент получает ответ, закрывает соединение и выводит в консоль обработанный ответ, и так далее до конца массива.
Код клиента:
const net = require('net');

const vacabulary = ['one','two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'red', 'yellow', 'blue', 'white', 'black'];

(async () => {
    for (let i = 0; i < vacabulary.length; ++i){
        try {
            const res = await getTranslate(vacabulary[i]);
            console.log(res[0] + ' -> ' + res[1]);
        } catch (err) {
            console.log(err);
        }
    }
})();

async function getTranslate(word){
    return new Promise((resolve, reject) => {
        try{
            const client = net.createConnection({port: 1337});

            client.on('connect', () => client.write(word));

            client.on('data', (response) => {
                resolve([word, response.toString()]);
                client.end();
            });

            client.on('error', (error) => {
                console.log(error);
                client.end();
            });
        } catch (err) {
            reject(err);
        }
    });
}

Код сервера:
const net = require('net');

const server = new net.Server()
server.maxConnections = 2;

server.on('connection', (socket) => {
    socket.on('data', (data) => {
        data = data.toString();
        setTimeout(() => {
            socket.write(data.toUpperCase());
        }, 5000);
    });
});

server.on('listening', () => {
    console.log('Server started')
});

server.on('error', (e) => {
    if (e.code === 'EADDRINUSE') {
      console.log('Address in use, check if port 1337 is occupied and restart server. Exiting...');
      process.exit(1);
    }
  });

server.listen(1337, '127.0.0.1');


text:
Q: Python seaborn heatmap grid - Not taking expected columns I have following pandas dataframe. Basically, 7 different action categories, 5 different targets, each category has 1 or many unique endpoints, then each endpoint got a certain score in each target.
There are total 250 endpoints.
action,target,endpoint,score
Category1,target1,endpoint1,813.0
Category1,target2,endpoint1,757.0
Category1,target3,endpoint1,155.0
Category1,target4,endpoint1,126.0
Category1,target5,endpoint1,75.5
Category2,target1,endpoint2,106.0
Category2,target1,endpoint3,101.0
Category2,target1,endpoint4,499.0
Category2,target1,endpoint5,207.0
Category2,target2,endpoint2,316.0
Category2,target2,endpoint3,208.0
Category2,target2,endpoint4,161.0
Category2,target2,endpoint5,198.0
<omit>
Category3,target1,endpoint8,193.0
Category3,target1,endpoint9,193.0
Category3,target1,endpoint10,193.0
Category3,target1,endpoint11,193.0
Category3,target2,endpoint8,193.0
Category3,target2,endpoint9,193.0
<List goes on...>

Now, I wanted to map out this dataframe as heatmap per category.
So, I used seabron facet grid heatmap with the following code.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = pd.read_csv('rawData.csv')
data = data.drop('Unnamed: 0', 1)

def facet_heatmap(data, **kwargs):

    data2 = data.pivot(index="target", columns='endpoint', values='score')
    ax1 = sns.heatmap(data2, cmap="YlGnBu", linewidths=2)

    for item in ax1.get_yticklabels():
        item.set_rotation(0)

    for item in ax1.get_xticklabels():
        item.set_rotation(70)

with sns.plotting_context(font_scale=5.5):

    g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5)

cbar_ax = g.fig.add_axes([.92, .3, .02, .4])

g = g.map_dataframe(facet_heatmap, cbar=cbar_ax, min=0, vmax=2000)
# <-- Specify the colorbar axes and limits

g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
g.fig.subplots_adjust(right=3)  # <-- Add space so the colorbar doesn't overlap the plot

plt.savefig('seabornPandas.png', dpi=400)
plt.show()

It actually generates heatmap grid. However, the problem is the each heatmap uses the same column for some reason. See attached screenshot below.

(Please ignore color bar and limits.)
This is quite odd. First, the Index is not in order. Second, each heatmap box only takes the last three endpoints (Endpoint 248, 249, and 250). This is incorrect. For category 1, it should take endpoint 1 only. I don't expect a gray box there..
For category2, it should take endpoint 2,3,4,5. Not endpoint 248, 249, 250.
How can I fix these two issues? Any suggestion or comments are welcome.

A: as mwaskom suggested: use the sharex parameter to fix your issues:
...

with sns.plotting_context(font_scale=5.5):

g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5,
                 sharex=False)

...


text:
Q: Port number being set by IIS in the x-Forwarded-For header is different than the originally-targeted port I have an IIS reverse-proxy set up on my dev box to test how my app treats requests that have gone through SSL offloading.  My application needs to recreate the original request, append some query string params, and send it back to the client.  By default, IIS/ARR/URL-rewrite does not seem to append the industry standard "X-Forwarded-Host" and "X-Forwarded-Proto" headers. Instead, the closest things I can find are "X-ARR-SSL" and "X-Forwarded-For".   I am happy to parse out the original IP from "X-Forwarded-For", but when I look at the port, it does not seem to make any sense. My SSL reverse-proxy is set up to listen on the default SSL port (443), but the port specified in the header is 52585.  My question is does anyone know how to figure out what the target port of the original request is? I want my application to be able to handle requests proxied by IIS robustly, but it looks like I'm going to have to guess at the port based on whether the request is HTTP or HTTPS.

A: X-Forwarded-For has nothing to do with the server.  It's the IP address of the client.  It's appended to the request headers so that the web server can identify the real client instead of the reverse proxy.  The other headers you mention were de-facto standards which have now been superceded by RFC 7239.  According to the RFC, the port number would be included in the host section of the Forwarded header like this:
Forwarded: for=192.0.2.60;proto=http;host=example.com:888;by=203.0.113.43

I suspect that some reverse proxies add the port number as part of the X-Forwarded-Host header, after a colon, just like it would be in the Host header, but since it's not a defined standard header, you'll just have to try it with your reverse proxy to see.
See also: What is a full specification of X-Forwarded-Proto HTTP header?


text:
Q: Display only nodes matched by variable length relationship query I have a Cypher query with a variable length relationship:
MATCH p = (a1:Article)-[:REFERENCES*3..]->(a2:Article) RETURN p;

This gets me the desired results in table and text view. However, in graph view it also displays nodes with fewer relationships. How can I filter those out?

A: Can you clarify what your desired results are? Using a variable length means you get all nodes in the range.
RETURN p will return entire path, including all nodes in path.
MATCH p = (a1:Article)-[:REFERENCES*3]->(a2:Article) RETURN a2

should return the nodes 3 hops away from a1.

A: It might have something to do with your Neo4j Browser settings.
The 'Connect result nodes' option is enabled by default. All relationships between the nodes matched in your query will be displayed with this enabled.
This happens even if you haven't explicitly mentioned that path/pattern/realtionship in your query.
You can find this option in the Browser Settings, available in the bottom left corner of your Neo4j Browser.
Adjust the Graph Vizualization settings in the Browser Settings drawer


text:
Q: how to use SAPUI5 library css in window.print? I have developed the SAPUI5 application which is having a print option.
When I click on print button, I am writing print area content into document and giving print by using window.print();
 var printContents = document.getElementById("printArea").innerHTML;
 var win = window.open("", "PrintWindow");
 win.document.write("
" + printContents + "
");
      setTimeout(function() {
       win.print();
       win.stop();
      }, 2000);

But the issue is I am missing SAPUI5 default library CSS in my print.
I need SAPUI5 default style sheet in my print,how to fix it?

A: I also came across same problem.
Please add below code between "var win..." and "win.document.write...".
$.each(document.styleSheets, function(index, oStyleSheet) {
  if(oStyleSheet.href){
    var link = document.createElement("link");
    link.type = oStyleSheet.type;
    link.rel = "stylesheet";
    link.href = oStyleSheet.href;
    //win.document.head.appendChild(link); --> this doesn't work in IE
    win.document.getElementsByTagName("head")[0].innerHTML = win.document.getElementsByTagName("head")[0].innerHTML + link.outerHTML;
  }
});


text:
Q: Why does log4j disable stack trace after (lots of) repetition of the same exception? At one of our customer installations we had thousands of occurrences of the same exception. After a lot of well logged stacktraces (9332) the occurrence of the exception is still logged, but without stacktrace. After restarting the java process, the same thing: This time we had 17858 stacktraces and then only the exception occurrence itself.
There is a similar question here, but no answer...
Is it a log4j feature or bug? (I believe in the former, because I really like, what those apache guys do)
Any ideas?

A: Using Java 5 or better?
Then you're seeing:

The compiler in the server VM now provides correct stack backtraces for all "cold" built-in exceptions. For performance purposes, when such an exception is thrown a few times, the method may be recompiled. After recompilation, the compiler may choose a faster tactic using preallocated exceptions that do not provide a stack trace. To disable completely the use of preallocated exceptions, use this new flag: -XX:-OmitStackTraceInFastThrow

Courtesy of the Java 5 release notes.

A: Sounds like a feature to me, at least if the stack traces really are identical. Why would you want to make your logs bigger (and thus harder to search) without getting any more information? Will check for configurability of this feature...
EDIT: I've had a look through the log4j code and there's no trace of it. This would strongly suggest that Robert's answer is correct. Nice VM feature IMO :)


text:
Q: SQL to retrieve tree structure nicely Given the simple data structure:
ID    |    Category_Name    |    Parent_ID

Example:
1          Cars                    0
2          Boxes                   0
3          Lamborghinis            1
4          VW Camper Vans          1
5          Big Boxes               2
6          Small Boxes             2
7          Cereal Boxes            2
8          Broken Lambos           3
9          Yellow Ones             3
10         Rusty                   8
11         Milkshake Stained       8
12         Chocolate Flavour       11
13         Strawberry              11
14         Indiscernible Solution  11

Representing a simple tree navigation structure, what would programatically be the best way to retrieve the tree in a presentable format?  Can we create an SQL statement to retrieve them 'in order'?
Thanks for any help!  If my approach is wrong, feel free to comment also.
I'm using SQL-Server 2000.

A: I usually build the tree structure in my application code. Partially because I'm more confident with c# than SQL, but it also because I usually need to process the data into suitable c# structures anyway.
SQL is quite bad at recursive structures like lists and trees. If I had to put the tree building in my database I'd go for a stored procedure. But there might be a smart way I don't know about.
If you use Oracle you might be able to hack something up with Connect By.

A: If you're using SQL Server 2008 you might want to try out the new hierarchyid data type.
If you're not then another way is to look into the nested sets model which works on all databases.
If you're using SQL Server 2005 and up you can use recursive CTEs to retreive the tree structure.

A: Not for SQL2000, but if you manage to upgrade to 2k5, you can do
WITH t AS(SELECT id, parent_id, category_name FROM mytable WHERE parent_id IS NULL
          UNION ALL
          SELECT c.id, c.parent_id, c.category_name FROM t p JOIN mytable c ON c.parent_id = p.id)
SELECT * FROM t


text:
Q: Salesforce API for CRUD operations on Standard Objects Good day!
Is there a documentation on how to perform crud operations on Salesforce Standard Objects? Can anyone point me to it?
What I need to do is to add entries on the picklist field of a Standard Object programmatically. For example, let's say I want a new option in my dropdown so I need to add an entry in a picklist field. So I was thinking if there is an API documentation to perform CRUD operations for Salesforce Standard Objects. Particularly showing what URL should be used and what payload should be passed.
I've bumped into Metadata API, Tooling API, and the SObject Describe API but it seems it is not what I am looking for. Or am I just missing something? Need help! Thanks in advance!
P.S. I am a newbie with salesforce.

A: You can't perform CRUD operations on metadata in the same way you can with standard sObjects. They're part of the configuration of the system, and you've got to jump through some more hoops in order to mutate them because of their wide-ranging effects on the operation of your CRM.
The API that you'll need to work with to make these updates is the Metadata API. Specifically, you'll need to create and deploy a StandardValueSet entity. The names of the Standard Value Sets corresponding to specific picklists in the standard data model is given here.
You cannot make this change in standard Apex. If you're trying to work in Apex, you'd have to use something like the apex-mdapi library. Any user under whose context the operation is run must have the appropriate permissions to access the Metadata API.
If you're working outside Salesforce, your application will make calls to the SOAP or the newer REST resources of the Metadata API to deploy ZIPped XML source code, or make CRUD-style calls like createMetadata().


text:
Q: Dynamically add checkboxes to a listview I am trying to make an app that takes the number of sets, and number of reps for each set from the user, and adds rows ( for each set) and checkboxes (for each rep)

for the reps: i made a method that takes the number of reps from the SQLite server, and loops through the number of reps to make the checkboxes.
for the sets: i made list adapter to make each row.

how can i make the reps be contained inside the rows?  thanks.
recyclerview adaptor:
'''
package com.example.workouttracker;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class WorkoutInterfacesAdapter extends RecyclerView.Adapter<WorkoutInterfacesAdapter.WorkoutInterfaceViewHolder> {

    Context mContext;
    private ArrayList<WorkoutInterfaceClass> sets;
    private LinearLayout linearLayout;

    public WorkoutInterfacesAdapter(Context mContext , ArrayList<WorkoutInterfaceClass> sets) {

        this.sets = sets;
        this.mContext = mContext;
    }

    @NonNull
    @Override
    public WorkoutInterfaceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.workout_interface_item,parent,false);
        return new WorkoutInterfacesAdapter.WorkoutInterfaceViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull  WorkoutInterfacesAdapter.WorkoutInterfaceViewHolder holder, int position) {
        holder.bind(sets.get(position));
        //new code:

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext,"Set number: " + sets.get(position).numberOfSets + " ,Rep Number: "+sets.get(position).numberOfReps,Toast.LENGTH_LONG).show();
                Intent intent = new Intent(mContext,WorkoutInterface.class);
                intent.putExtra("workout_sets",sets.get(position).numberOfSets);
                intent.putExtra("workout_reps",sets.get(position).numberOfReps);
                mContext.startActivity(intent);

            }
        });

    }

    @Override
    public int getItemCount() {
        return sets.size();
    }
    static class WorkoutInterfaceViewHolder extends RecyclerView.ViewHolder{

        TextView numberOfSets;
        int numberOfReps;
        CheckBox checkBox;
        LinearLayout linearLayout;

        public WorkoutInterfaceViewHolder(@NonNull View itemView) {
            super(itemView);
             numberOfSets =itemView.findViewById(R.id.edit_text_number_of_sets_item);
             checkBox=itemView.findViewById(R.id.checkbox_number_of_reps_item);
             linearLayout=itemView.findViewById(R.id.ll_checkbox_mother);
        }

        public void bind(WorkoutInterfaceClass sets) {
            //
           numberOfSets.setText("Set number:" + sets.numberOfSets); ;
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            numberOfReps=sets.numberOfReps;
            for (int i = 1; i <= numberOfReps; i++) {
                CheckBox checkBox = new CheckBox(linearLayout.getContext());
                checkBox.setId(View.generateViewId());
                checkBox.setText("Rep: "+checkBox.getId());
                checkBox.setOnClickListener((View.OnClickListener) linearLayout.getContext());
                System.out.println("Total Number Of Sets:"+numberOfReps + "And the index is : "+ i );

        }
    }

}}

'''

A: Try creating a custom layout that will contain all the necessary views and pass the layout in the onCreateView of you adapter class with a layout inflater.


text:
Q: Electron app not showing anything I make a simple "hello world" type Electron app. After double click the exe file it not open any window at all. Just a thread showing in windows tasks manager. I try to debug main thread js. But it show no error. And if I run development mode it works(cli: electron main.js).
ENV: windows 7, x64
Build command: electron-builder

A: Finally, I find the problem is package.json main property. The main property should point to main.js (main thread entry js file).


text:
Q: What does "a rope on a tree" mean? Bobby Seale, national chairman of the Black Panther Party and eighth defendant, says to Tom, one of the Chicago 7 group:

Bobby: The seven of you, you've all got the same father, right? You
all got the same father, right? "Cut your hair…don't be a fag, respect
authority, respect America, respect me." Your life, it's a "fuck you"
to your father, right? A little?
Tom Hayden: Maybe.
Bobby: And you can see how that's different from a rope on a tree?
Tom Hayden: Yeah.

What does "a rope on a tree" mean?
Source: The Trial of the Chicago 7 (2020)

A: As the comment says, it's an allusion to lynching, murder by a mob in the form of hanging.
Wikipedia "lynching"
I think what is happening here is that Bobby Seale, a black man, is suggesting that his white co-defendants aren't as seriously committed to protests as he is. They are all rebelling against their fathers (characterized as essentially the same person) and so are sort of dilettantes at protest, while he, as a black man in America, has faced the danger of mob murder all his life.

A:
I think what is happening here is that Bobby Seale, a black man, is suggesting that his white co-defendants aren't as seriously committed to protests as he is. They are all rebelling against their fathers (characterized as essentially the same person) and so are sort of dilettantes at protest, while he, as a black man in America, has faced the danger of mob murder all his life.

I'm pretty sure that's not what he meant at all. Bobby Seale knew that these people were committed to the protests and for the cause that they were fighting for. What he meant was that his fight is much bigger, much worse, and has been grounded in America for far too long and probably will be in the future. While he condemned American involvement in Vietnam, he didn't have the resources or time to waste on this trial while the ghettoisation of his community was destroying it from the inside and the pigs were hell bent on destroying whoever tried to fight for themselves.
His protest wasn't a fuck you to his father or part of a rebellious phase against the machine, his protest was survival, and ensuring his community survives - and he knew Hayden understood how it's different from the protest he was being accused of participating in.


text:
Q: Skip test command on maven build is not working I'm trying to build a maven project and skipping the test cases by running the command below:
mvn clean install -DSkipTests
However, I keep getting an error that I have test failures. From my understanding, it means that the build is still running the tests which I am trying to avoid for now. I have taken to consideration this existing question but I'm unsure if this is related to my case:
Maven package/install without test (skip tests)
Nonetheless, I did try the solution provided in this question. It did build my project but again, I am unsure if it did built the project the way I wanted to since package and install are different commands of maven.
Also, I did try to build it without the skip tests but I still got the same result errors.
Kindly correct me if I'm doing anything wrong. Any information will be greatly appreciated.


text:
Q: Finding Specific Text Records I am working on a project with a table having a text field as its Primary Key.  On on form, I have the [Name] listed in a list of items and want to open the corresponding record to that specific text record.  Here is what I am looking at:

Any help is greatly appreciated!
Sincerely,
Kevin

A: This will open a form with the Muscles button:

*

*Open Properties on the Muscles button and go to the On Click event on the Event tab. Click the three dots and choose Code Builder.

*Add the following code (change frmMuscles to the name of the form you are opening, MuscleName to the name of the field, and sfrmMuscles to the name of the subform):
docmd.OpenForm "frmMuscles",,,"MuscleName='" & me.sfrmMuscles.MuscleName.Value & "'"
Note that you need to point to the subform that has the name of the muscle desired to be opened and it needs to be surrounded by single quotes which are placed inside of double quotes.
This will give you a GO TO combo box:
Using the combo box wizard will get you most of the way there. And then you just edit the macro with a small change.

*

*Start by deleting your Go To and combo box.

*Grab a combo box off the tool bar and add it to your header. When you do that, you should get a combo box wizard that offers three options: pull from a table, add your own entries, or find a record on your form. Select the third option. (You can put the combo box in the body of your form and still get the third option but I like it in the header.)

*Go through the wizard and select your key field. Type in Go To: as the label of your combo box.

*This may be all you need for your preference. Try it out. My problem is that the combo box stays filled and if you move to a different record, the combo box does not update automatically. So instead, I edit the query and set the value of the combo box to blank (I would use 0 if it was a number field).

*To edit the macro, open the properties of your combo box and choose the Event tab. There is an embedded macro on the After Update Event. Click on the embedded macro and click the three dots to the right to edit the macro.

*Once the macro opens, you have a SearchForRecord option at the top. Under it, there is an "Add New Action" drop-down.

*In the "Add New Action", select SetProperty. That will open and allow you to enter values that you want to use.

*For Control Name, select the name of your combo box. If you don't know, the name is displayed in the tab at the top. For Property, select Value. Then in Value, enter "". This will blank the combo box. Click Close at the top and you will be asked to Save.
This should give you a combo box that moves to the selected record and then blanks out the combo box.


text:
Q: Comparing Two Words(Strings) What does this code mean?
if( item.compareTo(root.element) < 0 ){

   }

I read that:

"Compares two strings lexicographically. Returns an integer indicating
  whether this string is greater than (result is > 0), equal to (result
  is = 0), or less than (result is < 0) the argument."

But I don't don't get it. Can someone explain with an example please?

A: Take a look at the documentation of the Comparable interface, which defines the compareTo() method in the first place. The implementation of this interface in String follows the same conventions:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object

This means: if the current string is less than the string received as parameter (under the lexicographical order) return a negative integer value. If the current string is greater than the string received as parameter, return a positive integer value. Otherwise, the strings are equal and 0 is returned.

A: You would use this in sorting code to see if item belongs before root.element or not.

A: it checks if two Strings are equal like this.
a>A  would return a positive number as `a` is greater than `A`
A>a  would return a negetive number as `A` is less than `a`
a==a would return 0 as `a` is equal to `a`
a>Z  would return a positive number as 'a' is greater than 'A'
trend> zend would return a positive number as `t` is greater than 'z'

A: someObject.compareTo(anotherObject) returns a negative number if someObject comes before anotherObject.
Here's an example that compares String objects:
if ("apple".compareTo("zebra") < 0) {
    System.out.println("I will be printed");
}
else {
    System.out.println("I will NOT be printed");
}

A: If the word1= item, and word2= root.element and both are in a dictionary, word1 should appear before word2.


text:
Q: How can a NoClassDefFoundError suddenly happen? All of a sudden, without playing with the gradle file, from one compilation to another, I got this error:
java.lang.RuntimeException: An error occured while executing doInBackground()

Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/xml/stream/XMLInputFactory;

Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.xml.stream.XMLInputFactory" on path: DexPathList[[zip file "/data/app/com.vuzix.automation.dev-2/base.apk"],nativeLibraryDirectories=[/data/app/com.vuzix.automation.dev-2/lib/arm, /vendor/lib, /system/lib]]

Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

*

*I tried to disable Instant Run # not working

*I tried to delete app, clean, recompile # not working

*I even updated do Android Studio 3.4 and gradle class path to 'com.android.tools.build:gradle:3.4.0'
My gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.vuzix.automation.dev"
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    maven {
        url "https://nexus-repository.snips.ai/repository/snips-maven-releases/"
    }
}
configurations {
    all*.exclude group: "xmlpull", module: "xmlpull"
    all*.exclude group: "org.apache.commons", module: "commons-compress"
    all*.exclude group: "com.thoughtworks.xstream", module: "commons-compress"
}

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

dependencies {
    implementation 'com.vuzix:hud-actionmenu:1.1'
    implementation 'com.vuzix:hud-resources:1.1'
    implementation files('libs/core-1.58.0.0.jar')
    implementation files('libs/prov-1.58.0.0.jar')
    implementation files('libs/bcpkix-jdk15on-1.58.0.0.jar')
    implementation files('libs/prosys-opc-ua-sdk-client-server-evaluation-4.0.0-774.jar')
    implementation files('libs/slf4j-api-1.7.25.jar')
    implementation files('libs/slf4j-log4j12-1.7.7.jar')
    implementation files('libs/log4j-1.2.17.jar')
    implementation('ai.snips:snips-platform-android:0.62.3@aar') {
        transitive = true
    }

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    ['boofcv-android', 'boofcv-core'].each {
        String a -> api group: 'org.boofcv', name: a, version: '0.31'
    }
    api fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
}

Why is this happening?

A: I found out how to resolve the issue, even though I'm still wondering why it worked before.
I downloaded the com.bea.stax.impl_1.2.0.jar and the
stax-api-1.0-2.jar and put them in the libs folder. Then added the jars in File → Project Structure → Dependencies.
Clean, build, run—and voilà it worked.


text:
Q: Binary Search Tree Generics Java I am implementing a generic BST in java. The standard BST is in the file BST.java. I also have a subclass which adds additional functionality. I can't seem to get the generics working. I get the following error each time I compare whether in insert, get, or delete:
compareTo(Key) in java.lang.Comparable<Key> cannot be applied to (java.lang.Comparable)
    int cmp = k.compareTo(n.k);

BST.java
public class BST <Key extends Comparable<Key>, Value>
{
    //code here

    public Value Get (Key k)
    {
        Get(this.root, k);
    }

    private Value Get (Node n, Key k)
    {
        if (n == null || k == null) return null;
        int cmp = k.compareTo(n.k);
        if (k.compareTo(n.k) == 0) return (Value) n.v;
        if (cmp < 0) Get (n.left, k);
        if (cmp > 0) Get (n.right, k);
    }

    private class Node <Key extends Comparable<Key>, Value>
    {
        public Key k;
        public Value v;
        public Node left;
        public Node right;

        //code here
    }
}

BSTExtended.java
public class BSTExtended<Key extends Comparable<Key>, Value> extends BST<Key, Value>
{ //code here }

A: I believe your problem was that you were missing explicit references to your type parameters at various points in the definition of the BST class. There were also some pretty basic compiler errors in there.
In particular, have a look at this modified type signature for your Get function:
private Value Get (Node<Key, Value> n, Key k)

Here's the full class I got compiling:
public class BST <Key extends Comparable<Key>, Value>
{
    Node<Key, Value> root;
    //code here

    public Value Get (Key k)
    {
        return Get(this.root, k);
    }

    private Value Get (Node<Key, Value> n, Key k)
    {
        if (n == null || k == null) return null;
        int cmp = k.compareTo(n.k);
        if (k.compareTo(n.k) == 0) return (Value) n.v;
        if (cmp < 0) return Get (n.left, k);
        return Get (n.right, k);
    }

    private class Node <Key extends Comparable<Key>, Value>
    {
        public Key k;
        public Value v;
        public Node<Key, Value> left;
        public Node<Key, Value> right;

        //code here
    }
}


text:
Q: Problem install pgAdmin 4 v1.1 in desktop mode on Ubuntu 16.04 Following previous post How to install pgAdmin 4 in desktop mode on Ubuntu 16.04, I had an error (can't find Python.h). Also someone mentioned about changing to python3, how would I go by doing this?
Thanks in advance.
pip install pgadmin4-1.1-py2-none-any.whl

Processing ./pgadmin4-1.1-py2-none-any.whl

Requirement already satisfied: Flask-Principal==0.4.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: blinker==1.3 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: unittest2==1.1.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: testscenarios==0.5.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: extras==0.0.3 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: Jinja2==2.7.3 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: importlib==1.0.3 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: traceback2==1.4.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: Flask-WTF==0.12 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: pytz==2014.10 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: sqlparse==0.1.19 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: python-dateutil==2.5.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: six==1.9.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: passlib==1.6.2 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: pyrsistent==0.11.13 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: Flask==0.11.1 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: ordereddict in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: WTForms==2.0.2 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: Flask-Mail==0.9.1 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: Werkzeug==0.9.6 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: linecache2==1.0.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: SQLAlchemy==1.0.14 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Collecting psycopg2==2.6.2 (from pgadmin4==1.1)
  Using cached psycopg2-2.6.2.tar.gz
Requirement already satisfied: python-mimeparse==1.5.1 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Collecting html5lib==1.0b3 (from pgadmin4==1.1)
Requirement already satisfied: MarkupSafe==0.23 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: click==6.6 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Collecting speaklater==1.3 (from pgadmin4==1.1)
Collecting Flask-Security==1.7.5 (from pgadmin4==1.1)
Collecting simplejson==3.6.5 (from pgadmin4==1.1)
Collecting Babel==1.3 (from pgadmin4==1.1)
Requirement already satisfied: testtools==2.0.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Collecting pycrypto==2.6.1 (from pgadmin4==1.1)
  Using cached pycrypto-2.6.1.tar.gz
Collecting Flask-SQLAlchemy==2.1 (from pgadmin4==1.1)
Requirement already satisfied: pbr==1.9.1 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Collecting Flask-Gravatar==0.4.2 (from pgadmin4==1.1)
  Using cached Flask_Gravatar-0.4.2-py2.py3-none-any.whl
Collecting Flask-Login==0.3.2 (from pgadmin4==1.1)
Collecting beautifulsoup4==4.4.1 (from pgadmin4==1.1)
  Using cached beautifulsoup4-4.4.1-py2-none-any.whl
Collecting django-htmlmin==0.8.0 (from pgadmin4==1.1)
Requirement already satisfied: fixtures==2.0.0 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Requirement already satisfied: itsdangerous==0.24 in ./lib/python2.7/site-packages (from pgadmin4==1.1)
Collecting Flask-Babel==0.11.1 (from pgadmin4==1.1)
Requirement already satisfied: argparse in /usr/lib/python2.7 (from unittest2==1.1.0->pgadmin4==1.1)
Building wheels for collected packages: psycopg2, pycrypto
  Running setup.py bdist_wheel for psycopg2 ... error
  Complete output from command /home/edy/pgadmin4/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-cFch6n/psycopg2/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpvOLZfypip-wheel- --python-tag cp27:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.linux-x86_64-2.7
  creating build/lib.linux-x86_64-2.7/psycopg2
  copying lib/errorcodes.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/__init__.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/extras.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/extensions.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/_json.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/psycopg1.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/_range.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/tz.py -> build/lib.linux-x86_64-2.7/psycopg2
  copying lib/pool.py -> build/lib.linux-x86_64-2.7/psycopg2
  creating build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_bugX000.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/testutils.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_quote.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/__init__.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_lobject.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_errcodes.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_copy.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_connection.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_module.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_types_extras.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_psycopg2_dbapi20.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/testconfig.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_cursor.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_transaction.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_async.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_types_basic.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_dates.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_notify.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_bug_gc.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_with.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_cancel.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/test_green.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  copying tests/dbapi20.py -> build/lib.linux-x86_64-2.7/psycopg2/tests
  running build_ext
  building 'psycopg2._psycopg' extension
  creating build/temp.linux-x86_64-2.7
  creating build/temp.linux-x86_64-2.7/psycopg
  x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.6.2 (dt dec pq3 ext lo64)" -DPG_VERSION_HEX=0x090601 -DHAVE_LO64=1 -I/usr/include/python2.7 -I. -I/usr/include/postgresql -I/usr/include/postgresql/9.6/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.7/psycopg/psycopgmodule.o -Wdeclaration-after-statement
  In file included from psycopg/psycopgmodule.c:27:0:
  ./psycopg/psycopg.h:30:20: fatal error: Python.h: No such file or directory
  compilation terminated.
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for psycopg2

A: python.h should be included in python-dev-Package. You can install this package with these commands:
sudo apt install python-dev


text:
Q: React - react-scripts publicPath Is there possibility to override publicPath in react-scripts for dev env. I use symfony and I include react app inside twig so I had to change assets to serve from http://localhost:3000/static/js/bundle.js - this works fine but I have problem with static files because they are rendered in browser as '/static/media/logo.813ua.png' and my current url is http://localhost:8000
What I did is I run yarn eject and modify in webpack.config.dev.js: var publicPath = 'http://localhost:3000/' and everything is working fine but I don't want to eject so is there any possibility to do this without ejecting react-scripts ?

A: Specify your port with with process.env.PORT (package.json)
"scripts": {
  "start": "PORT=1234 react-scripts start"
}


text:
Q: Get remote address by SOCKET-identifier in a recv-hook I've installed a hook on the recv-function in Ws2_32.dll. Now, when recv is called, I want to get information about who sent the information. So I tried the following to get the remote address of the sender, but the address I get is always wrong and very unrealistic for the internet (e. g. I get 2.0.0.80).
What am I doing wrong?
int __stdcall TcpHook::my_recv(SOCKET s, char *buf, int len, int flags)
{
    sockaddr addr;
    int len2 = sizeof(addr);
    getpeername(s, &addr, &len2);

    char *sender = inet_ntoa(*(in_addr*)&addr);
    // print out sender etc.

    return tcpHook.recvOriginal(s, buf, len, flags);
}

The interesting point is that I don't have any information despite of the passed s (type SOCKET).

A: I found the solution... I just failed.
The correct code is:
inet_ntoa((*(sockaddr_in*)&addr).sin_addr);

It works.