Q:

Why does a list of arguments wrapped in braces return the last argument?

I'm correcting some basic Javascript assignments and a student has stumped me with this particular line in a constructor:
this.c = (255, 255, 255);

I'd like to explain to them (and to myself) why this statement, or any like it, will evaluate to the last 'argument' given.
console.log( ("foo", 42, {}, NaN) )  --> NaN
console.log( ("foo", 42, {}) )       --> Object
console.log( ("foo", 42) )           --> Number
console.log( ("foo") )               --> String
console.log( () )                    --> SyntaxError // no longer the same thing

In the case of their assignment, they use that property as an RGB value, yet only stick to monochrome and thus their code still functions as intended. I'd like to know what that statement is called (if it has a name?) and what's happening in terms of the JS spec that has it behaving like so.
Thanks in advance.

A:

It's the comma operator. It's an unusual operator: It evaluates its left-hand operand, throws that value away, evaluates its right-hand operand, and uses the result as its result value. You sometimes see it used where evaluating the first operand has a side-effect:

const a = (console.log("foo"), 42);
console.log(a);

The MDN page linked above is slightly inaccurate, suggesting that the comma operator accepts more than two operands. It doesn't, it's a binary operator (it accepts two operands); it's just that it's left-to-right associative, so
const a = (1, 2, 3);

is the same as
const a = ((1, 2), 3);


Q:

Why would Get-Service not find the service with powershell

I am having problems with a powershell script.
I wrote a script that would search for a windows service with a specific name, and it would Stop or Start this service.
It works when I run it on a server which I log into with a service account that I know that can access the service console.  However when it runs off of my build server, the script is no longer able to find the services.  I tried giving the service account that runs script the same privaledges as the other service account but that doesn't seem to work.
[System.ServiceProcess.ServiceController]$service = Get-Service -Name $ServiceName -ComputerName $Remoteserver -ErrorAction SilentlyContinue

That is the line that is not longer able to find the service.  What am I doing wrong.  Is there a way to impersonate a user that can find the service? Any help would be appreciated.

A:

You could try supplying the credentials of the service account using the -Credential parameter. However, since you imply that it used to work with the account that runs the script remotely and no longer does, I think a more likely culprit is that $ServiceName used to only match one service on the target computer, and now there is another service whose name matches that string. If more than one service matches the -Name parameter, Get-Service returns an array of ServiceController objects.
Try running it without ErrorAction -SilentlyContinue. If you get the following error message, then that's what's happening:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.ServiceProcess.ServiceController".

If you get a different error message, please add the full error message to the question.


Q:

Django static files not loading with no error signs

When I run the django server and try to load HTML files, it's not loading CSS files. I don't see any errors on the terminal or the website itself - just loading animation in the background. After I set up static files in settings.py, I ran collectstatic on the terminal which generated a new static file in the main file area with all the CSS/JS/fonts files.
~filepath

├── static/
│   ├── static/
│   │   └── admin/
│   │   └── css/
│       └── fonts/
│       └── images/
│       └── js/
├── templates/
│   └── base.html/
│   └── _partials/
│      └── footer.html
│      └── navbar.html
│   └── pages/
│      └── index.html
│      └── about.html

~settings.py
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'tvfb/static')
]

~urls.py (project)
urlpatterns = [
    path('', include('pages.urls')),
    path('admin/', admin.site.urls),
]

~urls.py (app)
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('about', views.about, name='about'),
]

~views.py
def index(request):
    return render(request, 'pages/index.html')

def about(request):
    return render(request, 'pages/about.html')

~base.html
{% load static %}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,400i,700,700i,900,900i" rel="stylesheet">

    <link rel="stylesheet" href="{% static 'css/open-iconic-bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/animate.css' %}">

    <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/owl.theme.default.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}">

    <link rel="stylesheet" href="{% static 'css/aos.css' %}">

    <link rel="stylesheet" href="{% static 'css/ionicons.min.css' %}">

    <link rel="stylesheet" href="{% static 'css/flaticon.css' %}">
    <link rel="stylesheet" href="{% static 'css/icomoon.css' %}">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">

    {% include '_partials/_navbar.html'%}

    {% block content %}
    {% endblock %}

    {% include '_partials/_footer.html'%}

<svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg>

A:

Erase the staticfilesdir:
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'tvfb/static')
]

Will remain like:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')

Run python manage.py collectstatic and dont forget to erase the cache of the browser as well.


Q:

how to load ns by default when starting repl

I am using lein2. I would like to load some ns by default when the repl starts. Is it possible to either specify in project.clj the ns that should be loaded, when lein2 repl is executed for that project?

A:

You will find a lot of answers in the sample project
;; Options to change the way the REPL behaves
:repl-options {;; Specify the string to print when prompting for input.
               ;; defaults to something like (fn [ns] (str *ns* "=> "))
               :prompt (fn [ns] (str "your command for <" ns ">, master? " ))
               ;; Specify the ns to start the REPL in (overrides :main in
               ;; this case only)
               :init-ns foo.bar
               ;; This expression will run when first opening a REPL, in the
               ;; namespace from :init-ns or :main if specified
               ;; This expression will run when first opening a REPL, in the
               ;; namespace from :init-ns or :main if specified
               :init (println "here we are in" *ns*)

Using a project.clj I had handy:
(defproject test "1.0.0"
  :repl-options { :init-ns test.core
                  :init (do
                          (use 'clojure.set)
                          (println (union #{1 2 3} #{3 4 5}))
                          (use 'incanter.core)
                          (println (factorial 5))) }
  :dependencies [[org.clojure/clojure "1.4.0"]
                 [incanter/incanter-core "1.3.0-SNAPSHOT"]])

When I fire up lein repl
$ lein repl
nREPL server started on port 1121
REPL-y 0.1.0-beta10
Clojure 1.4.0
    Exit: Control+D or (exit) or (quit)
Commands: (user/help)
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
          (user/sourcery function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
Examples from clojuredocs.org: [clojuredocs or cdoc]
      (user/clojuredocs name-here)
      (user/clojuredocs "ns-here" "name-here")
#{1 2 3 4 5}
120.0
test.core=>

A:

I sometimes use the :injections option in project.clj
to load namespaces. The following example will load the
foo.bar namespace when the lein2 command is executed:
(defproject org.example/sample "0.1.0-SNAPSHOT"
  :description "A sample project"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :injections [(use 'foo.bar)])


Q:

How to show text in image hover

I have a few tumbnails that I want to show some text on them in hover.  I could make them dark in hover but do not know how to add text.
example: http://www.lenzflare.com/video-production-portfolio/
Here is what I have done:
    a {
    display: inline-block;
    overflow: hidden;
    position: relative;
    }
    a:hover .play {
    background:url(http://goo.gl/yJqCOR) no-repeat center    center;
    opacity: 0.8;
    position: absolute;
    width: 200px;
    height: 200px;
    left: 50%;
    top: 50%;
    margin-left: -110px;
    margin-top: -150px;
    }

Demo: http://jsfiddle.net/jmXdh/79/

A:

Well I'm going to assume you want this in a list:
There are a few main concepts here: Relative positioning and how it works with absolute positioning, Source order, and your centering technique.
When giving position:relative; to the box, you are saying "I am the boundary now - for any absolutely positioned things within me" (unless they are relative, and then like that on down the line) - So, the absolutely positioned cover thing you want to fade in - is absolutely positioned to one or more edges of the relative box. (most people use top: 0; left: 0;) --- so the absolute box is no longer in the "flow" and lives in it's own magic world determined by the relative parent.
Source order: your html will appear bottom up when stacking. so your cover thing should be below the image (in the html order) - you could use z-index - but there is no need to do that.
The negative margins are not really awesome and unneeded here. You can just text align center them. I would do some tests and put borders around stuff so you can see what it actually happening. ALSO - I encourage you to use box-sizing: border-box; on everything...
Read about: Border box
HTML

Title

A little bit more about the thing

CSS
.thumbnail-list {
  list-style: none;
  margin: 0; paddingn: 0;
}

.thumbnail-list li {
  float: left;
}

a {
  text-decoration: none;
  color: inherit;
}

.thumbnail-list .image-w {
  display: block;
  position: relative;
  width: 16em;
}

.image-w img {
  display: block;
  width: 100%;
  height: auto;
}

.cover {
  position: absolute;
  top: 0; right: 0;
  bottom: 0; left: 0;
  width: 100%;
  height: 100%;
  color: rgba(255,255,255,0);
  text-align: center;
  transition: all 1s linear;
}

.cover:hover {
  background-color: rgba(0,0,0,.8);
  color: rgba(255,255,255,1);
  transition: all .2s linear;
}

.thumbnail-list h3 {
  font-size: 1.2em;
}

.thumbnail-list p {
  font-size: .9em;
}

Here is the code in action on jsfiddle


Q:

Removing the

I'm using Ruby, with the Nokogiri module, and i want to get the content of the body without the script elements.
Nokogiri parse uses XPATH or CSS 3.0. XPATH i really dont understand, and i can't find the CSS selector to achieve my goals.

A:

I don't think such selection is possible with XPath.
I'm not that familiar with Ruby or Nokogiri, but based on answers to a similar question, you might want to try selecting all script elements from the HTML document and removing them.
doc = Nokogiri::HTML(your_html)
doc.xpath("//script").remove

Adjust accordingly.


Q:

Unexpected token and missing ) after argument list

I'm having an issue with the phonegap ported versions of my app on several devices. On some devices the error (alert) is: "missing ) after argument list", while on other devices "Unexpected token =>".
{

(unless: (saved-games:) contains $_autosave_slot and (datavalues: (saved-
games:)) contains $_autosave_filename)[(goto: $_start_passage)]
}''[[New->$_start_passage]]

(link: "Continue")[(load-game: $_autosave_slot)]
''
Exit

some text

            some text

A:

I fixed it by addding my other JS code to the generated .html file or as an external source, rather than directly into engine I worked with.


Q:

Get an iteratable JSON from view in template without unicode values

I have created a python (2.7) dictionary with the following structure:
cntr_rgns = {'country_1':[region1, region2, region3], 'country_2':[region1, region2] ..}

I pass it to my contextdioctionary as:
ctx['regions'] = cntr_rgns

What I want is to display the values in my template.
In my template view I did that:
{% if regions %}
    {% for region in regions.items %}
        <option value={{ region }}>{{ region }}</option>
    {% endfor %}
{% endif %}

But I again get the unicode values:
(u'Canada',[u'somethong',u'something else',u..])
How can I get back an iteratable JSON or something?

A:

If you want JSON, you need to actually create some JSON.
 ctx['regions'] = json.dumps(cntr_rgns)


Q:

Get data with from 3 tables

I have these SQL Tables
gouvernorat
id  |nom
1   TUNIS
2   ARIANA
3   BEN AROUS
4   MANOUBA
5   NABEUL

delegation
id|id_gouvernorat| nom
1   1              EL MENZAH
2   1              EL HRAIRIA
3   1              EL KABBARIA
22  2              RAOUADE
23  2              SIDI THABET

id_gouvernorat is a foreign key of gouvernorat
tarifs_zone
zone_a|zone_b|prix
1      2      10
1      3      15
1      4      17
1      5      0
2      3      1
2      4      5

zone_a and zone_b are foreign key of delegation
I want to retrieve
The gouvernorat.nom,delegation.nom of zone_a, The gouvernorat.nom,delegation.nom of zone_b and the price without duplcates (A,B without B,A)
public function Get_zones($start, $length, $order, $dir,$search,$gouvernorat){
$sql='
SELECT (

SELECT delegation.id_gouvernorat
FROM delegation
WHERE tarifs_zones.zone_b=delegation.id)
AS zoneB,

gouvernorat.nom AS gouvernoratA,
gouvernorat.id AS zoneA,
delegation.nom AS delegationA,
tarifs_zones.prix AS prix,

(SELECT gouvernorat.nom
from gouvernorat
WHERE zoneB=gouvernorat.id)
AS gouvernoratB,

(SELECT delegation.nom
FROM delegation
WHERE tarifs_zones.zone_b=delegation.id)
AS delegationB

FROM tarifs_zones

JOIN delegation ON delegation.id = tarifs_zones.zone_a
JOIN gouvernorat ON delegation.id_gouvernorat = gouvernorat.id

HAVING (gouvernoratA= \''.$gouvernorat.'\' OR gouvernoratB= \''.$gouvernorat.'\' OR \'Tous les gouvernorats\'=\''.$gouvernorat.'\')
AND (delegationA LIKE \'%'.$search.'%\' OR gouvernoratA LIKE \'%'.$search.'%\' OR delegationB

LIKE \'%'.$search.'%\' OR gouvernoratB LIKE \'%'.$search.'%\' OR prix LIKE \'%'.$search.'%\')

ORDER BY '.$order.' '.$dir.'
LIMIT '. $start.', '.$length.';
';

return $this->db->query($sql);
}

This is my function but I feel it's too complex and I can't figure out a way to update the price of all zones depending on two gouvernorat.nom

A:

There is no need to use subqueries behind SELECT. You should not be afraid to use the same table twice in the JOINs. You just need to assign aliases in such cases.
Therefore your query will be something like
 SELECT d2.id_gouvernorat AS zoneB,
        g1.nom AS gouvernoratA,
        g1.id AS zoneA,
        d1.nom AS delegationA,
        tarifs_zones.prix AS prix,
        d2.nom AS gouvernoratB,
        d2.nom AS delegationB
 FROM tarifs_zones
 LEFT JOIN delegation d1 ON d1.id = tarifs_zones.zone_a     // delegation with alias d1 for zone_a
 LEFT JOIN delegation d2 ON d2.id = tarifs_zones.zone_b     // delegation with alias d2 for zone_b
 LEFT JOIN gouvernorat g1 ON d1.id_gouvernorat = g1.id
 LEFT JOIN gouvernorat g2 ON d2.id_gouvernorat = d2.id
 HAVING (gouvernoratA= \''.$gouvernorat.'\' OR gouvernoratB= \''.$gouvernorat.'\' OR \'Tous les gouvernorats\'=\''.$gouvernorat.'\')
      AND (delegationA LIKE \'%'.$search.'%\' OR gouvernoratA LIKE \'%'.$search.'%\' OR delegationB
      LIKE \'%'.$search.'%\' OR gouvernoratB LIKE \'%'.$search.'%\' OR prix LIKE \'%'.$search.'%\')
 ORDER BY '.$order.' '.$dir.'
 LIMIT '. $start.', '.$length.';


Q:

How to disable UIAlertAction depending on UITextField in UIAlertController?

I'm using a UIAlertController to present the user with a dialog to enter a 5 digit CRN. I want the Add button to be disabled until there are 5 and only 5 digit in the UITextField.
Here's what the UI looks like :

Here's the properties setup for the UIAlertController :
var alertController: UIAlertController!

var addAlertAction: UIAlertAction! {
    return UIAlertAction(title: "Add", style: .default)
}

Here's how I'm initializing them in the viewDidLoad method :
self.alertController = UIAlertController(title: "Add Class", message: "Input CRN", preferredStyle: .alert)
self.alertController.addAction(addAlertAction)
self.alertController.addAction(UIAlertAction(title: "Cancel", style: .destructive))
self.alertController.addTextField { (textField) in
    textField.delegate = self
    textField.keyboardType = .numberPad
}

Here's how I'm trying to disable/enable the button using the UITextFieldDelegate method :
func textFieldDidEndEditing(_ textField: UITextField) {
    if ((textField.text?.characters.count)! == 5) {
        self.alertController.actions[0].isEnabled = true
    } else {
        self.alertController.actions[0].isEnabled = false
    }
}

However, the button remains disabled (or enabled) all the time. It never gets enabled. What's going wrong ?

A:

Implement the logic in the shouldChangeCharactersIn delegate method of UITextField. This method gets fired on change in each character of textfield.
You can build the logic taking the range parameter into consideration.
Here is the code that works perfectly.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if ((range.location == 4 && range.length == 0) || (range.location == 5 && range.length == 1)) {
        self.alertController.actions[0].isEnabled = true
    }else{
        self.alertController.actions[0].isEnabled = false
    }

    return true;
}

Tested successfully in Swift 3, XCode 8 and iOS 10
Hope that helps.
Happy coding ...

A:

Try using the textfield's EditingChanged event as follow:
let addAction:UIAlertAction = UIAlertAction(title: "Add", style: .default)
addAction.isEnabled = false; //to make it disable while presenting

self.alertController = UIAlertController(title: "Add Class", message: "Input CRN", preferredStyle: .alert)
self.alertController.addAction(addAction)
self.alertController.addAction(UIAlertAction(title: "Cancel", style: .destructive))
self.alertController.addTextField { (textField) in
    textField.keyboardType = .numberPad
    textField.addTarget(self, action: #selector(self.alertTextFieldDidChange(field:)), for: UIControlEvents.editingChanged)
}

And the listener for text field should look like this:
func alertTextFieldDidChange(field: UITextField){
    let alertController:UIAlertController = self.presentedViewController as! UIAlertController;
    let textField :UITextField  = alertController.textFields![0];
    let addAction: UIAlertAction = alertController.actions[0];
    addAction.isEnabled = (textField.text?.characters.count)! >= 5;

}

Tested with Xcode 8 and swift 3. Worked for me.


Q:

How can I enable user to dynamically set logo in Apex 5?

I need to allow the user upload a number of logos and select a default, that will then become the logo that's shown at the top left of the screen.
Usually the logo is a static application file, so is there perhaps a way to make changes to those by the user? Or to set a static file as a select statement?
I also tried setting an application computation to set an application item but couldn't get that to work.
This is my first question on SO. If I'm asking something stupid, please go easy on me. Thanks.

A:

The way to solve this problem is to give the user a page for him to upload and manage the logos. (save them in the database)
Then create a RESTful Web Service that returns the image of a selected logo,
and use the link of the RESTful Web Service as the img src link.


Q:

How to render Jbuidler partials inside a model?

I am trying to render a jbuilder partial in a model like this:
class Reminder < ActiveRecord::Base
  ...
  def fcm_format
    Jbuilder.new do |json|
      json.partial! 'api/v1/gigs/summary', gig: remindable
    end
  end
end

But this gives me the following error.

TypeError: {:gig=>#} is not a symbol nor a string

Is there a way to render a partial inside of a model or a decorator maybe?

A:

A Jbuilder instance does not respond to partial!. partial! is contained in JbuilderTemplate. JbuilderTemplate's constructor is looking for a context before calling super on Jbuilder.new.
So the solution is to add a context. The problem is that within JbuilderTemplate, the context calls the method render and in models we don't have a built in way to render. So we need to stub out our context with an ActionController::Base object.
class Reminder < ActiveRecord::Base

  # Returns a builder
  def fcm_format
    context = ActionController::Base.new.view_context
    JbuilderTemplate.new(context) do |json|
      json.partial! 'api/v1/gigs/summary', gig: remindable
    end
  end

  # Calls builder.target! to render the json
  def as_json
    fcm_format.target!
  end

  # Calls builder.attributes to return a hash representation of the json
  def as_hash
    fcm_format.attributes!
  end
end


Q:

PDOMapping: a CAN Open Process Data Object Management Class

I'm looking for some feedback on Python best practices, general code quality, and bonus points if you have knowledge of CANOpen that you can leverage to find anything I missed functionality-wise, but isn't necessary! I'm hoping that this isn't too technical.
PDOMapping.py:
import CANOpen
import csv, StringIO, binascii
"""@package PDOMapping
This package defines a PDOMapping, which is the PDO interpretation of the DictionaryEntry, but instead does the heavy lifting for PDOs. It defines the methods for sending and retrieving PDOs from CANSock.
"""

class PDOMapping(object):
    """Provides an easy to use method for sending and recieving PDOs for a specific device."""

    def __init__(self, CANBus, deviceID):
        """Constructor for the PDOMapping. Takes in a CANBus to communicate over and a deviceID, and calculates the 8 possible PDO identifiers from there."""
        self.CANBus = CANBus
        self.deviceID = deviceID
        self.transmitPDOBases = {}
        self.recievePDOs = {}
        for i in range(1, 5):
            self.transmitPDOBases[str(i)] = 0x80 + (0x100 * i) + self.deviceID
            msg = CANOpen.PDO((0x100 + (0x100 * i) + self.deviceID), [0x00]*8)
            self.recievePDOs[str(i)] = msg
        for i in range(5, 9):
            self.transmitPDOBases[str(i)] = 0xC0 + (0x100 * (i - 4)) + self.deviceID
            msg = CANOpen.PDO((0x140 + (0x100 * (i - 4)) + self.deviceID), [0x00]*8)
            self.recievePDOs[str(i)] = msg

    def send(self, mappingList, value):
        """Takes in a list of different positions and a value. It breaks the value down into the appropriate number of bytes (The least amount possible) and then distributes the bytes to their different positions. This allows for one value to be spread over any number of different PDOs in any order. The mapping list must be ordered highest byte to lowest byte and specifies a tuple containing the PDO number and byte number for that bytes position. It then sends out all the PDOs needed to complete the message. Raises an exception if the value is too large for the provided list of positions, and returns false if the communication with CANSock failed, or true if everything went well."""
        stringValue = hex(value)
        stringValue = stringValue.replace('0x', '')

        if len(stringValue) > (len(mappingList) * 2):
            raise Exception('Value is too large to fit into the PDO!')
        # String needs to have an even number of characters
        if (len(stringValue) % 2) == 1:
            stringValue = '0' + stringValue

        while (len(mappingList) * 2) > len(stringValue):
            stringValue = "00" + stringValue

        valueStringList = []
        while len(stringValue) > 0:
            valueStringList.append(stringValue[-2:])
            stringValue = stringValue[:-2]

        valueList = []
        for v in valueStringList:
            valueList.append(int(v, 16))

        PDOsToSend = []
        for messageLocation in mappingList:
            self.recievePDOs[str(messageLocation[0])].payload[messageLocation[1]-1] = valueList.pop()
            if not self.recievePDOs[str(messageLocation[0])] in PDOsToSend:
                PDOsToSend.append(self.recievePDOs[str(messageLocation[0])])
        for pdo in PDOsToSend:
            worked = self.CANBus.send(pdo.toString())
            if worked == False:
                print "Got a bad response on a send!"
                return False
        return True

    def retrieve(self, mappingList):
        """Does the opposite of the send. Takes in a mapping list formatted in the same way as the send mapping, and then figures out which PDOs it needs to retrieve to construct the value, then does the appropriate bit shifting to create the value and returns that as an integer."""
        PDOsToRetrieve = []
        for messageLocation in mappingList:
            if not (messageLocation[0] in PDOsToRetrieve):
                PDOsToRetrieve.append(messageLocation[0])
        PDOS = {}
        for pdo in PDOsToRetrieve:
            PDOS[str(pdo)] = self.fetchPDO(pdo)
        value = '';
        for messageLocation in mappingList:
            value += PDOS[str(messageLocation[0])][messageLocation[1]]
        return int(value.replace('0x', ''), 16)

    def fetchPDO(self, pdoNumber):
        """Private method used to retrieve a PDO. This ensures that the whole PDO is grabbed at once as opposed to fetching the same PDO 4 times to get 4 different data bytes out of it."""
        PDOCOB = self.transmitPDOBases[str(pdoNumber)]
        response = self.CANBus.send(hex(PDOCOB))
        f = StringIO.StringIO(response)
        reader = csv.reader(f, delimiter= ',', skipinitialspace=True)
        message = reader.next()
        if message[-1] == 'T':
            print 'This is the dead message: ',
            print message
            raise Exception('PDO retrieve shows dead PDO!')
        return message

A:

Well, here are a few points that I noticed:

The docstrings are all a long single line, which is hard to read on StackExchange, and in most editors as well. I would suggest to wrap the docstrings to a reasonable line length.
Spelling error -- "recieve" (in recievePDOs) should be "receive"
Lots of hardcoded numbers (5, 9, 0x80, ...). Consider using named constants
The trailing semicolon on some lines (e.g. value = '';) is unnecessary and uncommon, remove it.
Using csv to parse the response in fetchPDO is quite "creative", but is this really the right tool for the job? Or is this overkill? Is a response really CSV?

Error handling appears to be inconsistent. Sometimes you return True/ Falseto indicate success/error, sometimes you use exceptions. I'd suggest to use exceptions throughout.

Don't raise Exception directly. Instead, create a PDOErrorclass derived from Exception, and raise that. This allows clients of your class to catch specifically only PDO errors.
Avoid print statements in library code. For example, instead of printing error details, include them in your custom exception class.
Some of your functions are quite long. To conform to the Single Responsibility Principle, you might want to factor out the building and parsing of messages into separate functions, preferably in a separate module. This would  also be easier to unit-test


Q:

Exchange open file attachtment msg

Hello everyone i'm try to get te content of a mail on outlook, this mail have a .msg as attachment and i'm try to open them.
                if (message.HasAttachments)
                {
                    try
                    {
                        var sender = message.Sender.Address;
                        var processed = ProcessAttachment(message, tmpStartFolder, tmpExtractFolder, dataCapFolder,sender);
                        emailMessage.Move(processed ? processFolder.Id : attentionFolder.Id);
                    }
                    catch (Exception r)
                    {
                        _logContext.Log(LoggerMessageType.Error, $"Function: ProcessImageList | Message: {r.Message} | Inner Message: {(r.InnerException != null ? r.InnerException.Message : "")}", DateTime.Now, Administrator, Environment.MachineName);
                    }
                }

 private bool ProcessAttachment(Item message, string tmpStartFolder, string tmpExtractFolder, string dataCapFolder, string sender)
{
    foreach (var fileAttachment in message.Attachments.Select(attachment => attachment as FileAttachment))
    {

    }
}

The message has the email and my fileAttachment.Name is null that means the Exchange Web Service doesn't allow .msg ?

A:

Gracias_Por_Nada.jpg
foreach (Attachment att in message.Attachments)
{
            //Load the attachment
            att.Load();
            //turnt the message.Attachments to a Item(Object)
            ItemAttachment ItemAtt = att as ItemAttachment;
            //Create a ItemSchema of Attachments in itemAtt
            ItemAtt.Load(new PropertySet(ItemSchema.Attachments));
            foreach (Attachment scannedAttachment in ItemAtt.Item.Attachments)
            {
                scannedAttachment.Load();
                //Loads all Item Attachments as File Attachments
                FileAttachment fileAttachment = scannedAttachment as FileAttachment;
                if (Regex.IsMatch(fileAttachment.Name, ".pdf|.PDF|.Pdf"))
                {

                }
            }
}


Q:

¿ Cómo ejecutar código si x clip de animación está ejecutándose? Unity

Me gustaría que alguien me ayudase con un problema que me ha surgido trabajando en Unity. Quiero, dentro del código del script, que cuando el personaje esté en cierto Clip, por ejemplo el clip Andar, haga o deje de hacer algo según ciertas condiciones, la cuestión está en como llamar al animador en el "if" para saber si estoy en "Andar", "Saltar" o lo que sea. Es decir si -- if (ani=="Andar") {…} -- . ¿Cómo hay que inicializar el componente Animation para tal fin? Gracias  de antemano.

A:

Si quieres comprobar la animación con su nombre:
anim_Animator.GetCurrentAnimatorStateInfo(0).IsName("Nombre animacion")


Q:

Meaning of ? in Java

ltVal = node.left  != null ? node.left.height  : 0;

I think this is written in Java, can anyone explain what this means? Can't understand this shorthand notation

A:

It is called  ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format
General Syntax :
boolean expression ? value1 : value2

your example:
ltVal = node.left  != null ? node.left.height  : 0;

as same as
  if( node.left != null)
       itVal = node.left.height
  else
       itval = 0;


Q:

A SQL console in QGIS

I know QGIS comes with its field calculator, which is not bad. It also comes with ftools which permits several operations on geometry and attributes. But we often need more control and I haven't seen any convenient tool in QGIS to perform such operations (where you can select fields you need for example or perform arithmetical operations on them while doing a spatial query).
Basically, I'd like to know if a SQL console (a kind of Mapinfo mapbasic window) is on the roadmap of QGIS and if not, if it would be hard to code it as plugin. If it exists yet, please let me know, i've missed it! ;-)

A:

RT Sql Layer plugin can do what you want (but it's not a console).

You can use python console too: 'PostGIS ’select’ statement as vector layer in QGIS'

A:

The new DB Manager plugin is now a standard part of QGIS from 1.8 forward.  It has autocomplete, syntax highlighting, and you can add layers created from a spatial query to your map.
In 1.9 (the development version for 2.0) DB Manager adds import / export functions that are pretty handy.

A:

there is a new plugin available: Fast SQL Layer.
It opens an docked sql console with code highlighting.


Q:

robocode engine: how to design (write) the runtime engine -- the robot world

IBM has (had) a free learn-Java program called RoboCode, in which custom robots could be written that would then do battle in a 2D space.  I would like to write the environment that supports such robots, but don't know what pattern or design to use.  Each robot is a thread.  Each thread is given a certain (indeterminate) amount of run-time by the JRE.  A robot world engine would start by building a list of the players/robots, then enter a loop that allows each player in turn to do whatever it likes: move forward, turn left, fire toward the northwest corner, whatever.  Each robot is also informed of events of interest: an enemy or several enemies are within range, it has been hit by a bullet, etc.
The combination of handling threads that are also event listeners (are they also producers?) confuses me; it seems that there's more to the game engine.  Even some general ideas would help.

A:

I'm Robocode engine developer. I joined 2 years ago and spent most of the time by refactoring Robocode engine. I wrote couple of articles during the time as my understanding grown. Not all of them are up to date, thought.
There are several difficult parts about it:
1) synchronization: we solved it by 'sending' messages between robot and battle. Updating the UI and other components is producer/consumer with non-mutable messages about each new state (game tick)
2) sandboxing malicious code (go and learn from our code)
3) design of API and rules to be constant for long years, because engine evolves, old robots stay same, but they must run and score same way as before. We hit several troubles here, for example people use the classes from API in their own logic. This wasn't intention. We had to make the classes final and with protected constructors. But now we can't change it to not broke existing robots.
For your question about events in Robocode. They all come each tick, we populate EventManager (priority queue) and then robot pulls one by one. Call is dispatched back to robot's implementation for each event. The subscription is automatic, implementation is always present in base class and you could override it in robot class. There is single thread for robot.
BTW: Next big thing seems to be extension of Robocode to allow for custom/plugable rules. It's design challenge. We are looking for smart, hard working people to join Robocode project to help us. Interested ?


Q:

Is there any way I can program stm32f103c8t6 through usb to ttl converter and using keil uvision 5?

I always get noUlink device found error.

A:

Reference Application note:
Please note that, yes it is possible to program the microcontroller using USB to TTL cable you have got.
You need to use ST software on the computer for that which will connect to the MCU through the specific UART interface on the board. The application note gives idea on which UART ports can be used and also about the ST software to be used. This information and Boot Pin configuration setting ( from application note again) should solve it.
Any reason why you have to use keil software only for programming?
If you are planning to debug the code, then you have to have a debugger whether standalone (ST Link, JLink ) or a Nucleo or other ST boards which have a dedicated STLink part in it.


Q:

onClick button add Focus in an input field but that input is invisible

this is my demo:
https://jsfiddle.net/larico/7d3851uf/1/
When click to search icon, the search Field was opened, so then should be focus on input, for writing in the field without clicking in the search field.
I was trying with this code:
$('.search').click(function(){
    $('#gosearch').focus();
});

but seems doesn't work.
how could I solve it,

A:

Since you have a transition you would need to use transitionend:
$('.search').click(function(){
  $(this).toggleClass('opened');
  $('.big-search').toggleClass('displayed').one('transitionend', function(){
     $('#gosearch').click().focus()
  });
});

You can see it here


Q:

Does google consider pdf or doc pages and html pages as a duplicate issue?

Do Pdfs or Docs create a duplicate content when they are compared with the simalar or identical content on your webpages?
I have a language learning website which offers classroom resource materials for teachers. I also want to put an interactive exercise of the same material ( as a demo to see the quality of the exercises) on the same page. As a consequence I'll have a print-out version and the interactive version of the same material on the same page.
Is it a real duplicate issue? Are download resources considered as a separate page or the fact that they are on the same page eliminates this problem?
Thanks,

A:

These are considered as duplicate.
But you can prevent your pdf and docs from being indexed.  You can use robots.txt or x-robots-tag to prevent the PDF files from getting indexed and that way you can solve your problem.
Read more about it here: html and pdf with same content.


Q:

Constants in the Rosenthal inequality

Let $X_1,\ldots,X_n$ be independent with $\mathbf{E}[X_i] = 0$ and $\mathbf{E}[|X_i|^t] < \infty$ for some $t \ge 2$.  Write $X = \sum_{i=1}^n X_i$.  Then we have the family of "Rosenthal-type inequalities":
$$ \mathbf{E}[|X|^t] \le C_1(t)\cdot \left(\sum_{i=1}^n \mathbf{E}[|X_i|^t]\right) + C_2(t)\cdot \left(\sum_{i=1}^n \mathbf{E}[X_i^2]\right)^{t/2} .$$
Henceforth, $c>0$ is some absolute constant.  I have seen in various papers that we can, for example, take $C_1(t) = C_2(t) = (ct/\log(t))^t$.  We can also take $C_1(t) = (ct)^t, C_2(t) = (c\sqrt{t})^t$.  Another option is $C_1(t) = c^t, C_2(t) = c^t\cdot 2^{t^2/4}$.
Is it known whether there is some non-trivial tradeoff curve for the relationship between $C_1(t)$ and $C_2(t)$?  For example, if I'm fine with setting $C_2(t) = (ct^{2/3})^t$, what's the best $C_1(t)$ I can get?

A:

$\newcommand{\de}{\delta}
\newcommand{\De}{\Delta}
\newcommand{\ep}{\varepsilon}
\newcommand{\ga}{\gamma}
\newcommand{\Ga}{\Gamma}
\newcommand{\la}{\lambda}
\newcommand{\Si}{\Sigma}
\newcommand{\thh}{\theta}
\newcommand{\R}{\mathbb{R}}
\newcommand{\X}{\mathcal{X}}
\newcommand{\E}{\operatorname{\mathsf E}}
\newcommand{\PP}{\operatorname{\mathsf P}}
\newcommand{\ii}[1]{\operatorname{\mathsf I}\{#1\}}$
According to Theorems 6.1 and 6.2, the best constants $C_1(t)$ and $C_2(t)$ are given by
\begin{equation}
 C_1(t)=(c\ga)^t,\quad C_2(t)=(c\sqrt\ga\,e^{t/\ga})^t
\end{equation}
for $\ga\in[1,t]$, up to a universal real constant $c>0$.
E.g., if you want $C_2(t) = (ct^{2/3})^t$, solving the equation $(ct^{2/3})^t=(c\sqrt\ga\,e^{t/\ga})^t$, you get $\ga\sim\dfrac{6t}{\ln t}$ as $t\to\infty$, so that you get $C_1(t)=\Big(\dfrac{ct}{\ln t}\Big)^t$ for some (possibly different) universal real constant $c>0$.
Exact versions of Rosenthal-type bounds for $t\in[2,3]\cup[5,\infty)$ are given in
Theorems 1.3 and 1.5; see also Proposition 1.2.


Q:

How to send sugar ORM database to server as a file?

I want to send my sugar orm database to server, I have read send a file in Android from a mobile device to server using http and Location of sqlite database on the device but I don't know how to get the path of my sugar orm db and send it as file, I don't want to send it as json ,just send it as a  file. Can anyone tell me how to send my orm database to server and what is the default path of sugar orm ?

A:

Sugar ORM is based on sqlite, so the path of sugar database is the same as sqllite.
For getting database path you can use:
Context context = this; // for Activity, or Service.
String dbname = "mydb.db";
Path dbpath = context.getDatabasePath(dbname);

The path would be something like:
/data/data/com.me.myapp/databases/mydb.db


Q:

Existence of Zero Divisors in $C(X,\mathbb{R})$

Consider any topological space $X$ and $\mathbb{R}$ be with usual topology. The set of all continuous functions from $X$ to $\mathbb{R}$, denoted by $C(X,\mathbb{R})$, is a commutative ring with unity under pointwise addition and pointwise multiplication. If we consider $X=[0,1]$ with usual topology, then $X$ is connected and $C(X,\mathbb{R})$ is not an integral domain. If $X$ is any set with indiscrete topology, then $X$ is connected and $C(X,\mathbb{R})$ is an integral domain. Again if we take $X$ with at least two different elements and if topology is taken as the discrete topology, then $X$ is disconnected and $C(X,\mathbb{R})$ is not an integral domain. So, from these facts I am unable to guess and prove anything about $C(X,\mathbb{R})$ when $X$ is arbitrary. Can anyone tell me about this fact? Does there exist any iff condition on $X$ to make $C(X,\mathbb{R})$ an integral domain?

A:

The only case when $C(X)$ is a domain is when it is trivial, i.e. there are no nonconstant (real-valued) functions on $X$. Given a nonconstant function, you can manipulate it (by composing with maximum, addition of a constant and multiplication by $-1$) to obtain two continuous functions with disjoint supports. (Edited in according to Pete L. Clark's suggestion: more explicitly, if $f(x)=a<b=f(y)$ and $c=(b-a)/3$,  consider $g_1=\max(0,f-a-2c)$ and $g_2=\max(0,b-f-2c)$. Then $g_1$ is nonzero where $f>b-c$ and $g_2$ is nonzero where $f<a+c$, so $g_1g_2=0$. Drawing a picture might help.)
I don't think there's a concise sufficient condition for that. It is clearly satisfied by the one-point space. It is clearly not satisfied by any nontrivial normal, or even completely regular space. On the other hand, there are many regular spaces with this property. For more information, see this related question, and this relevant paper.


Q:

What is the risk with electronic contract notes in India?

When you sign up for online commodity trading in India (and maybe even equities), if you opt for the convienience of electronic contract note, you are asked to sign a declaration that states:

I am aware of risk involved in dispensing with the physical contract
note, and do hereby take full responsibility for the same

What is the risk of choosing electronic notes over physical ones?

A:

The risk that you don't see it. It might end up in your spam folder, the email server might fail etc. A physical note may have a delivery receipt (courier company's counterfoil or post details) but it's very difficult to ensure delivery with e-contract-notes.
The risk that the note is modified before it gets to you. Physical contract notes are usually printed, and you are likely to notice modifications. E-notes can be changed (many such notes are sent as HTML in a non-encrypted zip file). Many brokers do digitally sign notes nowadays but it is no longer required.

But I think the regulation is a vestige of the past, and has mainly to do with 1) above, i.e. that they can't ensure delivery. There's no standard contract note format, or even a standard delivery mechanism either.


Q:

what does the condition in the following if statement do?

if (read(read(cin, data1), data2))

The question is a exercise of C++ Primer 5th Edition. The function read is define like following:
std::istream &read(std::istream &is, Sales_data &item)
{
    double price = 0;
    is >> item.bookNo >> item.units_sold >> price;
    item.revenue = price * item.units_sold;
    return is;
}

What does the condition in the if statement do? I can't understand this point.

A:

What does the condition in the if statement do? I can't understand
  this point.

You shouldn't ask for solutions of exercises; That diminishes the learning effect. Go through the chapter and the function again and see if you can spot important points.
Perhaps it helps if you write it out a little bit differently:
   std::istream& a = read(cin, data1);
   std::istream& b = read(a  , data2);
   if (b)
        // ...


Q:

Linux C: upon receiving a signal, is it possible to know the PID of the sender?

Suppose my C program handles SIGUSR1. When it receives the signal, is it possible to know who sent it? I.e,. to get the pid of that process?

A:

Yes, if you use the sigaction call to set up your signal handler instead of signal. Doing so will let you set up a signal handler that takes three parameters:

An int, for the signal number (just like signal)
A siginfo_t *, which is a structure containing all sorts of information about the source of the signal, including the pid of the sender if applicable. (It also includes some information about the cause of the signal for automatic signals like SIGSEGV.)
A ucontext_t *, which has to do with which thread got the signal. Mostly ignorable.

A:

Yes. Register your signal handler using sigaction with the SA_SIGINFO flag, filling in the sa_sigaction field. Now your handler function takes a siginfo_t* parameter, which includes a field si_pid.
Note that si_pid is only set under some circumstances. In your case, you'll want to check that check that si_code is set to SI_USER or SI_QUEUE. Read man 2 sigaction for more.

A:

Another option is using signalfd(). If you use signals to send information between processes, then a more structured signal handling than signal handlers is most likely what you want. struct signalfd_siginfo::ssi_pid is the sender.
Example from the man page:
#include <sys/signalfd.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main(int argc, char *argv[]) {
    sigset_t mask;
    int sfd;
    struct signalfd_siginfo fdsi;
    ssize_t s;

    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGQUIT);

    /* Block signals so that they aren't handled
       according to their default dispositions */

    if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1)
        handle_error("sigprocmask");

    sfd = signalfd(-1, &mask, 0);
    if (sfd == -1)
        handle_error("signalfd");

    for (;;) {
        s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo));
        if (s != sizeof(struct signalfd_siginfo))
            handle_error("read");

        if (fdsi.ssi_signo == SIGINT) {
            printf("Got SIGINT\n");
        } else if (fdsi.ssi_signo == SIGQUIT) {
            printf("Got SIGQUIT\n");
            exit(EXIT_SUCCESS);
        } else {
            printf("Read unexpected signal\n");
        }
    }
}

See also: sigqueue(). Like kill(), but you can pass an integer or pointer in the same call.


Q:

How can I check the topic of all channels in a guild?

I'm trying to check the channel topic using the code shown below but it keeps giving me a TypeError: Cannot read property 'includes' of undefined I'd love to have someone help me out. Thanks!
I've tried changing the function and researching the include method but I can't find anything related to discord.js
const guild = message.guild;
      const channel = message.guild.channels;
      function checking(channel) {
          channel.topic.includes(message.author.id)
      }
      const channelOpen = guild.channels.some(checking)
      if(channelOpen === true) return message.channel.send("You already have a ticket open!")```

Check the channel topic for the author of the message's ID and if it finds their ID in a topic, return with a message.

A:

  var count = 0
  message.guild.channels.forEach(i => {
    if(count == 1) return; //If ID is already found.
    if(i.type == 'voice') return; //If it's voice channel, return.
    if(i.topic == message.author.id){ count++; return message.reply('You already have a ticket open!') }
    //If ID is already found, increase the number to stop code from executing and message author about ticket.
  });

What I used:
forEach loop
if statements
channel properties: type, topic
Increment on count, you can ONLY change var and let variables.
More on variables: here.
If I helped you, please mark this as answer so I can get higher reputation. Thanks <3


Q:

Upload failed when I publish Moodle app on google play store?

I get this exception when I publish Moodle app to play sore, how can I fix these errors?

Upload failed You uploaded a debuggable APK.
For security reasons you
need to disable debugging before it can be published in Google Play.
Learn more about debuggable APKs. You uploaded an APK that was signed
in debug mode. You need to sign your APK in release mode. Learn more
about signing. You need to use a different package name because
"com.moodle.moodlemobile" already exists in Google Play.

Thanks

A:

You .apk must be signed so you can publish it on Google Play. For sign your .apk follow the links bellow:
For Cordoba platform: http://ilee.co.uk/Sign-Releases-with-Cordova-Android/
For Ionic platform: http://ionicframework.com/docs/v1/guide/publishing.html


Q:

How do I unhook an lambda event handler inside the lambda method?

So I looked on SO and found how to unhook anonymous event handlers and that is no problem. But the problem I have is how to unhook the event handler inside the instance of the event handler itself.
For example I have a timer:
System.Timers.Timer aTimer = new System.Timers.Timer();
System.Timers.ElapsedEventHandler handler = ((sender, args)
  =>
  {
      //aTimer.Elapsed -= handler;
      wc.CancelAsync();
  });
aTimer.Elapsed += handler;
aTimer.Interval = 100000;
aTimer.Enabled = true;

With the line commented out this works fine. But then I realised there is a possible memory leak as the ElapsedEventHandler is never unhooked. I therefore tried to add the commented out line to my ElapsedEventHanlder to unhook the timer from itself.
But I cannot compile the code because of the error:

Use of unassigned local variable "handler"

Is it possible to unhook the Elapsed event of my Timer when my timer completes?

A:

Split the declration and the assignment of your variable and it will work fine.
System.Timers.ElapsedEventHandler handler = null;

handler = ((sender, args)
  =>
  {
      aTimer.Elapsed -= handler;
      wc.CancelAsync();
  });

The way variable capture works handler will not be null when the event fires, it will be the anonymous delegate.


Q:

Set values of a jQuery collection using array

OK this would return an array of node values
var vals =  $('.items').map(function () { return $(this).val(); }).get();

What's the other way around, what's the setter from an array without the usual iteration including each?
Having an array and set each value to the corresponding node from the collection $('.items') using the api.

A:

Typically you would use the form of val() that takes a function:
$(".items").val(function(index, currentValue) {
    return vals[index];
});

The code above will iterate over the elements matching .items, and set their values to the respective array elements.


Q:

Should the [shooting] tag be burninated (or synonymized with another tag)?

The shooting tag currently has no tag wiki/excerpt.
It's not entirely clear to me what the specific purpose of this tag is that's not covered by existing tags. It seems weirdly specific, and yet vague. Based just on its current use, it seems like it's referring to ranged attacks made with firearms (though "shooting" on its own could potentially refer to attacks with bows and the like as well).
Currently, the tag appears on 2 shadowrun-sr5 questions, 3 questions with the savage-worlds and deadlands-reloaded tags, and 1 question tagged with savage-worlds (with no further specification). Upon further examination, the 4 Savage Worlds questions were all asked by the same user, who seems to have created the tag by virtue of simply adding it to their questions. They haven't been on the site since February 2019 - so it's not like I can just ask them what the tag's meant for.
The fact that the tag's only been used for Savage Worlds and Shadowrun questions doesn't inherently tell me anything about what the tag's about, other than that this one user made the tag (it's totally unclear whether it's a system-specific concept or not), and that 2 querents asking about Shadowrun SR5 just happened to assume based on the name that the tag fit.
The scope of the tag seems to be entirely covered by the ranged-attack tag to me, perhaps in conjunction with the firearms tag where relevant. It's not like we have a tag for "swinging a sword" or something, so it seems strange to have a tag that just refers to a particular kind of ranged attack. This is just an assumption, however.
Should the shooting tag be deleted, or synonymized with one of the above tags?
Alternatively, if the tag shouldn't be removed, when should it be used/what should it be used for?
(Tag wiki/excerpt suggestions are welcome, if suggesting the tag be kept - this would help clarify the focus of the tag and help differentiate it from the existing tags mentioned above.)

A:

I believe we should do nothing with it and leave it be.
Merging it with firearms seems inappropriate. In Fate, when you're using a bow or a slingshot or darts you're also Shooting but you're definitely not using firearms. ranged-combat wouldn't necessarily apply either; just because you're Shooting doesn't mean you're in combat with anyone. I suspect similar stuff is going on for the games already using the tag.
These tags have overlap but not such that shooting is inherently a synonym of either. There's also no specific problem occurring with the tag that calls for us to change things. Let's leave it be.
If/when this does actually cause any kind of problem for Savage Worlds or Shadowrun folks, they can bring up “hey why are we using shooting when we could be using ranged-combat?” or whatever on meta if they'd like to.


Q:

UPDATEs to a specific row in Cassandra appear to go missing

I'm experimenting with a 4-node Cassandra (1.2) cluster which I've just setup on CentOS 6.4 across 4 VMs. First, I created a keyspace with a replication factor of 3 and within it created a couple of tables and populated each one with a small number of rows - all using Cqlsh. Simple INSERTs, SELECTs and UPDATEs appeared to be working fine.
Then I started disconnecting some of the nodes randomly to see the capabilities of the cluster in action. While two of the nodes were offline, I ran a few SELECTs which returned the correct results. Subsequently, I attempted to update an existing row, which according to "nodetool getendpoints" was hosted on the offline nodes as well as on the local node on which Cqlsh was running. After bringing the two nodes back online, running a SELECT against the updated row did not return the updated data values. I waited a little and tried SELECTing again but that still kept returning the original data.
I also tried the following, none of which returned the updated data:

Re-running the UPDATE a few times
UPDATEing a different column in the same row - the field wasn't updated
Restarting all four nodes in the cluster

An UPDATE for the same column in a different row works fine, which along with #2 above leads me to think this is an issue with the row data.
The following snippet shows a SELECT returning the original data before and after a seemingly successful UPDATE:
cqlsh:demo> select email, active from users where email = 'john.doe@bti360.com';

email               | active
--------------------+--------
john.doe@bti360.com |   True

cqlsh:demo> update users set active = false where email = 'john.doe@bti360.com';

cqlsh:demo> select email, active from users where email = 'john.doe@bti360.com';

email               | active
--------------------+--------
john.doe@bti360.com |   True

I am new to Cassandra so I could very well be missing something. Any suggestions or troubleshooting tips (files to check or commands to run) to help uncover what is going on here would be much appreciated.

A:

This could be explained by a clock mismatch between servers.  The timestamp of the updates is set by the server receiving the update from the client.  If the servers are out of sync, you can get behaviour like this where an old update has a later timestamp so overrides subsequent writes.
To find out, firstly check the clocks on the servers.  You should always run NTP between Cassandra servers so the clocks are the same.
You can confirm if this is the actual issue by using WRITETIME to get the timestamp:
select WRITETIME(active) from users where email = 'john.doe@bti360.com';

This is microseconds since the epoch.  Write a value to a different row and get its timestamp.  If that is earlier then this will be the cause.


Q:

ios detect a change in wireless

Is there a notification that is dispatched when a user's device suddenly connects to wifi? Or something of this nature?
I'm wanted a certain selector/method in my app delegate to run whenever a user connects to wireless. How do I know when to perform my selector?
** EDIT **
I ended up finding an IOS 5 ARC friendly version of Reachability if anyone needs it.

A:

You should include the Reachability header and implementation from here.
I did a project a while ago where I needed to check if I was connected to WiFi at certain times. Here's some code that may be useful to you:
- (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return 0;
    }

    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
    return ((isReachable && !needsConnection) && !(nonWiFi)) ? YES : NO;
}

It returns true if connected to WiFi.
One way to detect when a change occurs would be to run an NSTimer and check if the result changes over time. You wouldn't want to run it too often though.


Q:

How to cast an IQueryable to a type List (Of Orders)

I asked a question a few days ago on how to add paging though records to a web page using an index based solution.
I need to be able to change the sort of  the list of orders using two parameters: strSortBy, and strSortDirection.
I am attempting to do it using IQueryable query:
query = temporders.AsQueryable.OrderBy(strSortBy + " " + strSortDirection)

But I am getting an error:
Unable to cast object of type 'System.Linq.EnumerableQuery`1[Order]' to type 'System.Collections.Generic.List`1[Order]'.

Line:
orderList.Items = query

This is my code for the up(next) button:
Dim temporders As System.Collections.Generic.List(Of Order) = orderList.Items

If Not temporders Is Nothing And Not String.IsNullOrEmpty(strSortBy) Then
    Dim query As IQueryable = Nothing
    query = temporders.AsQueryable.OrderBy(strSortBy + " " + strSortDirection)
    orderList.Items = query
End If

What am I doing wrong in the assignment? Any guidance is appreciated.
Thank you.
UPDATE
I change my code so I apply the OrderBy to the oderList.Items instead that to the tempOrders
orderList.Items.AsQueryable.OrderBy(strSortBy + " " + strSortDirection)

UPDATE
I was able to make it work this way:
orderList.Items = orderList.Items.AsQueryable.OrderBy(strSortBy + " " + strSortDirection).ToList

A:

Call ToList to materialize a query as a list:
orderList.Items = query.ToList()

But you seem to be casting, calling, AsQueryable, etc. when it's not clear why.
If orderList.Items is a List (Of Order) then why are you casting it?  If it's not then you may not need to do any casting at all.


Q:

Learning Abstract Algebra for a graduate degree

I would like to do a graduate degree in mathematics, and I have a
full year before I will be able to do so (for personal reasons). I
mainly have my weekends available to study.
I am interested in Abstract Algebra in general, I really liked courses
like groups, rings, field theory/Galois theory etc'.
I have always found analysis to be difficult for me and courses in
the scope of Abstract Algebra felt more natural and intuitive (though
I did have some difficulty with some of the more advanced parts of
those courses).
I was told that other then taking some credit points I will get a
question from the supervisor, one that is not solved yet but seems
at a reasonable difficulty to him, and I will have and I will have
to try and find a solution for it.
I would like to prepare myself, in this year, to have control over
varies subjects in Abstract Algebra so that I will be more likely
to be able to solve such a question (or even understand it, as there
are some subjects in Abstract Algebra that I have not learned in any
of the courses I took as an undergraduate student).
Also, I have lately been aware of some subjects that involve both
analysis and Abstract Algebra, such as topological groups.
I would be happy if I could avoid such topics, but I don't know what
type of mathematics is studied in a graduate degree level, so this
leads me to the following questions:

What topics of Abstract Algebra should I study in depth ? what
topics in Abstract Algebra should I be familiar with their basics
?
Are there any topics in analysis, topology etc' that are likely
to be needed for answering a graduate degree level type of questions
?
What should be the focus of my work, should I try to do many exercises
within the text, or focus on the proofs and the theory ?

I have the book Abstract Algebra by Dummit and Foote to study with,
as well as books in other area of mathematics such as Topology by
Monkers that might help me with this goal.
I would be extremely grateful for hearing opinions and advices on
this matter!
Added:
Note 1: I would like to mention that although I try to avoid analysis,
I still had to take courses in that, so I don't lack elementary knowledge
in many topics, I have taken: Introduction to functional analysis,
Real analysis (measure theory), complex analysis, ODE, Introduction
to numerical analysis, Introduction to probability theory (the course
didn't talk about $\sigma$ algebras and etc' but we did talk about
random variables, CLT, etc').
But I don't consider myself to be good at those topics (except maybe
probability that I really liked), I understand them, but I am about
average at them, so I don't expect that I would be able to do something
non-trivial at those topics.
I would like to extend my questions to include the complement of my
question to what to study for what I shouldn't spend my time on:
4) Are there topics in Abstract Algebra, or other in other areas that
I would need to know (maybe topology ?) that I can skip some parts
of (mainly non-core topics that are hard to learn) since they would
probably not help me (and due to lack of time) ?

A:

I will respond directly to this part of your question.

I would be happy if I could avoid such topics [analysis], but I don't know what type of mathematics is studied in a graduate degree level, so this leads me to the following questions:

What topics of Abstract Algebra should I study in depth ? what topics in Abstract Algebra should I be familiar with their basics ?

Are there any topics in analysis, topology etc' that are likely to be needed for answering a graduate degree level type of questions ?

What should be the focus of my work, should I try to do many exercises within the text, or focus on the proofs and the theory ?

Are there topics in Abstract Algebra, or other in other areas that I would need to know (maybe topology ?) that I can skip some parts of (mainly non-core topics that are hard to learn) since they would probably not help me (and due to lack of time) ?
I have the book Abstract Algebra by Dummit and Foote to study with, as well as books in other area of mathematics such as Topology by Monkers that might help me with this goal.

Firstly, I want to mention that unless you are absolutely certain that you are going to specialize in pure group or ring theory, then you will need some analysis. In fact, you'll probably need a lot of analysis. Explaining why is a bit more complicated. The short version is that almost every area of math relies or is at least informed by analysis, algebra, and topology; this is why most graduate programs (in the US anyway) require these as either graduate classes or graduate entrance exams or graduate qualification tests, etc.
To expand in a slightly longer way - calculus is pretty interesting, and lets you do a lot of things. A common thing that mathematicians do is put measures on weirder spaces so that you can have some variant of integration. In number theory (even algebraic number theory, which is often the same thing as algebraic geometry, which is often the same thing as commutative algebra, which is just algebra and group theory), we really like having measures called Haar measures on matrix groups, like the $GL(n), SL(n), Symp(n)$, etc. This lets us do integration on these groups. So we study functions invariant under actions of these groups, or functions invariant on certain cosets of these groups that behave nicely under ring translation, or some similar idea. And one way we do this is to integrate them, or consider an integral over a weighted average of a function across the cosets our function is invariant over (read: Eisenstein Series for example), to extract largely algebraic information about number fields. Or we consider representations (as in representation theory, which I clump into the larger algebra domain sometimes) and analytic extensions of representations. Everything I've mentioned here requires a certain comfort with topology, analysis, and algebra.
This is to say that algebra mixes quite a bit with analysis in many ways. You would really benefit from having a good understanding of analysis and topology. In particular, don't focus solely on algebra. The other answer says this a little, but I am going to emphasize this a lot. It is very important to understand analysis and topology, unless you are going do limit yourself to pure, remote group theory. And even then, I wouldn't recommend it.
But back to your question at hand about algebra:
I would prescribe a path into algebra. In a comment on the other answer, you mention that you know groups, ring, fields, Galois theory. Cool! You also say you have Dummit and Foote (by far my preferred introduction to group and ring theory). Then I suggest two paths:

Go learn more about whatever parts you liked most. Sylow theorems interest you? Try to learn your way through Burnside's theorem. You like Galois theory? Pick up some infinite-dimensional Galois theory and try your hand. Maybe you already know that? Go pick up some algebraic number theory text - as an intro algebraic number theory text builds nicely on basic field theory and Galois theory, and suggests further paths. To be fair, I'm biased - I'm a number theorist. The important thing is that you go and dig deeper into things that interest you.

Pick up Atiyah and MacDonald's Commutative Algebra (hopefully from a library, as they're proud), and do your best at all the exercises. This is the 'natural' extension of what to do next, and it's the real path into a serious interest into algebra in my opinion. I say that you should do all the exercises because this book is famous for having really important lemmas and theorems in the exercises as opposed to the exposition. This will also really set your group theory and ring theory in stone, and you have Dummit and Foote to fall back on if you need. If you know this already, you should next go to Lang's Algebra (quite a bit, scary thing - take a look at it first), Matsumura's Commutative Ring Theory (much, much, much higher than Atiyah MacDonald, even though they have essentially the same name), or Eisenbud's Commutative Algebra (also harder than Atiyah MacDonald, but designed for people interested in algebraic geometry - if you don't know what that is, look it up).

I'd like to add one more thing about your (3) - the problem with learning the proofs and theory is that there is no reason for them to stick on their own. You might open up Atiyah MacDonald and understand everything you read, for example. But I wouldn't expect much of it to last, unless you use it. So a good general philosophy is to read and try to absorb, but then do exercises to let it solidify. Well written exercises require you to build on the text, both as a review and to build intuition.
A hard problem is knowing how many exercises to do. Too many, you waste your time. Too few, you'll forget much. But this is sort of moot, as it's hard to know what problems are useful or good to do before you actually do them, and in some texts some problems are much much better for you than others. For this, I advise you to ask your advisor (or find someone who can provide some sort of guidance) for direction once you have an idea what sort of things you want to learn about.

A:

Here are my thoughts on your questions - they are, of course, limited by my own knowledge, so take this with a pinch of salt :

Groups, Rings and Fields (leading up to Galois theory) form the core of abstract algebra that is taught to almost everyone in graduate school. Depending on your background, I would recommend Herstein's Topics in Algebra. Start with group theory (Lagrange's theorem, Group actions, Sylow's theorems), then do some ring theory (focussing on polynomial rings), and finally start reading about field extensions. Get a solid grounding in group theory though.
Don't avoid Analysis and Topology. You might not enjoy it initially, but a lot of interesting mathematics happens when these different worlds collide (for instance, in functional analysis), and not knowing one would prevent you from appreciating this.
Focus on problems and examples. Do as many as you can, and use the theorems as black boxes until you have analysed the examples enough to appreciate the proofs. Then go back and learn the proofs (and more importantly, those techniques that show up again and again)


Q:

How to print all the contiguous subarray of the array

I was working on some algorithm and I wanted to find the contiguous subarray of the array.
For example, if my input array is as below,
vector<int> nums = {1, 2, 2, 3, 1}

I want to get the ouput vector as below,
vector<vector<int>> output;
//Output should contain {1, 2, 2, 3, 1}, {1, 2, 2, 3}, {2, 2, 3, 1},
//{1, 2, 2}, {2, 2, 3}, {2, 3, 1},{1, 2}, {2, 2},
//{2, 3}, {3, 1}, {1}, {2}, {2}, {3}, {1}

A:

I just figured out the algorithm, it is shown as below,
vector<vector<int>> Solution::sliceArray(vector<int> vect)
{
  vector< vector<int> > listOfVect;
  for (size_t i = 0; i < vect.size(); i++)
  {
    for (size_t j = 0; j <= i; j++)
    {
      vector<int>  indVect(vect.size() -i );
      copy(vect.begin() + j , vect.end() - i + j , indVect.begin());
      listOfVect.push_back(indVect);
    }
  }
  return listOfVect;
}


Q:

c++ template check type validation

for example,
enum tr {z, u};

template<tr T>
class test
{
      assert(T is z or u);//how can I add assertions in this field?
};

in the comment how can I add code to assert the template T should only be z or u?

A:

This can be done using static_assert as @πάντα-ῥεῖ already pointed out:
enum tr {z, u, bar};

template<tr T>
class test
{
      static_assert(T==z||T==u, "T must be z or u");
};

int main()
{
    test<z> t_valid;
    test<bar> t_fails; // compilation fails
    return 0;
}

live on ideone


Q:

Can padding length, and thus plaintext length, be considered public information when using aes-cbc?

Right now I'm using a simple padding system that takes the plaintext, hashes it with SHA512, and appends $x$ bytes of the hash as padding where $x$ is the delta between the plaintext and nearest blocksize multiple.
Is this considered a secure method of padding the message? I am also authenticating the encrypted data using HMAC-SHA512, would this effect the security?

A:

For AES CBC i would suggest you stick to the standards.
The PKCS7 padding scheme is pretty easy to implement and has been tested extensively now that its been out in the public for a while. I had implemented PKCS7 padding for my AES CBC cipher a few weeks ago and you can see the code here if it helps.
Note that hashing by itself does not provide you with authentication, you will need a MAC (Message Authentication Code) for that. If you like using the SHA family, you can use something like HMAC-SHA256.
Is there any particular reason why you wish to use hashed data as a pad? If you are looking for authenticated encryption, you should stick to the standards like GCM for AES.

A:

The size of the padding could be made public, if you don't mind leaking some additional information about the plaintext size. Using a hash as padding bytes however does not make sense; you can not use the hash as authentication tag or to check the integrity, so the hash calculation becomes spurious. It may even leak data through a side channel. In the best case it simply eats CPU resources without accomplishing anything.
It is better to use a vetted padding method such as PKCS#7 or bit padding. They may use a block of ciphertext more, but otherwise the implementation light on resources. Both padding methods are however vulnerable to padding oracle attacks. So you should generate a MAC or HMAC (using a second key) over the ciphertext. You should include all public information in the MAC calculation as well.
Alternatively you could use zero byte padding and a padding or plain text length indicator byte as this may save you a block of bytes to encrypt. In that case you should definitely include the length indicator in the MAC calculation as an attacker could otherwise fool you into adding or removing bytes from the plain text by simply changing the length indicator.
Finally you could of course use a block cipher in counter mode, possibly using an authenticated scheme such as GCM. This would rid you of padding altogether (the plaintext size is the ciphertext size) and would generate a message authentication tag without having to resort to two separate keys. As in the MAC calculation you should include all public data as additional authenticated data (AAD). Furthermore, you should be sure never to repeat the nonce/IV. You would not need a separate nonce and IV either.


Q:

How to guarantee that player fits rooms of a cave created by Cellular Automata?

I've implemented a cellular automata algorithm to generate a cave for my game and now I need my player object, which occupies 3x3 tiles in total, to be able to pass between the rooms.
The problem is that some of the rooms automatically created by cellular automata do not have the necessary width/height for the object to pass (example: a 2 x 3 tiles corridor).
How can I transform the result from the cellular automata so that I guarantee that the player is able to pass in any of the rooms? The idea is that this can be done in real time so that I can do an endless game.
This was done in GDScript but any examples in any other language, like C# for Unity, are welcome.
Update
As said in the comments, I could make a map where each cell would correspond to a 3x3 on the final map but, my problem is that I need the 1x1 tiles because my player should lose a life when hitting the walls (and that way I can create some kind of "spikes" based on the walls).
Given that, how can I add 1x1 tiles to the map created from the 3x3 and still guarantee that the player fits the cave's "corridors"?
Update 2
The only rules I currently have for CA are:

If total neighbour walls > 4, the cell becomes a wall
If total neighbour walls < 4, the cell becomes empty
Else, remains as it is

The total number of iterations for the CA is 2
Solution
I was able to do this the way that DMGregory said:

First I run the CA after building the map as I did before in order to add the "empty space adjacent to wall" cells (now on called EmptyNextToWall) to the map
Then I run the CA with the following rules, until none of them are verified (it did not pass 5 iterations on my scenarios):

If my current cell is EmptyNextToWall and has more than 4 EmptyNextToWall adjacent to it, make it an Empty cell
If my current cell is EmptyNextToWall and the adjacent diagonals are a Wall and a EmptyNextToWall, make it an Empty cell
If my current cell is EmptyNextToWall and there's no Empty cells around it, make it an Empty cell
If my current cell is a Wall and there's at least one adjacent Empty cell, make it an EmptyNextToWall
If my current cell is EmptyNextToWall and there's no adjacent Walls, make it an Empty cell

A:

A (binary) cellular automaton can't "see" features larger than its kernel size / neighborhood.
If we consider the case of "a passage too small for a 3x3 character to fit," that could be a wall, followed by two open spaces, then another wall — ie. it's a feature that's 4 tiles wide.
So if you're using a cellular automaton with a 3x3 kernel / neighborhood, then your cell update logic can't detect the difference between this case and a wall next to unlimited open space. It can't see all the way from one wall to the opposite wall over a 2+ tile gap to know that it's too narrow and choose to fill it in / carve it wider as a result.
So, one option is to widen your kernel. A 5x5 kernel will let you detect passages 3 tiles wide with a wall on either side, and carve out/fill in spaces narrower than this.
The downside is that the automaton gets a little more complex: needing more rules to handle the greater set of variations in its neighbourhood, and more taps/samples per cell to evaluate the next state.

Another potential option is to move beyond the binary, by adding more cell values. Then each cell could store one of:

0: "wall"
1: "empty space adjacent to wall"
2: "empty space touching only empty space"

This is effectively a simplified distance field. The 2 values form a mask of locations your 3x3 character's center point could occupy as it navigates the map, and the 1 values form a "shoulder" outlining the walls.
Now even a CA with a 3x3 neighborhood can detect the difference between a 3-wide passage:
[ 0   1   2 ] 1   0
  0 [ 1   2   1 ] 0
  0   1 [ 2   1   0 ]

and a 2-wide passage:
[ 0   1   1 ] 0   0
  0 [ 1   1   0 ] 0
  0   1 [ 1   0   0 ]

(Here using square brackets to denote the left & right edge of the kernel as it scans across a feature)
Again the trade-off here is complexity: your cell storage needs more bits, and your cellular automaton rules need more cases to handle the various permutations of open cells adjacent/not adjacent to walls. You also need to ensure your rules maintain (or eventually re-establish) the invariant that no 2s are found adjacent to a 0.


Q:

If a base goes without power long enough will all my plants/fish die?

I'm new to Subnautica, and have just started building deeper bases powered by bioreactors. This is working well, but every time I dive down to the base I am scared that; the power went out, all my plants died, and I won't have enough air to double back up to the surface. Occasionally power was out when I arrived and my plants didn't die. I don't know if that is because I got there quickly enough, or if my plants simply won't die.
Right now I'm fueling my bioreactor with marblemelons. In the future I hope to transition to using fish when I get the alien containment tank. As such I'd like an answer that applies to food like marblemelons, and fish in an alien containment tank/aquarium.

A:

Plants and the aquariums do not require power.  They therefore will be fine should the power cut out.
Plants don't require oxygen to survive, and fish inside the aquarium do not need oxygen either. So even if the base ran completely out of oxygen, they will be fine.


Q:

Dar baixa no estoque com Triggers SQL

comecei a fazer um curso sobre SQL e estou em duvida em relação aos triggers
esta é a tabela
create table Produto (
    codProduto int primary key identity(1,1),
    Nome varchar(50),
    Quantidade int,
    Preco smallmoney
);
create table ItemVenda (
    codVenda int identity(1,1),
    foreign key (codProduto) references Produto(codProduto),
    codProduto int primary key,
    Quantidade int
);

preciso fazer um trigger para que após eu dar insert na tabela venda produto seja debitada a quantidade inserida na tabela produto, como eu poderia fazer isso?

A:

Na maioria dos casos o ideal é não guardar atributos de cálculo nas tabelas, porém se você quiser fazer uma TRIGGER para isso, ficaria da seguinte forma:
IF OBJECT_ID('tgr_itemvenda_ai', 'TR') IS NULL
BEGIN
  EXEC('CREATE TRIGGER tgr_itemvenda_ai ON ItemVenda FOR INSERT AS BEGIN SELECT 1 END');
END;
GO

ALTER TRIGGER tgr_itemvenda_ai
ON ItemContrato
FOR INSERT
AS
BEGIN
  SET NOCOUNT ON;

  UPDATE p
     SET p.Quantidade = p.Quantidade - i.Quantidade
    FROM Produto p
         INNER JOIN inserted i ON i.codProduto = p.codProduto;
END;
GO

A sugestão que te dou para não ter necessidade de usar TRIGGER é utilizar uma tabela estoque em que você realize o fechamento mensalmente ou conforme a sua necessidade:
CREATE TABLE Estoque(
  codEstoque INT  PRIMARY KEY IDENTITY(1, 1),
  codProduto INT  NOT NULL,
  Quantidade INT  NOT NULL,
  Inicio     DATE NOT NULL,
  Fim        DATE NOT NULL,
  CONSTRAINT fk_EstoqueProduto FOREIGN KEY(codProduto) REFERENCES Produto
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

Considerando que você tenha uma coluna data na tabela Venda:
SELECT e.codProduto,
       CONVERT(VARCHAR(10), e.Inicio, 103) AS Inicio,
       CONVERT(VARCHAR(10), e.Fim, 103) AS Fim,
       e.Quantidade - SUM(iv.Quantidade) AS disponivelFim
  FROM Estoque e
       INNER JOIN ItemVenda iv ON iv.codProduto = e.codProduto
       INNER JOIN Venda v ON v.codVenda = iv.codVenda
 WHERE v.data BETWEEN e.Inicio AND e.Fim
 GROUP BY e.codEstoque,
          e.codProduto,
          e.Inicio,
          e.Fim,
          e.Quantidade


Q:

rotate UIImageView around an arbitrary point

I have a UIImageView that I rotate around its center:
imageHorizon.layer.anchorPoint = CGPointMake(0.5, 0.5);
imageHorizon.transform = CGAffineTransformRotate(imageHorizon.transform, angleToRotate*(CGFloat)(M_PI/180));

Sometimes I also move this image to the left or right and then rotate again. I would like to keep the rotation center all the time on the same point (which is actually the center of the super view). How can I do that ?
cheers,

A:

self.imgView.layer.anchorPoint = CGPointMake(0.0,1.0);
self.imgView.layer.position = CGPointMake(100,200.0);
CGAffineTransform cgaRotateHr = CGAffineTransformMakeRotation(-(3.141/4));
[self.imgView setTransform:cgaRotateHr];

A:

This is an older question, but the other solutions did not work well for me, so I came up with another solution:
Rotating an image is essentially just a normal rotation with a translation applied, ensuring that the point you want to rotate around is still in the same spot after the rotation.  To do this, calculate the position's CGPoint in your image before the rotation, get the position after the rotation, and apply the difference as a translation on the image, "snapping" it into the right position.  Here is the code that I've been using:
Keep in mind that the translation should be applied via CGAffineTransform, not moving the .center, because the translation will need to be relative to the rotation, and CGAffineTransformTranslate() takes care of that.
// Note: self is the superview of _imageView

// Get the rotation point
CGPoint rotationPointInSelf = self.center; // or whatever point you want to rotate around
CGPoint rotationPointInImage = [_imageView convertPoint:rotationPointInSelf fromView:self];

// Rotate the image
_imageView.transform = CGAffineTransformRotate(_imageView.transform, angle);

// Get the new location of the rotation point
CGPoint newRotationPointInImage = [_imageView convertPoint:rotationPointInSelf fromView:self];

// Calculate the difference between the point's old position and its new one
CGPoint translation = CGPointMake(rotationPointInImage.x - newRotationPointInImage.x, rotationPointInImage.y - newRotationPointInImage.y);

// Move the image so the point is back in it's old location
_imageView.transform = CGAffineTransformTranslate(_imageView.transform, -translation.x, -translation.y);

A:

You can make the image a subview of another view and then rotate the superview to get that effect. Another approach is to set the anchorPoint property as described in the docs.


Q:

Very long 'Unique ID' in Windows 2008 DHCP Server Leases - why? What is the device?

I notice on one Windows 2008 R2 DHCP server the device with the first IP in the range has a strange looking Unique ID of the format

636333652e356639322e326262332d445c458e41258s23148914e1554654566661636531

And the DNS name HP.domain.local
See screenshot.  Does anyone know what this is and why it doesn't show a standard MAC for the unique ID?

A:

Split the string in pairs and convert hex to ascii, you will get cc3e.5f92.2bb3-Vlan-interface1, it is most probably one of your HP switches registering.


Q:

Beginner Microsoft power point one picture at a time

Hi I am doing a presentation and wanted to know how I could display one picture at a time on each slide because right now if I click a slide it displays all the pictures at once. I want to display each picture by itself so I can talk about it .
Thank you

A:

Select the picture and add an animation (Animation Ribbon).
Make sure the Animation Pane is displaying.
Select the next picture and add an animation.
Now use the drop-down for the second picture on the animation pane and set the animation to "Start on Click".

Repeat steps 3 and 4 for each picture or element you want to show. If you set the animation to "Appear with previous" you can make more than one element appear with one click.


Q:

Does Allah have emotions?

Somewhere I've heard, that emotions are transient things, but Allah is ethernal. And thus, Allah can't have emotions. It deeply surprised me, because I think, the only reason for the supreme being to create the world is the love. He doesn't need us, we can't give Him anything which he would need.
Thus, the only reason for Him to create us, is that He loves us. If you have a million of dollars, there is no problem for you to give a cent (or even much more) to a poor man.
But these are only my speculations.
Do the Quran mentions anything about Allah's emotions?

A:

If you call the possessing of the following qualities - Mercy, Love, Anger as emotions, then YES, Allah has emotions. As they're described in Qur'an in many places.
If you ask Does Allah has emotions like us,
then I would say NO, because comparing ourselves with Allah is highly not advisable, but still to answer, we might call ourselves possessing these qualities too i.e. Mercy, Love, Anger, but we won't be expressing them perfectly or always whenever necessary. But Allah's way of expressing emotions remains constant towards a person or creation of his if that person/creation meets the necessary conditions.
May the creator guide us all.


Q:

Twitter Rest APIのアクセストークンの再取得は必要でしょうか？

OAuth認証の時にGETで取得したアクセストークンに必要な情報を使いまわしたいと考えています。
一度認証を行うと、「oauth_token」と「oauth_verifier」をGETで取得することができ、
その値を元にアクセストークンを取得して、ユーザー情報を取得できます。
そのため、一度取得した「oauth_token」と「oauth_verifier」をSessionに保存して、
自動投稿するページ毎にその値でユーザー情報を取得して、tweetを行いたいです。
例えば、サービス無いでツイート内容を選べて、かつ、複数回ツイート出来るようにしたい場合、
毎回認証を挟まずに済むのであれば、アクセストークンの取得を最初のOAuth認証だけで集約できるので効率的です。
しかし、実際に実装すると、sessionに保存した情報ではアクセストークンが取得できません。
Twitterでは、投稿毎に、毎回OAuth認証をでコールバックさせる事が必要なのでしょうか？
その都度、Twitterでアプリケーションの連携画面を出さないようにすることはできないのでしょうか？

A:

（どのラッパーライブラリ等を利用されているのかは知りませんが、）
oauth_tokenはアクセストークン取得のためのワンタイムトークンになります。（ので当然再利用はできませんし、アクセストークンを取得したら破棄しましょう）
一度アクセストークンの取得までたどり着けたら、そこでセッションに持つべきなのはアクセストークン（およびそれのペアのsecret）です。


Q:

Deciding what columns to use for partitioning

I am having trouble deciding what fields of my table to base the partition. Currently there are a total of 8 indexes on the table out of a total of 14 columns. The problem is the indexes are taking up too much space 2 to 1 compared to the data and we need to reduce the size of the DB, and at least maintain current speed. 3 of the indexes have a significantly lower cardinality (in the teens) than the rest (in the millions). There are over 40 million rows in the table.
The index data type looks something like this:
datetime
smallint(6) (low cardinality)
varchar(20) (low cardinality)
int(15)
int(15)
varchar(100)
varchar30
char(1) (low cardinality)

and a few others. All the indexes are non unique and of type BTREE.
I created a test table and removed the indexes with the lowest cardinality but the queries take a bit longer. I'd like suggestions on two aspects:

What indexes should be kept and, which should be removed.
What columns should my partitioning be based on.

The table definition:
Create Table: CREATE TABLE `mytable` (
  `date` datetime DEFAULT NULL,
  `time` smallint(6) DEFAULT NULL,
  `source` varchar(20) DEFAULT NULL,
  `b` int(15) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `ttype` char(1) DEFAULT NULL,
  `ag` char(1) DEFAULT NULL,
  `direction` char(1) DEFAULT NULL,
  `mode` char(1) DEFAULT NULL,
  `username` varchar(30) DEFAULT NULL,
  `name` varchar(15) DEFAULT NULL,
  `authentication` char(1) DEFAULT NULL,
  `authenticated_id` varchar(75) DEFAULT NULL,
  `status` char(1) DEFAULT NULL,
  KEY `date` (`date`),
  KEY `time` (`time`),
  KEY `b` (`b`),
  KEY `name` (`name`),
  KEY `username` (`username`),
  KEY `source` (`source`),
  KEY `b2` (`b`),
  KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

A:

Always have an explicit PRIMARY KEY for any InnoDB table.  If practical, use a "natural" key -- a column, or combination of columns, that is unique.  Otherwise, add an AUTO_INCREMENT.
Learn about "composite indexes" -- this is using more than one column in an index.  It is often a good optimization.  It is not the same as having an index on each column.
It is OK for the indexes to take up more space than the data.  A quick survey showed 1/4 of my tables have that.  Having good indexes improves performance far more than the bulkiness hurts performance.
Each Index is updated for each row INSERTed, so having too many indexes hurts INSERTs (some).
You mentioned partitioning; did you mean "PARTITION BY ..."?  Don't do it unless you have a particular purpose.  I know of only 4 use cases; see my blog.
Do not bother to index low-cardinality columns (flags, enums, etc).  They won't be used.  If you have a status flag that is 10/90, then an index on just that column would be used for the 10, but not for the 90.  A composite index starting with that column may be always useful when all the columns (in the index) are in the WHERE clause.
The most important performance setting for InnoDB is to set innodb_buffer_pool_size to about 70% of available RAM.
It is usually a bad idea split DATE and TIME into two fields.  Look at how messy your SELECTs have to be.
How to create good indexes: http://mysql.rjweb.org/doc.php/index_cookbook_mysql
Show us some of the SELECTs; we can advise further.


Q:

Create helpers function for displaying validation errors

To display validation errors after input field I using:

    {!! Html::decode(Form::label('first_name','First Name:*',['class'=>'control-label col-sm-3'])) !!}

        {!! Form::text('first_name',null,['class'=>'form-control']) !!}
        @if ($errors->has('first_name'))

                {{ $errors->first('first_name') }}

        @endif

    {!! Html::decode(Form::label('last_name','Last Name:*',['class'=>'control-label col-sm-3'])) !!}

        {!! Form::text('last_name',null,['class'=>'form-control']) !!}
        @if ($errors->has('last_name'))

                {{ $errors->first('last_name') }}

        @endif

// and so on......

This code works perfectly. But I have to write almost same code in every single input box. So, I planned to make a global function to display errors. To achieve this I did the following.

Create a helpers.php inside app folder
Write the following code:
function isError($name){
    if($errors->has($name)){
        return ''.$errors->first($name).'';
    }
}

run composer dump-autoload
Used it in blade file this way:

    {!! Html::decode(Form::label('first_name','First Name:*',['class'=>'control-label col-sm-3'])) !!}

        {!! Form::text('first_name',null,['class'=>'form-control']) !!}
        {{ isError('first_name') }}

    {!! Html::decode(Form::label('last_name','Last Name:*',['class'=>'control-label col-sm-3'])) !!}

        {!! Form::text('last_name',null,['class'=>'form-control']) !!}
        {{ isError('last_name') }}

Now, when I go to create.blade.php I have an error

Undefined variable: errors (View: D:\xampp\htdocs\hms\resources\views\guest\create.blade.php)

I know the problem is in helpers.php because I didn't defined the $errors, I just paste that code from blade file.

A:

The problem is that the $errors variable is undefined within the scope of your helper method.
This can be easily solved by passing the $errors object to the isError() helper method.
Helper
function isError($errors, $name){
    if($errors->has($name)){
        return ''.$errors->first($name).'';
    }
}

Blade Template
{!! isError($errors, 'first_name') !!}


Q:

Knapsack with one additional constraint

This is the old and famous knapsack problem : Knapsack Problem
Here I have Knapsack problem with one constraint.
I have Knapsack with size W = 100000000 and N = 100 items I  wrote the dynamic solution for it the Complexity of my algorithm is  O(100000000*100) and this is too big in both time and space but there is one condition here that either W ≤ 50000 or max 1≤ i ≤ n Vi ≤ 500. so  if my Knapsack size is more than 50000 my maximum value of items is limited.
So now I wonder how can I reduce the time Complexity of my algorithm with this condition I thought Knapsack problem depends on the size of knapsack and the number of items so how the value of items can change the change  my algorithm?

A:

Instead of creating a table of size W*n, where each entry D[x][i] indicates the best value (highest) you can get with at most x weight using the first i items, use the table where now D[x][i] is the minimal weight needed to get to value of x, using the first i elements:
D(0,i) = 0                i>0
D(x,0) = infinity         x > 0
D(x,i) = infinity         x<0 or i<0
D(x,i) = min{ D(x,i-1), D(x-value[i],i-1) + weight[i])

When you are done, find max{ x | D(x,n) <= W) } - this is the highest value you can get, using at most W weight, and is done by a linear scan of the last line of the DP matrix.
Checking which variation you need is done by a single scan of the data.


Q:

R - Plotting two variables as lines on ggplot 2

I am trying to plot this data frame on one line graph (with points) using ggplot2, i have managed it on excel easy enough but i would like to generate it in R.
Wakatobi <- read.table("Wakatobi SST.txt", header=T)
Wakatobi

A:

You need to first melt your data using reshape.
df <- data.frame(Month = c("Jan", "Feb", "Mar", "Apr"),
                 Var1 = rnorm(4),
                 Var2 = rnorm(4) + 1)

df2 <- melt(df, id.vars="Month", measure.vars=c("Var1", "Var2"))

ggplot(df2, aes(x=Month, y=value, group=variable, color=variable)) + geom_point() + geom_line()


Q:

To discover and pair Bluetooth Devices

How to discover and pair Android Bluetooth devices using Java? Any codes for me to refer to?

A:

the following code will discover the list of paired and the unpaired devices after that u have to implement the Client and server, which takes care of pairing the devices and sending data to the devices, for tat u can make use of the BluetoothChatSample which will give an idea to u.
private Set<BluetoothDevice> pairedDevices;
public static ArrayList<Object> BondedDeviceList;
public static ArrayList<Object> NewDeviceList;

 public void makeDiscoverable()
{
    discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    activity.startActivity(discoverableIntent);
}

//It will Add the paired device in the BondedDeviceList
public void queryPairedDevice(){
    pairedDevices = mBluetoothAdapter.getBondedDevices();

    // If there are paired devices
    if(pairedDevices==null)
    {
        //No Bonded Devices

    }else
    {
        if (pairedDevices.size() > 0) {
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                BondedDeviceList.add(device);
            }
            BondedDeviceList.add("End");
        }
    }
}

//Broadcast Receiver will find the Available devices and the discovery finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action.trim())) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                NewDeviceList.add(device);
            }
            // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            if (NewDeviceList.isEmpty() == true) {
                String noDevices = "No Devices";
                NewDeviceList.add(noDevices);
            }
            System.out.println("Discovery Finished!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            NewDeviceList.add("End");
        }
    }
};

//This is query for the bluetooth devices
public void queryDevices(){
    actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    activity.registerReceiver(mReceiver, actionFoundFilter);
    // Don't forget to unregister during onDestroy

    discoveryFinishedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    activity.registerReceiver(mReceiver, discoveryFinishedFilter);
    // Don't forget to unregister during onDestroy
    queryPairedDevice();
    mBluetoothAdapter.startDiscovery();
}

//Unregister the receivers
public void unregisterReceiver() {
    // Make sure we're not doing discovery anymore
    if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
    }
    // Unregister broadcast listeners
    activity.unregisterReceiver(mReceiver);
}

Cheers.