Q:

Returning multiple values from a method in Objective-C

I asked a similar question, but I couldn't get it working exactly. I'm building an iPhone app, and there is a method that I want called from different files. I figured the easiest way would simply be to make a method in another file, and call the method from the other files.
Here are some problems. I need to return multiple values from the method, after passing it multiple values. For example, I'm passing it: (int, int, int, string, string).  And it needs to return all of those values, after they have been changed. Someone showed me this code:
- (NSDictionary *)EndOfTurn:(int)varTurns withFatness:(int)varFatness
{
    varTurns--;

    if (varTurns <= 0) {
        varFatness = varFatness - 5;
    }
    else {
        varFatness += 2;
    }

    return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:varFatness], @"FATNESS", [NSNumber numberWithInt:varTurns], @"TURNS", nil];

}

However, this code doesn't work, and I need some more information to really understand it.  Let's assuming I'm passing it these values:
int varMoney;
int varNumSheep;
int varNumShepherds;
NSString *test1;
NSString *test2;

So I need to get all of these values back from the method.
How do I declare this in the header file?  This should be in an Objective-C file, but could you give me the code for the entire file so I can see where it would go with the @implementation and @end, whatnot.  Also, how would I call this method?

A:

What about passing in the values as pointers?
For example:
- (void) getValuesForInt:(int *)int1 anotherInt:(int *)int2 aBool:(BOOL *)bool1 anotherBool:(BOOL *)bool2 {
  if (*int1 == 42 && *int2 == 0) {
    *int1 = 0;
    *int2 = 42;
  }
  if (*bool1 == NO) {
    *bool2 = YES;
  }
}

Then you can invoke it like:
int int1 = 42;
int int2 = 0;
BOOL bool1 = NO;
BOOL bool2 = NO;
[self getValuesForInt:&int1 anotherInt:&int2 aBool:&bool1 anotherBool:&bool2];
NSLog(@"int1: %d int2: %d bool1: %d bool2: %d", int1, int2, bool1, bool2);
//prints "int1: 0 int2: 42 bool1: 0 bool2: 1"

Edit:
This works equally well with objects.  You'll often see this used when dealing with NSError objects:
NSError *error = nil;
[anObject doSomething:foo error:&error];

Can be implemented as:
- (void) doSomething:(id)terrible error:(NSError **)error {
  if ([terrible isEqual:reallyBad]) {
    if (error != nil) { *error = [NSError errorWithDomain:@"domain" code:42 userInfo:nil]; }
  }
}

A:

You can use a block closure to pass back multiple values from a method like this. -rrh
[self heyFunctionGiveMeBackTwoValuesFromThisFruitArray:@[@"apple", @"orange", @"banana", @"apple"] findThisFruit:@"apple" closureFunction:^(int fruitCount, NSString* fruitString)
{
    NSLog(@"Two values returned, int-fruitCount:%d, NSString-fruiteString:%@", fruitCount, fruitString);
}];

- (void)heyFunctionGiveMeBackTwoValuesFromThisFruitArray:(NSArray*)fruitsArray findThisFruit:(NSString*)findThisFruit closureFunction:(void (^)(int fruitCount, NSString *fruitString))passBackResultsUsingThisClosure
{
    NSInteger fruitsFound = 0;
    NSString* fruitsMessage = [NSString stringWithFormat:@"No %@ Found", findThisFruit];
    for (NSString* string in fruitsArray)
    {
        if ([string compare:findThisFruit] == NSOrderedSame)
        {
            fruitsFound++;
        }
    }
    if (fruitsFound > 0)
    {
        fruitsMessage = [NSString stringWithFormat:@"You have %@ on your list this many times:%d", findThisFruit, fruitsFound];
    }
    passBackResultsUsingThisClosure(fruitsFound, fruitsMessage);
}

Results:
Two values returned, int-fruitCount:2, NSString-fruiteString:You have apple on your list this many times:2

A:

Since you can only return a single value from any method in C and C-derived languages, you simply need to return a single value that represents all of your other values. This is what your sample code is doing with an NSDictionary.
The sample code is correct, even if it's a bit contrary to common Objective-C style.
What you declare in the header file is simply the declaration of the method, that is:
@interface MyClass : NSObject
- (NSDictionary *)EndOfTurn:(int)varTurns withFatness:(int)varFatness;
@end

In the source file, then:
@implementation MyClass
// code, as given above
@end


Q:

Why is mass a form of energy?

Why is mass a very concentrated form of energy? Does it have to do something with photons, phonons or nucleus?

A:

Mass is not a "concentrated" form of energy. I'll come to this later but first let's understand the relation between mass and energy.
In relativity, energy and momentum are parts of a unified object called the four momentum vector $(E, \mathbf{p}$). Now, just like usual vectors in Euclidean geometry, there is a magnitude attached to this vector which is given by $\sqrt{E^2-|\mathbf{p}|^2}$, this is what is mass $m$. Just like the length of a displacement vector doesn't change when you rotate your coordinate system in Euclidean geometry, the magnitude of the four momentum vector doesn't change among different inertial frames in relativity. This magnitude, the mass $m$, thus, is a coordinate independent way to characterize the energy-monentum content of a system. Now, if you go to a reference frame where the momentum $\mathbf{p}$ vanishes, you get that the energy $E_0$ in such a frame which we call rest frame is equal to $m$.
Thus, mass is the energy of a system in its rest frame, i.e., in the reference frame where the momentum of the system is zero. In other words, $E_0 = m$.
So far I've done everything in natural units where $c=1$. If you restore the factors of $c$, you'll write $E_0 = mc^2$. The factor of $c^2$ gives the illusion that mass is a concentrated form of (rest) energy because it looks like a small amount of mass corresponds to a large value of rest energy. However, this is purely an illusion created out of our traditional choices of units which are different for energy and mass. In the natural system of units, as I wrote, the rest energy and mass are exactly equal. Saying that mass is a concentrated form of (rest) energy would be like saying length of my arm in meters is a concentrated form of length of my arm in nanometers.
Sociological edit: Why do people like to believe mass/matter is a concentrated form of energy?
From comments on this and other answers, it seems necessary to address this point. OK, so mass is what I described above. Now, what does it imply about the mass of a system of particles? Very simple, you go to frame of reference where the spatial momentum $\mathbf{p}$ of the system is zero and the energy of the system in this frame (i.e., the rest energy of the system) is what the mass of the system is. If you are trapped in Newtonian intuition, you'd expect this mass to be the sum of the masses of individual particles. This is obviously not true in relativity, just like other Newtonian things. For example, if you have a neutron decaying to a proton, an electron, and an anti-neutrino, the mass of the the system of the proton, the neutron, and the anti-neutrino would be exactly the same as the mass of the neutron (because mass is conserved) but this total mass would not be equal to the naive summation of the individual masses of the three particles. See, a related answer of mine. So, since the mass of the neutron would not be the same as the sum of the masses of the proton, the electron, and the neutrino, people like to say that some mass of the neutron is now converted to kinetic energy of these particles. Since the difference of the sum of the masses of the resulting particles and the mass of the neutron is a "small" number in the units in which we measure mass and the kinetic energy of the resultant particles would be a relatively "big" number in the units in which we measure energy, people like to say that mass is the concentrated form of energy. But particle physicists use natural units where they measure both mass and energy in electron volts. This would make sure that the difference of the sum of the masses of the resulting particles and the mass of the neutron is exactly the same as the kinetic energy of the resulting particles. So in conclusion, all of this confusion arises because people like to talk using Newtonian intuition and they also like to use unnatural units. :)

A:

The fact that mass and energy are two realisations of the same thing is a direct consequence of the theory of special relativity. Nothing more is required to find this other than Einstein postulates.
The fact that mass and energy are the same thing, although was considered a very strange result at the time, has been countlessly proven experimentally. In accelerators physicists do it all the time: initial particles are given a lot of energy, $17$ TeV in the center of mass frame at CERN for example, smashed together to create countless other particles whose masses can be many times higher than the ones of the particles we started from.
In a general sense it has nothing to do with specific particles you mentioned, but more with the way our universe is built.


Q:

Moving from mysql to mysqli or pdo?

Duplicate: mysqli or PDO - what are the pros and cons?

I'm looking to move a website from mysql to either mysqli or pdo as primarily a learning tool, but also for performance increases if possible.
I have read through http://php.net/manual/en/mysqli.overview.php and it seems like both would suit my needs, but it doesn't lean strongly either way.
The site currently uses primarily non object orientated code, but I do have experience with OO in other languages.  A huge majority of the queries are simple complex select statements with very little update/inserts.  What do you suggest as being the most useful both from my own education and for this specific site?
If you need any additional information please let me know.
Thanks.

A:

PDO Pro's:

Native to PHP as of 5.x
Supports named parameters as opposed
to numerically indexed ?'s
Same abstraction library supports multiple different RDBM's

Mysqli Con's:

Has issues with properly storing and
retrieving large objects in the
database.
No support for named parameters.

Otherwise, both libraries are basically different flavors of the same thing. They both have functions to quote parameters and both support parameterized queries.
If none of the above arguments sway you, then go with whichever library you prefer based on its syntax, style, etc.

A:

I don't believe PDO would give you any performance increase, but it gives you these two very attractive long-term benefits:

you can scale your app to use other databases with just a few code changes
the PDO library has much of the security built in

If you don't understand the benefits to #1 and #2, then just stick with the tried-and-true mysql library (you are at least using mysql_real_escape_string though, right)?
If I were learning a new PHP database library, I believe PDO is the way to go, especially if you are creating a web app that may be used on a variety of systems other than your own server.

A:

From http://www.php.net/manual/en/mysqli.overview.php :

While PDO has its advantages, such as a clean, simple, portable API,
  its main disadvantage is that it doesn't allow you to use all of the
  advanced features that are available in the latest versions of MySQL
  server. For example, PDO does not allow you to use MySQL's support for
  Multiple Statements.


Q:

How to switch to modal window in the background

I don't know if this problem is specific to Quicksilver or a general problem with modal windows. I use QS to launch an applescript:
"run 'command' with administrator privileges"

But the modal window from QS to enter my password appears without focus. I can't I need to click on the window with the mouse in order to be able to activate it. I would guess that this is because QS has launched the applescript "in the background" as it were, and already returned focus to the previous app.
Is there a way to switch to this modal window using keyboard actions? It's something I need to do every morning and it's very annoying to have to switch over to it with the mouse every time. I can't command-tab to Quicksilver when the dialog is active.

A:

The solution was obvious once I saw it: first make Quicksilver the foreground app, then it won't return focus to another app when the script runs.
tell application "Quicksilver" to activate
do shell script "pmset -c displaysleep 180" with administrator privileges


Q:

How to delete parent+child nodes based on specific condition using python

SAMPLE XML FILE
<ArticleSet>

        <ForeName>a</ForeName>
        <LastName>b</LastName>
        <Affiliation>harvard university of science. abc@gmail.com</Affiliation>

        <ForeName>a</ForeName>
        <LastName>b</LastName>
        <Affiliation>-</Affiliation>

        <ForeName>a</ForeName>
        <LastName>b</LastName>
        <Affiliation>harvard university of science. ghi@yahoo.co.in</Affiliation>

</ArticleSet>

I want to delete all Articles whose <Affliation> has value -  . i.e whose Affliation looks like <Affliation>-</Affliation>
REQUIRED OUTPUT
<ArticleSet>

        <ForeName>a</ForeName>
        <LastName>b</LastName>
        <Affiliation>harvard university of science. abc@gmail.com</Affiliation>

        <ForeName>a</ForeName>
        <LastName>b</LastName>
        <Affiliation>harvard university of science. ghi@yahoo.co.in</Affiliation>

</ArticleSet>

A:

This will read the XML from input.xml and writes the modified document to output.xml:
import xml.etree.ElementTree as ET

dom = ET.parse('input.xml')
root = dom.getroot()

for article in root.findall('Article'):
    if article.find('Affiliation').text == '-':
        root.remove(article)

dom.write('output.xml')

EDIT: Using lxml, I am getting a significantly better performance (759 ms to process a file with 150,000
 entries). Not sure if it will be fast enough for 15 million entries, though.
from lxml import etree

dom = etree.parse('input.xml')
root = dom.getroot()

for article in dom.xpath('Article[Affiliation="-"]'):
    root.remove(article)

dom.write('output.xml')


Q:

What changes does an object undergo during a cast in .net?

I would like to know what happens to the object when we do a cast. Does the layout of the object gets restructured or does the method table changes or is it only to ensure my assignments don't break during runtime ?

A:

None!
All you are doing is "pretending" that it is a different type. Of course, if it doesn't inherit from that type (or is actually an instance of the type when downcasting) the cast fails and you get nothing (null) when using the "as" operator to cast, and explicit (C-Style) cast will throw.
Unless, that is, you are dealing with value types (especially number types). If you do the following:
double myDouble = 1.5f;
int myInt = (int)myDouble;
double myOtherDouble = (double)myInt;

You will get 1 for myInt and myOtherDouble, because the number is truncated when performing the conversion. Most of the other value types don't even support this kind of casting, because the conversion is not defined.


Q:

Finding the length of a video in Java and ffmpeg

Is there a way to find a length of a video using Java? I understand we can make use of ffmpeg to generated thumbnails and encode videos. But can it be used to get the length of the video?
Thanks and Regards
Abishek R Srikaanth

A:

If you just call ffmpeg -i filename it will print information about the file and you can parse the output to get needed information.


Q:

Moving from NetBeans 7 RC2 to 7.0.1

So, I've used the NetBeans 7 Release Candidate for a while now (and it's worked great). Today I realized 7.0.1 had already been released, so I downloaded it. However, upon opening 7.0.1, it only gave me the option to import my NB 6.9 settings, not my 7 RC2 settings. Does anyone know where the NB settings are stored (I'm on Mac OS X, BTW) so I can move them manually? Thanks!

A:

No one seemed to be able to answer me, and as far as I can tell, it isn't possible. I was forced to reconfigure NetBeans manually.


Q:

How to draw NSImage using NSRect or NSView

I'm just newbie about Appkit and macOS programming and I wanna change StatusBar icon while app is working. (Yes, I'm making menu bar app)
the problem is that I could make over 3600 images... No way! that's impossible...
So, All I wanna do is to make computer generate each image and change app's StatusBar icon every seconds.
At first, NSImage is required so change the status bar icon.
Below code is initial code.
statusBar = NSStatusBar.init()
    statusItem = statusBar.statusItem(withLength: 70.0)
    statusBarButton = statusItem.button!

    statusBarButton.image = NSImage(named: NSImage.Name("AppIcon"))
    statusBarButton.image?.size = NSSize(width: 18.0, height: 18.0)
    statusBarButton.imagePosition = .imageRight
    statusBarButton.title = "Menu Bar App"

OK, NSImage(named: NSImage.Name("AppIcon")) is initial app icon image that I prepared before and then I could convert something to NSImage.
I've searched a lot of things about that I can draw image, but nothing seemed proper or appropriate :(
So that's why I'm trying to post this question.
Is there any way to generate image by each seconds?
Please help me

A:

Create a custom NSView with an NSImage property and implement drawRect, simple example
class MyView: NSView {

    var image : NSImage? {
        didSet {
           needsDisplay = true
        }
    }

    init(frame frameRect: NSRect, image : NSImage?) {
        self.image = image
        super.init(frame: frameRect)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func draw(_ dirtyRect: NSRect) {
        image?.draw(at: .zero, from: bounds, operation: .sourceOver, fraction: 1.0)
    }
}

Add an instance of MyView to the subviews of statusBarButton.
When an image is assigned to the image property of the view it will be drawn.
To change the image periodically use a Timer.


Q:

How to handle if tab icon press is the current screen with react navigation

How would I be able to detect and implement an event handler for when a user presses on a tab button for the current screen?
Use Case: I'm trying to implement a camera button in the tab bar - navigating to the camera tab opens the camera viewer and changes the tab icon to a take picture icon, tapping on this camera tab button again while in the camera tab view will take a picture.
I currently implement the tabBarOnPress function on the tab navigation, but need to pass that event to the screen itself.
  tabBarOnPress: ({ previousScene, scene, jumpToIndex }) => {
    if (previousScene.routeName === 'Camera' && scene.route.routeName === 'Camera') {
      console.log('fire camera picture');
    } else {
      jumpToIndex(scene.index);
    }
  }

Ideally I'd like to be able to set an onPress or event handler on the camera screen.  How should I trigger a method in the target scene - should I pass a navigation prop or variable and use some sort of navigation received event on the screen itself?

A:

Setting a param on componentWillMount let me get a reference to the method
TabNavigator options:
  tabBarOnPress: ({ previousScene, scene, jumpToIndex }) => {
    if (previousScene.routeName === 'Camera' && scene.route.routeName === 'Camera') {
      scene.route.params.takePicture();
    } else {
      jumpToIndex(scene.index);
    }
  }

CameraScreen
  componentWillMount() {
    this.props.navigation.setParams({
      takePicture: this.takePicture,
    });

    // possibly we might need to also implement below for this issue -
    // https://github.com/react-navigation/react-navigation/issues/2955
    // InteractionManager.runAfterInteractions(() => {
    //   this.props.navigation.setParams({
    //     scrollToTop: this._scrollToTop,
    //   });
    // })
  }


Q:

How can I extract data from a text file and import into new output file?

Assume the following is the data in ctf_output.txt, I would like to extract title headings from Rod #, Surface Temp and Centerline Temp, and then only the highest temperature for each and for each rod.  Notice I put specific and significantly higher temps in each column with no repeats.
Rod 1
Surface Temperature Centerline Temperature
500         510
501         511
502         512
503         513
504         525
505         515
535         516
507         517
508         518
509         519
510         520
Rod 2
Surface Temperature   Centerline Temperature
500               510
501           511
502           512
503           513
504           555
505           515
540           516
507               517
508           518
509           519
510           520
Rod 3
Surface Temperature   Centerline Temperature
500           510
501           511
502           512
503           513
567           514
505           515
506           559
507           517
508           518
509           519
510           520

How can I do this with python?  I need a python script that will pull the data and populate a new output file with a format of:
Rod 1
Surface Temperature Centerline Temperature
535         525

Rod 2
Surface Temperature   Centerline Temperature
540           555

Rod 3
Surface Temperature   Centerline Temperature
567           559

A:

You'd read the file line by line, then keep track of the maxima and output those when the next section begins:
with open('ctf_output.txt', 'r') as temps, open(outputfilename, 'w') as output:
    surface_max = centerline_max = None
    for line in temps:
        if line.startswith('Rod'):
            # start of new section
            if surface_max is not None or centerline_max is not None:
                # write maximum for previous section
                output.write('{}\t\t\t{}\n\n'.format(surface_max, centerline_max))
            # write out this line and the next to the output file
            output.write(line)
            output.write(next(temps, ''))
            # reset maxima
            surface_max = centerline_max = 0
        elif line.strip():
            # temperature line; read temperatures and track maxima
            surface, centerline = [int(t) for t in line.split()]
            if surface > surface_max:
                surface_max = surface
            if centerline > centerline_max:
                centerline_max = centerline
    if surface_max or centerline_max:
        # write out last maxima
        output.write('{}\t\t\t{}\n'.format(surface_max, centerline_max))

The output uses 3 tabs, just like your input.
For your example input, this writes:
Rod 1
Surface Temperature Centerline Temperature
535         525

Rod 2
Surface Temperature   Centerline Temperature
540         555

Rod 3
Surface Temperature   Centerline Temperature
567         559


Q:

Working on historical data (incrementing properties)

I'm trying to write a CEP rule that would take all the existing ACTIVE alarms and increase a specific fragment bike_alarm.priority by 1 every minute. This is the whole structure of alarm:
{
    "count": 1,
    "creationTime": "2018-07-09T15:30:20.790+02:00",
    "time": "2014-03-03T12:03:27.845Z",
    "history": {
        "auditRecords": [],
        "self": "https://cumulocity.com/audit/auditRecords"
    },
    "id": "1024",
    "self": "https://cumulocity.com/alarm/alarms/1024",
    "severity": "WARNING",
    "source": {
        "id": "22022",
        "name": "01BIKE_STATION_NORTH",
        "self": "https://cumulocity.com/inventory/managedObjects/22022"
    },
    "status": "ACTIVE",
    "text": "Bike disconnected",
    "type": "bike_error_01",
    "bike_alarm" {
        "priority": 10
    }
}

This is what I managed to create (based mainly on this question):
create schema Alarm as Alarm;

create schema CollectedAlarms(
    alarms List
);

create schema SingleAlarm(
    alarm Alarm
);

@Name("Collecting alarms")
insert into CollectedAlarms
select findAllAlarmByTimeBetween(
    current_timestamp().minus(100 day).toDate(),
    current_timestamp().toDate()
) as alarms
from pattern[every timer:interval(30 sec)];

@Name("Splitting alarms")
insert into SingleAlarm
select
    singleAlarm as alarm
from
    CollectedAlarms as alarms unidirectional,
    CollectedAlarms[alarms@type(Alarm)] as singleAlarm;

@Name("Rising priority")
insert into UpdateAlarm
select
    sa.alarm.id as id,
    {
        "bike_alarm.priority", GetNumber(sa.alarm, "bike_alarm.priority". 0) + 1
    } as fragments
from pattern [every sa = SingleAlarm -> (timer:interval(1 minutes))];

the problem is that not all alarms are founded and even those that are the incrementation don't work, priority is set to null.
Additionally, could you point me in direction of some better documentation? Is this something you use?

A:

In general the esper documentation that you linked is the best place to look for the generic syntax.
In combination you probably sometimes also need the Cumulocity documentation for the specific stuff: http://cumulocity.com/guides/event-language/introduction
Coming to your problems:
You are miss-using a realtime processing engine to do cron-like batch operations. While it technically can be done this might not be the best approach and I will show you a different approach that you can take.
But first solving your approach:

The database queries like findAllAlarmByTimeBetween() will only return up to 2000 results and there is no way to get the next page like on the REST API of Cumulocity. Also if you say you want to handle only active alarms you should use a function that also filters for the status.
Getting null out of a function like getNumber() means the JsonPath wasn't found or the dataType is incorrect (using getNumber for a String). You can set a default value for that case as the third parameter. From you Json that you provided it looks correct though. The syntax errors in your code are copy paste errors I assume as otherwise you wouldn't have been able to deploy it.

In my opinion you should approach that differently:
On each incoming alarm raise the priority after one minute if it hasn't been cleared. Additionally trigger the 1 minute timer again. Like a loop until the alarm is cleared.
The pattern for this would like like that:
from pattern [
   every e = AlarmCreated(alarm.status = CumulocityAlarmStatuses.ACTIVE)
   -> (timer:interval(1 minutes)
      and not AlarmUpdated(alarm.status != CumulocityAlarmStatuses.ACTIVE, alarm.id.value = e.alarm.id.value))
];

You need one with AlarmCreated which will only cover the initial increase and a second statement that triggers on your own schema which is then run in a loop.
In general try to avoid as many database calls as you can. So keep the loop counter in your schema so you only always need to execute the update call of the alarm.


Q:

Making background images responsive - fullpage.js

I am using fullpage.js for parallax scrolling. Is it possible to make the background images responsive in nature when i re-size my window.
https://github.com/alvarotrigo/fullPage.js
Below is the example i am using.
https://github.com/alvarotrigo/fullPage.js/blob/master/examples/backgrounds.html
If you notice each of my section has the background-size property with cover, but its still not responsive when i re-size.
#section0,
#section1,
#section2,
#section3{
    background-size: cover;
}

A:

Look i don't know too much about fullpage.js
But i don know about resizing image according to your window size.....
first of all download any image and i named it sa.jpg

In above code we kept image within #box div. and we also added responsive named class to img element.Assign it a max-width value of 100%. This allows the width
to adjust to the browser width changes. Next, add a dynamic height property to the class.
Above code is responsive for img element..
Now if you want to use background image css property and resize your image according to screen size


Q:

Instalando Kali Linux en dispositivo Android

Estuve investigando y es posible instalar kalilinux o cualquier distribución de UNIX en los dispositivos Android, usando LINUX DEPLOY.
Dentro de dicho programa hay una opción para descargar la distribución y entre la configuración se selecciona la distribución que quieres bajar y te sale que arquitectura deseas: armel, armlhf, arm64, i386, amd64.
Mi dispositivo es Android 4.4.2 KitKat Modelo TR10CS1, procesador Intel ATOM z2550.
Leyendo conseguí que estos Intel son compatibles con i386, y quisiera saber: ¿Debo bajar ese tipo de IMG de kalilinux o bajar las ARM? pues también leí que los dispositivos Android trabajan con ARM

A:

El procesador de tu tablet es intel atom, compatible con arquitectura x86, asi que debes bajar la imagen i386


Q:

pyinstaller setup failed with "setup.py is not yet supposed to work. Please Use PyInstaller without installation."

I was trying to "pip install pyinstaller" on my Mountain Lion. It failed with
setup.py is not yet supposed to work. Please Use PyInstaller without installation.

There is a ticket for this (http://www.pyinstaller.org/ticket/629) but not helpful.
I was using pythonepd 7.1.

A:

As it says "it is not yet supposed to work" - if you read the documents you will find that you just unzip/unpack it into a local directory and run it from there.
You are not supposed to run setup.py in pyinstaller at all - see here for how to set up pyinstaller.
Once installed and on your path you run by typing pyinstaller your_main.py in your project directory.  You may have to generate a specification file and edit it for things to work correctly - See the documentation!


Q:

GlassFish Server works on Netbeans 7.2 but not on 7.3

I have just installed Netbeans 7.3. Prepared a sample web application.
But Glassfish does not start.
Error message is "....\nbproject\build-impl.xml:1036: Deployment error: GlassFish Server 3+ Server start failed. Cant create start proccess.
See the server log for details."
Unfortunately nothing in the server log.
I deleted domains folder and  server then recreated. Nothing changed. :(
Is it a bug related to http://netbeans.org/bugzilla/show_bug.cgi?id=217228 ?
Any solution?
My system is 64 Bit Windows 7 with Turkish locale.
Web application is Primefaces based, JSF 2.1

A:

I think this is about language settings.
You can change localization settings in the netBeans configuration file($NETBEANSHOME/etc/netbeans.conf).
Just add "--locale en" to end of the "netbeans_default_options" line.
Also you can start glassfish with asaadmin tool with following these steps.
1- execute C:\Program Files\glassfish-3.1.2.2\bin\asaadmin.bat
2- start-domain


Q:

How to hide only a part of the content of a li with CSS?

In the following code I would like to hide "Hello world" but keep visible my ul.myphotos with CSS.
Here is a sample of what I have:

        Hello world

Photo1

Photo2

A:

You cant do that with the code you have atm (well, yes you can with some rather "hacky" tricks...).
I'd propose a clean solution: Wrap that text in a separate tag, e.g.:

        Hello world

Photo1

Photo2

And now you can easily say:
li > span{
   display:none;
}


Q:

Representable functor from scheme to Groups

I want to do the following question (6.6k) in Vakli's Foundations of algebraic geometry

Suppose we have a contravariant functor $F$ from $Sch$ to $Groups$. Suppose further that $F$ composed  with the forgetful functor is represented by the object Y. Show that the group operations on $F(X)$ uniquely determine $m:Y×Y \rightarrow Y$, $i:Y \rightarrow Y$, $e:Spec\mathbb{Z} \rightarrow Y$. And the group operation on $Mor(X,Y)$ is the same as on $F(X)$

Suppose $F$ composites with the forgetful functor is equal to $h_Y$
I know that $m:Y×Y \rightarrow Y$ must be the product of  the projection morphism $π:Y×Y \rightarrow Y$ with itself and $e$ must be identity element of the group $Mor(spec\mathbb{Z} ,Y)$ For the morphism $i$, it composites with $f \in Mor(Y,Y) $ to give $f^{-1}$. But I have no idea why this morphism is unique. Also I don't know why $F(X)$ should have group structure induced by $Y$. I'm sorry if this is a stupid question. Any help or hints are appreciated.

A:

Consider the diagram given to you by the problem
$$
\begin{matrix}
& & \textbf{Groups} \\
F\nearrow & & \downarrow \\
\textbf{Schemes}^{op} & \xrightarrow{h_X} & \textbf{Sets}
\end{matrix}
$$
The question can be answered purely from a functor of points perspective since morphisms between representable functors can be turned into morphisms of schemes; so, what does it mean for $h_X$ to have the structure of a group schemes? You should have natural transformations
$$
\begin{align*}
&m:h_X\times h_X \to h_X \\
&\iota:h_X\to h_X \\
&e:h_\mathbb{Z} \to h_X
\end{align*}
$$
but what is a natural transformation? It's a map described on the functor evaluated on objects in your source category. So, because of the factorization of $h_X$ as $\text{Forget}\circ F$ we have for any morphism of schemes $S \to T$ a commutative diagram
$$
\begin{matrix}
h_X(T)\times h_X(T) & \xrightarrow{m(T)} & h_X(T) \\
\downarrow & & \downarrow \\
h_X(S)\times h_X(S) & \xrightarrow{m(S)} & h_X(S)
\end{matrix}
$$
where each row satisfies the diagrams for a group object in a category. You can do the same argument for the other group operations and call it a day.


Q:

Update UICollectionViewFlowLayout without creating a new UICollectionView?

I would like to update certain the UICollectionViewFlowLayout or a UICollectionView because I want to set the size of the cells to a specific number that needs to be calculated (screenwidth / 3) - 2.
However, I only know how to assign it by creating a new instance which would reset lots of properties and force me to redefine them. Can this be updated some where else? Or is there a good way to just update ItemSize?
UICollectionViewFlowLayout layout = new UICollectionViewFlowLayout
{
      SectionInset = new UIEdgeInsets(0, 0, 0, 0),
      MinimumInteritemSpacing = 2,
      MinimumLineSpacing = 2,
      ItemSize = new SizeF(Size, Size),
      ScrollDirection = UICollectionViewScrollDirection.Vertical,
};
ProfilesListView = new UICollectionView(ProfilesListView.Frame, layout);

A:

There's no need to initialize UICollectionViewFlowLayout again when you want to set the item's size. You can use UICollectionViewDelegateFlowLayout to programmatically modify the size:
public class MyCollectionDelegate : UICollectionViewDelegateFlowLayout
{
    public override CGSize GetSizeForItem(UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
    {
        return new CGSize(Size, Size);
    }
}

After setting this Delegate to your UICollectionView: ProfilesListView.Delegate = new MyCollectionDelegate();
You can modify it through changing the event GetSizeForItem() and forcing updating the UICollectionView ProfilesListView.ReloadData();


Q:

Wcf service server - authentication with usernametoken

we are trying to create server from given demo wsdl. Wsdl does not contains security but we need implement usernametoken where request header looks like this:
<soap:Header>
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:env="http://www.w3.org/2003/05/soap-envelope" env:mustUnderstand="true">
            <wsse:UsernameToken wsu:Id="UsernameToken-7dd435a5-b8bb-4388-bba3-f77512a14351">
                <wsse:Username>CES</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">e8I23Z92JGgSREAb=</wsse:Password>
                <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">v21JzUcrKZiZ7MC==</wsse:Nonce>
                <wsu:Created>2017-10-13T13:00:02.221Z</wsu:Created>
            </wsse:UsernameToken>
            <wsse:SecurityTokenReference>
                <wsse:Embedded wsse:ValueType="http://www.asktirweb.org/security/authentication/username" wsu:Id="alex"/>
            </wsse:SecurityTokenReference>
        </wsse:Security>
        <Action xmlns="http://www.w3.org/2005/08/addressing">http://www.asktirweb.org/services/TIRAccountingService-1/sendInvoice</Action>
        <MessageID xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:321a0dff-61a8-4eae-8934-7f06e8d87648</MessageID>
        <To xmlns="http://www.w3.org/2005/08/addressing">http://wiesbaden:8040/askdemo/hs/AskTirWebDemo/WsSecurityRequests</To>
        <ReplyTo xmlns="http://www.w3.org/2005/08/addressing">
            <Address>http://www.w3.org/2005/08/addressing/anonymous</Address>
        </ReplyTo>
    </soap:Header>

Any suggestions ?

A:

Please try the below custom binding, it might be useful to you.
<customBinding>
   <binding name="mybinding">
     <textMessageEncoding messageVersion="Soap12WSAddressing10">
     </textMessageEncoding>
     <security authenticationMode="UserNameOverTransport" includeTimestamp="false" >
     </security>
     <httpsTransport></httpsTransport>
   </binding>
 </customBinding>

And the request body captured by Fiddle.

Besides, can we use the WSDL file to generate the client configuration, which has contained the essential binding type and security authentication mode? Like the below Tools.
https://docs.microsoft.com/en-us/dotnet/framework/wcf/servicemodel-metadata-utility-tool-svcutil-exe
By default, it is a built-in tool in VS Developer Command Prompts.

svcutil https://vabqia969vm:21011

It will generate the output.config in the current directory, it contains the binding configuration to be used in WCF.
Feel free to let me know if there is anything I can help with.


Q:

Does casting a T pointer to a T' pointer and back yield the original pointer if T' is an incomplete type?

Consider the following snippet which is adapted from the Tor source code:
/* This can be a malloc wrapper with minimal initialization. */
other_t *make_other(void);

/* This struct is never defined. */
struct undef;
typedef struct undef undef_t;

undef_t *make_undef(void)
{
    other_t *other = make_other();
    return (undef_t*)other;
}

Assume that all undef_t pointers in the program are casted other_t pointers and assume further that all procedures which take undef_t* cast them to other_t* before use.
According to section 6.3.2.3 of the C99 standard, the cast within the return statement invokes undefined behavior if other is not correctly aligned as a pointer to undef_t, but if it is, casting the result of make_undef back to other_t* yields the original pointer as returned by make_other. However, undef_t is an undefined type, and I cannot find any alignment rules regarding these. Do these conversions still work like they would if undef_t was defined and had the right alignment?

A:

I don't think it makes any difference whether or not a type is incomplete.
Per C11 6.2.5.22, there are only three kinds of incomplete type that can be instantiated:

An array type of unknown size
A structure type of unknown content
A union type of unknown content

Further, per C11 6.2.5.28:

All pointers to structure types shall have the same representation and
  alignment requirements as each other. All pointers to union types
  shall have the same representation and alignment requirements as each
  other.

So the representation and alignment requirements for a pointer to a structure or a union are known, whether the type is complete or not, since you still know it's a pointer to a structure or union of some kind.
For arrays, since we know from C11 6.3.2.1.3 that:

an expression that has type "array of type" is converted to an
  expression with type "pointer to type" that points to the initial
  element of the array object

then we can conclude that a pointer to, say, int, and a pointer to an array of int must have the same alignment requirements, because you can use either to refer to the same object. In other words, all pointers to arrays of int have the same alignment requirements, whether the size is known or not.
So if you know you have a pointer to a structure, or if you know you have a pointer to a union, or you know you have a pointer to an array of a specified type, then you know what the alignment requirements are. The fact that the type is incomplete doesn't matter. Indeed, if this were not true, incomplete types would not be useful, because you'd never be able to reliably use pointers to them.
In your case, both undef_t and other_t are typedefd somewhere in your translation unit, so you know what kind of incomplete type you have, and you therefore know the alignment requirements for it, so there is no ambiguity created by the fact the type is incomplete. Of course, if you as the programmer use them without going to the trouble of finding this out for yourself, then you can still run into problems, if for example other_t is a pointer to a union and undef_t is a pointer to a structure. But this is just a normal problem of converting between pointers which may have different alignment requirements - nothing about this problem is made more difficult by one of more of the pointed-to types being incomplete.
EDIT - some further elucidation, based on comments:
A "pointer to incomplete type" can only ever point at an object of a complete type, because incomplete types obviously by definition cannot be instantiated (for the sake of brevity, I'm setting aside the possibility of malloc()ing an arbitrary amount of memory and pointing a pointer of incomplete type at it).
Pointers to incomplete types exist for the sake of being able to have and pass around pointers to aggregate and compound types without needing to have the type definition available. In other words, when you don't have enough information to be able to instantiate a particular type, but you do have enough information to be able to point to one. Opaque types work on this basis, where all the actual work is done in functions where the type definition is available, and the code that uses those types only needs to be able to store the address of the object so it can be passed to and from these functions.
In terms of alignment, the representation of a pointer can change depending on the alignment requirements of the object it points to. For instance, as pointed out in the comments, if all ints must be stored on 8-byte boundaries, then a pointer representation could potentially not store the 3 least significant bits, because they'll always be zero. But if you then attempt to convert a char pointer to an int pointer and back, you can lose information, because a char pointer must be able to point to individual bytes, and some of that information would be lost in this hypothetical conversion to int *.
Similarly, it might be case that some small structures could be aligned on, say, 4 byte boundaries, and larger ones on 32 byte boundaries. But the alignment requirements for pointers to structures must all be the same, precisely because of these pointers to incomplete types. At the place where you use a pointer to an incomplete structure type, you don't have the type definition available (if you did, it would be a complete type), and so you don't know whether you can ignore the least significant 5 bits, or only the least significant 3 bits, for example. So the alignment requirements for a pointer to an incomplete structure type have to be sufficiently permissive that they can correctly hold the location of any conceivable structure type. To make passing these around easier, we can see from the above quote that C requires all pointers to structure types to have the same alignment requirements. Some structures might still actually be aligned on 32 byte boundaries, for instance, but a pointer to that structure cannot be permitted to take full advantage of this, and it must be capable of holding the location of any structure type.
But, if all structure types were aligned on no smaller than 4 byte boundaries, for instance, then would be perfectly fine for pointers to structures, including pointers to incomplete structure types, to ignore the least significant 3 bits, because you can do that while still being sure that you can represent the location of any structure safely. Indeed the fact that C requires all pointers to structure types to have the same alignment requirements, and requires all pointers to union types to have the same alignment requirements, but does not require that the alignment requirements for pointers to structure types be the same as alignment requirements for pointers to union types, indicates that it would be possible for, say, pointers to structures to rely on a minimum 4 byte boundary, but for pointers to unions to rely on a minimum 8 byte boundary. In this case, you couldn't safely convert a pointer to an incomplete structure type to a pointer to an incomplete union type and back again.
This is why it's not correct to say, as another answer currently does, that "there are no alignment requirements for an incomplete type". But it does mean that incomplete types are not problematic for the original question, because as already explained, when you have an incomplete type, you at least know whether its a structure, or a union, or an array, and that's all you need to have complete knowledge of the alignment requirements.


Q:

Bootstrap CSS undesired overlapping elements

I'm typically more of a backend guy, but I find myself working on a project that requires some frontend work. I'm fumbling my way through using bootstrap, and I find myself stuck on the following:

    <image src="myimage.jpg" />

I want a gap between the end of the form and the top of the image, but col-md-6 seems to be resulting in there being overlap, and the image-div is vertically larger than it is on the same page with col-md-6 removed.
Admittedly, CSS has never been my forté, but I'm hoping to address that soon. In the meantime, can someone help me out with this issue?

A:

Seems you're not using the grid system correctly, you have to use rows and cols to separate your elements in your frontend.
Check this link about Bootstrap Grid System


Q:

How did color spaces get their names?

Why RGB instead of BGR, GBR or perhaps GRB?
Why CMYK instead of YMCK, KMCY, CKMY, YKMC and etc?

A:

I presume RGB is in that order simply because it is the common spectral order — RoyGBiv, in other words. You will sometimes see BRG or otherwise when a particular computer image format happens to store the channel data in that order.
CMYK, on the other hand, is that way because that's the order the inks are normally applied in process color. See for example this article on four-color printing.

A:

Perhaps it’s as simple as the positions occupied by the colors on the spectrum.


Q:

Drawing a square on a rectangular window in opengl

I am drawing a 3d cube in LWJGL 3.It renders fine with the window size being 600 * 480.It renders a perfect cube.
But if i increase the window's width to 900 while the height remains the same.
The cube have a rectangular shape.
In 640 * 480 resolution the front face of cube is :

In 900 * 480 resolution the front face of cube is :

I want to render a perfect square without it resembling a rectangle.
if required the,
The render loop is as follows :
private void loop() {

GL.createCapabilities();

        // Set the clear color
        glClearColor(0f, 0.0f, 0.0f, 0.0f);

        float x = 0.5f;
        float y = 0.5f;
        float z = 0.5f;
        float[] vertices = new float[] {
                // VO
                -x, y, z,
                // V1
                -x, -y, z,
                // V2
                x, -y, z,
                // V3
                x, y, z,
                // V4
                -x, y, -z,
                // V5
                x, y, -z,
                // V6
                -x, -y, -z,
                // V7
                x, -y, -z, };

        float[] colours = new float[] {
               0.5f, 0.0f, 0.0f,
              0.0f, 0.5f, 0.0f,
             0.0f, 0.0f, 0.5f,
             0.0f, 0.5f, 0.5f,
              0.5f,0.0f, 0.0f,
             0.0f, 0.5f, 0.0f,
              0.0f, 0.0f, 0.5f,
              0.0f, 0.5f, 0.5f, };

        int[] indices = new int[] {
                // Front face
                0, 1, 3, 3, 1, 2,
                // Top Face
                4, 0, 3, 5, 4, 3,
                // Right face
                3, 2, 7, 5, 3, 7,
                // Left face
                6, 1, 0, 6, 0, 4,
                // Bottom face
                2, 1, 6, 2, 6, 7,
                // Back face
                7, 6, 4, 7, 4, 5, };

        RawModel model = Loader.loadRawModel(vertices, indices, colours);
        ShaderProgram shader = null;

        Transformation transformation = new Transformation();

        try {

            shader = new ShaderProgram(Utils.loadTextFile("src/shaders/vertexShader.txt"),
                    Utils.loadTextFile("src/shaders/fragmentShader.txt"));
            shader.link();
            shader.createUniform("projectionMatrix");
            shader.createUniform("worldMatrix");
        } catch (Exception e) {
            e.printStackTrace();
        }

        float rotation = 0;

        while (!glfwWindowShouldClose(window)) {
            glEnable(GL11.GL_DEPTH_TEST);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            shader.bind();

            shader.setUniform("projectionMatrix", transformation.getProjectionMatrix((float) Math.toRadians(60),
                    (float) (width / height), 0.1f, 1000f));
            shader.setUniform("worldMatrix", transformation.getWorldMatrix(new Vector3f(0, 0, -3f),
                    new Vector3f(rotation, rotation, rotation), 1));
            model.render();

            shader.unBind();

            glfwSwapBuffers(window);
            glfwPollEvents();
        }

        shader.dispose();
        Loader.dispose();
    }

A:

Thanks to @Derhass the problem is solved now.The problem was that i calculated the aspect ration as :
float aspectRatio = (float)(900/480);

which equals to 1.0f .
But when i added f to both width and height :
float aspectRatio = (float)(900f/480f);

It gave the right aspectRatio of 1.875.
now the cube appears as  square.


Q:

Unable to mirror AVCaptureVideoPreviewLayer on macOS

I'm using AVCaptureVideoPreviewLayer (macOS, not iOS) to capture video input from an attached camera. I've setup a capture session and created a UIView to display the image:
self.captureLayer = AVCaptureVideoPreviewLayer(session: self.captureSession);
self.playerView.layer = self.captureLayer;

Everything is working fine, and I see the image from the camera, but now I want to mirror the image (vertically). I'm using a CATransform3DMakeScale:
self.captureLayer.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0);
Instead of mirroring the image however, the layer just goes blank (background of the parent view).
I've tried other transforms (e.g. resizes) and they work fine. I've also tried mirroring the superlayer:
self.captureLayer.superLayer?.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0);
And this works (although it mirrors the entire window including the title bar!).
Any help appreciated. I believe the transform is correct, but for some reason it's not applying to a AVCaptureVideoPreviewLayer.

A:

You can make use of avcaptureconnection properties to do this.
self.cameraLayer = AVCaptureVideoPreviewLayer(session: frontVideoSession)
self.cameraLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill

    if (self.cameraLayer!.connection.isVideoMirroringSupported)
    {
        self.cameraLayer!.connection.automaticallyAdjustsVideoMirroring = false
        self.cameraLayer!.connection.isVideoMirrored = true
    }

You can read more about this at https://developer.apple.com/reference/avfoundation/avcaptureconnection/1389172-isvideomirrored

The isVideoMirrored flag allows you to choose whether you want to mirror the video or not. If it is set to true, it will mirror the video, if it set to false, it will not mirror. In order for you to use this flag, you must set automaticallyAdjustsVideoMirroring flag to false.

Wrote an example code for you https://github.com/manishganvir/mac-camera-mirror-example. Please check the same. Snippet below
do {
         let input = try AVCaptureDeviceInput(device: camDevice)

          VideoSession.addInput(input)

          self.cameraLayer = AVCaptureVideoPreviewLayer(session: VideoSession)
          print(" connection " , self.cameraLayer!.connection.isVideoMirroringSupported , self.cameraLayer!.connection.automaticallyAdjustsVideoMirroring);

          if (self.cameraLayer!.connection.isVideoMirroringSupported)
          {
                 self.cameraLayer!.connection.automaticallyAdjustsVideoMirroring = false
                 self.cameraLayer!.connection.isVideoMirrored = true
          }
          self.cameraLayer!.frame = self.view.bounds

          self.view.layer = self.cameraLayer!
          self.view.wantsLayer = true

          VideoSession.startRunning()
   }


Q:

textbox and richtextbox in c#

I want when i write number in textbox
for example:
I write number four in textbox and then click button
in richtextbox I have four "A" (AAAA)
Whwn write number 6
in richtextbox I have six "A" (AAAAAA)

A:

var sb = new StringBuilder();
for(int i = 0 i < int.Parse(textBox.Text); i++)
{
    sb.Append("A");
}
rtb.Text = sb.ToString()


Q:

How to get selectedItem from ListView from a button click in the listView Item

I have a list view item which has a button and displays properties on an object. I have the command property set up for the button using the mvvm pattern which fires correctly.
My issues is that when a press the button it does not also get the selected item, I am guessing that it has not fired the selectedItem event.
Is it possible to force this event when the button is pressed?
 <Button
         Height="20"
         Width="20"
         Grid.Column="3"
         Grid.Row="0"
         Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.RemoveClick}"
         CommandParameter="{Binding SelectedItem, ElementName=serverListView, Mode=TwoWay}">

A:

You may :
- set the commandParameter of your command to {Binding}
- Bind the SelectedItem to some Property of your VM
- Set this property to the command parameter in the begining of your command execute method


Q:

Maven hosting with Bintray

I am having issues with hosting maven jars with Github (site-maven-plugin) so I want to move with Bintray asap.
What are the steps to host a existing maven jar in bintray?
Here is my error when doing: mvn releae prepare
Caused by: org.apache.maven.shared.release.ReleaseFailureException: You don't have a SNAPSHOT project in the reactor projects list.

What I have now is I can do mvn clean install with no problems at all. Can I just upload the files under ./m2 repo? I basically uploaded the .jar and .pom I found in the maven repository.

How can I access the library I uploaded on Bintray from my pom.xml?

A:

You can get started with publishing from Maven to Bintray by copy-pasting some pom parts from "Set Me Up" guide:

Full user manual is available as well.
Please note, that you can't upload SNAPSHOTs to Bintray. It's a distribution platform and it is not intended for development process.
Saying that, you are welcome to take advantage of a free Artifactory account for hosting your snapshot during development.
Using OJO you don't need to use the troublesome Maven Release Plugin anymore. Once you're satisfied with the snapshots quality you can promote them to be releases and upload them to Bintray in one REST call (or click of a button in Jenkins),


Q:

created images not recognized in android gallery

I'm creating an app that creates and saves images. Currently I am saving them to /sd_card/my_app_name/. The files are there and everything, but they are not recognized from the Android's gallery. Is there any way to fix this?
Thanks!
well, I figured this out quickly enough :
try {
            MediaStore.Images.Media.insertImage(getContentResolver(), filePath, "image name", "image dexscription");  } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

A:

The way to do this is this:
MediaStore.Images.Media.insertImage(getContentResolver(), filePath, image name, details);


Q:

grab the word in a url using jquery?

i have a url that will be consistent in this format:
http://www.name.com/heart/game/2012/topics/SOMETHINGHERE.html
I need to grab the 'SOMETHINGHERE' after topics/ and use that as a variable.  I can get the current url:
var currentUrl = $(location).attr('href');

but not sure how to target and get just "SOMETHINGHERE" part?

A:

Split the url into parts based on the slashes and then remove the .html from the end of the last part of the url:
var currentUrl = $(location).attr('href');
var urlParts = currentUrl.split( "/" );

var something = urlParts[urlParts.length-1].substr( 0, urlParts[urlParts.length-1].lastIndexOf( ".html" ) );


Q:

Retrofit call in Kotlin Coroutines viewModelScope

Recently I've updated my ViewModel to use new viewModelScope. From its' implementation, I see that Dispatchers.Main.immediate is set as the default CoroutineDispatcher for viewModelScope.
So when printing the current Thread in viewModelScope.launch it gives Thread[main,5,main]
But here is my question. Although this runs in Main Thread, the following code works for me which performs a network call.
viewModelScope.launch {
    userRepo.login(email, password)
}

Here userRepo.login(email, password) is suspend function, which calls Retrofit suspend function.
So how this works, if my Current Thread is Main Thread?

A:

It works because Retrofit's suspend implementation delegates to Call<T>.enqueue. This means it already executes on its own background executor by default instead of using the caller's Dispatcher.


Q:

Convert python dict to json object with formatted keys and values

So i have my dict from my form post
post_dict = dict(request.POST)
item_data = {}

for key, value in post_dict.items():
   if 'item_data' in key:
      field = key.split('[')[1].replace(']', ' ')
      item_data[key] = ' '.join(value)

data = json.dumps(item_data)
print(data)

Right now it prints as follows:
{"item_data[username]": "johndoe", "item_data[email]": "johndoe@gmail.com",...

i just need it to print like so:
{
  "username": "johndoe",
  "email": "johndoe@gmail.com",
  ...
}

How can I remove "item_data" and format the key and values appropriately?

A:

Use item_data[field] = ... per Tadhg McDonald-Jensen's comment and replace
data = json.dumps(item_data)

with
data = json.dumps(item_data, indent=2, separators=(',', ': '))


Q:

Is there any way to get the xpath of element stored following page object model from a separate file?

Suppose I have stored WebElment in LoginPage.java class as shown below.
@FindBy(xpath="//input[@name='user_name']") WebElement username;

Now from my test file say VerifyLogin.java I want to access xpath of username which is stored in above LoginPage.java file something like this
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
loginPage.username;//then it should return the xpath //input[@name='user_name']

I know the above approach is wrong, but is there any way to get only the xpath that was stored in LoginPage file that I can use in VerifyLogin file?

A:

If you need it outside of the page object then your design is not that good .
Anyhow if you really want it the following should do the job
@FindBy(xpath="//input[@name='user_name']")
public WebElement username;

new YourPageObject().username;


Q:

How to make a thread wait for a notify for a specific time and execute code according to whether it received a notify or not?

I'm trying to implement something which is a bit of a variation of UDP.
The server thread receives datagram packets, parses them, and passes them to the appropriate thread. If it receives a message, it replies with an acknowledgement and passes it to the ReceiveMessage Thread which prints it onscreen.
I have a SendMessage Thread and a ReceiveMessage thread.
I want the SendMessage thread to send a packet, and wait for an acknowledgement for a specific timeout period. I want to send a notify() to SendMessage, if the server receives an acknowledgement, and if it doesn't, I want the SendMessage thread to timeout and execute different code in both cases. How can I achieve this?
public class ListenThread extends Thread{

protected DatagramSocket socket = null;
protected Boolean on = true;
protected String id;
protected HashMap <String,Contact> people = null;
protected String user;

public ListenThread(String macadd, String user, HashMap <String, Contact> people) throws SocketException
{
    super("ListenThread");
    this.socket = new DatagramSocket(3333);
    this.id=macadd;
    this.people = people;
    this.user = user;
}

@Override
public void run()
{

    while (on)
            {

                byte[] buf = new byte[256];
                try{
                        // receive request
                        DatagramPacket packet = new DatagramPacket(buf, buf.length);
                        socket.receive(packet);

                        String packdetails[] = new String(packet.getData(), 0, packet.getLength()).split(":");//Important part of receiving request. Tool used to parse the request
                        InetAddress address = packet.getAddress();

                        if(packdetails[0].equals("D"))  // if it's a Detection Packet
                        {/* Handle what to do with Detection packets */
                            }// end of small if
                        }//end of big if
                        else if(packdetails[0].equals("M"))// implies, Message type packet
                        {
                            Timestamp t =new Timestamp(new Date().getTime());
                            //Send Acknowledgement
                            String PString = new String("A:"+id);
                            buf = PString.getBytes();
                            packet = new DatagramPacket(buf, buf.length, address, 3333);

                            new ReceiveMessage(packdetails, address, people, t).start();
                        }
                        else// if it's an acknowledgemnt
                        {
                            //notify the sendmessage thread
                        }
                    }//end of try
                    catch (UnknownHostException e)
                    {
                        System.err.print("Unable to find IP of current machine");
                    }
                    catch (IOException except)
                    {
                        System.err.print("Network Problem : Unable to send packets!");
                    }
            }//end of while
    }//end of run

}//end of class
public class SendMessage extends Thread{
protected Contact person = null;
protected String Message = null;

public SendMessage(Contact person, String Message)
{
    this.person=person;
    this.Message= Message;
}
@Override
public void run()
{
    System.out.println(person.getusername()+": "+Message);
    try
    {
        person.SendMessage(Message);
        Thread.currentThread().wait(500);// If i get notify => received acknowledgement
    }
    catch(IOException e)
    {
        System.err.println("Unable to send message!");
    }
    catch (InterruptedException e)
    {
        System.err.print("Woken before receiving notify");
    }
}

A:

There are many to achieve this, You could opt for CountDownLatch or CyclicBarrier where the Sender thread would wait for the receiver to act on the barrier. Another alternative would be for the receiver thread to put the ack  message in a blockingQueue and the sender could consume the ack from the queue while waiting on it.


Q:

How to get a iframe in an Image Map?

I have been working on the side bar where it says Click On Game Lists Below on http://www.bespoke-arcades.co.uk/store/arcade-machines/16-synergy-elite-arcade-machine.html on the left hand side.
I have an image map because I would rather have one image downloaded than a ton (as it slows down loading times).
But the image map won't allow me to use class="iframe" in the <area> tag. If I do  it will work and open up a fancybox iframe popup, but if I use the imagemap the class="iframe" function isn't really accepted.
Is there any work around to making this work? I have the fancybox js and css on the page in question. I also have the correct javascript to work if I use that class function.

A:

Try changing this :

by this :

... of course, don't forget to add class="iframe" to each area tag.
Also check this answer or this for further reference.


Q:

Gulp + Sass + Del - Random behaviour

I don't understand why this simple script behaves differently depending on the del plugin setup.
When I launch gulp sass I just want to clean the public/css dir and "compile" the css from sass. So far so good:
gulp.task('clean-css', del.bind(null,['./public/css']));

gulp.task('sass', ['clean-css'], function () {
  return gulp.src('./resources/sass/**/*.scss')
    .pipe(plugins.sass({outputStyle: 'compressed'}))
    .pipe(gulp.dest('./public/css'));
});

However if if change the clean-css task to:
gulp.task('clean-css', del(['./public/css']));

Then it only works every other time. The first it cleans and generates the css, the next one it removes the directory but doesn't generate anything.
So, what's the difference between del(['./public/css']) and del.bind(null,['./public/css'])? Why does it affect the script in that way?
UPDATE:
The times when it doesn't generate anything I am seeing this error:
events.js:141
      throw er; // Unhandled 'error' event
            ^
Error: ENOENT: no such file or directory, open 'C:\Users\XXXX\gulp-project\public\css\style.css'
    at Error (native)

A:

tl;dr
Gulp doesn't know when del is finished if no callback is provided. with or without bind, del works every other time if your sass task is run before del and files to be deleted actually exist.

According to the gulp documentation you should also provide the callback method to del. This is how gulp knows when a task is finished:
var gulp = require('gulp');
var del = require('del');

gulp.task('clean:mobile', function (cb) {
  del([
    'dist/report.csv',
    // here we use a globbing pattern to match everything inside the `mobile` folder
    'dist/mobile/**/*',
    // we don't want to clean this file though so we negate the pattern
    '!dist/mobile/deploy.json'
  ], cb);
});

gulp.task('default', ['clean:mobile']);

I suppose that the order in which your tasks are run is different each time, since gulp doesn't know when del is finished when no callback is provided. According to the documentation:

If you want to create a series where tasks run in a particular order, you need to do two things:

give it a hint to tell it when the task is done,
and give it a hint that a task depends on completion of another.


Q:

Possessive form for a surname ending with "z"

What is the proper possessive form for a surname that ends with “z”? Is it z’ or z’s?

A:

Spelling Possessives: A simple rule with zero exceptions
There is no special rule for surnames which does not also apply to common nouns.
For that matter, there is no special rule for singulars versus plurals, either. The possessive form is the same no matter how the word is spelled or what its number is or what its capitalization is, because it follows from the pronunciation not from the spelling.
There’s just one universal rule at work here, one with no exceptions, for forming possessives.  As I write in my related answer to the question Which singular names ending in “s” form possessives with only a bare apostrophe?

The most useful rule — and the most general and the easiest to remember — is simply that you add ’s whenever you actually say an extra /əz/ at the end when forming the possessive, compared with how you say the non-possessive version. Let your own ear be your guide. That’s all there is to it.  No fancy rules full of exceptions.  Just your own ear (as a native speaker, mind you).

This is true no matter how the word is spelled. It’s a sound law not a spelling rule, and as such has no exceptions due to spelling.  Here are the only two “rules” you need ever remember to form the possessive in English:

To form the possessive of anything,* add an apostrophe.
Then if and only if you say an extra “s” sound of some sort compared with how you pronounce the non-possessive form, and an ‹s› after the apostrophe.

I cannot overstress that it does not matter how it’s spelled to start with:

Spelling does not matter.

Capitalization does not matter.

This is about sounds, not about orthography. The only thing that matters is how it’s said, and it does not matter how you pronounce that ‹s›, provided it is not silent. It may be phonemic /s/ or /z/ or /əz/; you always spell it ‹s›.
Said with an extra -s

This is that waltz’s problem.
This is Fritz’s problem.
This is Bill Seitz’s problem.
This is the quiz’s problem.
This is Jezebel’s problem.
This is Jez’s problem.
This is the Prez’s problem.
This is Cruz’s problem.
This is Jess’s problem.
This is Jessie’s problem.
This is Juan Gómez’s problem.
This is Cristovão Conçalves’s problem. (But you might not add an /s/ sound; if not, don’t add it in spelling.)
This is Joan’s problem.
This is the Queen of England’s problem.
This is Elsa’s problem.
This is someone else’s problem.
This is Clarice’s problem.
This is my niece’s problem.
This is Carolina’s problem.
This is that corpus’s problem.
This is those corpora’s problem.
This is that genius’s problem.
This is that genus’s problem.
This is those genera’s problem.

But assuming you don’t add an /s/ to make these in their possessives when you say them (almost no one does), they only get a bare apostrophe not an extra letter:
Said without an extra -s

This is those waltzes’ problem.
This is the Gomezes’ problem. (English version)
This is those quizzes’ problem.
This is the Joneses’ problem.
This is both my nieces’ problems.
This is the Carolinas’ problem; Georgia has nothing to do with it.
This is Mercedes’ problem.
That was Socrates’ problem.
That was the Kingdom of the Two Sicilies’ problem.
This is that series’ problem.
This is those series’ problem.
This is that species’ problem.
This is those species’ problems.
He did it for conscience’ sake.
Oh for Heaven’s sake, just spell it like you say it and now it’s nobody’s problem!
Oh for goodness’ sake, just spell it like you say it and now it’s nobody’s problem!

The corollary to this is that if you do happen to be one of those rare people who actually do add an /s/ sound to one or another from the previous list, then you would have to spell it that way, too.
But not many people actually do say those with an extra /s/.

Footnotes

Anything but a personal pronoun, that is.


Q:

How to smear a histogram

I was asked to perform a Gaussian smearing on the bins of an histogram. What does this mean?

A:

There appears to be a difference in terminology (as so often is the case with a discipline used in so many areas), so I'm not 100% sure, but I think they're referring to kernel density estimation, with a Gaussian kernel, but performed on binned data.
[Edit: if someone familiar with how the term "Gaussian smearing" is used in physics - and how it would apply in relation to a histogram - could chime in, that would be good]
In that case, each observation is replaced with a scaled density (or more generally, a kernel, which needn't necessarily be positive), which has been scaled to area $\frac{1}{n}$, centered on the observation.
The scale (the standard deviation in the case of a Gaussian) of the kernel is a tunable smoothing parameter.
Presumably the intent is to place observations at bin-centers before smoothing (this discreteness leads to a need for larger kernel bandwidth to achieve a given amount of smoothness, though if the bins are small relative to the default bandwidth the effect is very small); another alternative would be to spread the observations throughout their bins, though I suspect this isn't the intent of the request in your case.
In the unbinned case, here's an illustration of the idea. Below are 7 observations
(5.996 22.687  8.868 15.883 14.727  5.896  9.397) marked with "+" symbols (there are two almost coincident at the far left), with one point (14.727) marked in bold red. The little red density there is the gaussian kernel of bandwidth 2.5; there are gray kernels placed above each of the other points. The green dashed curve is the kernel density estimate, which came from summing up the densities at a fine grid of points and joining to give a smooth curve.

The bandwidth I used in my illustration is a little small. There are automatic methods for choosing the bandwidth that usually do pretty well. I did my calculations in R; like many other stats packages, it comes with a function to automate the whole procedure, so I could do the following to get a plot like the green dashed one:
a = c(5.996, 22.687, 8.868, 15.883, 14.727, 5.896, 9.397)
plot(density(a,bw=2.5))

Below is the kernel density estimate generated by the default bandwidth in the same program (i.e. by using density(a)):

As you see, it's wider, and achieves a smoother looking result. Of course, 7 observations is unrealistic; here's a histogram and kernel density estimate for 200 observations from a gamma(10,1):

If you click on the kde tag that your post has (I believe it was added in an edit), you'll see many posts on the topic here. There's also a kernel tag by the look of it, which mostly seems to be doing the same job (though kernel can refer to other things than density estimation), and that has more hits still.

A:

The requester is probably referring to a kernel density smoother as Glen_b notes, but "smearing" is evocative of the shadowgram featured in the book Visual Statistics. To address the issue of choosing the right bin or kernel width, the shadowgram is a overlay of many different width choices.


Q:

Problem when set new image in scroll view after zoom

I use below code for getting zoom image in the scroll view.

(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return photo;
}

but i have problem when i click on next button and set new image it also zoomed.
so it is possible the the next image is normal size. when i click on next button.

A:

Try reseting the Zoom after the next scroll
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

   [scrollView zoomToRect:(CGRect)rect animated:(BOOL)animated]
    // or
   [scrollView setZoomScale:(float)scale animated:(BOOL)animated]

}


Q:

Unit test for a disabled timer

I have a component which regularly calls a function using a timer. From the outside I can configure the rate for that timer.
Testing this is basically trivial: Set up the timer, wait some time, count the calls to the function, and compare to what you expected.
Now there is also the option to disable the timer. How could I test for that?
Waiting for time x is not enough, as the timer may call at x+1.
Is there a better approach?

A:

don't try to test functionality of your language. if js provides you method setInterval then assume it works. what you should test that if your code calls setInterval properly. i don't know much about js testing but if you can, just mock it and check if it was called. if you can't mock it then use one more level of indirection. create your own wrapper for timer - without any logic, just passing invocations. then, in tests, you can check if that wrapper was called or not. i would avoid using wait/sleep in tests


Q:

Populate 5 fragment pages with separate arraylists

I've been stuck for days on this. I have an activity that will parse html and sort the information into 5 arraylists. Each arraylist is a weekday. I want to take each arraylist and display the information in a listview on a separate page, so monday will be displayed on one page and then by swiping you move to tuesday and so on.
I have taken the eclipse default scrollable tabs + swipe for navigation and I'm trying to build from there.
So essentially I want to populate 5 pages of data with 5 arraylists, 1 arraylist for each page. Any ideas how I assign an arraylist to listview in a specific page?
Here is the code I have so far
public class DisplayOnlineTimetable extends FragmentActivity {

SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
String value;
Document doc = null;
private ListView mainListView ;

static ViewGroup mViewGroup;
ViewPager mViewPager;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.display_online_timetable, menu);
    return true;
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        return DummySectionFragment.newInstance(i);
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        //monday
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
            //tuesday
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
            //wednesday
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
            //thursday
        case 3:
            return getString(R.string.title_section3).toUpperCase(l);
            //friday
        case 4:
            return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }
}

public void createTimetable(ArrayList<SingleClass> list, Elements elements, Day day)
{

}

private class CreateTimetables extends AsyncTask<URL, Integer, Long>
{
    protected Long doInBackground(URL... urls) {

    }

    protected void onPostExecute(Long result)
    {

    }
}

}
DummySectionFragment Class
public class DummySectionFragment extends ListFragment {
private Integer arrayListId;
ViewGroup myViewGroup;
public static final String CATEGORY_POSITION = "section_number";
public static DummySectionFragment newInstance(int pos) {
    DummySectionFragment f = new DummySectionFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt(CATEGORY_POSITION, pos);
    f.setArguments(args);

    return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    //get the id for your array list
    arrayListId = getArguments() != null ? getArguments().getInt(CATEGORY_POSITION) - 1 : 1;
}

//create the list view layout
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myViewGroup = container;
View v = inflater.inflate(R.layout.list_row, container, false);
return v;
 }

//populate the list view row
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ArrayAdapter<SingleClass> arrayAdapter =
 new ArrayAdapter<SingleClass>(getActivity(), android.R.id.list, R.layout.list_row);

    setListAdapter(arrayAdapter);
}

}

A:

What you need to do is standard, and you are almost there.
First in your ViewPager adapter's getItem methods, initiate the Fragment with which position it is on:
@Override
public Fragment getItem(int i) {
    return DummySectionFragment.newInstance(i);
}

Next, in your Fragment class, create a constructor to instantiate it:
public static DummySectionFragment newInstance(int pos) {
    DummySectionFragment f = new DummySectionFragment();

    // Supply num input as an argument.
    Bundle args = new Bundle();
    args.putInt(CATEGORY_POSITION, pos);
    f.setArguments(args);

    return f;
}

And now make your DummySectionFragment extend a ListFragment, and in the onActivityCreated method you  can populate it:
public class DummySectionFragment extends ListFragment {
    private Integer arrayListId;
    //the constructor from above

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //get the id for your array list
        arrayListId = getArguments() != null ? getArguments().getInt(CATEGORY_POSITION) - 1 : 1;
    }

    //create the list view layout
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    myViewGroup = container;
    View v = inflater.inflate(R.layout.fragment_list, container, false);
    return v;
}

    //populate the list view row
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ArrayAdapter<String> arrayAdapter =
     new ArrayAdapter<String>(this, android.R.layout.list, <your_array_list_row.xml>);

        setListAdapter(adapter);
    }
}

The above code for your Fragment class will get the id for your array based on the position of the fragment, and create an ArrayAdapter for it, and use this adapter to populate a listview fragment. Now all you have to do is create the xml layout for the list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

One last thing is make sure all your Fragment class are from the same set of library (eg. either the regular Fragment lib or support.v4).


Q:

Rendering Bitmap based on Views position in parent

I'm trying to make a simple image editor. At the beginning I've thought that it'll be a good idea to simply save view state as Bitmap but, as it turned out, there is a wide range of screen resolutions and that leads to huge quality (and memory usage) fluctuations.
Now I'm trying to make a module that renders views state translated to desired resolution.
In the code below I'm trying to recreate current state of the views in canvas:
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.test_1_1);
    bitmap = Bitmap.createScaledBitmap(bitmap, parentView.getMeasuredWidth(), parentView.getMeasuredHeight(), true);

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    for (View rootView : addedViews) {
        ImageView imageView = rootView.findViewById(R.id.sticker);

        float[] viewPosition = new float[2];
        transformToAncestor(viewPosition, parentView, imageView);

        Bitmap originalBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        Matrix adjustMatrix = new Matrix();
        adjustMatrix.postTranslate(viewPosition[0], viewPosition[1]);
        adjustMatrix.postScale(
                rootView.getScaleX(),
                rootView.getScaleY(),
                rootView.getWidth() / 2,
                rootView.getHeight() / 2);
        adjustMatrix.postRotate(rootView.getRotation(),
                rootView.getWidth() / 2,
                rootView.getHeight() / 2);

        canvas.drawBitmap(originalBitmap, adjustMatrix, paint);
    }

transformToAncestor function is from here.
public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
    point[1] = top + py + (point[1] - py) * sy + ty - scrollY;

    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToAncestor(point, ancestor, (View) parent);
    }
}

(author wrote a note that his function does not support rotation, but there's not much rotation in my example so I don't think that important for now).
My problem is:

First image is generated via saving the parent view state. Second one is generated by translating views position, rotation and scale onto canvas.
As you can see, on the canvas, not scaled stickers are positioned properly, but scaled are incorrectly positioned.
How to position those scaled views properly?

A:

I've managed to fix the issue myself.
It turned out my solution was nearly OK but I did not took into consideration that my manipulation of a matrix does change the arrangement of the original points, so my
rootView.getWidth() / 2,
rootView.getHeight() / 2

is no longer applicable as a center of the view after calling Matrix.postScale or Matrix.postRotation.
I wanted to:

apply scale with pivot on top left corner,
apply rotation with pivot on the center of the view.

Given the assumptions, here's the working code:
    // setup variables for sizing and transformation
    float position[] = new float[2];
    transformToAncestor(position, rootView, imageView);
    float desiredRotation = imageView.getRotation();
    float sizeDeltaX = imageView.getMeasuredWidth() / (float) imageBitmap.getWidth();
    float sizeDeltaY = imageView.getMeasuredHeight() / (float) imageBitmap.getHeight();
    float desiredScaleX = imageView.getScaleX() * sizeDeltaX * scaleX;
    float desiredScaleY = imageView.getScaleY() * sizeDeltaY * scaleY;
    float imageViewWidth = imageView.getMeasuredWidth() * imageView.getScaleX();
    float imageViewHeight = imageView.getMeasuredHeight() * imageView.getScaleY();

    float rootViewWidth = rootView.getMeasuredWidth();
    float rootViewHeight = rootView.getMeasuredHeight();
    float percentXPos = position[0] / rootViewWidth;
    float percentYPos = position[1] / rootViewHeight;
    float percentXCenterPos = (position[0] + imageViewWidth/2)
            / rootViewWidth;
    float percentYCenterPos = (position[1] + imageViewHeight/2)
            / rootViewHeight;

    float desiredPositionX = background.getWidth() * percentXPos;
    float desiredPositionY = background.getHeight() * percentYPos;
    float desiredCenterX = background.getWidth() * percentXCenterPos;
    float desiredCenterY = background.getHeight() * percentYCenterPos;

    // apply above variables to matrix
    Matrix matrix = new Matrix();
    float[] points = new float[2];
    matrix.postTranslate(
            desiredPositionX,
            desiredPositionY);

    matrix.mapPoints(points);
    matrix.postScale(
            desiredScaleX,
            desiredScaleY,
            points[0],
            points[1]);

    matrix.postRotate(
            desiredRotation,
            desiredCenterX,
            desiredCenterY);

    // apply matrix to bitmap, then draw it on canvas
    canvas.drawBitmap(imageBitmap, matrix, paint);

As you can see, the mapPoints method was the answer for my question - it simply returns points after tranformation.


Q:

Ensure integrity of other columns from foreign record

I have 3 tables:
Race
 - id PK

Racer
 - id PK
 - rank

Winner
 - id PK
 - race_id FK(Race.id)
 - racer_id FK(Racer.id)
 - rank
 - prize
 UNIQUE CONSTRAINT (race_id, rank)

Racer.rank is a non-unique values, as some players can tie to a rank. I try to have records in Winner to have its rank match the Racer.rank that it references to. The unique constraint is to ensure that each race has only one 1st place.
The integrity between Winner.rank and Racer.rank is to enforcing if we later update Racer.rank, we will have to update the value in Winner as well, or remove that Winner row. How can I enforce that matching?
Other separate question:
- Is there a keyword that describe what I try to accomplish? I try to search with "referential integrity", "foreign constraint non-unique"... but none gets me to satified result.

A:

Here is a rough sketch of the comments:
CREATE TABLE Race
( Race_id INT NOT NULL PRIMARY KEY  -- I prefer to use the same name through out the model
);

CREATE TABLE Racer
( Racer_id INT NOT NULL PRIMARY KEY  -- See above
, Rank INT NOT NULL
,   CONSTRAINT AK1_Racer UNIQUE (Rank, Racer_id) -- Super key
);

CREATE TABLE Result  -- Is not "Result" a better name than Winner?
-- I removed id
( Race_id INT NOT NULL
, Racer_id INT NOT NULL
, Rank INT NOT NULL  -- See below
, ...
,   CONSTRAINT PK_Result PRIMARY KEY (Race_id, Racer_id)
,   CONSTRAINT AK_Result UNIQUE (Race_id, Rank)
,   CONSTRAINT FK_Race FOREIGN KEY (Race_id)
                       REFERENCES Race (Race_id)
,   CONSTRAINT FK_Racer FOREIGN KEY (Rank, Racer_id)
                       REFERENCES Racer (Rank, Race_id)
);

EDIT:
I'm not sure why RANK is part of RACER. It seems like all kinds of possible ranks can be derived from WINNER (RESULT):
SELECT Racer_id
     , COUNT(1) as #races
     , AVG(Rank) as avg_rank
     , MIN(Rank) as lowest_rank
     , MAX(Rank) as highest_rank
     , ...
FROM Result -- Winner
GROUP BY Racer_id

If there is some other metric like score, time, etc that determines the rank per race, you may also consider storing that and derive rank from there. PostgreSQL and newer versions of MySQL have window functions like RANK() that is very useful for such calculations.


Q:

What to do with XML information after first startup of Android App

So im looking for some guidance in terms of storing data within my android application.
At the moment, i have an XML file that stores a bunch of Restaurant elements.
i read this file when the application starts and store all the restaurants in an ArrayList.
Now i am trying to add a favorite Restaurant  functionality. The only thing is, how would i store the favorite Restaurant.
Should the application read the information from the XML file and then place it into a database , or should i give an id to every Restaurant and then store their favorite Restaurant's inside the database.

A:

XML-files are nice if you want to include data that doesn't change. If you want to work with your data and change it, a Database is the common way.
But do it with an SQLiteOpenHelper, where you can also define some standard-values in the onCreate-method.

The first time your App starts (after the user installed it) and you want to access your Database through your SQLiteOpenHelper, the onCreate-method is called. In this method, you'll want to create your needed Database-tables.
If you want some standard data in your Database, this is also the place to add these (using some inserts).
After that, SQLite has created a database (which is actually a file in the applications /databases-directory), the Database exists (and can be used) as long as this file is there (which should be till the user deletes the app or your app deletes the Database). So you have a persistent data-storage. So you don't need an XML-file at all.
If you however need to get your Data from a XML-file (like from the Web), you can use a XML-parser to get your informations from the XML-file and put them in the Database using PreparedStatement's.


Q:

Male or female header on PCB?

I'm designing PCB which has pin header connectors(0.1" pitch). So my question is - Is it the standard to put female headers onto PCB and solder male headers to wires or vice versa?
My idea is next:
Female pin headers is better to put on PCB. Why? They are protected with plastic around them, so you can't accidentally short connections and damage PCB(assuming that PCB is more expensive than female headers).
PCB has 34 pins for Arduino and DS3231 module(those pins will be female pins), six pins are signal pins, one is VCC, one GND pin.

A:

My theory is that male headers are less likely to suffer damage by contamination since everything is "out there" and visible. Use the shrouded kind for more protection.
The females, when part of an IDC cable, are more easily replaced if they fail, rather than trying to replace a part on an expensive multilayer PCB.
You will find most products where there was a choice such as IDE disk drives and PCB motherboards will agree with this choice.

A:

There is no standard. Male pin headers on PCBs got their start in the electronics world back when ribbon cables became popular. These cables were equipped with 0.1" pitch female socket connectors which mated with male pin box headers. Over time many applications eliminated the shrouded box header in favor of the open male pin header due to cost and space savings reasons.
These days there are so many choices it really becomes a case of finding the connection technology that best fits the packaging concept for your electronics gadget.

A:

There's not a standard, but a good rule of thumb is to think about would happen if someone untrained took hold of the board. For example, mains wiring is always a socket in the wall so it is impossible or difficult to touch a live wire accidentally. If there is power being supplied by one side, I would generally make that a socket (female). Cost wise, male tends to be cheaper than female, so if you're doing big numbers that may also be a consideration for you.


Q:

Write a function to calculate the sum of numbers in python, which is called many times as sum (1) (2) (3)

You need to write a function on python that is called an indefinite number of times, each time it takes a number and returns their sum, for example sum (1) (2) (3) == 6. I found the code for javascript, but I did not find how to redefine it in python __str __ method for the function. How can I override a method or is there another solution?
The code I tried to write:
def sum(n):
    total = n
    def f(k):
        nonlocal total
        total += k
        # f.__str__ = lambda : print(total) # no
        return f
    return f

print(sum(1)(2)(3))

This is working javascript code:
function sum(a) {

  let currentSum = a;

  function f(b) {
    currentSum += b;
    return f;
  }

  f.toString = function() {
    return currentSum;
  };

  return f;
}

alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15

A:

What about this:
def summ(a):
    current_sum = a

    return lambda x: current_sum + x

print(summ(1)(2))
>>>3


Q:

Extjs6 : Get Clipboard data on Keydown event of combobox

I need to have access to the clipboard Data on keydown event in Extjs Combobox, to perform some operation.
I tried with window.clipboardData.
Please find the fiddle : https://fiddle.sencha.com/#fiddle/1cc2
Ext.create('Ext.form.field.Tag',{
    renderTo:Ext.getBody(),
    createNewOnEnter:true,
    store:[1,2,3],
    enableKeyEvents:true,
    listeners:{
        keydown:function(combo,e){
            if(e.getKey() === e.V && e.ctrlKey){
                //get Clipboard data here
                combo.preventKeyUpEvent = e.V;
                e.stopEvent();
            }
        }
    }
});

A:

I think you can add paste event listener to your combo (its picker actually) and get clipboard data using methods of ClipboardEvent interface, like this:
combo.getEl().addListener(
    'paste',
    function(event, element, options) {
        var clipboardData = event.browserEvent.clipboardData;
        console.log(clipboardData.getData('Text'));
    }
);

Working fiddle


Q:

Image visibility using javascript

I want to toggle the image using if-else but it didn't work, can someone please explain what is wrong with the code.

Toggle Image

I tried using "ternary operator"
img.style.visibility = checkForVisible ? "hidden" : "visible";

and it worked. I just want to know about the "if-else" code which doesn't work. Thanks

A:

You do this:
var checkForVisible = img.style.visibility == "visible";

The == "visible" makes it the result of the equals expression so it's going to be true or false.
Your if/else is checkForVisible == "visible" which won't work because is will only be true or false. You only need to compare once.
if(img.style.visibility == "visible"){
        img.style.visibility = "hidden";
    }
    else{
        img.style.visibility = "visible";
    }

A:

Use toggle instead of if else.

function toggleImg() {
  var img = document.getElementById('pic');
  img.classList.toggle('hidden');

}
.visible {
  display: block;
}
.hidden {
  display: none;
}

Toggle Image