text:
Q: how to mount ipv6 address to linux I am trying to mount a folder from ubuntu system having ip ipv6 as well as ipv4 address
root@:/home# ifconfig
br0       Link encap:Ethernet  HWaddr 16:37:81:2e:ce:e9
          inet addr:10.0.3.24  Bcast:10.0.7.255  Mask:255.255.248.0
          inet6 addr: 2001:db8::60fe:5bff:febc:912/64 Scope:Global
          inet6 addr: 2001:db8::e8a6:7d68:16b8:3d86/64 Scope:Global

I can able to ping ipv6 address from different linux system  :
[root@Abhitesh home]# ping6 2001:db8::60fe:5bff:febc:912
PING 2001:db8::60fe:5bff:febc:912(2001:db8::60fe:5bff:febc:912) 56 data bytes
64 bytes from 2001:db8::60fe:5bff:febc:912: icmp_seq=1 ttl=64 time=0.968 ms
64 bytes from 2001:db8::60fe:5bff:febc:912: icmp_seq=2 ttl=64 time=1.07 ms

I am getting error, when i am trying to mount with ipv6
[root@Abhitesh home]# mount -t nfs 2001:db8::60fe:5bff:febc:912:/home/abhitesh /home/mount/
mount.nfs: mount system call failed
[root@Abhitesh home]#

with ipv4 mount command is working.
Is that my command is wrong or i need to configure something, to mount with ipv6.
In my system ipv6 is enabled.
cat /proc/sys/net/ipv6/conf/all/disable_ipv6
0

A: Command is wrong NFS mount command should be
mount -t nfs [2001:db8::60fe:5bff:febc:912]:/home/abhitesh /home/mount/
IPv6 address should be in [].
and for CIFS mount command should be
mount -t cifs -o username=xxxx,password=yyyyy //2001:db8::60fe:5bff:febc:914/public /home/mount

A: For those who might ever need it, posting below the entries that worked for me. Using Arch linux and link-local IPv6 addresses.
/etc/exports entry on the server
/dir1    fe80::blah:blah:blah:blah(rw,sync,nohide)

/etc/fstab entry on client
[fe80::boom:boom:boom:boom%wlan0]:/dir1    /home/a/b/c    nfs    noatime,noauto,users    0 0

Command when mounting manually
sudo mount [fe80::boom:boom:boom:boom%wlan0]:/dir1 /home/a/b/c


text:
Q: Mongodb can dump but not to store "error restoring from  an insert is too big" I faced a problem in one of my customers db, there was a document that inflates to 16 MB size, which reached the limit of mongodb "max document size": https://docs.mongodb.com/manual/reference/limits/
To debug it I dumped the db with the mongodump command, which created BSON files for my db.
I tried to reload the dumped db to mongo on my machine with the command mongorestore, but I god the error:
Failed: Data.events: error restoring from /dbimport/Data/events.bson: an inserted document is too large

How can it be that I can't reload a dumped db?
I thought it may be because the size of the document is very close to the "max limit size" (16MB), but not exceeded it, so it's in my db, but when trying to import this document with the mongostore command it's too close to the "max limit size", so mongo refuses to insert it to the db.
Is there is an option to make the mongostore command to success in this scenario?

A: My solution was to manually open the BSON files (with python), find the big documents and remove some part of it, then write the BSON object to a new BSON file and load the edited BSON file, which was successfully stored to mongo.
This not fulfill my wish to be able to load the dumped db to the system without change it!
Python3:
import bson
from pprint import pprint

def get_bson_data(filename):
    with open(filename, "rb") as f:
        data = bson.decode_all(f.read())

    return data

def report_problematics_documents(data):
    problematics = []

    for item in data:
        if is_too_big(item):
            print(item)input("give me some more...")
            input("give me some more...")
            problematics.append(item)

    print(f"data len: {len(data)}")
    print(f"problematics: {problematics}")
    print(f"problematics len: {len(problematics)}")

def shrink_data(data):
    for i,  item in enumerate(data):
        if is_too_big(item):
            data[i] = shrink_item(item) # or delete it...
            print(f"item shrinked: {i}")

def write_bson_file(data, filename):
    new_filename = filename
    with open(new_filename, "wb") as f:
        for event in data:
            bson_data = bson.BSON.encode(event)
            f.write(bson_data)

def is_too_big(item):
    # you need to implement this one...
    pass

def shrink_item(item):
    # you need to implement this one...
    pass

def main():
    bson_file_name = "/path/to/file.bson"
    data = get_bson_data(bson_file_name)
    report_problematics_documents(data)

    shrink_data(data)
    report_problematics_documents(data)

    new_filename = bson_file_name + ".new"
    write_bson_file(data, new_filename)

    print("Load new data")
    data = get_bson_data(new_filename)
    report_problematics_documents(data)

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity - Making Camera Lock on To Enemy and stay behind player? I am attempting to create a Camera that moves with the Player but locks onto an enemy when the player clicks the lock on button. The behaviour is almost working as I want it, the camera locks onto the target. And when the player stand in-front of the target it works fine. However as soon as the player runs past the target, the camera behaves strangely. It still looks at the Enemy, however it does not stay behind the player. Here is the code that dictates the behaviour:
if(MouseLock.MouseLocked && !lockedOn){ // MOUSE CONTROL:
    Data.Azimuth += Input.GetAxis("Mouse X") * OrbitSpeed.x;
    Data.Zenith    += Input.GetAxis("Mouse Y") * OrbitSpeed.y;
} else if(lockedOn) { // LOCKON BEHAVIOUR:
    FindClosestEnemy();
}

if (Target != null) {
    lookAt += Target.transform.position;
    base.Update ();
    gameObject.transform.position += lookAt;
if(!lockedOn){
     gameObject.transform.LookAt (lookAt);
} else if(enemyTarget != null) {
     Vector3 pos1 = Target.transform.position ;
     Vector3 pos2 = enemyTarget.transform.position ;
     Vector3 dir = (pos2 - pos1).normalized ;
     Vector3 perpDir = Vector3.Cross(dir, Vector3.right) ;
     Vector3 midPoint = (pos1 + pos2) / 2f;
     gameObject.transform.LookAt (midPoint);
 }

}

And the Code for Finding the nearest Enemy:
void FindClosestEnemy ()  {
     int numEnemies = 0;
     var hitColliders = Physics.OverlapSphere(transform.position, lockOnRange);
     foreach (var hit in hitColliders) {
         if (!hit || hit.gameObject == this.gameObject || hit.gameObject.tag == this.gameObject.tag){
             continue;
         }
         if(hit.tag != "Enemy") // IF NOT AN ENEMY: DONT LOCK ON
             continue;
         var relativePoint = Camera.main.transform.InverseTransformPoint(hit.transform.position);
         if(relativePoint.z < 0){
             continue;
         }
         numEnemies += 1;
         if(enemyTarget == null){
             print ("TARGET FOUND");
             enemyTarget = hit;
         }
     }
     if(numEnemies < 1){
         lockedOn = false;
         enemyTarget = null;
     }
 }

As I said, teh behaviour almost works as expected, however I need the camera to stay behind the player whilst locked on and it must face the enemy/midPoint between the enemy and player. How can this be done? Thank you for your time.

A: To clarify your intent: you want to lock the position relative to the target (player), whilst setting the camera rotation to look at either the target or a secondary target (enemy)? And your current code performs the rotation correctly but the positioning is buggy?
The easiest way to fix the camera relative to another object is to parent it in the scene. In your case you could add the camera as a child under the Player game object.
If you would rather not do this then look at your positioning code again:
lookAt += Target.transform.position;
base.Update ();
gameObject.transform.position += lookAt;

I don't know where lookAt comes from originally but to me this looks all wrong. Something called lookAt should have nothing to do with position and I doubt you want to += anything in the positioning code given that you want a fixed relative position. Try this instead:
public float followDistance; // class instance variable = distance back from target
public float followHeight; // class instance variable = camera height
...
if (Target != null) {
    Vector3 newPos = target.position + (-Target.transform.forward * followDistance);
    newPos.y += followHeight;
    transform.position = newPos;
}

This should fix the positioning. Set the followDistance and followHeight to whatever you desire. Assuming your rotation code works this should fix the problem.


text:
Q: PDFlib Greek is not output I got a problem with display text in greek.
The "$text = '111 πορτοκαλί 111';" will only output the 111 and not the Text.
When I use the Font "Symbols" it's "ok".
But how to mix it up? Sometimes its Greek, sometimes French and so on...
Any hints?
$pdf = PDF_new();
pdf_set_parameter($pdf, "licensefile", "/etc/licensekeys.txt");
pdf_set_parameter($pdf, "compatibility", "1.6");
pdf_set_parameter($pdf, "textformat", "utf8");
PDF_begin_document($pdf, "", "");

$fontUnicode = PDF_load_font($pdf, "Helvetica",  "unicode", NULL);

PDF_begin_page_ext($pdf, 0, 0, "width=200 height=200");

pdf_setcolor($pdf, "both","cmyk",0.53,0.43,0.43,0.28);

PDF_setfont($pdf, $fontUnicode, 8);
$text = '111 πορτοκαλί 111';
PDF_show_xy($pdf, $text, 100, 100);

PDF_end_page_ext($pdf, '');
PDF_end_document($pdf, '');

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=test.pdf");
print $buf;
PDF_delete($pdf);

A: The problem here is that the PDF Core Font Helvetica used contains very few glyphs and, for example, glyphs for Greek.
In order for the PDF to display the text correctly, you must use a font that contains the appropriate characters. Not every font contains a glyph vor every character. Thus, when choosing a font, you must consider both the appearance (that is, whether you like the font face) and whether the font contains the characters you want to use.
For example, the current PDFlib packages include the NotoSerif-Regular font which contains many glyphs, including Greek. This could be a good approach. This is shown e.g. in the supplied starter_basic.php example which is also included in the PDFlib Cookbook.
https://www.pdflib.com/pdflib-cookbook/general/starter_basic/php/
This sample shows various ways how you can apply a string:
/* Plain ASCII text */
$p->fit_textline("en: Hello!", 50, 700, $optlist);

/* Unicode code points */
$p->fit_textline("gr: \u{0393}\u{03B5}\u{03B9}\u{03AC}!", 50, 650, $optlist);

/* UTF-8 text */
$p->fit_textline("ru: Привет!", 50, 600, $optlist);

/* PDFlib character reference */
$p->fit_textline("es: ¡Hola!", 50, 550, $optlist . " charref=true");

You can see the greek glyphs in the output:

I can only recommend that you start with the provided examples and then look for more sample code in the PDFlib Cookook. This usually leads to much better code in your application, because this code will then also match the PDFlib version you are using.
Outdated code which you might find somewhere can cause problems when updating.
Another recommendation:
in this example code use the deprecated functional PDFlib API (PDF_). This is no longer available with PDFlib 10 (the current version) and thus not recommended for new projects. (Please see PDFlib 10 Mingration Guide for details on this)
If you are starting from scratch, I would recommend to start with the latest PDFlib 10.


text:
Q: Protractor: Correct use of waitReady.js file in my tests We are using browser.wait extensively throughout the entire test suite. It became a headache when managing different timeouts for different scenarios. I came across a waitReady function(https://gist.github.com/elgalu/2939aad2b2e31418c1bb), but I am unable to utilize it in my code.
The directory looks like: (all files besides each other)
.
├── conf.js
├── main.js
├── waitReady.js

Main.js --->Contains all describe and it blocks
    require('./waitReady.js');
    describe(...){
    it{
    code...
expect(element.waitReady()).toBeTruthy();
    };
    });

For some reason the code does not find that function and my code keeps getting function not defined error. Do I need to initialize it somewhere?

A: Put the import into the onPrepare() in your protractor config:
onPrepare: function () {
    require('./waitReady.js');
},

A: I had no doubt Alecxe would answer this one :)
An alternate solution for managing timeout lengths, which I've found useful, is to add default timeout lengths to a basePage, or onPrepare. For this I use t-shirt sizes... Eg:
this.timeout = {
    's' : 500,
    'm'  : 1000,
    'l'  : 5000,
    'xl'  : 10000
};

Then call thusly:
browser.wait(someThingToWaitFor(), this.timeout.xl);


text:
Q: list array grouping I have an array of rectangle elements. each element in the array can be able to represent several diffrent rectangles in it. i would want to find out how can i group similar list items and show their count. e.g  the list contains 10 rectangle arrays. of the 10 there are 4 elements which are similar (i.e  4 rectangle elements with the same number, size, orientation of the rectangles in it) for the example i would love  to have an end result which shows a list of 7 alements and the count eg. the 6 single elements and the 7th elements showing a count of 4. c# or vb.net

A: If you can override Equals on your rectangle to determine when you consider two rectangles equal, you could do the following Linq query.
        List<Rectangle[]> rectangleArr;
        var query = (from r in rectangleArr.Cast<Rectangle>()
                     group r by r into gr
                     select new { Count = gr.Count(), Value = gr.Key });
        foreach (var item in query)
        {
            Console.WriteLine("Item: {0}, Count: {1}", item.Value, item.Count);
        }

If you don't want an anonymous type you could create a class:
class RectangleGroup
{
    public Rectangle Value { get; set; }
    public int Count { get; set; }
}

then select like this:
select new RectangleGroup() { Count = gr.Count(), Value = gr.Key }

A: You can use Tuple:
List<Rectangle> l = new List<Rectangle>();
l.Add(new Rectangle(1, 2, 3, 4));
l.Add(new Rectangle(1, 2, 3, 4));
l.Add(new Rectangle(10, 20, 30, 40));

var grouped = l
    .GroupBy(item => item)
    .Select(group => new Tuple<Rectangle, int>(group.Key, group.Count()));

foreach (var t in grouped)
{
    Console.WriteLine("There are {0} rectangles like {1}.", t.Item2, t.Item1);
}


text:
Q: How to dynamically bind xml or json data to bootstrap grid? how to make bootstrap grid editable? I'm new to bootstrap. My background is Asp.net but I haven't worked on the MVC architecture, but worked on only n-tier architecture. I was searching which is best and commonly used techniques to develop responsive asp.net application and I came across bootstrap as being best for responsive development with asp.net. I was just going through bootstrap grid. I could not find anyway to dynamically bind columns from returned data set (XML/j son), so that number of columns are created dynamically.
Another question is how do I make bootstrap grid editable without using any third party framework?

A: Like you I was an ASP.net guru and went on to use ASP.net MVC since it's inception, and the short answer is: you don't (or at least you don't have to).
In the world of MVC, bootstrap, JavaScript and jquery there are very useful JavaScript libraries that you can take advantage of. I recommend you use the Datatables Library. It easily binds to JSON data and is responsive as well.
Also check out the Admin LTE site. It will show you how a site can be built with just Bootstrap and JavaScript libraries.


text:
Q: Add lint to CI and mark a build fail when lint produces errors for Android Studio projects I need the Gradle build to be marked as a failure and it should be stopped automatically if running lint gives me an error. I made the changes in code as required but it did not result in any change.
Code:
lintOptions {
    // set to true to turn off analysis progress reporting by lint
    quiet true
    // if true, stop the gradle build if errors are found
    abortOnError true
    // if true, only report errors
    ignoreWarnings false
  }

Also apart from it, I need to add lint to CI. The CI software I use is Jenkins. SO I need to configure their android linting plugin of Jenkins such that the build is stopped and marked Failure if Lint gives an error.
I am very new to lint and CI, so please provide a detailed answer.

A: You don't need the Lint Jenkins plugin. Just put something this in your JenkinsFile.
try {
    sh './gradlew lint'
} finally {
    step([$class: 'ArtifactArchiver', artifacts: 'app/build/reports/staticAnalysis/lint/', fingerprint: true])
}

ArtifactArchiver is just to collect artifacts after lint check.


text:
Q: Using informats when creating a dataset from another dataset I've got a dataset that's full of data all in character format.
Now I want to create another dataset from this one, put put everything it it's correct decimal or date or character format.
Here's what I'm trying.

data work.testout;

    attrib account_open_date informat = mmddyy10.;

    do i = 1 to nobs;
        set braw.accounts point = i nobs = nobs;
        output;

    end;
    stop;
run;

this gives me:
Variable 'account_open_date' from data set braw.accounts (at line 7 column 21) has a different type (character) to the variable type on the data vector (numeric)

What's the best way of doing this?

A: You cannot use an informat to convert a variable directly from character to numeric.  At least in SAS proper, you cannot convert a variable from character to numeric, period, without using an intermediary.  You must do something along the lines of the following:
data want;
set have(rename=varwant=temp);
varwant=input(temp,MMDDYY10.);
drop temp;
run;

There you rename the (character) variable to a temporary name, then convert it to numeric using INPUT.


text:
Q: Change scatter plot XY series to named ranges with VBA I have a dynamic scatter plot that changes with a slider button. In order to do that i use two named ranges with the offset function, these named ranges vary when i move the slider button increasing or decreasing the X and Y ranges end value. The problem arises when i make a copy of this sheet. The chart in the new sheet won't have the named range on the series formula, but instead it adopts the range that was calculated in the first sheet, like this:
In the first sheet i have this:
=Serie('old_sheet'!$AD$3;'old_sheet'!DEF_RANGE;'old_sheet'!STRESS_RANGE;1)

But when i make a copy, the chart in the new sheet will become:
=Serie('new_sheet'!$AD$3;'new_sheet'!$G$19:$G$578;'new_sheet'!$F$19:$F$578;1)

So i need to change the formula manually to this:
=Serie('new_sheet'!$AD$3;'new_sheet'!DEF_RANGE;'new_sheet'!STRESS_RANGE;1)

I ask if anyone can help me implement a simple button that changes the series formula to what i want.
I have tried to record a macro of the steps i do to change the formula... but it doesn't always works.
Kind of stuck here... i would appreciate any help!
Regards

A: I have figured it out myself... Here's the code i used:
Private Sub CommandButton1_Click()

    sheet_name = ActiveSheet.Name
    MsgBox ("some message")
    ActiveSheet.ChartObjects("Graph_1").Activate
    ActiveChart.SeriesCollection(1).Select
    ActiveSheet.ChartObjects("Graph_1").Chart.SeriesCollection(1).Values = " '" & sheet_name      & "'!stress_range"
    ActiveSheet.ChartObjects("Graph_1").Chart.SeriesCollection(1).XValues = " '" & sheet_name & "'!def_range"

End Sub

Hope this can be useful for anyone with the same problem as me.
Thanks

A: The following procedure is a bit of a pain, but it preserves the fragile worksheet-scoped names.

*

*Save the workbook with the worksheet and chart.

*Move (don't copy) the sheet with the chart to a new workbook.

*Close the first workbook without saving, so upon reopening it will
still have the worksheet and chart in it.

*Save and close the new workbook with the moved worksheet and chart
(e.g. TempChart.xlsx). This workbook can now serve as a template if
used as in step 6 below.

*Reopen the original workbook.

*Reopen the new workbook. Move (don't copy) the worksheet and chart
from the new workbook to the original workbook.

Whenever you need another copy of this worksheet and chart, reopen the new workbook as in step 6 and move the sheet into the desired existing workbook.

A: I came up with a small variation on a big program I have, which assumes one chart on the copied sheet and one plotted series in that chart.
Sub FixSeriesRangeRefs()
  Const sXVALNAME As String = "DEF_RANGE"
  Const sYVALNAME As String = "STRESS_RANGE"

  Dim sFormula As String
  Dim vFormula As Variant
  Dim sXVals As String
  Dim sYVals As String

  With ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1)
    sFormula = .Formula
    vFormula = Split(sFormula, ",")

    sXVals = vFormula(LBound(vFormula) + 1)
    sXVals = Left$(sXVals, InStr(sXVals, "!")) & sXVALNAME
    vFormula(LBound(vFormula) + 1) = sXVals

    sYVals = vFormula(LBound(vFormula) + 2)
    sYVals = Left$(sYVals, InStr(sYVals, "!")) & sYVALNAME
    vFormula(LBound(vFormula) + 2) = sYVals

    sFormula = Join(vFormula, ",")
    .Formula = sFormula
  End With
End Sub


text:
Q: how to send navigator extras with Directions in findNavController().navigate() I what to set a transition animation for my view
search about it and understand must send navigator extras in navigate metod
its work for normal navigation but when what send argument with navigation show me this error

None of the following functions can be called with the arguments supplied:
private open fun navigate(p0: NavDestination, p1: Bundle?, p2: NavOptions?, p3: Navigator.Extras?): Unit defined in androidx.navigation.NavController
public open fun navigate(p0: Int, p1: Bundle?, p2: NavOptions?, p3: Navigator.Extras?): Unit defined in androidx.navigation.NavController

it's about first argument error
and this is my code
val extras = FragmentNavigatorExtras(image_cover to "image_cover")
    findNavController().navigate(
        MoviesFragmentDirections.actionMoviesFragmentToMovieItemFragment(
            moviesEntity.title,
            moviesEntity.image,
            moviesEntity.text,
            moviesEntity.video
        ),
        null,
        null,
        extras
    )

A: You can use the following "navigate" function variation to send the extras added to the NavDirections:
 /**
 * Navigate via the given {@link NavDirections}
 *
 * @param directions directions that describe this navigation operation
 * @param navigatorExtras extras to pass to the {@link Navigator}
 */
public void navigate(@NonNull NavDirections directions,
        @NonNull Navigator.Extras navigatorExtras) {
    navigate(directions.getActionId(), directions.getArguments(), null, navigatorExtras);
}

Modify your code like that to achieve that:
val extras = FragmentNavigatorExtras(image_cover to "image_cover")
findNavController().navigate(
    MoviesFragmentDirections.actionMoviesFragmentToMovieItemFragment(
        moviesEntity.title,
        moviesEntity.image,
        moviesEntity.text,
        moviesEntity.video
    ),
    extras
)


text:
Q: Does anyone have printer drivers for a HP Color LaserJet 1600 on Mac OSX 10.7? Does anyone have printer drivers for a HP Color LaserJet 1600 on Mac OSX 10.7?  Or really does anyone have a good solution for installing drivers?
We set up the foo2hp but it doesn't seem to support everything for the 1600.
http://foo2hp.rkkda.com/
If someone has a better solution please let me know.

A:
 We set up the foo2hp

That is the correct driver (at least in Linux land) according to openprinting.org.

but it doesn't seem to support everything for the 1600

The PPD file usually determines what features are supported.

http://www.openprinting.org/driver/foo2hp/ says

PPD files (and the Foomatic XML files to generate them) come with the driver

See http://foo2zjs.rkkda.com/foo2zjs.tar.gz

This sort of issue is why I only buy printers that support PCL5 and Postscript (or emulations of these) - I still have enough problems with printers.

A: Found an answer on the Apple Support site.  Remember that the solution for foo2hp is much older, while its a decent solution this one is better.  Seems like they're now offering HP drivers for their new flavors of OSX.
(HP Color LaserJet 1600 is similar to the HP Color LaserJet 2600)
Here's a support article updated as of July 5th, 2012:
http://support.apple.com/kb/HT3669#HP
Here's the file download:
http://support.apple.com/kb/DL907


text:
Q: Share an instance variable with another class I have two classes:
class Zoo

  def initialize(visitor)
      @visitor = visitor
  end

  def elephant
      Elephant
  end

end

class Elephant

  def self.all
      [:e1, :e2, :e3].reject_if { |e| @visitor.has_seen?(e) }
  end

end

Obviously, the above example won't work.
Is there any way to express this, so that I can call:
Zoo.new(:visitor_1).elephant.all

and access @visitor inside an Elephant class method?

A: Without knowing more about the models in your application, this is what you could do
class Elephant

   def self.all(visitor)
      [:e1, :e2, :e3].reject_if { |e| e.seen_by_visitor?(visitor) }
   end

   def seen_by_visitor?(visitor)
      # whatever code you need here to determine whether the given visitor has seen the elephant
   end

end

class Zoo

  def initialize(visitor)
      @visitor = visitor
  end

  def elephants
      Elephants.all(@visitor)
  end

end

Note that now Zoo depends on Elephant, but Elephant does not depend on Zoo.


text:
Q: Include Google Drive Picker in chrome extension I am trying to include a Google Drive Picker in a chrome extension. I followed this guide to build the chromes extension: https://developer.chrome.com/extensions/getstarted
And this guide to build the picker:
https://developers.google.com/picker/docs/
I used .setOrigin() to set the origin to the URL of the chrome extension. However the target origin provided remains https://docs.google.com and I get the following error:
cb=gapi.loaded_0:80 Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided ('https://docs.google.com') does not match the recipient window's origin ('chrome-extension://<EXTENSION ID>').

What am I doing wrong here?


text:
Q: How do I select a Right Click Menu Item on Browser Menu with Protractor/Javascript? I am trying to select "Back" after performing a Right Click. I can get the Right-Click menu.  I am getting an error when I try to select "Back".
Here is the code:
browser.driver.findElement(By.linkText("Back")).click();

I am using Chrome browser on MAC-OS.
Here is the error:

Message:  NoSuchElementError: no such element  (Session info:
  chrome=43.0.2357.130)  (Driver info: chromedriver=2.14.313457
  (3d645c400edf2e2c500566c9aa096063e707c9cf),platform=Mac OS X 10.10.3
  x86_64) (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 23 milliseconds

A: You can use following jQuery code to detect Right Mouse Click
$('#element').mousedown(function(event) {
    switch (event.which) {
        case 1:
            alert('Left Mouse button pressed.');
            break;
        case 2:
            alert('Middle Mouse button pressed.');
            break;
        case 3:
            alert('Right Mouse button pressed.');
            break;
        default:
            alert('You have a strange Mouse!');
    }
});

And that you can call following code to perform back button action (or go to lastly visited page)
window.history.back();

Hope this is what you are looking for.

A: It could be possible that you are trying to click on the menu before it appears.
var driver = browser.driver,
 wd = browser.wd,
 until = wd.until,
 elementToRightClick = driver.findElement(wd.By.linkText('foo'));
 driver.actions().click(elementToRightClick,wd.Button.RIGHT).perform();
 driver.wait(until.elementIsVisible(driver.findElement(wd.By.linkText('back')),5000, 'Element back was not visibile');
 driver.findElement(wd.By.linkText('back')).click();


text:
Q: How do I find a list of words in a sentence where each word might be separated by n other words I have a list of words i.e. "please find cat"
and I have a sentence "can you please find my pretty cat"
and I have variable indicating the number of words that can be between the "list" of words that determine if this is a match.
For this example, if the fuzziness value between the words was 2 or more, the answer would be true. If it was 1 or less then the answer would be false.
The 'fuzziness' variable can be used between any word. With a fuzzy value of 2 "please hello bob find my pretty cat". This would be true
The order matters, if the sentence was "find please my pretty cat". That would be false.
I'm making the presumption that there is a library in Python that I can uses. If not, then I was looking at regular expressions. Neither of which I've been able to find. Everything I've seen returns true if all the words are in the sentence, regardless of the gap between them.

A: Here is an example:
sentence = 'please find cat'
question = 'can you please find my pretty cat'
SENTENCE = sentence.split(' ')
QUESTION = question.split(' ')

sum(x in SENTENCE for x in QUESTION)

A: I don't know any builtin function doing this. re can help but I don't think it's necessary, and not a good idea either.
The old function I wrote here was wrong. What about this backtrack algorithm
def check_splitable(words_as_string, sentence, max_word_between):
  kw = words_as_string.split(' ')
  sw = sentence.split(' ')
  mx = max_word_between

  def _check_splitable(ki, si):
    if (ki >= len(kw)):
      # has come to last keyword,
      #   just check how many words rest in the sentence
      return len(sw) - si <= mx
    for i in range(mx + 1):
      if sw[si + i] == kw[ki]:
        if _check_splitable(ki + 1, si + i + 1):
          return True
    return False

  return _check_splitable(0, 0)

was = 'please find cat'
sen = 'can you please find your cat'
assert check_splitable(was, sen, 3) is True
assert check_splitable(was, sen, 2) is True
assert check_splitable(was, sen, 1) is False

sen = 'find your pretty cat please'
assert check_splitable(was, sen, 3) is False
assert check_splitable(was, sen, 2) is False
assert check_splitable(was, sen, 1) is False

sen = 'please a find find a a cat'
assert check_splitable(was, sen, 3) is True
assert check_splitable(was, sen, 2) is True
assert check_splitable(was, sen, 1) is False

sen = 'can you please find your cat thank you'
assert check_splitable(was, sen, 3) is True
assert check_splitable(was, sen, 2) is True
assert check_splitable(was, sen, 1) is False

A: I made a small script, I hope I understood your problem:
import numpy as np

def check(text, sentence, n):
    index = []
    for word in sentence.split(" "):
        if word in text.split(" "):
            i = sentence.split(" ").index(word)
            print("Word '"+word+"' found in sentence in position "+str(i+1)+".")
            index.append(i+1)
            #i+1 to make it more understandable
    #print(index)
    #print(np.diff(index))
    if any(t>(n+1) for t in np.diff(index)):
        # If there are n words between the words we are looking for, then the difference between words position should be n+1
        # E.g. First word is in position 2 and second is in position 6, there are 3 words between and 6-3=4=(3+1)
        print("No match found")
        return False
    else:
        print("Match found")
        return True

Examples:
text = "please find cat"
sentence = "can you please find my pretty cat"
n = 2
check(text,sentence,n) #True

n = 1
check(text,sentence,n) #False

n = 3
check(text,sentence,n) #True

text = "please find cat"
sentence = "can you please find my pretty little cat"
n = 2
check(text,sentence,n) #False

n = 3
check(text,sentence,n) #True

A: We can loop through the words of the sentence and find whether the current word matches the next one in the words sequence. If so, then remove it from the words sequence, record the index. Finally, find the difference between the indices and check whether all values fall below or equal to 2.
def get_fuzziness(words, sentence_words):
    remaining_words = words.copy()
    indices = []
    num_words = len(words)
    for idx, expr in enumerate(sentence_words):
        if expr == remaining_words[0]:
            indices.append(idx)
            remaining_words.pop(0)

    if len(indices) != num_words:
        return False  # not all words found

    diff = _get_distances(indices)
    return all(i <= 2 for i in diff)

def _get_distances(indices):
    return [
        second - first
        for first, second in
        zip(indices[:-1], indices[1:])
    ]

words = ['please', 'find', 'cat']
sentence = 'can you please find my cat'.split()
print(get_fuzziness(words, sentence))

sentence = 'can you please find my pretty cat'.split()
print(get_fuzziness(words, sentence))

sentence = 'find my cat please'.split()
print(get_fuzziness(words, sentence))

Output
True
False
False


text:
Q: Keep line breaks in element at web service I have got the following XML structure
<root>
    <element1>Some text</element1>
    <element2>Text with a
    new line</element2>
    <element3>More text</element3>
</root>

I load this XML content in my program like
Dim MyXmlDocument As New System.Xml.XmlDocument
MyXmlDocument.Load(MyXmlFile)

After this the structure is the same like above.
Now I use the document as parameter for a web service method.
MyService.DoSomething(MyXmlDocument)

<WebMethod()> _
Public Sub DoSomething(ByVal data As System.Xml.XmlDocument)
    'do something with the XML content
End Sub

My problem is that the structure is now changed to the following
<root>
    <element1>Some text</element1>
    <element2>Text with anew line</element2>
    <element3>More text</element3>
</root>

The line break was replaced with an empty string. This should not happen. Is there a possibility that the line breaks will be keeped during the sending via a web service?
The application and the web service are both .NET 2.0.

A: XML ignores sequences of whitespaces (blank, carriage returns, linefeeds) and merges them to a single whitespace.
One approach is to use
 as VKSingla suggests, another would be to enter the text in a CDATA element.
<root>
   <element1>
     <![CDATA[
         Some Text
     ]]>
    </element1>
   <element2>
     <![CDATA[
       Text with a <br />
       new line
     ]]>
    </element2>
    <element3>
     <![CDATA[
         More Text
     ]]>
    </element3>
</root>


text:
Q: What is the value of $w+z$ if $1I am having solving the following problem:

If the product of the integer $w,x,y,z$ is 770. and if $1<w<x<y<z$ what is the value of $w+z$ ? (ans=$13$)

Any suggestions on how I could solve this problem ?

A: Hint: $770$ is the product of four distinct primes.  Why must $w$, $x$, $y$, $z$ each be one of those primes?

A: I would proceed as follows. As you know that $$w \cdot x\cdot y\cdot z = 770$$ and $1 < w$, we can start with supposing that $w=2$. After dividing both sides of original equation by $w$, we are left with $$ x \cdot y \cdot z = 385.$$ Now, 3 does not divide 385, so it cannot be the next integer I try for $x$. However, we can find an integer not much larger than 3. Continue in this manner until you have found all of the integers.

A: Find the  prime factorization of the number. That is always a great place to start when you have a problem involving a product of integer. Now here you are lucky, you find $4$ prime numbers to the power of one, so you know your answer is unique.

A: The number 770 is the product of the prime numbers 2,5,7,11 ,
and 1<2<5<7<11
Thus, the answer is 2+11 = 13 .
Hope this helps


text:
Q: Parsing yaml using jackson databind causes MismatchedInputException The format of yaml I am trying to read is as follows
- name: storage
  scm: git
  src: git+https://bitbucket.org/cer/linux_storage_jenkins.git
  version: '5'
- name: linux_jenkins
  scm: git
  src: git+https://bitbucket.org/cer/linux_jenkins.git
  version: '8'

My model is simple
public class Requirementsyml {
    //setter and getter in place
    private List<Requirement> items;
}

public class Requirement {
    private String name;
    private String scm;
    private String src;
    private String version;
}

I am trying to read the yaml contents as follows:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Requirementsyml req = mapper.readValue(yaml_file_content, Requirementsyml.class);

However I am getting the following exception
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of Requirementsyml out of START_ARRAY token
Since the model has a list I think the input should not be mismatched.
I tried to provide yaml file as a java file object, instead of its content as string. The result remains the same. What am I missing?

A: yaml structure should be having items array/list
items:
- name: storage
  scm: git
  src: git+https://bitbucket.org/cer/linux_storage_jenkins.git
  version: '5'
- name: linux_jenkins
  scm: git
  src: git+https://bitbucket.org/cer/linux_jenkins.git
  version: '8'

or else you can read it as list of requirements with no change to yaml
@Test
void test() throws IOException {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    List<Requirement> requirements = mapper.readValue(new File("src/test/resources/requirements.yml"), new TypeReference<List<Requirement>>() {});
    assertEquals(2, requirements.size());
}

also make sure Requirement and other class has no args constructor, otherwise set appropriate flags on ObjectMapper


text:
Q: Spanish numbers rules The Real Academia de la Lengua Española (Royal Academy of Spanish Language) prohibits the use of commas as separators within numbers for every factor of 1000, since the comma is used as decimal separator. For example, what in English is written as 1,000,000.54, we write it as 1000000,54.
However, it is also required that a small space be used as separator (something like $1\,000\,000.54$). I would like to know how to do this automatically in LaTeX (possibly with babel). I could do it manually, but I have already written too many numbers, and some come from software that don't take into account these rules.
Thanks in advance for your answers!

A: This can be easily done using the siunitx package. As can be seen from the following MWE, one can input numbers with different decimal markers and get the same output. The decimal marker can be changed by output-decimal-marker white the group separator can be changed with group-separator.
\documentclass[spanish]{scrartcl}
\usepackage{babel}
\usepackage{siunitx}
\sisetup{output-decimal-marker = {,}}

\begin{document}
\num{1000000,54}

\num{1000000.54}

\num{100 00 00.54}
\end{document}


text:
Q: Using code page 437 and setlocale at the same time There's a few special characters from code page 437 that i want to use within a function that prints n-ary trees so i can do something like this:
http://www.randygaul.net/wp-content/uploads/2015/06/Capture1.png
(Basically something similar to the tree command in linux)
The problem is, my algorithm is using setlocale(LC_ALL, "Portuguese") which messes up with those special characters. I wanted to know if i can somehow apply C default locale to that function alone.

A: Just save the current locale, and then restore:
void func_with_my_own_locale(void) {
   const char * localesave = setlocale(LC_ALL, NULL);
   assert(localesave != NULL); // or some fprintf(stderr, ....);
   if (setlocale(LC_ALL, "CP437" /* or "" */) == NULL) {
       assert(0);
   }
   ......
   if (setlocale(LC_ALL, localesave) == NULL) {
       assert(0);
   }
}

Notice, locale is shared between all threads in a process, so you need to pause all other threads (or make sure they don't call any locale  dependent functions) while calling such function.
From posix setlocale:

Upon successful completion, setlocale() shall return the string associated with the specified category for the new locale. Otherwise, setlocale() shall return a null pointer and the program's locale is not changed.
  A null pointer for locale causes setlocale() to return a pointer to the  string associated with the category for the program's current locale.
  The string returned by setlocale() is such that a subsequent call with that string and its associated category shall restore that part of the program's locale.


text:
Q: FirebaseAuth.instance.onAuthStateChanged not showing my logged in state I am following a Flutter/Firebase tutorial and am having a problem with the Firebase authentication.
My understanding of the code is that the listener will redirect the user to the appropriate page depending upon the user login status. Fro the code this appears to be determined by the status of "snapshot.hasData" however when I run my code I am always directed to the FeedScreen.
I have added a couple of debugging print statements and their output is shown below. I cannot be logged in as I have no user records in Firebase.
Restarted application in 1,971ms.
I/flutter ( 6215): false
I/flutter ( 6215): ConnectionState.waiting
I/flutter ( 6215): true
I/flutter ( 6215): ConnectionState.active

The code is as shown below:
class MyApp extends StatelessWidget {

  Widget _getScreenId() {
    return StreamBuilder<FirebaseUser>(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (BuildContext context, snapshot) {
        print(snapshot.hasData);
        print(snapshot.connectionState);
        if (snapshot.hasData) {
          return FeedScreen();
        } else {
          return LoginScreen();
        }
      }
     );
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Learning Flutter',
      debugShowCheckedModeBanner: false,
      home: _getScreenId(),
      routes: {
        LoginScreen.id: (context) => LoginScreen(),
        SignupScreen.id: (context) => SignupScreen(),
        FeedScreen.id: (context) => FeedScreen(),
      }
    );
  }
}


text:
Q: history option in android web app I am building an android web app using WebView, and I want to add a history feature to it.  I can't seem to find a solution anywhere else so if anyone can help me that would be great. How can I have the app save all the history in a new Activity
(History.java)?
*activity_main.xml*
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" >

<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="490dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editText1" />

<Button
    android:id="@+id/go"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="@string/button_fix" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="300dp"
    android:layout_height="200dp"
    android:layout_alignBaseline="@+id/go"
    android:layout_alignBottom="@+id/go"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@+id/go"
    android:ems="10"
    android:hint="@string/type_url" >

    <requestFocus />
</EditText>

</RelativeLayout>`

MainActivity.java
public class MainActivity extends Activity implements OnClickListener {

private static final String TAG = "blaze web view 2";
private WebView wv;
private Button go;
private EditText url;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv = (WebView) findViewById(R.id.webview);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.setWebViewClient(new BlazeWebViewClient());
    wv.getSettings().setBuiltInZoomControls(true);
    wv.getSettings().setSupportMultipleWindows(true);
    wv.getSettings().setSupportZoom(true);
    wv.getSettings().setDisplayZoomControls(false);

    try {
        wv.loadUrl("http://www.google.com");
    } catch (Exception e) {
        e.printStackTrace();
    }

    go = (Button) findViewById(R.id.go);
    go.setOnClickListener(this);

    url = (EditText) findViewById(R.id.editText1);
    url.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {

    case R.id.go:
        String theWebsite = url.getText().toString();
        if ((theWebsite.isEmpty())) {
            go.setText("GO");
            wv.loadUrl("http://www.google.com");
        }

        else {
            theWebsite = "http://" + url.getText().toString();
            wv.loadUrl(theWebsite);
            go.setText("Home");
        }
        url.setText("");
        break;

    case R.id.editText1:
        go.setText("GO");
        Log.i("EDITTEXT", "EDIT TEXT WAS CLICKED");

    }

}

private class BlazeWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView webview, String Url) {
        webview.loadUrl(Url);
        return true;

    }
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
        wv.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
protected void onStart() {
    super.onStart();
    Log.i(TAG, "On Start");
}

@Override
protected void onRestart() {
    super.onRestart();
    Log.i(TAG, "On Restart");
}

@Override
protected void onPause() {
    super.onPause();
    Log.i(TAG, "On Pause");
}

@Override
protected void onResume() {
    super.onResume();
    Log.i(TAG, "On Resume");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Log.i(TAG, "On Destroy");
}

@Override
protected void onStop() {
    super.onStop();
    Log.i(TAG, "On Stop");
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    wv.saveState(outState);
    Log.i(TAG, "onSavedInstanceState");
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    wv.restoreState(savedInstanceState);
    Log.i(TAG, "RestoreInstanceState");
}

@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.back:
        back();
        return true;

    case R.id.forward:
        forward();
        return true;

    case R.id.refresh:
        refresh();
        return true;

    case R.id.chistory:
        history();
        return true;
    case R.id.History:
        History();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }

}

private void History() {
    Intent i = new Intent(this, History.class);
    startActivity(i);

}

private void history() {
    wv.clearHistory();
    Log.i("H", "Cleared History");
}

private void refresh() {
    wv.reload();
    Log.i("R", "Page Reloaded");
}

private void forward() {
    wv.goForward();
    Log.i("F", "Page Foward");
}

private void back() {
    wv.goBack();
    Log.i("B", "Page Backward");
}
    }

A: Are you perhaps looking for the doUpdateVisitedHistory and getVisitedHistory APIs? The first one lets you know when a user went to a new page (so you can save it in your history database) and the second one (optional) lets you tell the WebView the contents of your history database so that the visited links have a different color. Your History activity would then have to read your history database and list the entries it contains.


text:
Q: Can this Gstreamer pipeline be converted to FFMPEG? I would like to know if I can convert this GSTREAMER pipeline to a ffmpeg command:
udpsrc port=5000 caps="application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)JPEG2000, sampling=(string)GRAYSCALE, width=(int)1280, height=(int)480, payload=(int)96" ! rtpj2kdepay ! jpeg2000parse ! openjpegdec !  videoconvert ! appsink
This is because I would prefer not to add another dependency to the project but I could not make it work. Not sure if its possible at all...


text:
Q: PHP: Read from socket or STDIN I am learning socket programming in PHP and so I am trying a simple echo-chat server.
I wrote a server and it works. I can connect two netcats to it and when I write in the one netcat, I recive it at the other. Now, I want to implement what NC does in PHP
I want to use stream_select to see if I have data on STDIN or on the socket to either send the message from STDIN to the server or reading the incoming message from the server.
Unfortunately the example at the php manual doesn't give me any clue how to do that.
I tried to simply $line = fgets(STDIN) and socket_write($socket, $line) but it doesnt work. So I started to go down and just want stream_select to act up when the user typed the message.
$read = array(STDIN);
$write = NULL;
$exept = NULL;

while(1){

    if(stream_select($read, $write, $exept, 0) > 0)
        echo 'read';
}

Gives

PHP Warning:  stream_select(): No stream arrays were passed in
  /home/user/client.php on line 18

But when I var_dump($read) it tells me, that it is an array with a stream.
array(1) {
  [0]=>
  resource(1) of type (stream)
}

How do I get stream_select to work?

PS: In Python I can do something like
r,w,e = select.select([sys.stdin, sock.fd], [],[])
for input in r:
    if input == sys.stdin:
        #having input on stdin, we can read it now
    if input == sock.fd
        #there is input on socket, lets read it

I need the same in PHP

A: I found a solution. It seems to work, when I use:
$stdin = fopen('php://stdin', 'r');
$read = array($sock, $stdin);
$write = NULL;
$exept = NULL;

Instead of just STDIN. Despite php.net says, STDIN is already open and saves using
$stdin = fopen('php://stdin', 'r');
It seems not, if you want to pass it into stream_select.
Also, the socket to the server should be created with $sock = fsockopen($host); instead of using socket_create on the client side... gotta love this language and it's reasonability and clear manual...
Here a working example of a client that connects to an echo server using select.
<?php
$ip     = '127.0.0.1';
$port   = 1234;

$sock = fsockopen($ip, $port, $errno) or die(
    "(EE) Couldn't connect to $ip:$port ".socket_strerror($errno)."\n");

if($sock)
    $connected = TRUE;

$stdin = fopen('php://stdin', 'r'); //open STDIN for reading

while($connected){ //continuous loop monitoring the input streams
    $read = array($sock, $stdin);
    $write = NULL;
    $exept = NULL;

    if (stream_select($read, $write, $exept, 0) > 0){
    //something happened on our monitors. let's see what it is
        foreach ($read as $input => $fd){
            if ($fd == $stdin){ //was it on STDIN?
                $line = fgets($stdin); //then read the line and send it to socket
                fwrite($sock, $line);
            } else { //else was the socket itself, we got something from server
                $line = fgets($sock); //lets read it
                echo $line;
            }
        }
    }
}


text:
Q: How do I properly free certain malloc'd array elements? I'm using the following struct and methods:
struct cell {
    double x, y, h, g, rhs;
    struct key *keys;
};

void cellFree(struct cell *c)   {
    free(c->keys);
    c->keys = NULL;
    free(c);
    c = NULL;
}

void cellCopyValues(struct cell *targetcell, struct cell *sourcecell)   {
    targetcell->x = sourcecell->x;
    targetcell->y = sourcecell->y;
    targetcell->h = sourcecell->h;
    targetcell->g = sourcecell->g;
    targetcell->rhs = sourcecell->rhs;
    keyCopyValues(targetcell->keys, sourcecell->keys);
}

struct cell * cellGetNeighbors(struct cell *c, struct cell *sstart, struct cell *sgoal, double km)  {
    int i;

    // CREATE 8 CELLS
    struct cell *cn = malloc(8 * sizeof (struct cell));

    for(i = 0; i < 8; i++)  {
        cn[i].keys = malloc(sizeof(struct key));
        cellCopyValues(&cn[i], c);
    }

    return cn;
}

struct cell * cellMinNeighbor(struct cell *c, struct cell *sstart, struct cell *sgoal, double km)   {
    // GET NEIGHBORS of c
    int i;
    struct cell *cn = cellGetNeighbors(c, sstart, sgoal, km);
    double sum[8];
    double minsum;
    int mincell;

    cellPrintData(&cn[2]);

    // *** CHOOSE A CELL TO RETURN
    mincell = 3; // (say)

    // Free memory
    for(i = 0; i < 8; i++)  {
        if(i != mincell)    {
            cellFree(&cn[i]);
        }
    }

    return (&cn[mincell]);
}

When I call cellMinNeighbor() I need to return one of the 8 spawned neighbors (from cellGetNeighbors()) based on a selection criteria - however, the current method which I've applied to the free the other elements seems to be giving me the following error:
*** glibc detected *** ./algo: free(): invalid pointer: 0x0000000001cb81c0 ***

What am I doing wrong? Thanks.

A: You are allocating an array and then trying to free particular members.
Your cn is allocated to be an array of 8 struct cell, but you are actually trying to free &cn[0], &cn[1], &cn[2], which haven't actually been allocated using a malloc which requires it's own free.
You should free only those pointers you got by malloc and one good rule to remember is that the number of frees must correspond to the number of mallocs.
In this case, you malloc cn and the individual keys, but not &cn[1] etc. So freeing them is a mistake.
If you count the mallocs, you have 9, but frees are 16.


text:
Q: An HDD is fast when read by dd, slow otherwise After updating Ubuntu, I found that my non-root HDD become too slow. Just see the numbers:
pv /dev/sda > /dev/null

gives 200kb/s. Mounting it (takes a minute) and running
rsync -r /mnt/hdd2/ /tmp/111

gives the same 200kb/s. You would think the drive is dead, but
dd if=/dev/sda of=/dev/null bs=4M

gives 20Mb/s. Unfortunately, I have no place to copy the whole image of that drive to rescue the data.
I am not sure if it happened immediately after upgrade or after running fstrim. Why can it be like that?
I have already checked:

*

*Smartctl - squeaky clean. Did run tests.

*BIOS is in AHCI mode

*I tried to set the scheduler to noop - no difference at all.

A: I had shrinked the NTFS partition that was on that drive by 30%, created a second partition with btrfs and run fstrim on it. That immediately restored the speed.
Don't run fstrim on NTFS partition.


text:
Q: Marker should displace the whole text
<svg>some</svg>

Lorem Ipsum

.n-float-left {
    float: left;
}

.n-marker {
    width: 3rem;
    height: 3rem;
}

I have failed to make the marker displace the whole text. I don't need any text to the left of the line. How can I resolve this?

.n-float-left {
  float: left;
}

.n-marker {
  width: 3rem;
  height: 3rem;
}

.n-list-text {}

<svg fill="#054B71" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 102.34 256.49">
<path d="M50.653 1.165c-4.83.223-6.992 3.18-7.479 4.315-.519 1.211-7.615 11.779-7.615 11.779l-4.315 5.707v.258c-.77 1.196-1.826 2.948-2.256 4.239-.692 2.076-.697 2.24-.697 2.24l-.514 2.257 1.044-.863.863-2.938 1.59-4.087c.04 1.236.103 3.606-.03 5.465-.173 2.423-1.908 4.497-1.908 4.497v5.193s-.517.865-2.074 1.21c-1.557.347-2.074.005-.863.697 1.211.692 1.726.515 1.726.515l-1.56 3.285s-5.02 5.19-6.404 6.92c-1.384 1.73-12.626 13.671-12.626 13.671S.783 72.963.783 76.078c0 3.114 3.285 5.89 3.285 5.89s10.565 13.148 11.43 14.186c.865 1.038 1.207 3.986 1.726 7.1.52 3.115 7.268-2.77 7.268-2.77s1.732 1.555 2.77 2.074c1.038.519 2.59-.697 2.59-.697s.354 7.618.18 9.175c-.172 1.557-.702 14.701-.53 25.602.174 10.9-7.085 47.766-7.085 47.766l6.92 1.726s-.874 5.535-.182 11.764c.692 6.229 4.844 25.783 4.844 25.783l.53 8.993-.696.349-.697 2.256.182 2.074s-.87 2.422-.696 4.844c.173 2.423 1.044 4.149 1.044 4.149s.333 3.11 1.545 5.36c1.21 2.249 7.1 3.633 7.1 3.633l3.467-.167-1.559-7.615-.696-2.937s-.349-4.161-.349-8.66c0-4.499-2.243-9.863-2.589-14.535-.346-4.672 1.04-9.335 1.56-14.353.519-5.018 1.211-19.379 1.211-19.379s8.124.509 15.564.682c7.44.173 14.02-.863 14.02-.863s.337 4.853 1.029 8.66c.692 3.806 2.433 7.431 2.952 9.508l3.982 15.927-.53 8.826s-3.09 4.832-2.589 7.086c.346 1.557 2.075 4.496 2.075 4.496l.166 9.872 1.211.68s-.173-8.302 0-9.34c.173-1.039.872-.336 2.256.53 1.384.865 1.735 8.132 1.908 9.689.173 1.557 4.315 1.892 4.315 1.892l11.43-.68-7.1-5.542s-1.212-3.802-1.212-5.36c0-1.557-.696-6.759-.696-7.797 0-1.038-.508-2.94-.682-4.496-.173-1.558-1.559-10.038-1.559-10.038s-.342-30.615-.515-32.173c-.173-1.557-.696-4.678-.696-4.678l2.937-1.045s-2.076-7.611-2.422-9.341c-.346-1.73-1.722-10.728-3.452-21.802s-10.038-39.44-10.038-39.44v-6.056l1.03.166s-.349-4.323-.349-6.919c0-2.595-2.589-12.46-2.589-12.46s-.348-2.768-.348-3.633c0-.865 1.045-3.8 1.045-3.8s4.323 7.611 6.919 6.919c5.391-1.438 8.824-4.334 7.267-20.772-1.864-19.675-4.497-26.465-4.497-26.465l-6.237-1.56c-2.077-.519-7.949-2.77-7.949-2.77l.682-1.908.53-3.633 1.892 2.422-1.378-3.8.515-1.908-.696-2.422s-.513-3.46-1.378-6.056c-.865-2.596-3.294-7.092-5.89-10.553-2.595-3.46-7.09-6.397-12.626-6.57a12.95 12.95 0 0 0-1 0zm19.682 21.802.878 1.726.334 2.256-.863 1.544-.349-4.148v-1.378zm-31.309 2.24-1.559 3.286-2.422 1.56 1.907-3.453 2.074-1.393zm30.628 4.33v4.497l-.348.863-1.393-.681.878-2.09.863-2.588zm-35.988 3.8-.878 2.771-1.544 1.045.863-2.074 1.559-1.741zM34 36.639l.348 1.893-2.24.53 1.892-2.423zm-4.723 26.253a.947.947 0 0 1 .757.394c1.038 1.384 3.8 8.993 3.8 8.993l2.77 7.086 1.56 3.633v4.678l-1.56.349-6.056 6.404s-3.813-5.716-5.89-7.1c-2.075-1.385-5.015-3.983-5.707-5.194-.692-1.21-3.809-4.492-2.77-6.222 1.038-1.73 4.498-7.96 7.267-9.69 2.25-1.406 4.507-3.381 5.829-3.33z"></path>
</svg>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.

JSFiddle Snippet Link

A: You can wrap a container element around the whole content which has display: flex. That way the two child elements will remain side by side. You should then also add flex-shrink: 0; to the div that contains the image to keep its defined width (and not shrink):

.container {
  display: flex;
}

.n-marker {
  width: 3rem;
  height: 3rem;
  flex-shrink: 0;
}

<svg fill="#054B71" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 102.34 256.49">
<path d="M50.653 1.165c-4.83.223-6.992 3.18-7.479 4.315-.519 1.211-7.615 11.779-7.615 11.779l-4.315 5.707v.258c-.77 1.196-1.826 2.948-2.256 4.239-.692 2.076-.697 2.24-.697 2.24l-.514 2.257 1.044-.863.863-2.938 1.59-4.087c.04 1.236.103 3.606-.03 5.465-.173 2.423-1.908 4.497-1.908 4.497v5.193s-.517.865-2.074 1.21c-1.557.347-2.074.005-.863.697 1.211.692 1.726.515 1.726.515l-1.56 3.285s-5.02 5.19-6.404 6.92c-1.384 1.73-12.626 13.671-12.626 13.671S.783 72.963.783 76.078c0 3.114 3.285 5.89 3.285 5.89s10.565 13.148 11.43 14.186c.865 1.038 1.207 3.986 1.726 7.1.52 3.115 7.268-2.77 7.268-2.77s1.732 1.555 2.77 2.074c1.038.519 2.59-.697 2.59-.697s.354 7.618.18 9.175c-.172 1.557-.702 14.701-.53 25.602.174 10.9-7.085 47.766-7.085 47.766l6.92 1.726s-.874 5.535-.182 11.764c.692 6.229 4.844 25.783 4.844 25.783l.53 8.993-.696.349-.697 2.256.182 2.074s-.87 2.422-.696 4.844c.173 2.423 1.044 4.149 1.044 4.149s.333 3.11 1.545 5.36c1.21 2.249 7.1 3.633 7.1 3.633l3.467-.167-1.559-7.615-.696-2.937s-.349-4.161-.349-8.66c0-4.499-2.243-9.863-2.589-14.535-.346-4.672 1.04-9.335 1.56-14.353.519-5.018 1.211-19.379 1.211-19.379s8.124.509 15.564.682c7.44.173 14.02-.863 14.02-.863s.337 4.853 1.029 8.66c.692 3.806 2.433 7.431 2.952 9.508l3.982 15.927-.53 8.826s-3.09 4.832-2.589 7.086c.346 1.557 2.075 4.496 2.075 4.496l.166 9.872 1.211.68s-.173-8.302 0-9.34c.173-1.039.872-.336 2.256.53 1.384.865 1.735 8.132 1.908 9.689.173 1.557 4.315 1.892 4.315 1.892l11.43-.68-7.1-5.542s-1.212-3.802-1.212-5.36c0-1.557-.696-6.759-.696-7.797 0-1.038-.508-2.94-.682-4.496-.173-1.558-1.559-10.038-1.559-10.038s-.342-30.615-.515-32.173c-.173-1.557-.696-4.678-.696-4.678l2.937-1.045s-2.076-7.611-2.422-9.341c-.346-1.73-1.722-10.728-3.452-21.802s-10.038-39.44-10.038-39.44v-6.056l1.03.166s-.349-4.323-.349-6.919c0-2.595-2.589-12.46-2.589-12.46s-.348-2.768-.348-3.633c0-.865 1.045-3.8 1.045-3.8s4.323 7.611 6.919 6.919c5.391-1.438 8.824-4.334 7.267-20.772-1.864-19.675-4.497-26.465-4.497-26.465l-6.237-1.56c-2.077-.519-7.949-2.77-7.949-2.77l.682-1.908.53-3.633 1.892 2.422-1.378-3.8.515-1.908-.696-2.422s-.513-3.46-1.378-6.056c-.865-2.596-3.294-7.092-5.89-10.553-2.595-3.46-7.09-6.397-12.626-6.57a12.95 12.95 0 0 0-1 0zm19.682 21.802.878 1.726.334 2.256-.863 1.544-.349-4.148v-1.378zm-31.309 2.24-1.559 3.286-2.422 1.56 1.907-3.453 2.074-1.393zm30.628 4.33v4.497l-.348.863-1.393-.681.878-2.09.863-2.588zm-35.988 3.8-.878 2.771-1.544 1.045.863-2.074 1.559-1.741zM34 36.639l.348 1.893-2.24.53 1.892-2.423zm-4.723 26.253a.947.947 0 0 1 .757.394c1.038 1.384 3.8 8.993 3.8 8.993l2.77 7.086 1.56 3.633v4.678l-1.56.349-6.056 6.404s-3.813-5.716-5.89-7.1c-2.075-1.385-5.015-3.983-5.707-5.194-.692-1.21-3.809-4.492-2.77-6.222 1.038-1.73 4.498-7.96 7.267-9.69 2.25-1.406 4.507-3.381 5.829-3.33z"></path>
</svg>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: You could make your float layout adding floatto the text and ´calc´ in width propertie as your image has a fixed one:

.n-float-left {
    float: left;
}

.n-marker {
    width: 3rem;
    height: 3rem;

}

.n-list-text {
    float: left;
    width:calc(100% - 3rem);
}

<svg fill="#054B71" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 102.34 256.49">
<path d="M50.653 1.165c-4.83.223-6.992 3.18-7.479 4.315-.519 1.211-7.615 11.779-7.615 11.779l-4.315 5.707v.258c-.77 1.196-1.826 2.948-2.256 4.239-.692 2.076-.697 2.24-.697 2.24l-.514 2.257 1.044-.863.863-2.938 1.59-4.087c.04 1.236.103 3.606-.03 5.465-.173 2.423-1.908 4.497-1.908 4.497v5.193s-.517.865-2.074 1.21c-1.557.347-2.074.005-.863.697 1.211.692 1.726.515 1.726.515l-1.56 3.285s-5.02 5.19-6.404 6.92c-1.384 1.73-12.626 13.671-12.626 13.671S.783 72.963.783 76.078c0 3.114 3.285 5.89 3.285 5.89s10.565 13.148 11.43 14.186c.865 1.038 1.207 3.986 1.726 7.1.52 3.115 7.268-2.77 7.268-2.77s1.732 1.555 2.77 2.074c1.038.519 2.59-.697 2.59-.697s.354 7.618.18 9.175c-.172 1.557-.702 14.701-.53 25.602.174 10.9-7.085 47.766-7.085 47.766l6.92 1.726s-.874 5.535-.182 11.764c.692 6.229 4.844 25.783 4.844 25.783l.53 8.993-.696.349-.697 2.256.182 2.074s-.87 2.422-.696 4.844c.173 2.423 1.044 4.149 1.044 4.149s.333 3.11 1.545 5.36c1.21 2.249 7.1 3.633 7.1 3.633l3.467-.167-1.559-7.615-.696-2.937s-.349-4.161-.349-8.66c0-4.499-2.243-9.863-2.589-14.535-.346-4.672 1.04-9.335 1.56-14.353.519-5.018 1.211-19.379 1.211-19.379s8.124.509 15.564.682c7.44.173 14.02-.863 14.02-.863s.337 4.853 1.029 8.66c.692 3.806 2.433 7.431 2.952 9.508l3.982 15.927-.53 8.826s-3.09 4.832-2.589 7.086c.346 1.557 2.075 4.496 2.075 4.496l.166 9.872 1.211.68s-.173-8.302 0-9.34c.173-1.039.872-.336 2.256.53 1.384.865 1.735 8.132 1.908 9.689.173 1.557 4.315 1.892 4.315 1.892l11.43-.68-7.1-5.542s-1.212-3.802-1.212-5.36c0-1.557-.696-6.759-.696-7.797 0-1.038-.508-2.94-.682-4.496-.173-1.558-1.559-10.038-1.559-10.038s-.342-30.615-.515-32.173c-.173-1.557-.696-4.678-.696-4.678l2.937-1.045s-2.076-7.611-2.422-9.341c-.346-1.73-1.722-10.728-3.452-21.802s-10.038-39.44-10.038-39.44v-6.056l1.03.166s-.349-4.323-.349-6.919c0-2.595-2.589-12.46-2.589-12.46s-.348-2.768-.348-3.633c0-.865 1.045-3.8 1.045-3.8s4.323 7.611 6.919 6.919c5.391-1.438 8.824-4.334 7.267-20.772-1.864-19.675-4.497-26.465-4.497-26.465l-6.237-1.56c-2.077-.519-7.949-2.77-7.949-2.77l.682-1.908.53-3.633 1.892 2.422-1.378-3.8.515-1.908-.696-2.422s-.513-3.46-1.378-6.056c-.865-2.596-3.294-7.092-5.89-10.553-2.595-3.46-7.09-6.397-12.626-6.57a12.95 12.95 0 0 0-1 0zm19.682 21.802.878 1.726.334 2.256-.863 1.544-.349-4.148v-1.378zm-31.309 2.24-1.559 3.286-2.422 1.56 1.907-3.453 2.074-1.393zm30.628 4.33v4.497l-.348.863-1.393-.681.878-2.09.863-2.588zm-35.988 3.8-.878 2.771-1.544 1.045.863-2.074 1.559-1.741zM34 36.639l.348 1.893-2.24.53 1.892-2.423zm-4.723 26.253a.947.947 0 0 1 .757.394c1.038 1.384 3.8 8.993 3.8 8.993l2.77 7.086 1.56 3.633v4.678l-1.56.349-6.056 6.404s-3.813-5.716-5.89-7.1c-2.075-1.385-5.015-3.983-5.707-5.194-.692-1.21-3.809-4.492-2.77-6.222 1.038-1.73 4.498-7.96 7.267-9.69 2.25-1.406 4.507-3.381 5.829-3.33z"></path>
</svg>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.


text:
Q: Property 'sendEmailVerification' does not exist on type 'void' I am trying to send an email verification, and then set the data.uid to user.id, no matter where i put  promise there is always an error.
Here is my code
onCreate(form: NgForm) {
var user = new User();
user.name = form.value.name;
user.email = form.value.email;
user.contact = form.value.contact;
if(form.value.gender == "male") {
  user.gender = "male";
} else {
  user.gender = "female"
}
let loading = this.mProv.getLoader('Creating your account...', 0);
loading.present();
var promise = this.afAuth.auth.createUserWithEmailAndPassword(form.value.email, form.value.password)
  .then(data => {
    user.id = data.uid;
    this.userProvider.addUser(user)
      .then(_ =>
        loading.dismiss()
      )
      .catch(error => {
        console.log(error);
        loading.dismiss();
        this.mProv.showAlertOkMessage('Error','Sign up error. Please try again later.');
      });
  })
  .catch(error => {
    console.log(error);
    loading.dismiss();
    this.mProv.showAlertOkMessage('Error','Sign up error. Please try again later.');
  });
  promise.then(function(user) {
    user.sendEmailVerification();

    // firebase.auth().currentUser.sendEmailVerification();

  }, function(error) {
    console.log(error)
  })
}

Error messages = Property 'sendEmailVerification' does not exist on type 'void'.

If i put promise after .createUserWithEmailAndPassword
Error messages = Property 'uid' does not exist on type 'void'.

A: Typescript complains that uid does not exist on type void, probably try changing it as follows,
.then((data:any)=>{
   user.id = data.uid;
}


text:
Q: Passing argument to Resource file in o:validateOrder OmniFaces 2.0 Hi I'm developing and application with:
.JSF 2.1
.OmniFaces 2.0
I have a resource file with placeholder
comun.abm.fecha.factura.menor.ultimo.comprobante=La fecha de la Factura tiene que ser mayor o igual a la ultima fecha de emision del ultimo comprobante: {0}

and I have this validation:
<h:outputLabel value="#{msgs['facturacion.abm.generacion.padron.fecha.factura']}"
               for="fechaFactura"/>

<rich:calendar
    id="fechaFactura"
    datePattern="dd/MM/yyyy"
    showWeeksBar="false"
    enableManualInput="true"
    value="#{generacionPadronController.padronBean.fechaFactura}" />

<h:panelGroup>
    <rich:message for="fechaFactura"/>

    <o:outputFormat value="#{msgs['comun.abm.fecha.factura.menor.ultimo.comprobante']}"
                    var="_validacion">
        <f:param value="#{generacionPadronController.fechaEmisionComprobanteUltima}" />
    </o:outputFormat>

    <o:validateOrder id="validacionFechaFacturaMayorAFechaEmisionUltimoComprobante"
                     type="lte"
                     components="fechaFactura fechaEmisionComprobanteUltima"
                     message="#{_validacion}"
                     showMessageFor="fechaFactura">
    </o:validateOrder>
</h:panelGroup>

the validation works and send me empty message probably because the variable doesnt have a value, any other idea to accomplish this (passing argument to a bundle with o:validateOrder).
PD: I print the #{_validacion} and works ok in the page, but is empty when the validation is fired.

A: The <o:outputFormat var> is set during render response phase. However, the <o:validateXxx message> is evaluated during validations phase, which is too early.
Better use #{of:format1()} function instead.
<o:validateOrder id="validacionFechaFacturaMayorAFechaEmisionUltimoComprobante"
                 type="lte"
                 components="fechaFactura fechaEmisionComprobanteUltima"
                 message="#{of:format1(msgs['comun.abm.fecha.factura.menor.ultimo.comprobante'], generacionPadronController.fechaEmisionComprobanteUltima)}"
                 showMessageFor="fechaFactura">
</o:validateOrder>


text:
Q: Connecting ArcGIS Desktop to remote PostgreSQL database? I have setup PostgreSQL 9.5 on my local machine. I am trying to create a database connection from a coworkers laptop on the office network (let's say the network IP is 192.168.1.X). My database server is currently just called localhost (on port 5432). I was able to connect it to ArcGIS Desktop10.5 on the same machine using the add Database Connection option in ArcCatalog, no problem. So, I want to do the same on my coworkers computer. When I try, I get an "Unable to make database connection..." error.

I have configured my pg_hba.conf file multiple times to make sure that any computer on the networks (either 192.168.1.1 - the wifi or 10.1.10.1 - the ethernet) can access it  (with database authentication of course). I followed these ESRI configuration instructions.

Is there something I am missing?
Is there something else I need to do to make the database connection to postgres?
Can anyone see a problem with my pg_hba.conf file or with using "localhost" as the database instance?

A: OK, for the edification of anyone who runs into this problem; here is my answer. I am 99.9% positive that this issue was directly caused by a combination of McAfee and my personal computer firewall settings. Essentially, I completely removed McAfee and Turned Windows Defender Firewall off on my Private network (it's still set to On for Public). I was able to make the connection to the Postgres server using the , 5432 and find the specific database I wanted. Now I just need to figure out how to safely setup a Inbound Rule in the advanced setting of my firewall to allow connections from other machines on my network. If anyone has any advice on that, let me know.


text:
Q: Typing the date time in textbox, does not change the selected value of date picker I've used use babakhani Persian datepicker in my project.
There is a problem here. the selected value of date picker does not change on textbox value change!! How can I fix it in my project, myself?
JsFiddle
I used
$("#example1").change(
    function (e) {
        $("#example1").pDatepicker();
    };
});

but the error is:

too much recursion

since it calls change() recursively. (also .blur() is tested)

A: No need to use change event. you can directly use
$(document).ready(function () {
    $("#example1").pDatepicker();
});
Also there is an additional } in your code.


text:
Q: HC-05 Module sending data problem (Mater + Slave) I've been working with a Siemens PLC to send data using RS232. The communication itself is working perfectly, I can monitor it if I connect the PLC to my PC (via a serial comm port).
Now, I wanted to make this communication wireless. I found out about the HC-05 modules and decided to get a few. I set 2 of them up with my arduino (one as master, one as slave, both paired and using the UART 9600,1,0 which is the same that my PLC uses).
I made the following connections:
PC Connection (with a serial comm adapter)
PLC Connection
Let's say I want to send this string:
<SoH>1RZ<CR>

If I check my serial monitor, I get weird stuff. Like:
@#NULL©#NUL

The weird thing is that if I just remove the bluetooth modules and connect the PLC's Rx and Tx to the PC's Tx and Rx, respectively, the data is sent flawlessly. So I know that I have everything sorted out on the PLC/PC side.
Has anyone been through this, or does anyone have a suggestion that I can try?

A: RS232 typically uses ±12V. Negative voltages between -3V and -15V is logic high and positive voltages +3V till +15V is logic low.
Your bluetooth module on the other hand uses TTL logic. With a voltage range of 0-5V.
0-0.8V is low, 2-5V is high.
So
a) you cannot create the necessary voltage levels
b) you risk to destroy your 5V hardware by connecting it to ±12V.
c) you might run into problems as RS232 also has optional mechanisms for flow control. So Rx and Tx might not be enough.
You'll at least need a TTL-> RS232 level shifter for the PLC side and a USB to TTL serial adapter for the PC


text:
Q: c++ mpi segmentation fault on slurm I am running the same boost MPI C++ program on slurm and on my Mac. Both are running with 1 node 16 cores.... However, on my Mac, I never get the segmentation fault error while on SLURM super computing system, I almost always get the segmentation fault if i run on many cores (if I only run on 4 cores, the error does not happen, if on 32 cores, then it almost always happen) (it just seems like the segmentation fault is happening by randomness, each time)
[c558-403.stampede.tacc.utexas.edu:mpi_rank_0][error_sighandler] Caught error: Segmentation fault (signal 11)

by writing the execution of every line on the screen, I realize seg-fault for main happens at:
     mpi_world.recv(dst_rank, 1,spin_tmp);

and spin_tmp is:
     map<tuple<int,int,int,int>,int>  spin_tmp;

where as the tuple is from boost tuple. I am really struggling and have no idea what on earth is happening....
I would like to give a minimal version of code here:
main.cpp
int main (void){

    mpi::environment mpi_env;
    mpi::communicator mpi_world;
    if (mpi_world.rank()==0)
    {
        read_from_file(id, max_sites, J, prec, num_loops, translation_algorithm,
                       basic_exact_mode, pseudo_mode, pseudo_mode_with_proof,
                       verbose, very_verbose, obscenely_verbose,input_PRIM_output_PRIMOUT_mode,limit_dimension,constant,mu,mu_translation_algorithm,mu_constant,work_with_mu,scan_chemical_potential,new_cluster_algorithm,use_new_pair_terms,use_new_triplet_terms, output_more_states,output_states_below_hull,how_much_lower,output_states_how_sparse,use_level_method,use_weighted_dual_average,global_parameters);

    }
    else
    {
        bool restart_signal=true;

        periodic_slave();
        return 0;
    }

      corecode(components, x_range, y_range, z_range, max_sites, num_loops,
             Ji,
             lowerboundclustertype, upperboundclustertype, cellrepresentation,
             lower_bound, upper_bound, unitcell, periodicity, J_for_proof,
             id, pseudo_mode, pseudo_mode_with_proof, basic_exact_mode,
             very_verbose, obscenely_verbose,limit_dimension,new_cluster_algorithm,use_new_pair_terms,use_new_triplet_terms,map_periodicity_to_spin,  use_level_method, use_weighted_dual_average,global_parameters);
}

in periodic_function.cpp (specifically for slave)
void periodic_slave()
{
    mpi::communicator mpi_world;

    cout<<"\n hello I am slave: "<<mpi_world.rank()<<" received the global parameters"<<endl;

    bool kill_all_slave=false;

    broadcast(mpi_world,kill_all_slave,0);

    while (kill_all_slave==false) {

        vector<tuple<int,int,int,int,int,int> > periodicity_vector;

        std::cout << "[SLAVE: " << mpi_world.rank()<< "] I am waiting to receive periodicity vector"<<endl;

        periodicity_vector.clear();

        broadcast(mpi_world,periodicity_vector,0);

        std::cout << "[SLAVE: " << mpi_world.rank()<< "] I am waiting to J "<<endl;

//        J.clear();

        map<set<tuple<int,int,int,int,int> >, double> J;

        broadcast(mpi_world,J,0);

        int x_range,y_range,z_range;
        double min_bound;
        map<int,int> component;

        cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" received 3rd set of the global parameters"<<endl;

        broadcast(mpi_world,x_range,0);
        broadcast(mpi_world,y_range,0);

        cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" received 4th set of the global parameters"<<endl;
        broadcast(mpi_world,z_range,0);
        broadcast(mpi_world,component,0);
        cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" received 5th set of the global parameters"<<endl;

        broadcast(mpi_world,min_bound,0);

        cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" received 6th set of the global parameters"<<endl;

        bool stop = false;
        string status="initial";
        mpi_world.send(0, 0, status);
//
        cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" I am going to send to root status"<<endl;

        mpi_world.recv(0, 0, stop);

        cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" I am going to receive stop signal from root"<<endl;

        while(!stop) {

            map< tuple<int,int,int,int,int,int>, map<set<tuple<int,int,int,int,int> >, double> > clustertype_periodic;

            // Wait for new job

            unsigned int job_id = 0;

            cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" I am going to receive job id from root"<<endl;

            mpi_world.recv(0, 0, job_id);

            cout<< "[SLAVE: " << mpi_world.rank()<<"] hello I am slave: "<<mpi_world.rank()<<" I am going to receive stop min bound from root"<<endl;

            mpi_world.recv(0, 1, min_bound);

            std::cout << "[SLAVE: " << mpi_world.rank()

            << "] Received job " << job_id << " from MASTER.\n"<<endl;

            // Perform "job"

            map<tuple<int,int,int,int>,int>  spin_tmp;
            double energy_tmp=0;

            tuple<int,int,int,int,int,int>  periodicity_now;
            {
                int i=job_id;
                periodicity_now=periodicity_vector[i];
                int a0=periodicity_now.get<0>();
                int a1=periodicity_now.get<1>();
                int a2=periodicity_now.get<2>();
                int a3=periodicity_now.get<3>();
                int a4=periodicity_now.get<4>();
                int a5=periodicity_now.get<5>();

                {
                    if (pseudo_mode) {

                        periodic(a0, a1, a2, a3, a4, a5,
                                 J, x_range, y_range, z_range, component,
                                 spin_tmp,
                                 energy_tmp,
                                 clustertype_periodic, min_bound, id,
                                 true, false, false,
                                 obscenely_verbose,global_parameters);

                        //                    {
                        //                        spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)]=spin_tmp;
                        //                        energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)]=energy_tmp;
                        //                    }
                    }
                    else if (basic_exact_mode){

                        periodic(a0, a1, a2, a3, a4, a5,
                                 J, x_range, y_range, z_range, component,
                                 spin_tmp,
                                 energy_tmp,
                                 clustertype_periodic, min_bound, id,
                                 false, true, false,
                                 obscenely_verbose,global_parameters);

                        //                    {
                        //                        spin_periodic[make_tuple(a0,a1,a2,a3,a4,a5)]=spin_tmp;
                        //                        energy_periodic[make_tuple(a0,a1,a2,a3,a4,a5)]=energy_tmp;
                        //                    }

                    }

                }
            }

            // Notify master that the job is done

            std::cout << "[SLAVE: " << mpi_world.rank()

            << "] Done with job " << job_id << ". Notifying MASTER.\n"<<endl;

            status="finish";

            mpi_world.send(0, 0,status);
//            std::cout << "[SLAVE: " << mpi_world.rank()<< "] I have sent status back to master"<<endl;

            //note here, I deliberated exclude cluster_type_periodic which may be the culprit of a lot of bad computing performance for realistic system

            //send periodicity, spin_tmp and energy_tmp

            //        and remember to send more detail;

            mpi_world.send(0, 1,spin_tmp);
            std::cout << "[SLAVE: " << mpi_world.rank()<< "] I have sent spin_tmp back to master"<<endl;
            mpi_world.send(0, 2,energy_tmp);
            std::cout << "[SLAVE: " << mpi_world.rank()<< "] I have sent energy_tmp back to master"<<endl;
            mpi_world.send(0, 3,periodicity_now);
            std::cout << "[SLAVE: " << mpi_world.rank()<< "] I have sent periodicity_now back to master"<<endl;

            // Check if a new job is coming

            mpi_world.recv(0, 0, stop);
            std::cout << "[SLAVE: " << mpi_world.rank()<< "] I have receive stop from master and stop is "<<stop<<endl;

        }

        std::cout << "[SLAVE: " << mpi_world.rank()<< "] I am waiting for signal whether kill_all_slave"<<endl;

        broadcast(mpi_world,kill_all_slave,0);

        std::cout << "[SLAVE: " << mpi_world.rank()<< "] I receive kill_all_slave signal as "<<kill_all_slave<<endl;

    }

    std::cout << "~~~~~~~~ Rank " << mpi_world.rank() << " is exiting ~~~~~~~~~~~\n"<<endl;

}

For solver.cpp (for MASTER)
void corecode(map<int, int> component,
              int x_range, int y_range, int z_range,
              int max_sites,
              int loopnumber,
              map<set<tuple<int,int,int,int,int> >, double> &J,
              map<set<tuple<int,int,int,int,int> >, double> &lowerboundclustertype,
              map<set<tuple<int,int,int,int,int> >, double> &upperboundclustertype,
              map<tuple<int,int,int,int>,int> &cellrepresentation,
              double &lower_bound, double &upper_bound,
              map<tuple<int,int,int,int>,int> &unitcell,
              tuple<int,int,int,int,int,int> &periodicity,
              map<set<tuple<int,int,int,int,int> >, double> &J_for_proof,
              std::string id,
              bool pseudo_mode,
              bool pseudo_mode_with_proof,
              bool basic_exact_mode,
              bool very_verbose,
              bool obscenely_verbose,
              double limit_dimension,bool new_cluster_algorithm,int use_new_pair_terms,int use_new_triplet_terms, map<tuple<int,int,int,int,int,int>, map<tuple<int,int,int,int>,int> > &map_periodicity_to_spin, bool use_level_method,bool use_weighted_dual_average ,solver_variable &global_parameters)
{

    mpi::communicator mpi_world;

    cout<<"\n what is global_parameters.dedicated1D: "<<global_parameters.dedicated1D<<" what is  dimension==1:"<<(dimension==1)<<endl;

    if (!(global_parameters.dedicated1D==true&&dimension==1)) {

        // Obtain upper bound estimate on the energy
        if (max_sites > 0){

            vector<tuple<int,int,int,int,int,int> > periodicity_vector;
            periodicity_vector.clear();

            bool done=false;

            cout<<"\n debug 02819374 periodicity_vector.size(): "<<periodicity_vector.size()<<endl;

            bool kill_all_slave=false;
            usleep(100000);
            cout<<"[MASTER] I am broadcasting kill_all_slave"<<endl;

            broadcast(mpi_world,kill_all_slave,0);

            usleep(100000);
            cout<<"[MASTER] I am broadcasting periodicity_vector"<<endl;

            broadcast(mpi_world,periodicity_vector,0);

            usleep(1000000);
            cout<<"[MASTER] I am broadcasting J"<<endl;

            broadcast(mpi_world,J,0);

            usleep(1000000);
            cout<<"[MASTER] I am broadcasting x_range"<<endl;

            broadcast(mpi_world,x_range,0);
            usleep(100000);
            cout<<"[MASTER] I am broadcasting y_range"<<endl;

            broadcast(mpi_world,y_range,0);
            usleep(100000);
            cout<<"[MASTER] I am broadcasting z_range"<<endl;

            broadcast(mpi_world,z_range,0);
            usleep(100000);
            cout<<"[MASTER] I am broadcasting component"<<endl;

            broadcast(mpi_world,component,0);
            usleep(100000);
            cout<<"[MASTER] I am broadcasting minbound"<<endl;

            broadcast(mpi_world,min_bound,0);
            usleep(100000);
            //            lets write something here, for loop starts here:
            set<int> killed_slave;
            map<int, string > status_of_slave;

            // Initialize requests
            unsigned int job_id = 0;
            std::vector<mpi::request> reqs(mpi_world.size());

            //            cout<<"\n hello I am root: I am going to send to receieve status status"<<endl;

            // Send initial jobs
            for (unsigned int dst_rank = 1; dst_rank < mpi_world.size(); ++dst_rank) {

                // Post receive request for new jobs requests by slave [nonblocking]
                cout<<"[MASTER] I am i receving status_of_slave: "<<dst_rank<<endl;

                reqs[dst_rank] = mpi_world.irecv(dst_rank, 0,status_of_slave[dst_rank]);
                ++job_id;
            }

            //            cout<<"\n hello I am root: I finish status request"<<endl;

            // Send jobs as long as there is job left
            while(job_id < periodicity_vector.size()) {
                bool stop;
                for (unsigned int dst_rank = 1; dst_rank < mpi_world.size(); ++dst_rank) {
                    // Check if dst_rank is done
                    //                    cout<<"status_of_slave["<<dst_rank<<"] is "<<status_of_slave[dst_rank] <<endl;
                    if (reqs[dst_rank].test()) {
                        cout<<"[MASTER] I receive reqs[dst_rank].test() is: "<<1<<endl;
                        cout<<"status_of_slave["<<dst_rank<<"] is "<<status_of_slave[dst_rank] <<endl;

                        if(status_of_slave[dst_rank]=="finish") {
                            //note here, I deliberated exclude cluster_type_periodic which may be the culprit of a lot of bad computing performance for realistic system

                            cout<<"[MASTER] I receive finish status "<<endl;

                            //                            remember to receive more detail output;
                            //                            and update the things you want to update;
                            map<tuple<int,int,int,int>,int>  spin_tmp;
                            double energy_tmp=0;
                            mpi_world.recv(dst_rank, 1,spin_tmp);
                            cout<<"[MASTER] I receive spin_tmp status "<<endl;

                            mpi_world.recv(dst_rank, 2,energy_tmp);
                            cout<<"[MASTER] I receive energy_tmp status "<<endl;

                            tuple<int,int,int,int,int,int>  periodicity_now;

                            mpi_world.recv(dst_rank, 3,periodicity_now);
                            cout<<"[MASTER] I receive periodicity_now status "<<endl;

                        }

                        std::cout << "[MASTER] Rank " << dst_rank << " is done.\n"<<endl;
                        // Check if there is remaining jobs
                        if (job_id  < periodicity_vector.size()) {
                            // Tell the slave that a new job is coming.
                            stop = false;
                            mpi_world.isend(dst_rank, 0, stop);
                            // Send the new job.
                            //                            std::cout << "[MASTER] Sending new job (" << job_id
                            //                            << ") to SLAVE " << dst_rank << ".\n"<<endl;
                            mpi_world.isend(dst_rank, 0, job_id);
                            mpi_world.isend(dst_rank, 1, min_bound);

                            reqs[dst_rank] = mpi_world.irecv(dst_rank, 0,status_of_slave[dst_rank]);
                            ++job_id;
                        }
                        else {
                            // Send stop message to slave.
                            stop = true;
                            mpi_world.send(dst_rank, 0, stop);
                            killed_slave.insert(dst_rank);
                        }
                    }
                }
                usleep(1000);
            }
            std::cout << "[MASTER] Sent all jobs.\n";

            // Listen for the remaining jobs, and send stop messages on completion.
            bool all_done = false;
            while (!all_done) {
                all_done = true;
                for (unsigned int dst_rank = 1; dst_rank < mpi_world.size(); ++dst_rank) {

                    //                    cout<<"[MASTER] check if Slave "<<dst_rank<<" is killed?"<<endl;

                    if(killed_slave.count(dst_rank)==0)
                    {
                        //                        cout<<"[MASTER] Slave "<<dst_rank<<" is not yet killed"<<endl;
                        //
                        //                        cout<<"[MASTER] last round; checking status message from slave "<<dst_rank<<endl;

                        if (reqs[dst_rank].test()) {

                            cout<<"[MASTER] last round; checking status message from slave "<<dst_rank<<endl;
                            cout<<"status_of_slave["<<dst_rank<<"] is "<<status_of_slave[dst_rank] <<endl;

                            if(status_of_slave[dst_rank]=="finish") {
                                //note here, I deliberated exclude cluster_type_periodic which may be the culprit of a lot of bad computing performance for realistic system

                                cout<<"[MASTER] I receive finish status from slave "<<dst_rank<<endl;

                                //                            remember to receive more detail output;
                                //                            and update the things you want to update;
                                map<tuple<int,int,int,int>,int>  spin_tmp;
                                double energy_tmp=0;
                                mpi_world.recv(dst_rank, 1,spin_tmp);
                                cout<<"[MASTER] I receive spin_tmp status "<<endl;

                                mpi_world.recv(dst_rank, 2,energy_tmp);
                                cout<<"[MASTER] I receive energy_tmp status "<<endl;

                                tuple<int,int,int,int,int,int>  periodicity_now;

                                mpi_world.recv(dst_rank, 3,periodicity_now);
                                cout<<"[MASTER] I receive periodicity_now status "<<endl;

                                spin_periodic[periodicity_now]=spin_tmp;
                                energy_periodic[periodicity_now]=energy_tmp;

                                cout<<"[MASTER] I updated spin_periodic and energy_periodic "<<endl;

                                {
                                    double dump1;
                                    findminmax(energy_periodic, min_bound, dump1);
                                    matchnumber(energy_periodic, min_bound, min_list);

                                    if (very_verbose){
                                        cout << "\nUB: " << min_bound << ", LB: " << lowerbound_from_compat << "; Periodicity: ";
                                        printvector(min_list);
                                        cout << endl;
                                    }

                                    if (min_bound <= lowerbound_from_compat+1e-5*max_value_of_J) {
                                        done=true;
                                    }

                                }

                                cout<<"[MASTER] I updated minlist and minbound "<<endl;

                            }
                            // Tell the slave that it can exit.
                            bool stop = true;
                            mpi_world.send(dst_rank, 0, stop);
                            killed_slave.insert(dst_rank);
                            cout<<"[MASTER] I stopped slave "<<dst_rank<<endl;

                        }
                        else {
                            all_done = false;
                        }
                    }

                }
                usleep(1000);
            }
            std::cout << "[MASTER] Handled all jobs, killed every process.\n";
        }

    }
}

The logic of the code shall have no issue, since it runs completely fine on my Mac with 16 cores... However, mysterious segmentation fault happens when I run it on Stampede super computer (sometimes even with as low as 8 cores)... This is very mysterious...

A: I think basically this is impossible to debug... Because I try the same program on Nersc, running on 240 cores without any issue....


text:
Q: java: display the elements from a database I wrote some java code to display database,  when I run the code it gives me just the last  element of database , but I wanna  display all elements of table
the code :
public String RecupererPuissance() {
    try {
        Connection con =  myDbvoiture.getConnection();
        String queryPattern ="select Power from bd_voiture";
        PreparedStatement pstmt =  con.prepareStatement(queryPattern);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            puissance=rs.getString("Power");
            System.out.println(puissance);
        }
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
    return puissance;
}

What should I do? Can anyone please help me to display all values?
Thank you for helping me.

A: I think the problem is with your code that the value of puissance is overwritten every time you get the next element. Only the last value is returned. You should put the results into a list and return the whole list:
public List<String> RecupererPuissance() {
    List<String> puissances = new ArrayList<String>();
    try {
        Connection con =  myDbvoiture.getConnection();
        String queryPattern ="select Power from bd_voiture";
        PreparedStatement pstmt =  con.prepareStatement(queryPattern);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            puissance = rs.getString("Power");
            puissances.add(puissance);
            System.out.println(puissance);
        }
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
    return puissances;
}

A: public String RecupererPuissance() {
    try {
        Connection con =  myDbvoiture.getConnection();
        String queryPattern ="select Power from bd_voiture";
        PreparedStatement pstmt =  con.prepareStatement(queryPattern);
        ResultSet rs = pstmt.executeQuery();
        rs.first();
        int count=0;
        while (rs.next()) {
        System.out.println("count = "+count);
        count+=1;
            puissance=rs.getString("Power");
            System.out.println(puissance);
        }
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
    }
    return puissance;
}

If you see count printed only 1 time :
it would mean that you have only 1 row in column Power
and you maybe referring to the wrong column in your code


text:
Q: Can yield return values across multiple assemblies? As the title says can yield return values across multiple assemblies?
For instance assume the following solution exists:
SolutionA
    |
    |-Project A
    |
    |-Project B

If Project B is referenced by Project A, can a method in Project B yield values to a method in Project A?

A: Iterator blocks (that is, methods that contain the yield keyword) are specific to that one method, in the sense that from anywhere outside of that method it is no different than any non-iterator block that returns an IEnumerable or IEnumerator.  You can't, for example, yield a value to an iterator other than "yourself", so to speak.  It's easier to show through code:
public class Foo
{
    public static IEnumerable<int> Bar()
    {
        yield return 1;
        Baz();
    }

    private static void Baz()
    {
        //there's no way for me to yield a second item out of Bar here
        //the best I can do is return an `IEnumerable` and have `Bar`
        //explicitly yield each of those items
    }
}

You can of course consume an iterator block from anywhere in which the method is accessible.  You can call Bar from another method in the same class, from another class in the same assembly, or from another referenced assembly.  To any of those callers it's no different than any other method returning an IEnumerable.

A: Linq and its extension methods live in a different assembly than the one i use them from. So yes :) (edit: at least that was a very important reason to lean on the positive. Confirmation was pretty quick )
And confirmed just now between a console application assembly and a class library assembly :)
public IEnumerable<string> test()
{
     yield return "1";
     yield return "2";
     yield return "3";
     yield return "4";
}

in the class library is completely callable in the console application:
var t =new ClassLibrary1.Class1();
foreach (var test in t.test())
{
    Console.WriteLine(test);
}

A: Why shouldn't it? From the outside, an iterator is just a method with the return type IEnumerable<T>, so if you're able to call the method, it will "yield return values across multiple assemblies".