text:
Q: How to fix Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'? I always encounter this in Frontend says Access to XMLHttpRequest at 'api/abc/xyz' from origin 'localhost://2800/api/abc/xyz' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried this to add in Backend
`
 http.authorizeRequests()
     .antMatchers(HttpMethod.OPTIONS).permitAll()
     .anyRequest().authenticated();

`
and my frontend AJAX CALL API:
 `
$.ajax({
        'type': 'GET',
        'url': '/api/vessel/?vesselId=' + $('#vessel_id').val() + '&page=1&size=100',
        'headers': {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": `Bearer ${session}`
        },
        success: function(response) {console.log(response)}
 });

`
But after that I still encounter that error.
`
@Override
    protected void configure(HttpSecurity http) throws Exception {

        // Disable CSRF (cross site request forgery)
        http.csrf().disable();

        // No session will be created or used by spring security
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Entry points
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // Disallow everything else..
                .anyRequest().authenticated();

        // If a user try to access a resource without having enough permissions
        //http.exceptionHandling().accessDeniedPage("/login");

        // Apply JWT
        http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

        // Optional, if you want to test the API from a browser
        // http.httpBasic();
    }

`

A: You have to config the CORS Configurations. Add the following class in your Project. You can change this as per your requirements.
WebConfig.java
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type,"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }
}

 @Override
    public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
            .antMatchers(HttpMethod.OPTIONS,"/**");
          //URL you want to ignore
    }

@Override
    protected void configure(HttpSecurity http) throws Exception {

        // Disable CSRF (cross site request forgery)
        http.csrf().disable();

        // No session will be created or used by spring security
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Entry points
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                // Disallow everything else..
                .anyRequest().authenticated();

        // If a user try to access a resource without having enough permissions
        //http.exceptionHandling().accessDeniedPage("/login");

        // Apply JWT
        http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

        // Optional, if you want to test the API from a browser
        // http.httpBasic();
    }


text:
Q: Why won't a script added dropdown box update the text in the box to the selection chosen I have a dropdown box and two input fields. when I click the dropdown box and select a dropdown option the text in the dropdown box changes to the text of the selection I clicked on.
I also have a function that creates another row that's identical to the dropdown box and two input fields mentioned above but when this row has been created the dropdown box text does not change.
I am at a complete loss as to why the 2nd (or 3rd,4th ...) dropdown box doesn't change its text. I looked at changing the way it is created to include an iterated name and alter the function to take in the name of the generated menu but that quickly became cumbersome. any help would be appreciated.
The HTML for the fields (the function to generate new fields works fine and just spits out the below HTML again)

                        <button onclick="drop_down_selection()" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Payment type </button>

Progress payment

legal fees

Loss Adjustor fees

                    <input type="text" class="form-control"
                        name="paymentNote" placeholder="Enter source of data"  />

                    <input type="number" step="0.01" class="form-control"
                        name="paymentAmount" placeholder="Amount"  />

the function to change the text of the dropdown menu when clicked
    $('#dropdown-menu li').click( function(e) {
        $('#dropdown_title').html($(this).find('a').html());
    });

Any Help would be great.
edit
I checked out the answer Event binding on dynamically created elements?
This hasn't really helped (more to do with my lack of understanding i suspect)
I have changed the Html to

                            <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Payment type </button>

Progress payment

legal fees

Loss Adjustor fees

                        <input type="text" class="form-control"
                            name="paymentNote" placeholder="Enter source of data"  />

                        <input type="number" step="0.01" class="form-control"
                            name="paymentAmount" placeholder="Amount"  />

I have changed the function to change to text to

Now when I generate new drop down boxes, the first one works as expected (i click the drop down menu > select my option > the text of the dropdown menu changes to what I selected)
but when a new drop down box is created, I click the dropdown box > click the option I want > then the text of the 1st drop down box changes.
Do you have any suggestions?
again, thanks for any help.
Edit 2
This is the code that generates the fields with the drop down box that should change its text when an option is clicked on.
        function add_payment_figure_fields() {

            var objTo = document.getElementById("paymentFigureFields");
            var divtest = document.createElement("div");
            divtest.innerHTML = '

<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Payment type </button>

Progress payment

legal fees

Loss Adjustor fees

<input type="text" class="form-control" name="paymentNote" placeholder="Enter source of data"  />

<input type="number" step="0.01" class="form-control" name="paymentAmount" placeholder="Amount"  />

';
            objTo.appendChild(divtest)

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: InfluxDB restore error : updating metadata on influxd service failed I am having a restore problem with InfluxDB (v 1.7.9). I did a backup on an ubuntu 18.04 machine to be able to export it to another machine with another instance of InfluxDB.
The backup process is OK using the command:
influxd backup -portable -database db_to_backup /mnt/backup
After that, I tried to import the database again with the command:
influxd restore -portable -db db_to_backup -newdb db_test_import /mnt/backup
I launched this on the same machine and also on the other machine which both have ubuntu 18.04. I get this error:
restore: updating metadata on influxd service failed: err = read tcp 127.0.0.1:33328->127.0.0.1:8088: read: connection reset by peer, n = 16
I also launched this restore command on an Ubuntu 16.04 machine and the restore is good.
The "ufw" is disabled and I have exactly the same Influx configuration files on all machines.
UPDATE 1:
It is possible to make a backup from the Ubuntu 18 and to import in Ubuntu 16. It is also possible to make a backup from the Ubuntu 16 and to import to an Ubuntu 18 but when I make a backup from the Ubuntu 18 to an Ubuntu 18 version this is where the error occurs.

A: A mix of your two solutions worked for me:
sudo influxd restore -portable -database importedDBname -newdb DBtoimporttoname /pathtodump


text:
Q: Magento 1.7: product images showing in localhost but not in server After uploading my Magento 1.7 store from localhost to server, some images are not showing in the frontend nor in the backend.
I checked the  property both in localhost and in the server, but they are not the same and I don't understand why, because the code that generates them is the same.
The template I am using is media.phtml under app/design/frontend/default/default/template/design/catalog/product/view/media.phtml , and this is the code generating the image:
    <a href="<?php echo $this->helper('catalog/image')->init($_product, 'image'); ?>" rel="grupo">
        <?php
                $_img = 'helper('catalog/image')->init($_product, 'image')->resize(330).'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" />';
                echo $_helper->productAttribute($_product, $_img, 'image');
        ?>

But I get the following paths (example):

*

*In localhost (works fine): /media/catalog/product/cache/1/image/330x/9df78eab33525d08d6e5fb8d27136e95/p/l/plancha-de-metacrilato-transparente-cristal-transparencia.jpg

*In server (different path without my image): /media/catalog/product/cache/1/image/330x/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/image.jpg
So as you can see, the two paths are not the same.
Why the piece of code $this->helper('catalog/image')->init($_product, 'image') doesn't return the same in localhost than in the server?
Any help is much appreciated.


text:
Q: SharePoint REST POST to upload file produces corrupted or empty file I've got this jquery/REST process that I thought was uploading a PDF file to SPO 2013 Document library, but it's only producing an empty or corrupt.  Anybody know why?
function ProcessUpload(fileInput) {
    var reader = new FileReader();
    reader.onload = function (result) {
        var fileName = '',
         libraryName = '',
         fileData = '';

        var byteArray = new Uint8Array(result.target.result)
        for (var i = 0; i < byteArray.byteLength; i++) {
            fileData += String.fromCharCode(byteArray[i])
        }

        // once we have the file perform the actual upload
        PerformUpload(fileInput.name, fileData);

    };
    reader.readAsArrayBuffer(fileInput);
}

function PerformUpload(fileName, fileData) {
    var url;

    //var path = appWebUrl; var p = path.split('/');var approot = p[0]+"//"+p[2]+"/"+p[3]+"/"+p[4];

        url = 'https://mytenant.sharepoint.com/sites/dev' +
        "/_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/Files/add(url=@TargetFileName,overwrite='false')?"+
          "@TargetSite='" + 'https://mytenant.sharepoint.com/sites/dev'+ "'" +
            "&@TargetLibrary='Documents'" +
            "&@TargetFileName='CV" + fileName + "'";
            alert(url);

    // use the request executor (cross domain library) to perform the upload

$.ajax({
        url: url,
        type: "POST",
        headers: {
            "Accept": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()

        },
        data: JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }),

        contentType: "application/json;odata=verbose",
        binaryStringRequestBody: true,
        body: fileData,
        success:successHandler,
        error: errorHandler
    });
}

A: What I have working is the following:
Method
 POST

URL
http://www.somewhere.com/testsite/_api/web/GetFolderByServerRelativeUrl('/testsite/Shared Documents')/Files/add(url='filename.png',overwrite=true)

Header
Content-Type: application/octet-stream
Accept: application/json;odata=verbose
X-RequestDigest: ...

Body
Raw binary bytes (no JSON)

Then in the JSON response, load the URI from the result
d.ListItemAllFields.__deferred.uri

to get the Item ID and perform regular metadata updates to set title (and content type if needed)
I haven't used the 'binaryStringRequestBody' parameter method, but if you read the section "Working with Files and Folders" here, http://msdn.microsoft.com/en-us/magazine/dn198245.aspx, you will see the method you are using is limited in how large the files can be, where as the POST with a RAW binary is not limited. That might also simply be your problem that your test file is too large for that method.

A: b1c10's answer is probably on the right track, stating that the problem might be on the file input, try to check if you actually upload the correct stream to the REST API. If the stream is already corrupted before the actual upload, it has nothing to do with your POST.
Try to convert your stream back to the original file locally and see what that tells you.
If you (or anyone else, as this question is somewhat older) are by any chance using the ng-file-upload library by danialfarid to select your files, that might be the source of your problem.
I was also getting corrupted files after the upload, and found that the library was adding an extra header and footer to the binary stream.
So before you upload you would have to strip off some bytes at the beginning and end of your stream.
This guy 'Capt. Rochefort' wrote a blogpost with more details and some code to help you strip off the culprit bytes that corrupt your stream.
For me, stripping of the header and footer fixed the problem, as my stream was already faulted before the actual POST.
Hope it helps.

A: Data corrupted ? the problem is on fileInput:
function ProcessUpload(fileInput)
reader.readAsArrayBuffer(fileInput);

Some point to reflect:
But how can you get the fileinput ? if get fileList(files) give error or corrupt, why this parameter is file, only "FILE".
And other, i have used RequestExecutor to upload files and not AJAX with JQUERY.
But anyway, here's a suggestion, not is good practice but a solution:
Page App:
    <input type="file" id="files" />
    <input type="button" id="btnupload" onclick="ProcessUpload()" value="Upload" />

Script App:
'use strict';

var AppUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

function uploadFile(fileName, fileData) {
    // create the deferred object
    var def = new $.Deferred();

    var fileCollectionEndpoint = String.format("{0}/_api/sp.appcontextsite(@target)/web/lists/getByTitle('{1}')/rootfolder/files/add(overwrite=false, url='{2}')?@target='{3}'", AppUrl, "Documents", fileName, hostUrl);
    var scriptbase = hostUrl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", function() {
        var executor = new SP.RequestExecutor(AppUrl);
        // Send the request.
        executor.executeAsync({
            url: fileCollectionEndpoint,
            method: "POST",
            body: fileData,
            binaryStringRequestBody: true,
            headers: {
                "accept": "application/json;odata=verbose"
            },
            success: function(data) {
                def.resolve("File Uploaded!");
            },
            error: function(err) {
                var errJson = $.parseJSON(err.body);
                def.reject(errJson.error.message.value);
            }
        });
    });
    return def.promise();
}

function ProcessUpload() {
    var fileslist = $("#files")[0].files;
    if (fileslist.length > 0) {
        var FileInput = fileslist[0];
        var fileData = '';
        var reader = new FileReader();
        reader.onload = function(result) {
            var byteArray = new Uint8Array(result.target.result)
            for (var i = 0; i < byteArray.byteLength; i++) {
                fileData += String.fromCharCode(byteArray[i])
            }
            // once we have the file perform the actual upload
            var callUpload = uploadFile(FileInput.name, fileData);
            callUpload.done(function(result) {
                alert(result);
            });
            callUpload.fail(function(result) {
                alert(result);
            });

        };
        reader.readAsArrayBuffer(FileInput);
    }
}

function getQueryStringParameter(urlParameterKey) {
    var params = document.URL.split('?')[1].split('&');
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split('=');
        if (singleParam[0] == urlParameterKey) return decodeURIComponent(singleParam[1]);
    }
}

Search Links:
RequestExecutor
Upload File JS


text:
Q: Swift3 Unable to link referencing outlet I'm defining a Custom UIView based on a XIB. Therefor I have copied CustomXIBSwift-master from Github. That works very well. I adapted it briefly for my purposes.
The label (lblTitle) is linked as a referencing outlet to the File's Owner

Now I also want to make a referencing outlet for the second sublabel to File's Owner. However I'm not able to linke this using the dot-line method nor by including the IBOutlet manually.

Based on the CustomXIBSwift-master the XIB is of type UIView. When I specify a custom class (instead of UIView) it crashes.
Part of the SWIFT code:
func loadViewFromNib() {
    let bundle = Bundle(for: type(of: self))
    let nib = UINib(nibName: "SlidingAlertView", bundle: bundle)
    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
    view.frame = bounds
    view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.addSubview(view);
}

How can I make a referencing outlet from this View to the Swift file?

A: I was not able to make a connection between the UILabels and the File's Owner. It appeared that also for the File's Owner thee Custom Class can be specified.


text:
Q: Append rows to a Google Sheet using drive.file scope Is it possible to append rows to an existing Google Sheet using drive.file scope?
The https://www.googleapis.com/auth/drive.file scope is defined as

Per-file access to files created or opened by the app

in the Sheets docs and

Per-file access to files created or opened by the app. File
  authorization is granted on a per-user basis and is revoked when the
  user deauthorizes the app

in the Drive docs.
What does Google mean by "opened" by the app? Open isn't a method in the API.
I've built an app that uses the drive.file scope, and the app authenticates and receives tokens just fine. When I try to append a row to an existing Sheet, the API response is a 404.
If I authenticate the same app using the more broad scope https://www.googleapis.com/auth/spreadsheets, the app has no trouble appending rows to the same Sheet. I don't want to use a more broad scope that requires app verification because the app is an OAuth based plugin, a type of app Google says should not require Sensitive or Restricted scopes or verification. My app also fits the criteria Google recommends for the drive.file scope here.
I have found all these questions that are near duplicates and have no definitive answers:

*

*Request specific file permissions with Google Sheets / Google Drive API

*AuthToken for drive.file scope returning 404

*Getting Google file picker to work with drive.file scope

*How to use the scope https://www.googleapis.com/auth/drive.file correctly

*Is there anyway to get private file of user with drive.file scope

*Is the https://www.googleapis.com/auth/drive.file enough to create and update files or is the scope /drive needed?

A: I concluded no, it is not possible. I designed my app to have a "Create Sheet" button as a workaround, and the drive.file scope works fine to append rows and make other edits to a Sheet that my app creates.


text:
Q: pymongo - use a custom cursor class Is it possible in pymongo to have the collection.find() method return a custom cursor class that inherits from the base, but redefines how iteration occurs?
I'd like to instantiate app specific models from the mongo data within the cursor right at iteration time.  The documents have a type attr that will determine what kind of instance should be created.  I was thinking the next method could look within this data and decide which type to create and return.  Inheriting from the cursor is easy enough, but I can't figure out where to hook this into the find() operation?
EDIT Alternatively...
What I'm doing currently is to use yield to spit out a generator that will classify the object after the fact when the fetch is performed.
@classmethod
def gather(cls,place_id):
    """
    Gather instances of all the shouts for one place
    """
    shouts = cls.collection.find({'place_id':place_id})
    for s in shouts:
        yield Shout.classify(s)

@classmethod
def classify(cls,shout):
    if shout.type == 1:
        return Type1(dict(shout))
    elif shout.type == 2:
        return Type2(dict(shout))
    elif shout.type == 3:
        return Type3(dict(shout))

The problem is that this doesn't preserve the original approach to bracket key access that is encapsulated in the default pymongo Cursor.
If I were to create a wrapper class that will just accept a cursor instance and wrap its methods, which magic methods will I need to override to preserve the iteration behavior of the original cursor?  I'm thinking something like this:
class StuffCursor():

    cursor = False

    def __init__(self,cursor):
        self.cursor = cursor

    def __getattr__(self,attr):
        #This passes off most key-based calls, like bracket-access, to the cursor
        return getattr(self.cursor,attr)

This is just what I could think of, but anything that would stack some additional processing on top of an iterator, and then return the modified iterator, would work.

A: Hate to answer my own question, but this may prove to be of good use to anyone googling.  Here's what I ended up going with:
class ShoutCursor():
    """
    Custom cursor class that will instantiate shout models
    at query time.
    """

    cursor = False

    def __init__(self,cursor):
        self.cursor = cursor
        self.cursor.sort('created',DESCENDING)

    def __iter__(self):
        for ent in self.cursor:
            yield Shout.classify(ent)

    def __len__(self):
        return self.cursor.count()

    def __getitem__(self,index):
        try:
            ents = itertools.islice(self.cursor,index,index+1)
            return [Shout.classify(ent) for ent in ents][0]
        except TypeError:
            return list(Shout.classify(ent) for ent in itertools.islice(self.cursor,index.start,index.stop,index.step))

    def sort(*args,**kwargs):
        self.cursor.sort(*args,**kwargs)

    def __getattr__(self,attr):
        return getattr(self.cursor,attr)

The __iter__ and __getiem__ methods are where the modified, instantiated models are loaded up into generators are returned.  The other methods preserve native cursor action.  Passing a cursor into __init__ sets up the functionality, so special, per iteration logic can be performed as the objects are fetched from mongo.

A: I don't know if "monkey patching" could be used to achieve this, but I ended up doing it as shown below. This allows me to add/override functions on the Cursor class.
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.cursor import Cursor
from pymongo.database import Database

class CustomCursor(Cursor):
    # Customize Cursor here, either by overriding or extending with more methods

class CustomCollection(Collection):
    def __init__(self, database: Database, name: str) -> None:
        super().__init__(database, name)

    # find_one seems to use find, but you may need to override in more places.
    def find(self, *args, **kwargs):
        return CustomCursor(self, *args, **kwargs)

class CustomDatabase(Database):
    def __init__(self, client: MongoClient, name: str) -> None:
        super().__init__(client, name)

    def __getitem__(self, name: str) -> CustomCollection:
        return CustomCollection(self, name)

# usage:
client = MongoClient('127.0.0.1', 27017)
database = CustomDatabase(client, 'mydb')

I defined a Serializable base class, with a from_dict and to_dict method. This allowed me to define a to_list() on the CustomCursor so that I could query and get class-instances back:
result: List[School] = database.schools.find().to_list(School)


text:
Q: Time is not showing right in Excel when formulated correctly This is my formula.
=XLOOKUP(A2,Ticket_Import!B:B,Ticket_Import!T:T/86400,"Empty")

When I run this without the division it shows the actual number in cell Ticket_Import!T:T, which is 172855.
Now if we use the basic math of 172855/86400 should come out to be 2.044... which would be 2 days and 44 minutes?
But when I format it to show time, it shows it as 0:00:55.
When I try to put the cell as time it shows up as 00:00:00, or Jan-00
Now, I am pretty good at running excel scripts but I must be overthinking this.
Can someone please help me figure this out?
My cells are formatted for hh:mm:ss btw.


text:
Q: Python - How do I differentiate between two list elements that point to the same object? I have a Ring structure implemented as follows (based on a cookbook recipe I found):
class Ring(list):

    def turn(self):
        last = self.pop(0)
        self.append(last)

    def setTop(self, objectReference):
        if objectReference not in self:
            raise ValueError, "object is not in ring"

        while self[0] is not objectReference:
            self.turn()

Say I do the following:
x = Ring([1,2,3,4,4])
x.setTop(4)

My code will always set the first 4 (currently x[3]) to x[0]. It seems (via object identity and hash id testing between x[3] and x[4]) that Python is reusing the 4 object.
How do I tell Python that I really want the second 4 (currently x[4]) to be at the top?
Apologies for the basic question ... one of the downfalls of being a self-taught beginner.
Thanks,
Mike
===EDIT===
For what it's worth, I dropped the setTop method from the class. I had added it to the standard recipe thinking "hey, this would be neat and might be useful." As the answers (esp. "what's the difference", which is spot on) and my own experience using the structure show, it's a crappy method that doesn't support any of my use cases.
In other words, adding something because I could instead of fulfilling a need = fail.

A: From Learning Python, 4th edition -- Chapter 6:

At least conceptually, each time you generate a new value in your script by running an
  expression, Python creates a new object (i.e., a chunk of memory) to represent that
  value. Internally, as an optimization, Python caches and reuses certain kinds of un-
  changeable objects, such as small integers and strings (each 0 is not really a new piece
  of memory—more on this caching behavior later). But, from a logical perspective, it
  works as though each expression's result value is a distinct object and each object is a
  distinct piece of memory.

The question is..
if x[3] is x[4]:
    print "What's the difference?"

A: If you know you want the second, then do
x = Ring([1,2,3,4,4])
x.setTop(4)
x.turn()
x.setTop(4)

You can enhance setTop() to take an additional parameter and do it inside.

A: Cpython has an "integer cache" for smallish integers, so that values from -5 up to 255 (may vary by version or Python implentation) reuse the same object for a given value. That is, all 4s are the same int object with a value of 4. This is done to reduce the necessity for object creation.
There are a few ways to work around this.

*

*You can use long integers (e.g., write 4L instead of 4). Python does not use the cache for long integers. (You could also use floats, as these are likewise not cached.) If you do a lot of math with the numbers, however, this could incur some performance penalty.

*You can wrap each item in a list or tuple (reasonably convenient because there is simple syntax for this, though it's more syntax than long integers or floats).

*You can create your own object to wrap the integer. The object would have all the same methods as an integer (so it works like an integer in math, comparisons, printing, etc.) but each instance would be unique.

I personally like using long ints in this case. You can easily convert the integers to longs in the constructor, and in any method that adds an item.

A: It sounds like you always want to turn at least once, right? If so, re-write your setTop method like so:
def setTop(self, objectReference):
    if objectReference not in self:
        raise ValueError, "object is not in ring"

    self.turn()
    while self[0] is not objectReference:
        self.turn()

Then it cycles between the expected states:
>>> x = Ring([1,2,3,4,4])
>>> x
[1, 2, 3, 4, 4]
>>> x.setTop(4)
>>> x
[4, 4, 1, 2, 3]
>>> x.setTop(4)
>>> x
[4, 1, 2, 3, 4]
>>> x.setTop(4)
>>> x
[4, 4, 1, 2, 3]

A: I also don't know enough to be sure, but I guess numbers, even though beeing objects, are the same objects when used in different points of your code.
Why do I think so? Look:
>>> type(2)
<type 'int'>
>>> type(lambda x:x)
<type 'function'>
>>> 2 is 2
True
>>> (lambda x: x) is (lambda x: x)
False

2 objects are not identical when created twice. But numbers are not created by you, they are already there. And it makes no sense to give one 4 a different object from another 4. At least I don't see one.

A: For small numbers, python will have a cache of objects premade to avoid the costs of making new objects. They will have the same object identity. Java does this as well. You need a way to make it avoid doing this.

A: Python reuses small integers and short strings. As far as I know, there's no way around this - you'll have to get along with this and the fact that setTop only rotates until the first match. I suppose you could add an optinal parameter, n = 1, and turn until the n th match. But that's kinda beside the point, isn't it?
Unrelatedly, consider this:
>>> class Point(object):
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __eq__(self, other):
...         return (self.x == other.x and self.y == other.y)
...
>>> a_ring = Ring(Point(1, 2), Point(15, -9), Point(0, 0))
>>> a_ring.seTop(Point(15, -9))
Traceback ...
...
ValueError: object not in ring

Not how it is supposed to work, is it? You should use while self[0] != objectReference (which is btw a misleading name) to avoid this.


text:
Q: RetryLogic using AOP is not working for MongoItemWritrer , but the same is working for my custom Readers and writers RetryLogic using AOP is not working for MongoItemWritrer , but the same is working for my custom Readers and writers
Is there anything that I'm doing wrong here.
Below is the code snipopet.

<bean id="retryAdvice"
class="org.springframework.retry.interceptor.RetryOperationsInterceptor">
    <property name="retryOperations" ref="taskBatchRetryTemplate" />
</bean>
<bean id="taskBatchRetryTemplate" class="org.springframework.retry.support.RetryTemplate">
    <property name="retryPolicy" ref="genericRetryPolicy" />
    <property name="backOffPolicy">
        <bean class="org.springframework.retry.backoff.ExponentialBackOffPolicy">
            <property name="initialInterval" value="${mongoloader.backOffPeriod.initialInterval}"/>
            <property name="maxInterval" value="${mongoloader.backOffPeriod.maxInterval}"/>
            <property name="multiplier" value="${mongoloader.backOffPeriod.multiplier}"/>
        </bean>
    </property>
    <property name="listeners">
        <bean class="com.company.ens.myload.job.StepRetryListener"/>
    </property>
</bean>

<bean id="genericRetryPolicy" class="org.springframework.retry.policy.SimpleRetryPolicy"  >
    <constructor-arg index="0" value="${mongoloader.retry.limit}"/>
    <constructor-arg index="1">
        <map>
            <entry key="org.springframework.data.mongodb.CannotGetMongoDbConnectionException" value="true"/>
            <entry key="org.springframework.jdbc.CannotGetJdbcConnectionException" value="true"/>
            <!--  Just included the below exception for testing purpose, needs to be removed -->
            <entry key="java.io.FileNotFoundException" value="true"/>
            <entry key="org.springframework.dao.DuplicateKeyException" value="true"/>
        </map>
    </constructor-arg>
</bean>

//including only my step configution here
<batch:step id="Step4a-MainFlow_TranslateRawFedObjectsToFilingModel"
                allow-start-if-complete="false">
                <batch:tasklet>
                    <batch:chunk reader="rawFedObjectMongoReader"
                        processor="translatingProcessor" writer="SctModelMongoWriter"
                        commit-interval="100"/>
                </batch:tasklet>
                <batch:listeners>
                    <batch:listener ref="step4aListener"/>
                </batch:listeners>
</batch:step>

Did not find any posts related to my question. Any help would be appreciated.


text:
Q: How to reference scala Enumeration from other package I'm having trouble understanding why I can't reference a scala enum type.
The problem is that sometimes I can reference enums:
enum(UserStatus)

and sometimes it complains about not being able to find the enum
not found: type UserStatus

How come I sometimes cannot reference the Enumeration class?
The generated source for the enum seems to be ok, and it works great with another enum that I have which lives in the same place, same usage...
Any Suggestions?
More info
The generated source for the enum is:
public final class models.UserStatus extends java.lang.Object{
    public static final scala.Enumeration$Value Busy();
    public static final scala.Enumeration$Value Free();
    public static final scala.Enumeration$ValueSet$ ValueSet();
    public static final scala.Enumeration$Value withName(java.lang.String);
    public static final scala.Enumeration$Value apply(int);
    public static final int maxId();
    public static final scala.Enumeration$ValueSet values();
    public static final java.lang.String toString();
}

I'm trying to implement an enum mapper for play framework 2.0
def enumFormat[E <: Enumeration](enum: E): Formatter[E#Value] = new Formatter[E#Value] {
  def bind(key: String, data: Map[String, String]) = {
    Formats.stringFormat.bind(key, data).right.flatMap { s =>
      scala.util.control.Exception.allCatch[E#Value]
        .either(enum.withName(s))
        .left.map(e => Seq(FormError(key, "error.enum", Nil)))
    }
  }
  def unbind(key: String, value: E#Value) = Map(key -> value.toString)
}

And this method that calls the mapper
def enum[E <: Enumeration](enum: E): Mapping[E#Value] = of(enumFormat(enum))

This means that the mapper automatically converts between a enum when using the form binding
Pseudo code of usage.
package models {
  object UserStatus extends Enumeration {
    val Free = Value("free")
    val Busy = Value("busy")
  }

  case class User(
    status: UserStatus.Value = UserStatus.Free
  )
}

package controllers {
  imports models._
  val userForm = Form(
    mapping(
      "status" -> enum(UserStatus)
    )(User.apply)(User.unapply)
  )
}

A: Your problem may come from the fact that in Scala you can use the same identifier for a type and for a value.
When you write the following:
object Foo extends Enumeration {
  val A, B, C = Value
}

You define a Foo object, but you don't define a Foo type. If you come from a Java background you may not find this behavior intuitive.
So what's the type of the Foo enumeration values? Their type is Foo.Value (that's called a path dependent type).
If you want to define a Foo type corresponding to the enumeration values type, you can alias the Foo.Value type:
object Foo extends Enumeration {
  type Foo = Value    // Type alias
  val A, B, C = Value
}

Now you can refer to the enumeration type by writing Foo.Foo. You can import the fields of the Foo object to reduce the syntactic overhead:
import Foo._
def bar(foo: Foo): String = foo match {
  case A => "value A"
  case B => "value B"
  case C => "value C"
}

In the above code, the first line refers to the Foo object, and the second line refers to the Foo type.


text:
Q: What is the right way to pass parameters to a Kohana 3.3 controller called through HMVC? I am trying to use Kohana 3.3 HMVC approach. I have created a view and a controller for generating a segment of a page (meant to be integrated into the actual web page by another controller and to be never accessed through HTTP from outside a controller) filled with data records retrieved through ORM. What I need is to pass some data (records selection criteria) from the top controller through the middle controller to the ORM model. Altering GET/POST data as suggested here seems wacky (as it is going to alter the whole application state rather than of the target controller as far as I understand) (but perhaps it is considered okay in the PHP world, I don't know (I am coming from the strict C++/C#/Java/Scala world), let me know if so). Is there a better way?

A: The HMVC approach works just like a normal request except that it has its own instance of the request class. From the HMVC sub request you can access the parent request object by loading the initial request.
 $parent_request_query = $this->request->initial()->query();

You can also access the current request.
 $current_request_query = $this->request->current()->query();

You could also just pass parameters.
 $params = array(
      'passing' => 'data'
 );
 echo Request::factory('controller/action')->query($params)->execute()->body()


text:
Q: Function to insert integers in an array in a sorted way So assuming that i start with an array [0,0,0,0]. And in this array i will be adding exactly 4 values. Lets say 2,1,3,4. So my main function will look like:
 public static void main(String[] args) {
        int[] arr = new int[4];
        insertSortedInArr(2,arr);
        insertSortedInArr(1,arr);
        insertSortedInArr(3,arr);
        insertSortedInArr(4,arr);
    }

I tried an implementation of a method insertSortedInArr() which i also found online, but it is not quite working. I tried to find what goes wrong with it but i couldn't manage to find the bug. This is the method:
 public static void insertSortedInArr(int val,int[] arr){
        int i;
        for(i=0;i<arr.length-1;i++){
            if (arr[i] == 0){
                arr[i] = val;
                return;
            }
            if (val < arr[i])
                // value must be inserted in arr[i]
                break;
        }
        // move everything right
        for(int k=i; k<arr.length-1; k++){
                arr[k+1]=arr[k];
        }
        arr[i]=val;
    }

My output of this method gives me: [1, 2, 2, 4].
If you could find what's going wrong or have a better implementation of this method it would be appreciated. Thanks.

A: The problem is in the "move everything right" part.
You are iterating from left to right, but this will overwrite the next element.
Instead, iterate from right to left:
for (int k=arr.length-1; k > i; k--){
    arr[k]=arr[k - 1];
}

A: Since you know already the values, I think we don't even need a loop here. We can just do the following :
public static void insertSorted(int val, int arr[]) {
    if(arr[val - 1] == 0) {
        arr[val-1] = val;
    }
}

or better, just insert the values to array in random order, and use
Arrays.sort(arr);

Hope that it helps.

A: There can be a minor improvement related to detection of the first free element where available values should be moved:
public static void insertSortedInArr(int val, int[] arr) {
    int i;
    for (i = 0; i < arr.length; i++) {
        if (arr[i] == 0) {
            break;
        } else if (val < arr[i]) {
            int j;
            for (j = i + 1; arr[j] != 0 && j < arr.length; j++); // find first 0
            for (int k = j; k > i; k--) { // shift elements right to the first free cell
                arr[k] = arr[k - 1];
            }
            break;
        }
    }
    arr[i] = val;
    System.out.println(Arrays.toString(arr));
}

Test:
int[] arr = new int[4];
insertSortedInArr(4,arr);
insertSortedInArr(2,arr);
insertSortedInArr(1,arr);
insertSortedInArr(3,arr);

Output:
[4, 0, 0, 0]
[2, 4, 0, 0]
[1, 2, 4, 0]
[1, 2, 3, 4]


text:
Q: mysql procedure error occurrence 'Subquery returns more than 1 row' select query
    select concat('call db_name.tmp_proc(', '\'' , TABLE_SCHEMA, '\'' ',' , '\'' , TABLE_NAME  , '\'' ',30,1' ');' )
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA='logdb';

    result

    call db_name.tmp_proc('logdb','monthly_test',30,1);
    call db_name.tmp_proc('logdb','monthly_test1',30,1);
    call db_name.tmp_proc('logdb','monthly_test2',30,1);
    call db_name.tmp_proc('logdb','monthly_test3',30,1);
    call db_name.tmp_proc('logdb','monthly_test4',30,1);

    5 rows in set (0.00 sec)

Create this query as a procedure
DROP PROCEDURE test$$
CREATE PROCEDURE test() BEGIN
DECLARE result INT default 0;
SET @result = (select concat('call db_name.tmp_proc(', '\'' , TABLE_SCHEMA, '\'' ',' , '\'' , TABLE_NAME  , '\'' ',30,1' ');' )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='logdb');
PREPARE stmt1 FROM @result;
EXECUTE stmt1;
END$$

call test$$

ERROR 1242 (21000): Subquery returns more than 1 row

ERROR 1242 (21000): Subquery returns more than 1 row
This error has occurred and cannot be executed.
Is there a way to eliminate errors and execute all queries of results?

============
============
It was revised as follows with reference to the advice and performed well without errors.
Thank you.

delimiter $$
DROP PROCEDURE test$$
CREATE PROCEDURE test() BEGIN
-- DECLARE result text(65535) ;
-- DECLARE cnt int default 0;
DECLARE i int default 0;

SET @cnt = (select count(*) -1 as cnt FROM INFORMATION_SCHEMA.TABLES  WHERE TABLE_SCHEMA='logdb' AND CREATE_OPTIONS ='partitioned' ) ;

WHILE i <= @cnt DO

SET @result = (select concat('call db_name.tmp_proc(', '\'' , TABLE_SCHEMA, '\'' ',' , '\'' , TABLE_NAME  , '\'' ',30,1' ')' )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA='logdb' limit i, 1) ;
PREPARE stmt1 FROM @result;
EXECUTE stmt1;

SET i = i + 1;
END WHILE;

END$$

call test$$


text:
Q: Calling Long Press Button action only once not rapid fire Here is my code for a long press. When I long-press the button, it keeps getting called. How do I set it up so it only gets called once and then gets called again only once the finger is release and the long press is started again?
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector (tap))
    let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(long))
    tapGesture.numberOfTapsRequired = 1

    self.reminderButton.addGestureRecognizer(tapGesture)
    self.reminderButton.addGestureRecognizer(longGesture)

A: use this code in your selector
@objc func gestureAction(gesture: UIGestureRecognizer) {
if let longPress = gesture as? UILongPressGestureRecognizer {
    if longPress.state == UIGestureRecognizer.State.began {

    } else {

    }
}


text:
Q: Determine the kernel of a linear map $f:U \to V$ Let $U=<\begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & 0\end{pmatrix}, \begin{pmatrix}0 & 0 & -1 \\ 0 & 1 & 0\end{pmatrix}, \begin{pmatrix}2 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix}>$ and $V= <\begin{pmatrix}2& 0 & 0 \\ 0 & 2 & 0 \end{pmatrix}, \begin{pmatrix} 0 & 1 & 1 \\ 0 & 1 & 1\end{pmatrix}$>.
Let $f:U \to V$ such that
$$f \begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & 0\end{pmatrix}= \begin{pmatrix} 2 & 1 & 1 \\ 0 & 3 & 1\end{pmatrix}$$
$$f \begin{pmatrix}0 & 0 & -1 \\ 0 & 1 & 0\end{pmatrix} = \begin{pmatrix} 4 & 2 & 2 \\ 0 & 6 & 2\end{pmatrix}$$
$$f \begin{pmatrix}2 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix} = \begin{pmatrix} 1 & 1/2 & 1/2 \\ 0 & 3/2 & 1/2\end{pmatrix}.$$
I have to determine $ker(f)$ and $Im(f)$. Normally, if we work with $R^n$ and the standard basis, I've no problems, but this setting with matrices and non-common vector spaces confuses me: please, could you show me how to work out this problem?
Thank you very much in advance.

A: Let's denote the generators of $U$: $u_1$, $u_2$ and $u_3$ (in your very order) and those of $V$: $v_1$ and $v_2$. Note $f(u_1)=v_1+v_2$ and  $f(u_2)$ and $f(u_3)$ are colinear with $f(u_1)$. With this information you can deduce $\operatorname{im} f$ and you can write the matrix of $f$ relative to the bases $(u_1,u_2,u_3)$ and $(v_1,v_2)$.
Indeed \begin{align*}f(\lambda_1u_1+\lambda_2u_2+\lambda_3u_3)&=\lambda_1f(u_1)+\lambda_2f(u_2)+\lambda_3f(u_3)\\
&=\lambda_1(v_1+v_2)+2\lambda_2(v_1+v_2)+\frac12\lambda_3(v_1+v_2)\\
&=\Bigl(\lambda_1+2\lambda_2+\frac12\lambda_3\Bigr)(v_1+v_2),\end{align*}
which shows  the image is contained in the subspace generated by $v_1+v_2$. Conversely, $v_1+v_2$ is attained by $u_1$. So $\operatorname{im} f =\langle v_1+v_2\rangle$.
The above equation shows $\lambda_1u_1+\lambda_2u_2+\lambda_3u_3 \in \ker f$ iff $\,\lambda_1+2\lambda_2+\frac12\lambda_3=0$. It will be a subspace of dimension $2$. You may choose e.g. $-u_1+2u_3$ and $2u_1-u_2$ which are clearly independent, so that
$$\ker f =\bigg\langle\begin{pmatrix}3&0&1\\ 0&2&0\end{pmatrix},\begin{pmatrix}2&0&3\\ 0&1&0\end{pmatrix}\bigg\rangle. $$

A: Since $u_i$ generate $U$ it follows every element of $U$ can be written in the form $\sum c_iu_i$. As Bernard noted, $f$ acts such that $u_1\mapsto v_1+v_2,u_2\mapsto2(v_1+v_2),u_3\mapsto\frac12(v_1+v_2)$. It follows that $\operatorname{im}(f)$ is generated by $v_1+v_2$ alone.
Now, since we know the action of $f$ on these generators of $U$ in terms of the generators $v_i$ of $V$ we can represent $f$ as a matrix: $$\begin{bmatrix}1&2&1/2\\1&2&1/2\end{bmatrix}$$
Just find two independent $(x,y,z)$ such that $x+2y+\frac12z=0$; the easiest trivial examples are $(0,1/2,-2)$ and $(-2,1,0)$, which therefore span $\ker(f)$.


text:
Q: How to dispatching an email or a message box when something happend on a folder to another local machine? I have a Windows Server which some local users put files that I need to manage quickly, however, I can't see my server every hour. There is a way to Windows Server itselfs warns me that I need to take care of new files of the shared folder? Someone knows if there are some free aplication that does it??

A: Found some options on another post:

*

*Directory-Monitor

*Filehamster

*Foldertrack


text:
Q: Random Equation Test. Correct or Wrong answer I have been trying to write a test which involves random numbers to make equations for the user to answer. I have wrote it so that two int are assigned to a random number and the console writes the equation. I have used an if statement for the program to dictate whether the users answer is correct or incorrect. However it is always either correct or incorrect depending on the code i write. I can't write it so that the program decides the answer.
        int iE3 = rnd.Next(1, 11);
        int iE13 = rnd.Next(1, 11);
        int iA3 = iE3 * iE13;
        int answer3 = iE3 * iE13;
        Console.WriteLine("The third equation is {0} * {1}", iE3, iE13);
        Console.ReadLine();

        if ( answer3 == iA3)
        {
            Console.WriteLine("Well done you got it right!");
        }
        else
        {
            Console.WriteLine("Unfortunately you got it incorrect.");
        }

A: You are ignoring the users input, you need to assign the result of the ReadLine:
int answer3 = Int32.Parse(Console.ReadLine());

Of course with error handling incase they don't enter a number etc...


text:
Q: Method reference and boolean So I have been having a go with using the method reference in Java 8 (Object::Method). What I am attempting to do, which I have done before but have forgotten (last time I used this method reference was about 4 months ago), is find the amount of players that != online using the Method Reference.
public static Set<Friend> getOnlineFriends(UUID playerUUID)
{
    Set<Friend> friends = new HashSet<>(Arrays.asList(ZMFriends.getFriends(playerUUID)));

    return friends.stream().filter(Friend::isOnline).collect(Collectors.toSet());
}

public static Set<Friend> getOfflineFriends(UUID playerUUID)
{
    Set<Friend> friends = new HashSet<>(Arrays.asList(ZMFriends.getFriends(playerUUID)));

    return friends.stream().filter(Friend::isOnline).collect(Collectors.toSet());

As you can see I managed to so it when the player (friend) is online but I cannot figure out how to filter though the Set and collect the offline players. I'm missing something obvious, but what is it?!?!
Thanks,
Duke.

A: In you code
public static Set<Friend> getOnlineFriends(UUID playerUUID)
{
    Set<Friend> friends = new HashSet<>(Arrays.asList(ZMFriends.getFriends(playerUUID)));

    return friends.stream().filter(Friend::isOnline).collect(Collectors.toSet());
}

you are creating a List view to the array returned by ZMFriends.getFriends(playerUUID), copy its contents to a HashSet, just to call stream() on it.
That's a waste of resources, as the source type is irrelevant to the subsequent stream operation. You don't need to have a Set source to get a Set result. So you can implement your operation simply as
public static Set<Friend> getOnlineFriends(UUID playerUUID)
{
    return Arrays.stream(ZMFriends.getFriends(playerUUID))
                 .filter(Friend::isOnline).collect(Collectors.toSet());
}

Further, you should consider whether you really need both, getOnlineFriends and getOfflineFriends in your actual implementation. Creating utility methods in advance, just because you might need them, rarely pays off. See also "You aren't gonna need it".
But if you really need both operations, it's still an unnecessary code duplication. Just consider:
public static Set<Friend> getFriends(UUID playerUUID, boolean online)
{
    return Arrays.stream(ZMFriends.getFriends(playerUUID))
                 .filter(f -> f.isOnline()==online).collect(Collectors.toSet());
}

solving both tasks. It still wastes resource, if the application really needs both Sets, as the application still has to perform the same operation twice to get both Sets. Consider:
public static Map<Boolean,Set<Friend>> getOnlineFriends(UUID playerUUID)
{
    return Arrays.stream(ZMFriends.getFriends(playerUUID))
                 .collect(Collectors.partitioningBy(Friend::isOnline, Collectors.toSet()));
}

This provides you both Sets at once, the online friends being associated to true, the offline friends being associated to false.

A: There are 2 ways I can think of:
friends.stream().filter(i -> !i.isOnline()).collect(Collectors.toSet());
But I guess that's not what you want, since it's not using a method reference. So maybe something like this:
public static <T> Predicate<T> negation(Predicate<T> predicate) {
    return predicate.negate();
}
...
friends.stream().filter(negation(Friend::isOnline)).collect(Collectors.toSet());


text:
Q: Understanding beams in pst-optexp I'm apparently missing something fundamental in how beams interact with interfaces. I have prepared three simple examples, with the hopes that someone can explain to me why certain things happen.
Example 1
This much makes sense. I have an incoming beam at normal incidence on a mirror, and the drawbeam statement is specified in the form (node){component}(node). The beam reflects back, just like you would expect it to.
\documentclass[pstricks]{standalone}
\usepackage{pst-optexp}
\begin{document}
\begin{pspicture}(-1.5,-1.5)(1.5,1.5)
    \pnode(-1,0){in}
    \pnode(0,0){mir}
    \pnode(1,0){out}
    \pnode(-1,-1){low}
    \pnode(-1,1){high}
    \mirror(low)(mir)(high)
    \drawbeam[linecolor=red,arrows=->](in){1}(in)
    % \drawbeam[linecolor=blue,arrows=->](low){1}(high)
\end{pspicture}
\end{document}

If I replace the drawbeam statement with (in){1}(out) the beam stops at the mirror (doesn't reflect and doesn't pass through). This makes sense, a beam shouldn't pass through a mirror that isn't transmissive (ideally, of course).

Example 2
This case is pretty similar to the last one, the only difference is that the incoming beam is at an angle. Again, if the drawbeam statement is (low)(mir)(high) the beam stops at the mirror, but reflects if the statement is (low){1}(high).
\documentclass[pstricks]{standalone}
\usepackage{pst-optexp}
\begin{document}
\begin{pspicture}(-1.5,-1.5)(1.5,1.5)
    \pnode(-1,0){in}
    \pnode(0,0){mir}
    \pnode(1,0){out}
    \pnode(-1,-1){low}
    \pnode(-1,1){high}
    \mirror(low)(mir)(high)
    % \drawbeam[linecolor=red,arrows=->](in){1}(in)
    \drawbeam[linecolor=blue,arrows=->](low){1}(high)
\end{pspicture}
\end{document}

Example 3
Here's something that just baffles me. Individually, the beams in examples 1 and 2 draw just fine when specified as (node){component}(node). When I draw them together, however, only the red arrow shows up (the picture is identical to the first picture in example 1). Why can't I have both beams drawn as specified below?
\documentclass[pstricks]{standalone}
\usepackage{pst-optexp}
\begin{document}
\begin{pspicture}(-1.5,-1.5)(1.5,1.5)
    \pnode(-1,0){in}
    \pnode(0,0){mir}
    \pnode(1,0){out}
    \pnode(-1,-1){low}
    \pnode(-1,1){high}
    \mirror(low)(mir)(high)
    \drawbeam[linecolor=red,arrows=->](in){1}(in)
    \drawbeam[linecolor=blue,arrows=->](low){1}(high)
\end{pspicture}
\end{document}

Questions

*

*Why can't I specify the beam path as (node)(node)(node) rather than (node){component}(node)?

*Why can't I draw both of the beams in example 3?

My Setup

*

*OS X Yosemite

*Latest version of MacTex (updated a week ago)

*Edited in MacVim using latex-suite

*Compiled using xelatex -interaction=nonstopmode

A: What you observed with your two questions can both be classified as bugs:

*

*Running your third example which xelatex gives a ghostscript error, which is why you don't see the second beam. Using latex + dvips + ps2pdf works fine.
I don't use xelatex, and I don't know all the internal details about how it deals with Postscript code. There is one special hack in \drawbeam, which could be the culprit here. Don't know if I'll be able to fix it.

*In general it should be possible to use three different nodes like with
\drawbeam(low)(mir)(high)

This should draw two lines, but actually draws only a single one from (low) to (mir). So, this is also a bug. However, to connect only nodes you don't need \drawbeam, but can likewise use \psline.
In general, the purpose of having components and connect them with \drawbeam is to have the reflection and refraction calculated automatically. By giving only a component name/number to the macro it can for itself select which interface to use, what its properties are, and draw the beam accordingly.
Consider using a semi-transparent mirror instead of a simple one:
\documentclass[pstricks]{standalone}
\usepackage{pst-optexp}
\begin{document}
\begin{pspicture}(-1.5,-1.5)(1.5,1.5)
    \pnode(-1,0){in}
    \pnode(0,0){mir}
    \pnode(1,0){out}
    \pnode(-1,-1){low}
    \pnode(-1,1){high}
    \mirror[mirrortype=semitrans, mirrordepth=-0.2](low)(mir)(high)
    \drawbeam[linecolor=blue,arrows=->](low){1}(high)
    \psdots(low)(mir)(high)
\end{pspicture}
\end{document}

You see, that the first node, (low) gives the starting point, and the center node of the mirror gives the direction of the starting beam. The rest is given  by the laws of refraction and reflection. You'll also notice, that the beam doesn't end at the (high) node, because that doesn't fit to the traced beam path.


text:
Q: UITextField in a storyboard static UITableViewCell is not accepting input I have created a static tableview cell containing a UITextField using storyboards in Xcode 4.5.2 (this also happens in 4.6 DP1).  Tapping on the UITextField brings up the keyboard, but the text field does not accept input from the keyboard.  If I add text to the field programatically, the text will appear, but I am still not able to add text via the keyboard (or via the main keyboard when using the simulator).  The only key that does work on the keyboard is the "Delete" key.  Has anyone experienced this and know what the cause may be?

A: Does the textField has IBOutlet property, and also you connect IBOutlet in storyboard?


text:
Q: script to split a string google sheet I need help please here with a script for google sheet. I got a zapier which take some information from a system and paste it on my google, The problem is that the system send the info as a string with comas like that one : andres,locuara@gmail.com,Albania,creation loca,holatu@gmail.com
So I was using the formula SPLIT on google sheet and that formula works fine but the problem is that everytime when zapier send the information to the sheet I dont know what happened but zapier delete the formular from the sheet so I need to go manualy and do the formula again to to split the info and put where it needs to be. So I would like to make an script which cannot be deleted and do all the job as It needs to be on the whole sheet.
I got that structure like this:

and I would like that the script does the job in every cell automatically in the whole sheet. Please is there someone who can help me out with that . ? Thanks a lot =)

A: This should do the trick.
It will add an item to your command tab bar in Google Sheet when you open the Sheet. Then you just press run and wait.
function onOpen() {
  // Try New Google Sheets method
  try{
    var ui = SpreadsheetApp.getUi();
    ui.createMenu('Split cells')
    .addItem('Run', 'main')
    .addToUi();
  }

  // Log the error
  catch (e){Logger.log(e)}

}

function main() {

  var settings = {
    dataCol: 3,
    nameCol: 4,
    /*
    mailCol: 5,
    teamCol: 6,
    teamNameCol: 7,
    contactCol: 8,
    spreadsheet: {}
    */

  }

  settings.dataCol--;
  settings.nameCol--;
  /*
  settings.mailCol--;
  settings.teamCol--;
  settings.teamNameCol--;
  settings.contactCol--;
  */

  settings.spreadsheet = SpreadsheetApp.getActiveSheet().getDataRange().getValues();

  for (var i = 1; i < settings.spreadsheet.length; i++) {
    var arr = settings.spreadsheet[i][settings.dataCol].split(",");
    for (var j = 0; j < arr.length; i++) {
      settings.spreadsheet[i][settings.nameCol + j] = arr[j] ;
    }

  }

  SpreadsheetApp.getActiveSheet().getDataRange().setValues(settings.spreadsheet);

}

A: Try arrayformula:
D2:
=ARRAYFORMULA(SPLIT(C2:INDEX(C:C,COUNTA(C:C)),","))


text:
Q: Meteor: Select option from dynamically filtered dropdown Similar scenario as Meteor dynamically filter dropdown when another dropdown is selected : I'm able to populate the items in select #2 depending on select #1.
But I cannot programmatically set a specific option of select #2 to selected - at least not right after the change event of select #1 - because the items are not yet populated.
.html:

  <title>Dropdown</title>

  {{> hello}}

<template name="hello">

    {{#each products}}

{{name}}

    {{/each}}

  <select id="main-cat">
    <option>Select One</option>
    {{#each categories}}
      <option value="{{name}}">{{name}}</option>
    {{/each}}
  </select>

  <select id="sub-cat">
    <option>Select One</option>
    {{#each subCategories}}
      <option value="{{name}}">{{name}}</option>
    {{/each}}
  </select>

</template>

.js:
if (Meteor.isClient) {

  Template.hello.helpers({
    products: function() {
      return Products.find();
    },

    categories: function() {
      return Categories.find();
    },

    subCategories: function() {
      return Session.get("selectedMainCat") && Categories.findOne({ name: Session.get("selectedMainCat") }).subCategories;
    }
  });

  Template.hello.events({
    "click li": function () {
      $("#main-cat").val(this.category);
      Session.set("selectedMainCat", $("#main-cat").val()); // now #sub-cat should be filled because of subCategories helper above
      $("#sub-cat").val(this.subCategory); // this should select the appropriate subcat, but doesn't. apparently it's slightly too early...
    },

    "change #main-cat": function() {
      Session.set("selectedMainCat", $("#main-cat").val());
    }

  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    Categories.remove({});
    Categories.insert(
      {
        name: "MainCategory1",
        subCategories: [
          {name: "SubCategory1.1"},
          {name: "SubCategory1.2"}
        ]
      }
    );
    Categories.insert(
      {
        name: "MainCategory2",
        subCategories: [
          {name: "SubCategory2.1"},
          {name: "SubCategory2.2"}
        ]
      }
    );

    Products.remove({});
    Products.insert({
      name: "myProduct1",
      category: "MainCategory2",
      subCategory: "SubCategory2.2"
    });
    Products.insert({
      name: "myProduct2",
      category: "MainCategory1",
      subCategory: "SubCategory1.2"
    });

  });
}

collection.js:
Products = new Mongo.Collection('products');
Categories = new Mongo.Collection('categories');


text:
Q: Teradata DBS state is 7: System is operational without PEs - Sessions are not allowed I have installed Vmware teradata player TDExpress14.10_Sles11_40GB on Ubuntu.
I am getting "DBS state is 7: System is operational without PEs - Sessions are not allowed" when using "pdestate -a";
I found some solutions related with vproc manager like;
http://teradata-suresh.blogspot.com/2011/02/when-you-may-get-10065-wsa-e-host.html
But they are windows based. I don't know how to start vprocmanager in linux wm.

A: the vprocmanager is a windows application from a time where the TD Express was installed natively on your Windows. - looooong time ago.
As of now you have to use the same tools like Admins in the productive environment. You should either try /etc/init.d/tpa [stop|start] or /usr/pde/bin/tpareset.
Because there will be a reason why the RDBMS doesn't startup properly it's worth to check the log file /var/log/messages.
You can check the syntax and the other tools in the documentation in the book "Utilities" (1102).
Horst


text:
Q: Casperjs and Failed to save screenshot with captureSelector I have such code :
  casper.thenOpen(url, function() {
    this.echo('Opening at ' + width);
    //give some time for the page to load
    casper.waitFor(function check() {
      return this.evaluate(function() {
        return document.querySelectorAll('#browse-packshots').length > 0;
      });
    }, function then() {
      //set the viewport to the desired height and width
      this.viewport(width, height);
      //Set up two vars, one for the fullpage save, one for the actual viewport save
      var FPfilename = saveDir + '/fullpage-' + width + ".png",
          ACfilename = saveDir + '/' + width + '-' + height + ".png";

      //Capture selector captures the whole body
      this.captureSelector(FPfilename, 'body');
      //capture snaps a defined selection of the page
      this.capture(ACfilename,{top: 0,left: 0,width: width, height: height});
      this.echo('snapshot taken');
    },function timeout() {
      this.echo("Too long . No screenshot taken").exit();
    },10000);
  })

Casper version is 1.0.4 on Mac. When I want to use captureSelector I'm getting
[error] [phantom] Failed to save screenshot to fullpage-1440.png;
                  please check permissions...

With capture there is no problem. I event try with sudo but with no effect.

A: I think I found answer . I change one stuff in code:
this.captureSelector(FPfilename, 'html');

Have not idea why it wasn't working.


text:
Q: How do I Read/Write an ArrayList of Arraylists of Objects to/from a file? I have a custom object (AppDetails) that saves String values in pairs (Title, Details).
I have made an ArrayList of this object, which is then the object of another ArrayList.
ArrayList<ArrayList<AppDetails>> appBox;

protected class AppDetails {
    protected String DetailTitle;
    protected String DetailDesc;

    public AppDetails() {
        DetailTitle = "";
        DetailDesc = "";
    }

    public void setDetailTitle(String s) {
        DetailTitle = s;
    }

    public void setDetailDesc(String s) {
        DetailDesc = s;
    }

    public String getDetailTitle() {
        return DetailTitle;
    }

    public String getDetailDesc() {
            return DetailDesc;
    }

}

What is the best way to save this into internal storage in Android?
I want to be able to retrieve this appBox and load it on app startup, and save it to file every time a new ArrayList of AppDetails is created.

A: You can serialize your data to xml and save such xml using preference API. See preference API official page.
In a nutshell, the following code sample:
sPref = getPreferences(MODE_PRIVATE); //MODE_PRIVATE is a constant means that saved data will be accesed via current app only
Editor ed = sPref.edit(); //Editor for writing data
ed.putString(SAVED_TEXT, stringToWrite); //Prepare the string to save. SAVED_TEXT is a key for xml data chunk that will be saved
ed.commit(); //Save data

For your specific example it's possible to do something like the following:
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
for(List<AppDetails> lst : appBox){
    for(AppDetails appDetails : lst){
        ed.putString(appDetails.DetailTitle, appDetails.DetailText);
    }
}
ed.commit();

A: This can be achieved in different ways.
Considering that the arrays are not supposed to be large (tens of objects or even hundreds) you can insert them as SharedPreferences. To make your life easier i would suggest to parse the main array into a JSON string using GSON library in Android before storing into SharedPreferences.
Another approach would be to use SQLite, so a database. You may design 1 table as follows:
Id  |  MainArrayIndex   |  Title  |  Description
 1  |        0          | title1  | desc
 2  |        1          | title2  | desc
 3  |        2          | title3  | desc
 4  |        0          | title4  | desc

Or even design 2 tables, one for holding the index to the main array (so you would reduce the data size) and one for storing the data themselves.


text:
Q: I want to calculate the geoaccumulation index of heavy metals using using for loop and keys function in python I want to write a function that performs a vector operation (Igeo) on all the columns in dataframe (data1)  using a dictionary (sbv2) and the code below:
Igeo = log(data1.el/(1.5*sbv2.el))

for el in sbv2.keys():
    for el in data1.keys():
        data1[str(el)] = np.log(data[el]/(1.5*sbv[el])
    with pd.ExcelWriter('C:\Users\USER\Jupyter_Projects\Data_Analysis\Geochemistry\output\Pollution_Indices.xlsx') as writer:

    data1.to_excel(writer,sheet_name="Igeo")
    writer.save()

The code gives the syntax error below:
File "", line 7
with pd.ExcelWriter('C:\Users\USER\Jupyter_Projects\Data_Analysis\Geochemistry\output\Pollution_Indices.xlsx') as writer:
^
SyntaxError: invalid syntax
data1.head
sbv2 = {"Hg": 0.056, "V": 53, "Cr":35, "Co": 12, "Ni": 19, "Cu":14, "Zn":52, "As":2, "Cd":0.102, "Pb":17, "U":2.5
}

A: don't forget that Python uses '\' as an escape character in strings, so in Windows-style paths '\' should be doubled, as in:
"C:\\Users\\ .... "


text:
Q: android: paint onto ARGB bitmap without changing alpha channel I want to use paint to change the color values of an ARGB bitmap.
I want to keep the original alpha values from the bitmap.
I dont want to make any change to the alpha values in the bitmap. I need them to stay the same. The alpha values are different in each pixel and must be preserved.
How can i restrict the channels that paint alters the values for?


text:
Q: color theme options in emacs I am running Emacs 24 from the terminal of my mac, when I do:
M-x load-theme

Emacs asks:
Custom theme name:

I would very much like to answer that question, but I don't know what options I have! I've been searching online for over an hour. Most related answers tell me: "Now just type the theme you want." or "Here is one awesome customized theme!".
One person mentions hit TAB to autocomplete to show a list, but hitting TAB only moves my cursor forward. (Hitting TAB on my windows 7 Emacs works though).
I would appreciate any help on this matter: How do I find what themes(names) I can choose from?
Thank you!

A: OSX comes with Emacs 22 preinstalled as well. You might be running Emacs 22 from the Terminal accidentally (perhaps you just typed emacs -nw which would normally start Emacs 22).
Normally in Emacs 24, after M-x load-theme you'd get the prompt Load custom theme: and pressing TAB once at this point would show the list of all available themes.


text:
Q: iOS remove all Activity Indicators i have a Problem with my Activity Indicators. I have an Button which reload a Website and Display between a Activity Indicator. The Problem is if the User hits more than 1 Times on the Button it will rebuild a new Indicator and this Indicator freezes on the Screen all the Time.
Button disabling is not working. Has anyone a Solution for this Problem. Please help.
Here is my Code:
-(IBAction) buttonReload {
Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){

    UIAlertView *myAlert = [[UIAlertView alloc]
                            initWithTitle:@"No Inet!" message:@"You need a Inet Connection..."
                            delegate:self
                            cancelButtonTitle:@"Ok"
                            otherButtonTitles:nil];
    [myAlert show];
    [myAlert release];
}

else
{

    //Website loading
    [self performSelector: @selector(doLoadWebsite)
               withObject: nil
               afterDelay: 0];
    return;
}
}

- (void) doLoadWebsite
{

//add activity indicator
NewsActivity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(140.0f, 180.0f, 40.0f, 40.0f)];
[NewsActivity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview: NewsActivity];
[NewsActivity startAnimating];

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(finishActivity) userInfo:nil repeats:YES];
//NewsActivity.backgroundColor = [UIColor grayColor];
NewsActivity.hidesWhenStopped = YES;
// Show Status Bar network indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

//perform time-consuming tasks
//load News Website
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];
}

-(void) finishActivity {

if (!webView.loading) {
    [self.NewsActivity removeFromSuperview];
    [NewsActivity stopAnimating];

    //Hide network activity indicator
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
else {
    [NewsActivity startAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
 }

}

A: You should perform stopAnimating , removeFromSuperView once the page is loaded. If the user refreshes the page again, you can again add it to the subView and startAnimating.


text:
Q: Is there an option in Glue to update a table? I have data partitioned by day stored in S3, i.e. customer/year=2020/month=04/day=05, and I have a crawler cataloging that data. Data arrives daily. Is there an option in Glue to update the customer table in that example? For instance, let's say that new customers are discovered on day=06, then, it got added to the table, but let's say that existing customers have updated fields, then, is there an option to only update the table? Or is it a new record to the table?
Currently, when configuring a crawler to discover partitioned data, the partition fields get added to the record. I guess what I'd like to know is if it's possible to constantly have a table representing the latest state of the data?
Thanks in advance.
K

A: Summarising your question
Is there an option in Glue to update the customer table in that example?

You can only add new partitions to the table when they come in. This means that if you have a customer record in the previous partitions and the a new record came in day=06 for the same customer, this new record comes in with a new partition date and is visible along with the data for the same customer with previous partitioned dates. You cannot update the same customer record (if its on s3), unless and until you read all the files and do some sort of ranking to create a new dataset.


text:
Q: Is it possible to run a Neo4j cluster with strong consistency? The docs of Neo4j state that when running in HA mode, you get eventual consistency. This is a quote from that page:

All updates will however propagate from the master to other slaves
  eventually so a write from one slave may not be immediately visible on
  all other slaves

My question is: is there a configuration that will allow me to write a cluster with strong consistency, of course at the cost of reduced performance? I'm looking for some sort of active-passive failover cluster configuration.

A: There is such an config option. ha.tx_push_factor determines to how many slaves a transaction should be pushed to synchronously. When setting this to ha.tx_push_factor=<clustersize>-1 you have immediate full consistency.


text:
Q: How is Nightmare Difficulty Different in Orcs Must Die? I just finished beating Orcs Must Die! in the middle difficulty. I was considering playing through in nightmare mode, but I don't care to if it is all the same levels. How is nightmare different?

A: Yes, it is all the same levels.  However, they are significantly more difficult because:

*

*The enemies that spawn are significantly more difficult (more heavy orcs, ogres, etc)

*Your traps and weapons do less damage

*There is no wait time between rounds

A: Same levels, as mentioned.
To expand on nightmare, the Orcs Must Die wiki page mentions that the changes in this difficulty are:

*

*Decreased player health by 50%

*Decreased rift points by 50%

*Increased Mob health by 20%

*Increased Mob damage by 20%

*Orc Warriors have Shields

*Guardians receive 20% less damage.

*All breaks between waves (including at the start of the stage, before the first wave is unleashed) are only 3 seconds long.


text:
Q: How can I solve this kind of error, I'm using word embedding word2vec: InvalidArgumentError: Graph execution error: i am trying to train a model using cnn method with tensorflow and keras, but i keep getting the error bellow this code , could anyone help me or give me at least a peace of advice?
#Convolutional Neural Network (CNN) with Word2Vec
    CNN_Word2Vec_model = Sequential([
        Embedding(input_dim =word2Vec_embedding_matrix.shape[0], input_length=max_len, output_dim=word2Vec_embedding_matrix.shape[1],weights=[word2Vec_embedding_matrix], trainable=False),
        SpatialDropout1D(0.5),
        # ... 100 filters with a kernel size of 4 so that each convolution will consider a window of 4 word embeddings
        Conv1D(filters=100, kernel_size=4, padding='same', activation='relu'),
        #**batch normalization layer** normalizes the activations of the previous layer at each batch,
        #i.e. applies a transformation that maintains the mean activation close to 0 and the activation standard deviation close to 1.
        #It will be added after the activation function between a convolutional and a max-pooling layer.
        BatchNormalization(),
        GlobalMaxPool1D(),
        Dropout(0.2),
        Dense(50, activation = 'relu'),
        Dense(5, activation = 'softmax')
    ])

    #Customized the evaluation to analyse the model in terms of accuracy and mean value accuracy
    def mean_pred(y_true, y_pred):
        return K.mean(y_pred)
    CNN_Word2Vec_model.compile(loss="sparse_categorical_crossentropy", optimizer=Adam(0.01), metrics=['accuracy'])
    #CNN_Word2Vec_model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam(0.01), metrics=['accuracy', mean_pred, fmeasure, precision, auroc, recall])

    CNN_Word2Vec_model.summary()

When I feed data to CNN model with word embedding (word2vec) in the below code then I got the error, so please how can I resolve it.
CNN_Word2Vec_model_fit = CNN_Word2Vec_model.fit(X_tra, y_tra, batch_size=batch_size2, epochs=num_epochs, validation_data=(X_val, y_val), callbacks=[early])

the full error is below:
InvalidArgumentError          Traceback (most recent call last)
<ipython-input-48-7214f2a862e6> in <module>()
----> 1 CNN_Word2Vec_model_fit = CNN_Word2Vec_model.fit(X_tra, y_tra, batch_size=batch_size2, epochs=num_epochs, validation_data=(X_val, y_val), callbacks=[early])
      2 #CNN_Word2Vec_model_fit = CNN_Word2Vec_model.fit(X_tra, y_tra, batch_size=batch_size2, epochs=num_epochs, validation_data=(X_val, y_val))

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     53     ctx.ensure_initialized()
     54     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 55                                         inputs, attrs, num_outputs)
     56   except core._NotOkStatusException as e:
     57     if name is not None:

InvalidArgumentError: Graph execution error:

Detected at node 'sequential/embedding/embedding_lookup' defined at (most recent call last):
    File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
      "__main__", mod_spec)
    File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
      exec(code, run_globals)
    File "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
      app.launch_new_instance()
    File "/usr/local/lib/python3.7/dist-packages/traitlets/config/application.py", line 846, in launch_instance
      app.start()
    File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelapp.py", line 499, in start
      self.io_loop.start()
    File "/usr/local/lib/python3.7/dist-packages/zmq/eventloop/zmqstream.py", line 431, in _run_callback
      callback(*args, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/tornado/stack_context.py", line 300, in null_wrapper
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
      return self.dispatch_shell(stream, msg)
    File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell
      handler(stream, idents, msg)
    File "/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
      user_expressions, allow_stdin)
    File "/usr/local/lib/python3.7/dist-packages/ipykernel/ipkernel.py", line 208, in do_execute
      res = shell.run_cell(code, store_history=store_history, silent=silent)
    File "/usr/local/lib/python3.7/dist-packages/ipykernel/zmqshell.py", line 537, in run_cell
      return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
      interactivity=interactivity, compiler=compiler, result=result)
    File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
      if self.run_code(code, result):
    File "/usr/local/lib/python3.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
      exec(code_obj, self.user_global_ns, self.user_ns)
    File "<ipython-input-47-169eb83cb089>", line 2, in <module>
      CNN_Word2Vec_model_fit = CNN_Word2Vec_model.fit(X_tra, y_tra, batch_size=batch_size2, epochs=num_epochs, validation_data=(X_val, y_val))
    File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 64, in error_handler
      return fn(*args, **kwargs)
    File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1384, in fit
      tmp_logs = self.train_function(iterator)
Node: 'sequential/embedding/embedding_lookup'
indices[233,187] = 10690 is not in [0, 8262)
     [[{{node sequential/embedding/embedding_lookup}}]] [Op:__inference_train_function_5282]

A: When I ran into this it was because the shape of my data and the model input were incompatible/ I think it can also be caused by the the training data shape and model output being incompatible. So my recommendation would be to check the shape of your inputs/outputs and make sure they are what you want.


text:
Q: How to have Marquee kind of text in vb.net? Is there any way to make the text in a Windows Form to scroll like the text in a marquee tag in HTML?

A: You can use a timer and a couple of variables to help you do so.  Something like this can be done...
'Class-level variables.
Private m_intMarqueeCounter As Integer = 1
Private m_bolMarqueeIncrementUp As Boolean = True

Private Sub YourMarqueeTimer_Tick()

   'You can decide what number is best for your app.
   If m_intMarqueeCounter = 10 Then

      m_bolMarqueeIncrementUp = False

   End If

   If m_intMarqueeCounter = 0 Then

      m_bolMarqueeIncrementUp = True

   End If

   Dim intX As Integer
   For intX = 0 to m_intMarqueeCounter

      frmYourForm.Text = " " & "Your Title"

   Next

   If m_bolMarqueeIncrementUp Then

      m_intMarqueeCounter += 1

   Else

      m_intMarqueeCounter -= 1

   End If

End Sub

A: Const marqueeText As String = "The quick brown fox...   "
Dim sb As New System.Text.StringBuilder
Dim direction As Boolean = False 'true = left to right, false = right to left

Private Sub Timer1_Tick(sender As System.Object, _
                        e As System.EventArgs) Handles Timer1.Tick

    If sb.Length = 0 Then sb.Append(marqueeText)
    If direction Then
        sb.Insert(0, sb(sb.Length - 1))
        sb.Remove(sb.Length - 1, 1)
    Else
        sb.Append(sb(0))
        sb.Remove(0, 1)
    End If
    Me.Text = sb.ToString
End Sub


text:
Q: My project is working on google colab but not working on pycharm My project is a handwriting digit analyzer. It is working on Google Colab but is showing an error on Pycharm. The statement that is making it work in colab is "%matplotlib inline" this line is showing an error in pycharm.
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline

mnist = fetch_openml("mnist_784")

plt.figure(figsize=(20, 4))
    for index, (image, label) in enumerate(zip(mnist.data[:5], mnist.target[:5])):
    plt.subplot(1, 5, index + 1)
    plt.imshow(np.reshape(image, (28, 28)), cmap="gray")
    plt.title("Number: %s" % label)
X_train, X_test, y_train, y_test = train_test_split(mnist.data, mnist.target, test_size=0.2)
mdl = LogisticRegression(solver="lbfgs")
mdl.fit(X_train, y_train)
predictions = mdl.predict(X_test)
score = mdl.score(X_test, y_test)

index = 0
plt.imshow(np.reshape(X_test[index], (28, 28)))
print("Prediction: " + mdl.predict([X_test[index]])[0])

cm = metrics.confusion_matrix(y_test, predictions)
plt.figure(figsize=(9, 9))
plt.imshow(cm, cmap='Pastell')
plt.title('Confusion Matrix for MNIST Data')

plt.xticks(np.arange(10))
plt.yticks(np.arange(10))

plt.ylabel('Actual Label')
plt.xlabel('Predicted Label')

plt.colorbar()

width, height = cm.shape
for x in range(width):
    for y in range(height):
        plt.annotate(str(cm[x][y]), xy=(y, x), horizontalalignment='center',
verticalalignment='center')

Traceback (most recent call last):
File "C:\Users\Asus\PycharmProjects\pythonProject\Handwriting_Digit_Recognition\digit.py", line 15, in
plt.imshow(np.reshape(image, (18, 18)), cmap="gray")
File "<array_function internals>", line 5, in reshape
File "C:\Users\Asus\PycharmProjects\pythonProject\venv\lib\site-packages\numpy\core\fromnumeric.py", line 299, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "C:\Users\Asus\PycharmProjects\pythonProject\venv\lib\site-packages\numpy\core\fromnumeric.py", line 55, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "C:\Users\Asus\PycharmProjects\pythonProject\venv\lib\site-packages\numpy\core\fromnumeric.py", line 44, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
ValueError: cannot reshape array of size 1 into shape (18,18)

A: %matplotlib inline is a message to Jupyter notebook to render images into the notebook itself. You need to remove that line if you use your code from Pycharm.

A: After the for loop on line 13, try indenting all code until the
X_train, X_test, y_train, y_test = train_test_split(mnist.data, mnist.target, test_size=0.2) line (but don't indent that line). The error has nothing to do with %matplotlib inline, but I think this is the solution. Let me know ASAP if it works. This is assuming the rest of your code works, though!
Don't forget that Python depends on indentation unlike other languages
!

A: It is the problem coming from the conflict when Pycharm uses GPU. The solution is to add the code when you use tensorflow:
import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allocator_type = 'BFC' #A "Best-fit with coalescing" algorithm, simplified from a version of dlmalloc.
config.gpu_options.per_process_gpu_memory_fraction = 0.3
config.gpu_options.allow_growth = True
tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session(config=config))


text:
Q: Why Future always returns error for HTTP request? It was working perfectly fine when I opened last time. But now it always throws an error.
import 'dart:convert';
import 'package:easy_shop/main.dart';
import 'package:http/http.dart' as http;
import '../models/api_response.dart';
import '../models/group.dart';
class GroupService {
  String url = MyApp.BASE_URL;
  Future<APIResponse<List<Group>>> getGroupList() {
    return http.get(url + '/api/group?&pagenumber=0&pagesize=20').then((data) {
      print('Status code : ${data.statusCode}');
      if (data.statusCode == 200) {
        final Iterable jsonData = json.decode(data.body);
        final List<Group> groups =
            jsonData.map((e) => Group.fromJson(e)).toList();
        return APIResponse<List<Group>>(data: groups);
      }
      return APIResponse<List<Group>>(
          error: true, errorMessage: 'An error occured');
    }).catchError((_) => APIResponse<List<Group>>(
        error: true, errorMessage: 'An error occured'));
  }
}


text:
Q: Different database for tests and development profile I'm thinking would be a good approach to have a database in memory (H2 for example) only for tests.
Development and Production profiles I think should use the same database (mysql, postgresql, mongoDB or whatever).
With this approach, tests can be executed without modify the database used on development, and it would be faster than executed on a no-memory database.
To use the same engine database for production and development profiles could prevent bugs due to different implementations of a same specification.
What do you think?

A: Sounds similar to a question I was wondering about a few months back. Does this answer help with what you're looking for? https://stackoverflow.com/a/24170862/1098564


text:
Q: flask socket-io, sometimes client calls freeze the server I occasionally have a problem with flask socket-io freezing, and I have no clue how to fix it.
My client connects to my socket-io server and performs some chat sessions. It works nicely. But for some reason, sometimes from the client side, there is some call that blocks the whole server (The server is stuck in the process, and all other calls are frozen). What is strange is that the server can be blocked as long as the client side app is not totally shutdown.This is an ios-app / web page, and I must totally close the app or the safari page. Closing the socket itself, and even deallocating it doesn't resolve the problem. When the app is in the background, the sockets are closed and deallocated but the problem persists.
This is a small server, and it deals with both html pages and the socket-server so I have no idea if it is the socket itself or the html that blocks the process. But each time the server was freezing, the log showed some socket calls.
Here is how I configured my server:
socketio = SocketIO(app, ping_timeout=5)
socketio.run(app, host='0.0.0.0', port=5001, debug=True, ssl_context=context)

So my question is:
What can freeze the server (this seems to happen when I leave the app or web-site open for a long time while doing nothing). If I use the services normally the server never freezes. And how I can prevent it from happening (Even if I don't know what causing this, is there a way to blindly stop my server from being stuck at a call?
Thanks you for the answers

A: According to your comment above, you are using the Flask development web server, without the help of an asynchronous framework such as eventlet or gevent. Besides this option being highly inefficient, you should know that this web server is not battle tested, it is meant for short lived tests during development. I'm not sure it is able to run for very long, specially under the unusual conditions Flask-SocketIO puts it through, which regular Flask apps do not exercise. I think it is quite possible that you are hitting some obscure bug in Werkzeug that causes it to hang.
My recommendation is that you install eventlet and try again. All you need to do is pip install eventlet, and assuming you are not passing an explicit async_mode argument, then just by installing this package Flask-SocketIO should configure itself to use it.
I would also remove the explicit timeout setting. In almost all cases, the defaults are sufficient to maintain a healthy connection.