text:
Q: DAO with Null Object Pattern After Reading:
Effective Java (See Item 43) - Joshua Bloch
Clean Code (Don't Return Null) - Uncle Bob
Avoiding != null statements
Null Object pattern
I was looking for an answer to the question of what a DAO should return when a search ends up to be for an entity that does not exist for non-collection objects.
Collection object is really ok by using empty array or emptyList methods. But with non-collections it might be harder. An alternative solution is to never return null and instead use the Null Object pattern.
But I have no idea to integrate with Null Object pattern with DAO and I really excited to see great integration with Null Object pattern and DAO pattern especially for model(dto) object return case.
I would appreciate and welcome any best design pattern, scenario and suggestion.

A: All you need to do is return an empty object - say a customer entry you would have in your DAO something like
if (result == null) { return new EmptyUser(); }
where EmptyUser extends User and returns appropriate entries to getter calls to allow the rest of your code to know it is an empty object (id = -1 etc)
A small example
public class User {
    private int id;
    private String name;
    private String gender;
    public String getName() {
       //Code here
    }
    public void setName() {
       //Code here
    }
}

public class EmptyUser extends User {

    public int getId() {
       return -1;
    }

    public String getName() {
       return String.Empty();
   }
}

public User getEntry() {
   User result = db.query("select from users where id = 1");
   if(result == null) {
       return new EmptyUser();
   }
   else {
       return result;
    }
}

A: Indeed introducing null reference is probably one of the worse mistake in the programming languages' history even its creator Tony Hoare calls it his billion-dollar mistake.
Here are the best alternatives to null according to your Java version:
1. Java 8 and above
Starting from Java 8  you can use java.util.Optional.
Here is an example of how you could use it in your case:
public Optional<MyEntity> findMyEntity() {
    MyEntity entity = // some query here
    return Optional.ofNullable(entity);
}

2. Prior to Java 8
Before Java 8 you can use com.google.common.base.Optional from Google Guava.
Here is an example of how you could use it in your case:
public Optional<MyEntity> findMyEntity() {
    MyEntity entity = // some query here
    return Optional.fromNullable(entity);
}

A: In my experience, in real-life scenarios where a single entity should be returned returning a null is actually either a data inconsistency error or lack of data whasoever. In both cases the really good thing to do is to crate and throw your own DataNotFoudException. Fail fast.
I'm using mybatis as ORM and recently I started writing some theoretically single-result mapper selects as returning lists and validating checking the amount of returned data in dao, and throwing exceptions when the returned amounts do not match dao's method assumptions. It works pretty well.


text:
Q: Is better to use S.H.I.V or rookies in missions? I have reached a point where I have a S.H.I.V but I am not sure if I should use them or not.
Pros

*

*SHIV has better stats than a rookie

*SHIV can suppress

*SHIV does not panic.

*SHIV are immune to psi attacks?

*If they die, no humans die (this is more an ethic issue than a game issue, I wonder if other squad mates got moral penalties if a SHIV is destroyed as they get if soldier dies)

Cons

*

*I lose the experience benefits

*SHIVs are more expensive than soldiers

*SHIVs needs more time to build than rookies to be recruited.

*SHIVs have less hit points than a rookie with proper armor.

Are there any more pros and cons that I am not aware of? What is better to use as scout, SHIV or rookies?

A: I would say it comes down to whether you need the added firepower or not. SHIV's - especially the upgraded versions - are incredibly strong to say how easy they are to get ( as opposed to training up a rookie). I usually balance how hard the mission will be with a rookie, which later in the game are essentially walking targets.. against any sort of training agenda I might have at that time.
I would say that the use of a SHIV does strike me as a "make your life easier now, pay later" sort of decision. But maybe an acceptable one.

A: After trying them out in the past, I only use SHIVs in endgame now. This is because
(a) Hover SHIVs are available
(b) By this point in the game, money is no longer tight (Although Elerium may be, and SHIVs require that too)
(c) Hopefully I'm no longer too desperate for promotions....
Hover SHIVs with plasma weaponry have 20 health, 40 defence, something like 95 aim, a gun that seems to be equivalent to a Heavy Plasma, and the ability to fly - with twice as much flight fuel as Archangel Armour. They can also move a really long way in one turn. The high defence is to some extent cancelled out by the fact that they can't use cover, but they still make for very mobile, very accurate and fairly hard-to-kill units. On open maps I sometimes use them as flying scouts.
They're certainly not a good substitute for a soldier in all circumstances, but Plasma Hover SHIVs can be a good choice in some circumstances. I'm not at all convinced about the lesser varieties, in terms of their abilities or the cost of developing them earlier in the game.
EDIT: To more directly answer the question: Hover SHIVs are more capable than rookies. In the late game, when you have spare cash and do not need to promote more soldiers, they can be a good choice - especially on open maps or ones where flying is useful.

A: SHIVs are a reasonable choice for the advantages you already mentioned. Overall I consider them superior to rookies, especially as the SHIVs get more advanced. I consider them inferior to experienced, properly equipped soldiers, pretty obviously. Therefore, I only use SHIVs when I can't put together a full squad when my top soldiers are wounded, and I could only field rookies instead.
That being said, with a maximum team size of only 6, you should generally try to have all your team members survive and not use any of them (shiv or not) as scouting cannon fodder. Most of the time, especially late game, you simply need every bit of fire power you can get, and losing a single member can put a serious dent into your ability to deal with multiple Muton Elites and Sectopods.
There are sufficient options to scout with soldiers, without having to expect casualities:

*

*Only move in small increments (no dashing), and, if the situation allows, never leave cover for the whole movement to prevent triggering enemy overwatch.

*To avoid enemy Overwatch damage, use Assault soldiers with Lightning Reflexes to scout unknown/hostile areas.

*Use Ghost armor to be invisible, which makes any soldier a 100% safe scout. Bonus points for ghosted assault soldiers with Alloy Cannons.

*Use Snipers with Battle Scanners. Limited to 2 uses per sniper, but 100% safe.

A: I've never liked the SHIVs personally, as they cost more to research/build/setup than a human soldier, along with the other downsides you've mentioned.  I'd much rather bring a rookie/squaddie (or otherwise underleveled soldier) along for the ride than a SHIV if I have the choice.  The investment I'd make in a SHIV I would rather make in gear or other base improvements.  A properly equipped soldier will beat a SHIV hands down in terms of versatility and firepower.  Even if the squaddie dies, I get to keep his gear, although the destruction of a SHIV is a loss of all the cash/resources invested.
However, I think the root problem here is that you're losing scouts frequently.  Stop doing that, and you'll be much better off.  I explained my strategy in this answer, but the general gist in this situation follows.
If you don't know where aliens are, cycle through your squad until you've got your scout selected.  Use the scout to look for aliens in the first half-move of your scout's turn.  If you find them, have the scout retreat and set up an overwatch ambush with the rest of your team.  If you don't find them, move everyone up using half-moves, and set up a perimeter with overwatch and wait out the enemy turn.  Your scouts should generally never engage directly.
(There are exceptions and caveats - for instance, on a terror mission where you need to move quickly, you might opt to be a bit more aggressive.  If you've got all the time in the world, though, use it.)
When you find aliens, you're generally outnumbered - your one soldier discovers a group of usually at least 3.  The aliens then get a "free move" to set up defensively to react to your position.  This puts you at a disadvantage, and you can't afford disadvantages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Call a JSF method via JS i have a for loop in JS code, i want to call a method with parameters written in a JAVA managed bean that calculate a value and return a new one that will be used in the JS
Note: i'm using primefaces in the xhtml page
and handsontable to display data
that's how my js looks like
function updateMoneyValue(){
   var thetable; //the handsonTable
   for (var i =0 ; i < thetable.length ; i++)
      {
         var myNewValue = theBeanMethod (firstParam , secondParam);
      }
}

A: You can use PrimeFaces remote command component (
).

RemoteCommand enables executing backing bean methods and do partial
  update triggered by custom client side script. This example
  demonstrates a use case where a certain part of a page can be lazily
  loaded on demand.

Add it to the view it in a following way:

And use it in Javascript like so:

or call it from an event handler like so:

...

If you additionally want to pass parameters to the server make a following call:

The listener could be like:
public void listen(){
    FacesContext context = FacesContext.getCurrentInstance();
    Map<String,String> params = context.getExternalContext().getRequestParameterMap();
    System.out.println(params.get("param1"));
    System.out.println(params.get("param2"));
}

A: There's no way to do that directly.
Your java/jsf code is parsed and executed on server and then sent to client (browser). Only in browser javascript starts executing.
If you want to call some bean's method and get the result from client/javascript, you need to initiate new network request via AJAX call or somewhat. Also you can try to rework the logic of your application.

A: you can use primefaces remoteCommand component. you can find details about remoteCommand in this blog post.
http://blogs.bytecode.com.au/glen/2013/09/25/calling-primefaces-remotecommand-with-javascript-arguments.html


text:
Q: Creating Arrays of Objects in nested Objects with Javascript Given the following javascript object structure, which is typically what is returned by firebase
var data = {
  'id1' : {
    'fname' : 'value',
    'lname' : 'value',
    'things' : {
      'thing1' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing2' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing3' : {
        'brand' : 'value',
        'name' : 'value'
      }
    }
  },
  'id2' : {
    'fname' : 'value',
    'lname' : 'value',
    'things' : {
      'thing1' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing2' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing3' : {
        'brand' : 'value',
        'name' : 'value'
      }
    }
  }
};

How would you convert it to
[
  {
    'fname' : 'value',
    'lname' : 'value,
    'things' : [
      {
        'brand' : 'value',
        'name' : 'value'
      },
      {
        'brand' : 'value',
        'name' : 'value'
      },
      {
        'brand' : 'value',
        'name' : 'value'
      }
    ]
  },
  {
    'fname' : 'value',
    'lname' : 'value,
    'things' : [
      {
        'brand' : 'value',
        'name' : 'value'
      },
      {
        'brand' : 'value',
        'name' : 'value'
      },
      {
        'brand' : 'value',
        'name' : 'value'
      }
    ]
  }
]

Keeping in mind that the nested objects could get deeper than this. There are many implementations to convert nested structures to arrays, but I have not seen anyone make this specific conversion. I've been racking my brain for a while and have only come very close but have yet to get it just right.
I already have this code which doesn't do anything with deeper objects like 'things'.
var collection = [];
for(key in data) {
  collection.push(data[key]);
}

I'm struggling with making it recursive.
EDIT
I would imagine it needs to be in wrapped in a function that can call itself so that it can be made recursive.

A: Here's a solution that doesn't require knowing the keys, assuming that you want to convert every other level of nesting:
function toArrayOfObjects(obj) {
  var collection = [];
  for (key in obj) {
    var value = obj[key];
    if (typeof value === 'object' && !Array.isArray(value)) {
      var childObj = {};
      for (childKey in value) {
        var childValue = value[childKey];
        if (typeof childValue === 'object' && !Array.isArray(childValue)) {
          childObj[childKey] = toArrayOfObjects(childValue);
        } else {
          childObj[childKey] = childValue;
        }
      }
      collection.push(childObj);
    } else {
      collection.push(value);
    }
  }
  return collection;
}

A: Something like this should do the trick:
function convert(object, propNamesToConvert) {
  var array = [];
  Object.keys(object).forEach(function(key) {
    array.push(visit(object[key], propNamesToConvert));
  });
  return array;
}

function visit(object, propNamesToConvert) {
  var result = {};
  Object.keys(object).forEach(function(key) {
    var value = object[key];
    if (typeof(value) === 'object') {
      // objects are either 'things to be converted' or we need to traverse further down the rabbit hole
      if (propNamesToConvert.indexOf(key) >= 0) {
        value = convert(value, propNamesToConvert);
      }
      else {
        value = visit(value, propNamesToConvert);
      }
    }
    result[key] = value;
  });
  return result;
}

console.log(JSON.stringify(visit(data, ['things'])));

It could probably be shortened considerably, but this works. It would be way better to translate the hard-coded ['things'] into something that is less maintenance-prone.

var data = {
  'id1' : {
    'fname' : 'value',
    'lname' : 'value',
    'things' : {
      'thing1' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing2' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing3' : {
        'brand' : 'value',
        'name' : 'value'
      }
    }
  },
  'id2' : {
    'fname' : 'value',
    'lname' : 'value',
    'things' : {
      'thing1' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing2' : {
        'brand' : 'value',
        'name' : 'value'
      },
      'thing3' : {
        'brand' : 'value',
        'name' : 'value'
      }
    }
  }
};

function convert(object, propNamesToConvert) {
  var array = [];
  Object.keys(object).forEach(function(key) {
    array.push(visit(object[key], propNamesToConvert));
  });
  return array;
}

function visit(object, propNamesToConvert) {
  var result = {};
  Object.keys(object).forEach(function(key) {
    var value = object[key];
    if (typeof(value) === 'object') {
      if (propNamesToConvert.indexOf(key) >= 0) {
        value = convert(value, propNamesToConvert);
      }
      else {
        value = visit(value, propNamesToConvert);
      }
    }
    result[key] = value;
  });
  return result;
}

console.log(JSON.stringify(visit(data, ['things'])));
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

A:

var newData = [];
var dataKeys = Object.keys(data);
for(var i=0; i<dataKeys.length; i++)
{
    newData.push(data[dataKeys[i]]);
}


text:
Q: Can't get Composer to work on Windows I'm trying to use https://github.com/phpWhois/phpWhois in my PHP scripts, but can't get it to work. I'm an absolute beginner when it comes to using Composer.
This is what I tried:

*

*Cloned the git repo locally

*Installed Composer for Windows

*In Powershell, navigated to the local repository

*Typed composer require. Composer first asked me: Search for a package:, where I simply pressed ENTER. Then, Composer installed various packages in the vendor directory (phpunit, symfony, sebastian, etc.), and it created an autoload.php file.

But if I include that autoload.php in my example script (the basic example on the phpWhois Github main page), it generates the following error:

Fatal error: Class 'phpWhois\Whois' not found in /home/myServer/www/myApp/api/whoistest.php on line 12

Well, the Installation manual on the Github page says I should run
php composer.phar require "phpwhois/phpwhois":"~4.0"

So I tried the following in the Powershell console:
composer require "phpwhois/phpwhois":"~4.0"

[UnexpectedValueException]
Could not parse version constraint :~4.0: Invalid version string ":~4.0"

Then this:
composer require "phpwhois/phpwhois"

Problem 1

*

*Conclusion: remove phpwhois/phpwhois dev-master

*Can only install one of: phpwhois/phpwhois[dev-master, 4.2.3].

*Can only install one of: phpwhois/phpwhois[dev-master, 4.2.4].

*Can only install one of: phpwhois/phpwhois[v4.2.5, dev-master].

*Installation request for phpwhois/phpwhois dev-master -> satisfiable by phpwhois/phpwhois[dev-master].

*Installation request for phpwhois/phpwhois ^4.2 -> satisfiable by phpwhois/phpwhois[4.2.3, 4.2.4, v4.2.5].

Then this:
composer require "phpwhois/phpwhois:~4.0"

which gave the same error as above.
I tried various other syntaxes to specify the version here, but none of them worked.
Any ideas?

A: Ok, let's  start from the beginning.

*

*Download the latest composer.phar from getcomposer.org (scroll down to manual install).

*Put it in your project root directory.

*Remove all your current require statements from your composer.json.

*Open a terminal and navigate to your project root.

*Execute php composer.phar require phpwhois/phpwhois.

*Execute php composer.phar install.

*Include the autoloader in your code: require vendor/autoload.php.


text:
Q: How best to restore BootCamp partition from Acronis TrueImage backup? The replacement for my dead Macbook Pro Retina arrived yesterday, and the Mac side of things was restored from a Synology NAS in 30 mins, which was great...
But on the BootCamp partition, it's a different story: I was using Acronis TrueImage for my Windows backups, and a recent backup was indeed sitting happily on the NAS - but, how to restore it?
The Acronis Recovery CD won't run on a Mac, apparently (and, I have no superdrive...)
After some thought and experiment, here's what I ended up doing

*

*Installed Acronis trial version on a 'real' PC

*Connect a USB disk to the PC

*Recover the bootcamp partition to the USB disk

*Connect the USB disk to the Mac

*Install WinClone on the Mac ($20 well spent...)

*Create a WInClone image file from the USB disk (slow...)

*Create a FAT partition on the Macbook SSD

*Restore the WinClone image onto the FAT partition

*Reboot, and pray...

Now, while this worked, and the bootcamp partition was successfully re-added to VmWare fusion, it feels like a really long-winded way of doing it.
So, Is there a more direct way of doing this? Could Target Disk mode help (thunderbolt, remember...)
Note - I know I could in future just keep a Winclone backup on the NAS, but then I'd lose the ability to extract individual files from the backup, and also I'd be backing up the entire partition each time, rather than just the changes.

A: By using enclosure for your 2.5" disks, I think you could just run the True Image on a PC to copy your TIB backup to your new partition on the SSD. How about this as an idea?


text:
Q: Determine in Java, whether a file is a picture, having only binary data The situation is this: in my code I download a picture from the Internet as an array of bytes: byte[] imageBytes. And then I make the object of my MyImage class:
public class MyImage {

    private String imageName;
    private byte[] data;

    // Constructor, getters, setters
}

Create object:
MyImage myimg = new MyImage("some_name", imageBytes);

Then I use my resulting object.
I have a question: can I somehow make sure, that I downloaded the picture file?
It seems that each file type has its own signature (that is, the first bytes of the file). But there are a lot of different types of files. And if I compare the signature of my file with all existing types of signatures, then these will be very large checks.
Is it possible to make the check simpler: do I currently have an image (no matter what type) or not image?
Why do I want to do this: what if the user mistakenly passes a link not to an image, but to a file of a different type (for example, an archive). And in this case, I would like to determine in the code that the wrong file was downloaded and give the user an appropriate error message.

A: One way could be to check the Content-Type header that is sent from the server you download from. Another one could be the same algorithm that is used by the Linux file command. It would be tedious to reimplement that in Java.
So I suggest to either

*

*check the Content-Type header

*assuming you are on a *nix system: store the data in a file, then exec file and get the result

*just try to parse the image and let the graphics library decide. If successful, check the image you obtained

*some libraries are listed in How to reliably detect file types?

*The most promising way would be to ask the JDK via probeContentType()


text:
Q: Replace only leading NaN values in Pandas dataframe I have a dataframe of time series data, in which data reporting starts at different times (columns) for different observation units (rows). Prior to first reported datapoint for each unit, the dataframe contains NaN values, e.g.
    0   1   2   3   4 ...
A   NaN NaN 4   5   6 ...
B   NaN 7   8   NaN 10...
C   NaN 2   11  24  17...

I want to replace the leading (left-side) NaN values with 0, but only the leading ones (i.e. leaving the internal missing ones as NaN. So the result on the example above would be:
    0   1   2   3   4 ...
A   0   0   4   5   6 ...
B   0   7   8   NaN 10...
C   0   2   11  24  17...

(Note the retained NaN for row B col 3)
I could iterate through the dataframe row-by-row, identify the first index of a non-NaN value in each row, and replace everything left of that with 0. But is there a way to do this as a whole-array operation?

A: notna + cumsum by rows, cells with zeros are leading NaN:
df[df.notna().cumsum(1) == 0] = 0

df
     0    1   2     3   4
A  0.0  0.0   4   5.0   6
B  0.0  7.0   8   NaN  10
C  0.0  2.0  11  24.0  17

A: Here is another way using cumprod() and apply()
s = df.isna().cumprod(axis=1).sum(axis=1)
df.apply(lambda x: x.fillna(0,limit = s.loc[x.name]),axis=1)

Output:
     0    1     2     3     4
A  0.0  0.0   4.0   5.0   6.0
B  0.0  7.0   8.0   NaN  10.0
C  0.0  2.0  11.0  24.0  17.0


text:
Q: Как вычислить неопределённый интеграл на JavaScript? Мне нужна библиотека (js), которая может найти первообразную функции, которую я передаю как строку.
Например:
integrate("x") //возвращает (1/2)*x^2
Я нашёл несколько библиотек, которые могут это сделать. Например nerdamer, algebrite, newton-lib и подобное.
Но проблема всех этих библиотек, что они не могут корректно работать со сложными функциями, такими как:
3*sin(2*x)*cos(x)^4
3*sin(2*x)sin(x)^4
(5(ln(5*x))^4)/x

При этом есть куча онлайн сервисов, которые способны работать и со сложными функция.
Например:  https://www.wolframalpha.com/calculators/integral-calculator/
https://math24.biz/integral
https://math.semestr.ru/math/int.php
http://maxima.cesga.es/index.php?c=hnhv2ra5cen4jb6x0pmyp&n=1 и подобное

Есть ли всё-таки библиотека (желательно на js), которая способна работать со сложными функциями и выдавать то, что выдают эти онлайн-сервисы?


text:
Q: storage() is unavailable use object construction FIRStorage() and database() is unavailable use object construction FIRDatabase() When I put the code:
let databaseRef = FIRDatabase.database().reference()

I get the error:

database() is unavailable use object construction FIRDatabase()

And with:
let storageRef = FIRStorage.storage().reference()

I get the error:

storage() is unavailable use object construction FIRStorage()

I've added import FirebaseDatabase and import FirebaseStorage and have added them to my pod file and i have Xcode 7.2.1 and swift 2.

A: Ok so assuming your're using the newest version of swift and firebase pods, it's now written as Database instead of FIRDatabse and Storage instead of FIRStorage.
Furthermore, your podfile needs to have
pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Storage'

for what you're doing.
Make sure that when you close, you save the Podfile and then run podinstall. Furthermore, its important that you use the .xcworkspace not the .xcodeproj after installing.
Lastly, I think you should only need
import Firebase

because it includes database and storage.

A: First one is import like this:
import Firebase

Then create an object by:
let ref = Database.database().reference()

After latest release, FIRDatabase changed to Database


text:
Q: How to start a virtual machine with an empty disk using python-libvirt? I am trying to write a script that creates a virtual machine from scratch. I am using python 3 and libvirt to achieve this. I know there's easy ways using commandline tools, but for my specific application, I can't use those.
My virtual machine is defined as such:
<domain type='qemu'>
  <name>QEMU_test</name>
  <memory>219200</memory>
  <currentMemory>219200</currentMemory>
  <vcpu>2</vcpu>
  <os>
    <type arch='x86_64' machine='pc'>hvm</type>
    <boot dev='cdrom'/>
    <boot dev='hd'/>
  </os>
  <devices>
    <emulator>/usr/bin/qemu-system-x86_64</emulator>
    <disk type='file' device='cdrom'>
      <driver name='qemu' type='raw' />
      <source file='/vm/ubuntu-18.04.2-desktop-amd64.iso'/>
      <target dev='hdc'/>
      <readonly/>
    </disk>
    <disk type='file' device='disk'>
      <driver name='qemu' type='raw' />
      <source file='/vm/test/test2.img'/>
      <target dev='hda'/>
    </disk>
    <graphics type='vnc' port='-1'/>
    <interface type='network'>
      <source network='default'/>
      <model type='virtio' />
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
      <mac address="00:11:22:33:44:55"/>

    </interface>
  </devices>
</domain>

All I am doing is creating a connection to 'qemu:///system', reading the XML configuration file into a variable and executing 'createXML' to create a transient guest domain.
The issue I have is probably partly due to my lack of understanding of how Operating Systems start up.
The file 'test2.img' is a file generated using '/dev/zero'. It was created following the process described here:
Python libvirt API - create a Virtual Machine
Trying to start this machine results in kernel panic:
Kernel Panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)

I am guessing this is because the 'initramfs' parameter in the XML needs to be specified for empty disks, or otherwise there needs to be a way to partition the disk so that the expected root partition exists.
My question then is: Is there a portable way to do any of that using Python?
I don't want to explicitly specify any paths as I want this script to be as portable as possible (unless there's a standard I can use for all Operating Systems that I'm missing). I'd also prefer if I didn't have to distribute anything except the script to have it work, if possible.
Edit to clarify behaviour: If I use a Debian CD, I can see the initial menu pop up with the installation options, however once I select one, a kernel panic is caused.

A: Using /dev/zero to create a 'raw' disk image should work, but generally it's better to use 'qemu-img' for these types of things. Either way, just creating a disk image like that and then trying to boot off of it won't work as there's no operating system inside it to boot from.
Is the VM actually booting off of the ubuntu CDROM media? I would expect that to work even if test2.img is totally empty, and then you can use the ubuntu installer to populate test2.img.

A: Well shit. After messing around with the --debug switch and minimizing the configuration that virt-* tools create as a default, I finally found out why it wasn't working:
I didn't give the VM enough memory.
This results in different kernel panics for different Operating Systems. For example, Ubuntu complains that rootfs cannot be found. Debian complains that it failed to kill init.
The default unit for memory is KibiBytes, which is 1024 bytes. This means my configuration gave the VM a little over 214 Mebibytes (2^20 bytes) to work with. Turns out you can't do much with that except complain.


text:
Q: Clear webView cookies (Swift) How can I clear all cookies for few hosts in my webView?
Method from this question not working.
I'm trying to work with vk.com oauth and it does not have user-logout method, so deleting cookis is one of existing ways to make other user possible to log in
Answer is below

A: Nothing above worked for me.
Using the following:

*

*Swift 5

*Xcode 12.4

*WebKit

Below is the solution worked for me:
func removeCookies() {
    HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
    print("All cookies deleted")

    WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
        records.forEach { record in
            WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
            print("Cookie ::: \(record) deleted")
        }
    }
}

A: swift 4
func removeCookies(){
    let cookie = HTTPCookie.self
    let cookieJar = HTTPCookieStorage.shared

    for cookie in cookieJar.cookies! {
        cookieJar.deleteCookie(cookie)
    }
}

A: UIWebView is nearly  deprecated.
So for WKWebView instance make this code:
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore

cookieStore.getAllCookies {
    cookies in

    for cookie in cookies {
        cookieStore.delete(cookie)
    }
}

A: I made it by
        let cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage()

        for cookie in cookieJar.cookies! {
           // print(cookie.name+"="+cookie.value)
            cookieJar.deleteCookie(cookie)
        }

Swift 4
func removeCookies(){
    let cookieJar = HTTPCookieStorage.shared

    for cookie in cookieJar.cookies! {
        cookieJar.deleteCookie(cookie)
    }
}

A: One liner in Swift 5
HTTPCookieStorage.shared.cookies?.forEach(HTTPCookieStorage.shared.deleteCookie)

A: By avoiding Force Unwrap
private func clearCookie2(){
    let storage = HTTPCookieStorage.shared
    if let cookies = storage.cookies{
        for cookie in cookies {
            storage.deleteCookie(cookie)
        }
    }
}

And if you want to delete only specific cookie
let DOMAIN_NAME = "abc.com"
private func clearCookie(){
    let storage = HTTPCookieStorage.shared
    if let cookies = storage.cookies{
        for cookie in cookies {
            if(cookie.domain.contains(DOMAIN_NAME)){
                storage.deleteCookie(cookie)
            }
        }
    }
}

A: Variation to remove based on date. .distantPast to remove all
HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)


text:
Q: Multilevel XML ForEach WPF I need to get the values from many nodes in a XML that is a few levels deep.
Valid XML Sample
<?xml version="1.0" encoding="UTF-8"?>
 <server>
  <id>245723</id>
  <name>Server Name</name>
  <host>IP Address</host>
  <port>Port</port>
   <servertype>
    <type>Linux</type>
    <cpu>Linux</cpu>
     <connections>
       <connection>
         <id>1234</id>
         <con_type>new</con_type>
       </connection>
       <connection>
         <id>565665</id>
         <con_type>new</con_type>
       </connection>
       <connection>
         <id>908546546466</id>
         <con_type>old</con_type>
       </connection>
     </connections>
    </servertype>
   </server>

So basically I need to access and run through a foreach inside the connections node. I have used the below code to get the first level nodes values (each node) into a listbox. Works well.
C# Code for reading XML
string urlAddress = "url to xml file on server";
XDocument itemz = XDocument.Load(urlAddress);

foreach (var item in itemz.Descendants("server"))
{
    string name = item.Element("id").Value;

    //adding value to a listbox (sample)
    lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);
}

Is there a way to use the same code(as such) to get each item(value) under the connections nodes. So something like flow example below
  server> servertype > connections > foreach connection > get values of connection

would it require something like
foreach (var item in itemz.Descendants("server")) {

    foreach (var item in itemz.Descendants("connections"))  {

        //foreach connection
        foreach (var item in itemz.Descendants("connection")) {

            //add connection id to listbox
            lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);
        }
    }
}

**********Edit**********
Using the below code to fetch multiple values to listbox output
//foreach connection inside connections

//connection node inner node values
string id = item.Element("id").Value);
string type = item.Element("type").Value);
string other = item.Element("other").Value);
string etc = item.Element("etc").Value);

lstBox.Items.Add(txtBoxName.Content = id + type + other + etc;

A: To add all "id" element values for all "connection" nodes to your lstBox, you can simply do this:
XDocument itemz = XDocument.Load(urlAddress);

// ...

foreach (var item in itemz.Descendants("connection"))
    lstBox.Items.Add(txtBoxName.Content = item.Element("id").Value);

There is no need to traverse the hierarchy yourself, that is what Descendants will do for you.
Although the txtBoxName.Content = ... is a funny construction, of which the purpose is not clear to me. Why would you be setting this repeatedly, instead of using the last item added to set as its content.


text:
Q: Check if UIColor is dark or bright? I need to determine whether a selected UIColor (picked by the user) is dark or bright, so I can change the color of a line of text that sits on top of that color, for better readability.
Here's an example in Flash/Actionscript (with demo):
http://web.archive.org/web/20100102024448/http://theflashblog.com/?p=173
Any thoughts?
Cheers,
Andre
UPDATE
Thanks to everyone's suggestions, here's the working code:
- (void) updateColor:(UIColor *) newColor
{
    const CGFloat *componentColors = CGColorGetComponents(newColor.CGColor);

    CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
    if (colorBrightness < 0.5)
    {
        NSLog(@"my color is dark");
    }
    else
    {
        NSLog(@"my color is light");
    }
}

Thanks once again :)

A: Swift 4 Version
extension UIColor {
    func isLight() -> Bool {
        guard let components = cgColor.components, components.count > 2 else {return false}
        let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
        return (brightness > 0.5)
    }
}

A: W3C has the following:
http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
If you're only doing black or white text, use the color brightness calculation above. If it is below 125, use white text. If it is 125 or above, use black text.
edit 1: bias towards black text. :)
edit 2: The formula to use is ((Red value * 299) + (Green value * 587) + (Blue value * 114)) / 1000.

A: Here is a Swift (3) extension to perform this check.
This extension works with greyscale colors. However, if you are creating all your colors with the RGB initializer and not using the built in colors such as UIColor.black and UIColor.white, then possibly you can remove the additional checks.
extension UIColor {

    // Check if the color is light or dark, as defined by the injected lightness threshold.
    // Some people report that 0.7 is best. I suggest to find out for yourself.
    // A nil value is returned if the lightness couldn't be determined.
    func isLight(threshold: Float = 0.5) -> Bool? {
        let originalCGColor = self.cgColor

        // Now we need to convert it to the RGB colorspace. UIColor.white / UIColor.black are greyscale and not RGB.
        // If you don't do this then you will crash when accessing components index 2 below when evaluating greyscale colors.
        let RGBCGColor = originalCGColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil)
        guard let components = RGBCGColor?.components else {
            return nil
        }
        guard components.count >= 3 else {
            return nil
        }

        let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000)
        return (brightness > threshold)
    }
}

Tests:
func testItWorks() {
    XCTAssertTrue(UIColor.yellow.isLight()!, "Yellow is LIGHT")
    XCTAssertFalse(UIColor.black.isLight()!, "Black is DARK")
    XCTAssertTrue(UIColor.white.isLight()!, "White is LIGHT")
    XCTAssertFalse(UIColor.red.isLight()!, "Red is DARK")
}

Note: Updated to Swift 3 12/7/18

A: Simpler Swift 3 extension:
extension UIColor {
    func isLight() -> Bool {
        guard let components = cgColor.components else { return false }
        let redBrightness = components[0] * 299
        let greenBrightness = components[1] * 587
        let blueBrightness = components[2] * 114
        let brightness = (redBrightness + greenBrightness + blueBrightness) / 1000
        return brightness > 0.5
    }
}

A: For me using only CGColorGetComponents didn't worked, I get 2 components for UIColors like white. So I have to check the color spaceModel first.
This is what I came up with that ended up being the swift version of @mattsven's answer.
Color space taken from here: https://stackoverflow.com/a/16981916/4905076
extension UIColor {
    func isLight() -> Bool {
        if let colorSpace = self.cgColor.colorSpace {
            if colorSpace.model == .rgb {
                guard let components = cgColor.components, components.count > 2 else {return false}

                let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000

                return (brightness > 0.5)
            }
            else {
                var white : CGFloat = 0.0

                self.getWhite(&white, alpha: nil)

                return white >= 0.5
            }
        }

        return false
    }

A: Swift3
extension UIColor {
    var isLight: Bool {
        var white: CGFloat = 0
        getWhite(&white, alpha: nil)
        return white > 0.5
    }
}

// Usage
if color.isLight {
    label.textColor = UIColor.black
} else {
    label.textColor = UIColor.white
}

A: Using Erik Nedwidek's answer, I came up with that little snippet of code for easy inclusion.
- (UIColor *)readableForegroundColorForBackgroundColor:(UIColor*)backgroundColor {
    size_t count = CGColorGetNumberOfComponents(backgroundColor.CGColor);
    const CGFloat *componentColors = CGColorGetComponents(backgroundColor.CGColor);

    CGFloat darknessScore = 0;
    if (count == 2) {
        darknessScore = (((componentColors[0]*255) * 299) + ((componentColors[0]*255) * 587) + ((componentColors[0]*255) * 114)) / 1000;
    } else if (count == 4) {
        darknessScore = (((componentColors[0]*255) * 299) + ((componentColors[1]*255) * 587) + ((componentColors[2]*255) * 114)) / 1000;
    }

    if (darknessScore >= 125) {
        return [UIColor blackColor];
    }

    return [UIColor whiteColor];
}

A: If you prefer the block version:
BOOL (^isDark)(UIColor *) = ^(UIColor *color){
    const CGFloat *component = CGColorGetComponents(color.CGColor);
    CGFloat brightness = ((component[0] * 299) + (component[1] * 587) + (component[2] * 114)) / 1000;

    if (brightness < 0.75)
        return  YES;
    return NO;
};

A: Following method is find color is light or dark in Swift language based on white in color.
func isLightColor(color: UIColor) -> Bool
{
   var white: CGFloat = 0.0
   color.getWhite(&white, alpha: nil)

   var isLight = false

   if white >= 0.5
   {
       isLight = true
       NSLog("color is light: %f", white)
   }
   else
   {
      NSLog("Color is dark: %f", white)
   }

   return isLight
}

Following method is find color is light or dark in Swift using color components.
func isLightColor(color: UIColor) -> Bool
{
     var isLight = false

     var componentColors = CGColorGetComponents(color.CGColor)

     var colorBrightness: CGFloat = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
     if (colorBrightness >= 0.5)
     {
        isLight = true
        NSLog("my color is light")
     }
     else
     {
        NSLog("my color is dark")
     }
     return isLight
}

A: For everything that's not grayish, the RGB inverse of a color is usually highly contrasted with it.
The demo just inverts the color and desaturates it (converts it to a gray).
But generating a nice soothing combination of colors is quite complicated.
Look at :
http://particletree.com/notebook/calculating-color-contrast-for-legible-text/

A: UIColor has the following method to convert to HSB color space:
- (BOOL)getHue:(CGFloat *)hue saturation:(CGFloat *)saturation brightness:(CGFloat *)brightness alpha:(CGFloat *)alpha;

A: My solution to this problem in a category (drawn from other answers here). Also works with grayscale colors, which at the time of writing none of the other answers do.
@interface UIColor (Ext)

    - (BOOL) colorIsLight;

@end

@implementation UIColor (Ext)

    - (BOOL) colorIsLight {
        CGFloat colorBrightness = 0;

        CGColorSpaceRef colorSpace = CGColorGetColorSpace(self.CGColor);
        CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);

        if(colorSpaceModel == kCGColorSpaceModelRGB){
            const CGFloat *componentColors = CGColorGetComponents(self.CGColor);

            colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
        } else {
            [self getWhite:&colorBrightness alpha:0];
        }

        return (colorBrightness >= .5f);
    }

@end

A: - (BOOL)isColorLight:(UIColor*)color
{
    CGFloat white = 0;
    [color getWhite:&white alpha:nil];
    return (white >= .85);
}

Added Swift 5 version:
var white: CGFloat = 0.0
color.getWhite(&white, alpha: nil)
return white >= .85 // Don't use white background

A: If you want to find the brightness of the color, here is some pseudo code:
public float GetBrightness(int red, int blue, int green)
{
    float num = red / 255f;
    float num2 = blue / 255f;
    float num3 = green / 255f;
    float num4 = num;
    float num5 = num;
    if (num2 > num4)
        num4 = num2;
    if (num3 > num4)
        num4 = num3;
    if (num2 < num5)
        num5 = num2;
    if (num3 < num5)
        num5 = num3;
    return ((num4 + num5) / 2f);
}

If it is > 0.5 it is bright, and otherwise dark.


text:
Q: whats the correct way to define custom builds of vendor libraries in bower_components? I am using the yeoman webapp generator with requirejs and I have installed canjs using bower.
canjs has a dir structure like the following
app/bower_components/canjs/amd/can.js
app/bower_components/canjs/amd/can/control.js
app/bower_components/canjs/amd/can/control/route.js
etc..

Inside the can.js file is the following.
define(["can/util/library", "can/control/route", "can/model", "can/view/ejs", "can/route"], function(can) {
    return can;
});

All of the dependancy files (control.js, route.js) have their dependancies listed inside define() functions.
What I want to do is customise the canjs build and replace "can/view/ejs" with "can/view/mustache". I can get it to work by changing the reference to ejs within the can.js file but that means I'm editing a vendor file inside of bower_components dir.
I have tried to create a mycan.js build within my scripts dir which looks the same as the can.js file (except for the mustache dependency change) in bower_components and then I change the config to look like this.
require.config({
    paths: {
        jquery: '../bower_components/jquery/jquery',
        can: '../bower_components/canjs/amd/can',
        etc..

Then I require the mycan module in any of my files that need it.
This will work properly if I comment out the code inside bower_components/canjs/amd/can.js but if I don't comment the file out, it will require both builds (including the can/view/ejs file I didn't want).
In the require docs http://requirejs.org/docs/api.html under usage 1.1, it has an example of
•   www/
•   index.html
•   js/
•   app/
•   sub.js
•   lib/
•   jquery.js
•   canvas.js
•   app.js

and in app.js:
requirejs.config({
     //By default load any module IDs from js/lib
    baseUrl: 'js/lib',
    //except, if the module ID starts with "app",
    //load it from the js/app directory. paths
    //config is relative to the baseUrl, and
    //never includes a ".js" extension since
    //the paths config could be for a directory.
    paths: {
        app: '../app'
    }
});

// Start the main app logic.
requirejs(['jquery', 'canvas', 'app/sub'],
function   ($,        canvas,   sub) {
    //jQuery, canvas and the app/sub module are all
    //loaded and can be used here now.
});

Here they are using a path which is a directory, not a file. The sub module is getting found because it matches app/sub with the app in the paths config.
If I define my own version of can within the main.js file which contains the require.config then it seems to work but then when I go to build the app, it says
tim@machine:~/server/javascript/yoman:ruby-1.9.3: (master)$ grunt
Running "jshint:all" (jshint) task
Linting app/scripts/main.js ...ERROR
[L54:C1] W117: 'define' is not defined.
define('can', [

Warning: Task "jshint:all" failed. Use --force to continue.

Aborted due to warnings.

Elapsed time
default     567ms
jshint:all  124ms
Total       691ms

Whats the correct way for me to make a custom build of vendor libraries within bower_components?
Here is my main.js. This version works but fails when linting.
require.config({
    paths: {
        jquery: '../bower_components/jquery/jquery',
        bootstrapAffix: '../bower_components/sass-bootstrap/js/affix',
        bootstrapAlert: '../bower_components/sass-bootstrap/js/alert',
        bootstrapButton: '../bower_components/sass-bootstrap/js/button',
        bootstrapCarousel: '../bower_components/sass-bootstrap/js/carousel',
        bootstrapCollapse: '../bower_components/sass-bootstrap/js/collapse',
        bootstrapDropdown: '../bower_components/sass-bootstrap/js/dropdown',
        bootstrapPopover: '../bower_components/sass-bootstrap/js/popover',
        bootstrapScrollspy: '../bower_components/sass-bootstrap/js/scrollspy',
        bootstrapTab: '../bower_components/sass-bootstrap/js/tab',
        bootstrapTooltip: '../bower_components/sass-bootstrap/js/tooltip',
        bootstrapTransition: '../bower_components/sass-bootstrap/js/transition',
        can: '../bower_components/canjs/amd/can'
    },
    shim: {
        bootstrapAffix: {
            deps: ['jquery']
        },
        bootstrapAlert: {
            deps: ['jquery']
        },
        bootstrapButton: {
            deps: ['jquery']
        },
        bootstrapCarousel: {
            deps: ['jquery']
        },
        bootstrapCollapse: {
            deps: ['jquery']
        },
        bootstrapDropdown: {
            deps: ['jquery']
        },
        bootstrapPopover: {
            deps: ['jquery']
        },
        bootstrapScrollspy: {
            deps: ['jquery']
        },
        bootstrapTab: {
            deps: ['jquery']
        },
        bootstrapTooltip: {
            deps: ['jquery']
        },
        bootstrapTransition: {
            deps: ['jquery']
        }
    }
});

define('can', [
    'can/util/library',
    'can/control/route',
    'can/construct/proxy',
    'can/model',
    'can/view/mustache',
    'can/route'
], function(can) {
    'use strict';
    return can;
});

require(['app', 'jquery'], function (app, $) {
    'use strict';
    // use app here
    console.log(app);
    console.log('Running jQuery %s', $().jquery);
});

A: JSHint is complaining because require is in an external file. All require's functions are defined before your script loads, but because they're not inside the script JSHint thinks they're custom code which you forgot to define. This is an easy fix; add a predef config so that define, require are already passed to JSHint before it starts linting your files.
  jshint: {
     options: {
        // all of your other options...
        predef: ['define', 'require']
     },
     files : ['app/scripts/main.js']
  },


text:
Q: Why cellphone cameras don't have optical zoom I have just basic understanding of Physics from elementary school. But I still wonder, why after 10 years of cameras in cellphones, there is no "small-pack" optical zoom.
I think there should be no problem to make small, but still precise lenses. It should not be a problem to make small light sensor, while keeping large resolution. It should not be a problem to make tiny electric motor or servomotor to move the lenses and pack all that into 1 cm x 1 cm x 0.5 cm packing.
So what is the problem? I think there may be 3 explanations:

*

*There is some limit in physics (nature), that does not allow to
do that (which one?)

*There is some limit in engineering, which makes tiny optical zoom extremely expensive.

*It might work, but nobody came yet with the idea to make  tiny optical zoom.
Can you validate or disprove any of 1/2/3?

A: The fundamental reason for this is that light is quantized. If it wasn't for this, it would in theory be possible to scale down any camera to an arbitraily small size. However, as a camera is scaled down, less light will enter it and therefore fewer photons. As the number of photons hitting a pixel goes down, the shot noise goes up (the signal-to-noise-ratio goes as $\sqrt{N}$, where $N$ is the number of photons). This means there are fundamental limits to how small you can make the optics for a camera and still get acceptable noise levels. What these limits are exactly depends on a number of parameters, like light conditions, resolution, field of view (i.e. zoom level), quantum efficiency of the detector. The mobile cameras that exist tend to have fixed wide-angle optics (i.e. large fild of view = more light), because that reduces the noise problem. It might be possible to build tiny cameras with optical zoom, but they would probably produce very low quality images for the high zoom levels.


text:
Q: Question about the Proof of Bolzano-Weierstrass Theorem I am trying to wrap my head around the proof of B-W Theorem. Everything has been smooth so far, except when it comes to this. Please note that it has been proven, by the Nest Intervals Property, that there exists some $x\in\mathbb{R}$ such that $x\in\bigcap^\infty_{n=1}I_n$. Also, the proof supposes that there exists some $n\in\mathbb{N}$ such that $\epsilon>\text{ length of $I_n$}$. The aim here is to prove that $x$ is the limit point of a subset $S$ in $\mathbb{R}$.
It follows that given $\epsilon>0,$ if $y\in I_n$, then $|y-x|\leq\text{ length of $I_n$}<\epsilon$. (Ok.)
Therefore, the $\epsilon$-neighborhood of $x$ is a subset of $I_n$ (Why?). Since $I_n\cap S$ is infinite, there exists some $y\in S$ such that $y\in S\cap N_\epsilon(x)$ with $y\neq x$. (I don't get this.). Since the choice of $\epsilon$ is arbitrary, $x$ is a limit point of $S$.
(Note: $N_\epsilon(x)$ is the $\epsilon$-neighborhood of $x$.)
Please help.
Thanks.


text:
Q: Python memory limit? Clear GC when close to limit? How would I clear garbage collected objects before performing other memory intensive operations? Or is it done automatically when the memory is full?
Why does it seem that Python (+Eclipse) throws a Memory Exception at 2 GB (Win32) whereas actually still some memory is unused on Windows? Are there limits defined anywhere?

A: You can tweak the performance of the garbage collector with the gc module -- for example, with gc.set_threshold -- or you can "manually" collect the garbage: gc.collect. However, I believe that most of the time, objects are collected as soon as their refcount goes to zero.
So to be explicit about it, (thanks delnan!) garbage collection is only an issue when there are cyclic references that keep refcounts from reaching zero.
Note also this line from the gc docs:

To debug a leaking program call gc.set_debug(gc.DEBUG_LEAK).

A: On Windows 32bit Application have a limit of 2GB maximum memory. There a is a boot option that will bump it to 3Gb. You can also try upgrading to 64bit Windows/Python.


text:
Q: Biblatex urldate set to today When writing a document I want the urldate (the date of visit) of online bibliographical entries set to the day of compilation. Consider the following MWE:
\documentclass{article}
\usepackage[backend=biber]{biblatex}
\begin{filecontents}{references.bib}
@online{abc,
title = {This is a Title},
author = {Author, Some},
url = {http://www.somesite.com},
date = {2013-10-10},
urldate = {\year-\month-\day} % this does not work. Also urldate = {\today} doesn't.
}
\end{filecontents}

\addbibresource{references.bib}
\begin{document}
\cite{abc}.
\printbibliography
\end{document}

Unfortunately this does not work. The hypthens are in the text because biblatex expect dates to be in the form of yyyy-mm-dd. Any ideas on how to resolve this issue?

A: You can achieve this with the following:
\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map[overwrite=true]{
       \pertype{online}
       \step[fieldset=urldate,fieldvalue={\the\year-\the\month-\the\day}]
    }
 }
}

This definition overwrites every urldate field of the type online and used the current date.
\documentclass{article}
\usepackage[backend=biber]{biblatex}
\usepackage{filecontents}
\begin{filecontents}{references.bib}
@online{abc,
title = {This is a Title},
author = {Author, Some},
url = {http://www.somesite.com},
date = {2013-10-10},
urldate = {xxxx} % this does not work. Also urldate = {\today} doesn't.
}
\end{filecontents}

\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map[overwrite=true]{
       \pertype{online}
       \step[fieldset=urldate,fieldvalue={\the\year-\the\month-\the\day}]
    }
 }
}
\addbibresource{references.bib}
\begin{document}
\cite{abc}.

\printbibliography
\end{document}

A: Not exacty what you asked for, but perhaps a compromise of sorts, taking into consideration @Seamus' comment. I store a specific date (if you want, today) in a string and refer to that string in the single entries.
\documentclass{article}
\usepackage[backend=biber]{biblatex}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@string{today = {2013-12-11}}

@online{abc,
title = {This is a Title},
author = {Author, Some},
url = {http://www.somesite.com},
date = {2013-10-10},
urldate = today,
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}
\cite{abc}.
\printbibliography
\end{document}


text:
Q: RLMResults sortedArrayUsingComparator behavior I've got a one to many property that returns a RLMResults for an objectsWhere: query. I need to sort this data by linking up uid's in a linked list fashion (each object has a previousId property which points to the uid property of the object before it).
I can do this with an NSArray with sortedArrayUsingComparator like this:
myArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(MyRLMObject *obj1, MyRLMObject *obj2) {
    if ([obj1.parentTileId isEmpty]) { // head of the list must be sorted first
        return NSOrderedDescending;
    } else if ([obj1.previousId isEqualToString:obj2.uid]) {
        return NSOrderedDescending;
    } else {
        return NSOrderedAscending;
    }
}];

However, RLMResults only has sorting based on 1 property. Is there a way to get the same logic with RLMResults? As a fallback solution how can I convert RLMResults into NSArray to perform this?


text:
Q: Move Image on JFrame without repaint() I'm trying to build a 2d game.
I have a background-image that static and an Image of the character. When i press a move-key (WASD) the Mainclass (were the keylistener is) calling a function in a class called Player The function is changing the location of the character (Image). And after this function is called i use repaint() to repaint the character on new position.
If i remove the background i can see the old images still left from the other positions. So this meens i have to repaint the player and the background for each step.
There might be a better solution for this? Worst case scenario: It's an onlinegame and there are many players moving around and each 100 milliseconds the repaint is called for update every players posisions. I have a feeling this will take out all the memory of the players computer or at least the game will not feel so good

A: Don't paint directly in the JFrame content pane. Instead, override paintComponent() in a JComponent. This AnimationTest draws into a JPanel, which is double buffered by default. The example also shows one approach to examining the time budget devoted to painting.

A: As far as I know, there is no other solution. Repainting every 100 ms generally isn't too memory intensive on most computers.

A: I think repaint is the only solution, I once created a 2d car simulation game and that's what i do, I also change the coordinates of all Car objects and then repaint the whole thing. I tried to simulate 2000 Car objects running at 100 ms repaint on all of them without trouble. hehe fun

A:
(i used a jpanel inside the jframe) and use bufferedimage of java.awt.image

Instead you can try using a JLabel with Icons. Then all you do is invoke the setLocation(...) method of the label. The Swing RepaintManager will look after repainting the old location and the new location.
Here's an example to get you started. This example uses separate Timers for each image. In your game you would reset the location of all images at the same time when your single Timer fires.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AnimationBackground extends JLabel implements ActionListener
{
    int deltaX = 2;
    int deltaY = 3;
    int directionX = 1;
    int directionY = 1;

    public AnimationBackground(
        int startX, int startY,
        int deltaX, int deltaY,
        int directionX, int directionY,
        int delay)
    {
        this.deltaX = deltaX;
        this.deltaY = deltaY;
        this.directionX = directionX;
        this.directionY = directionY;

        setIcon( new ImageIcon("dukewavered.gif") );
        setSize( getPreferredSize() );
        setLocation(startX, startY);
        new javax.swing.Timer(delay, this).start();
    }

    public void actionPerformed(ActionEvent e)
    {
        Container parent = getParent();

        //  Determine next X position

        int nextX = getLocation().x + (deltaX * directionX);

        if (nextX < 0)
        {
            nextX = 0;
            directionX *= -1;
        }

        if ( nextX + getSize().width > parent.getSize().width)
        {
            nextX = parent.getSize().width - getSize().width;
            directionX *= -1;
        }

        //  Determine next Y position

        int nextY = getLocation().y + (deltaY * directionY);

        if (nextY < 0)
        {
            nextY = 0;
            directionY *= -1;
        }

        if ( nextY + getSize().height > parent.getSize().height)
        {
            nextY = parent.getSize().height - getSize().height;
            directionY *= -1;
        }

        //  Move the label

        setLocation(nextX, nextY);
    }

    public static void main(String[] args)
    {
        JPanel panel = new JPanel(null)
        {
            Image image = new ImageIcon("mong.jpg").getImage();

            protected void paintComponent(Graphics g)
            {
                g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
                super.paintComponent(g);
            }
        };
        panel.setOpaque(false);
//      panel.add( new AnimationBackground(10, 10, 2, 3, 1, 1, 10) );
        panel.add( new AnimationBackground(300, 100, 3, 2, -1, 1, 20) );
        panel.add( new AnimationBackground(200, 200, 2, 3, 1, -1, 20) );
        panel.add( new AnimationBackground(50, 50, 5, 5, -1, -1, 20) );
//      panel.add( new AnimationBackground(0, 000, 5, 0, 1, 1, 20) );
        panel.add( new AnimationBackground(0, 200, 5, 0, 1, 1, 80) );

        JFrame frame = new JFrame();
        frame.setContentPane(panel);
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(400, 400);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}

You will need to provide a background image and an image for the label where the code creates an ImageIcon.

A: There is efficient to redraw only part of your component.  Read this tutorial.
Basically you have to call component.repaint(posX, posY, length, height) twice:
once at he old player image position (will repaint the background) and then at the new position.
(This solution was also proposed by G_H in the comments.)


text:
Q: Find a complex number geometrically
Consider the triangle $\Delta ABC$, which $D$ is the midpoint of segment $BC$, and let the point G be defined such that $(GD)= \frac{1}{3}(AD)$. Assuming that $z_A, z_B, z_C$ are the complex numbers representing the points $(A, B, C)$:
a. Find the complex number $z_G$ that represents the point $G$
b. Show that $(CG)= \frac{2}{3}(CF)$ and that $F$ is the midpoint of the segment $(AB)$

How would you go about solving this? I would apply the distance formula but I am not given any actual complex number. I know that a complex number can be represented as a vector connected to origin.

A: Let $z_1, z_2, z_3$ be the points A,B,C. Then it is clear that
$$D=\frac{z_2+z_3}{2}$$
The parametric equation of the line from $D$ to $A$ is
$$\gamma(t)=\frac{z_2+z_3}{2}+t (z_1 -\frac{z_2+z_3}{2})$$
Therefore $G=\gamma( \frac{1}{3} )$ which you can simplify.
For the second part  take the midpoint of AB and repeat the calculation. If you get exactly the same answer  then you are done.


text:
Q: Is elements' order always kept, saving an array into a serialized field? I would like to save an array of strings into a "serialize" field. But I'm afraid that its order will not be kept, when I deserialize it.
I've done some test, and it seems ok. Have you  suggestions?
Thanks in advance
P.s. I'm working with Ruby 1.8.7 and rails 2.3.x

A: If it's an array, then yes. Arrays are ordered.
Sets are not (guaranteed) to be ordered. Hashes (keys, values, pairs) are also not (guaranteed) ordered.
Hmm, that hash ordering thing seems to be ruby-version-dependent:
Hash ordering preserved between iterations if not modified?
I would always assume unordered hashes, though.


text:
Q: How can I quote back-tics in a bash function? I want a function in my .bash_profile like this:
function usb() {
    cd `pwd`
}

But when I run that, it does not go to the current directory, it goes to my home directory. I tried quoting the back-tics a few different ways, but could not figure it out.

A: Without getting into why you would want to write this function, it should look like
usb () {
    cd "$(pwd)"
}

usb () { "`pwd`"; } would work, but $(...) is generally preferred over `...`.


text:
Q: Connect VB.net to SQL Server Express mdf I am very experienced with MS Access, but I am trying to transition to to VB.net and SQL Server.  I am trying to build a multi-user database.  The mdf file would be on some computer on the LAN, and each connected computer would have the application.  I need a way to let the end users select the path to the mdf file, so only one mdf file is used.  I've got a working method, but I want to make sure I'm on the right track.  When a form loads, I have this:
My.Settings("mslConnectionString") = "Server=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=E:\Documents\Visual Studio 2013\Projects\WindowsApplication3\WindowsApplication3\msl.mdf;"

Is that an appropriate way to link to the backend mdf file?  What I envision doing is making a form where the end user can navigate to the correct network path, and then I guess I'd store that path in a text document.  When the form is opened, it would first look at the text document and change the path at runtime.  Thanks in advance.

A: What you have there is a "LocalDB" connection string.  LocalDB is a lightweight implementation of SQL server that can attach directly to an mdf file.  It is commonly used to have one "client" attached to it at a time.  You can't share that same .mdf file directly from multiple applications like you can with Access.
If you want to do something like that with SQL, you need to install SQL Server.  SQL Server will attach to the .mdf file and allow multiple connected clients to use it at the same time.
The full version of SQL Server is /very/ expensive, but there is a "Lite" version that is free, with a few restrictions, called SqlExpress.
It is also possible to set up LocalDB in such a way as it hosts the database file as if it were a full sql server, but this involves a little bit more work and complexity.  If you want more information about this, check out MSDN, specifically the section that talks about "Named Instances".


text:
Q: Is a continuous function necessarily the pointwise limit of a sequence of uniformly continuous functions? The pointwise limit of a sequence of uniformly continuous functions needn't be continuous. I've been wondering about the converse:

Is a continuous function $f$ necessarily the pointwise limit of some sequence of uniformly continuous functions $(f_n)_{n\in\mathbb{N}}$?

I'm having trouble establishing or disproving this.

A: If the domain of $f$ is $\Bbb R$, then the answer is yes. The proof is quite easy: let $f_n: \Bbb R \to \Bbb R$ defined by
$$f_n(x)= \begin{cases}
f(-n) & x<-n \\
f(x) & -n \le x \le n \\ f(n) & x>n \end{cases}$$
these are uniformly continuous and they pointwise converge to $f$.


text:
Q: react boolean attribute not working, video not autoplaying I have a react <video> component. And I have added autoplay as an attribute.
<video autoplay muted src="/vids/vid.mp4">

And not working. But when I set autoplay="true" it starts working.
<video autoplay="true" muted src="/vids/vid.mp4">  //Works

why is it for a boolean attribute, only putting autoplay is not working on react? on other occasions for attributes like hidden it works.
Why is this happening? Which one is the correct way to specify boolean attribute?

A: I had the same problem with the autoplay attribute with React. You want to use autoPlay instead. You should then just be able to use it like this:
<video autoPlay muted src="/vids/vid.mp4">


text:
Q: Kohana Cache Module not loading set servers (kohana 3.2) I am having an issue with the Cache module Configuration.
I have done the following:

*

*put Cache::$default = 'memcachetag'; in bootstrap.php

*copied modules/cache/config/config.php to application/config/config.php with the following config:
return array(
  // Override the default configuration
  'memcachetag'   => array(
    'driver'         => 'memcachetag',  // Use Memcached as the default driver
    'default_expire' => 8000,        // Overide default expiry
    'servers'        => array(
       // Add a new server
       array(
         'host'       => 'server',
         'port'       => 11211,
         'persistent' => FALSE
       )
    ),
    'compression'    => FALSE
  )
);

The problem is the 'servers' are not being overridden so its always pulling from the modules config file (host name is localhost always)
I am make an instance with Cache::instance() and checking the values with echo Debug::vars(Cache::instance());
Thanks in advance!

A: I solved this by creating a new Cache config group that was named different then all the others and then setting that as the default group in bootstrap.

A: Your file listing needs to be built up the same in all three layers of a Kohana project (system, modules and application) to allow for overloading of files.
So you need to put your overloaded config file in application/config/cache.php and not in modules/application/config.php. The cache config file is in modules/cache/config/cache.php so this file will get overloaded with your config file.
Look here: http://kohanaframework.org/3.2/guide/cache/config#group-settings

Below are the default cache configuration groups for each supported driver. Add to- or override these settings within the application/config/cache.php file.


text:
Q: Read XML file with namespace , using java i'd like to know how i can browse this XML file to get some values (like VersionXSD, Support, etx...). Without namespaces i can do it but with namespace i get no result.
<?xml version="1.0" encoding="UTF-8"?>
<ROOT Id="myRefId"
xsi:schemaLocation="urn:ir:si_my_xsd_07.xsd"
xmlns="urn:ir:se_pelmed" xmlns:nmsps="urn:siram:nmsps"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Horodatage>2013-03-05T12:00:00</Horodatage>
<VersionXSD>01.01</VersionXSD>
<BASE>
    <nmsps:Numero>NUM-123-456</nmsps:Numero>
    <nmsps:Type>TATA</nmsps:Type>
    <nmsps:Support>PASTIS</nmsps:Support>
    <nmsps:DateLimite>2013-03-04</nmsps:DateLimite>
    <nmsps:Serial>0</nmsps:Serial>
    <nmsps:BASEA>
        <nmsps:NomFamille>Paul</nmsps:NomFamille>
        <nmsps:Prenom>Hilaire</nmsps:Prenom>
        <nmsps:DateNai>1979-10-11</nmsps:DateNai>
        <nmsps:Sexe>Masculin</nmsps:Sexe>
    </nmsps:BASEA>
    <nmsps:BASEC Id="1">
        <nmsps:Validite>2013-03-04</nmsps:Validite>
        <nmsps:Sub>true</nmsps:Sub>
        <nmsps:Stup>true</nmsps:Stup>
    </nmsps:BASEC>
    <nmsps:BASED Id="1">
        <nmsps:Numero R="DD1">numero1</nmsps:Numero>
        <nmsps:Categorie>Categorie1</nmsps:Categorie>
    </nmsps:BASED>
    <nmsps:BASED Id="2">
        <nmsps:Numero R="DD2">numero2</nmsps:Numero>
        <nmsps:Categorie>Categorie2</nmsps:Categorie>
    </nmsps:BASED>
    <nmsps:BASED Id="3">
        <nmsps:Numero R="DD3">numero3</nmsps:Numero>
        <nmsps:Categorie>Categorie3</nmsps:Categorie>
    </nmsps:BASED>
</BASE>
</ROOT>

A: You can either bypass the namespace using local-name() i.e. //*[local-name()='Support']
or instantiate one as flup suggested, which is how I would do it, it makes things much easier.


text:
Q: Mix webcam video, audio with gstreamer How to mix h264 format with audio on webcam with gstreamer?
gst-launch-1.0 -v v4l2src device=/dev/video2 ! video/x-h264,framerate=30/1,width=1920,height=1080 \
! queue ! mux. \
alsasrc device=hw:1 ! queue ! audioconvert ! fdkaacenc \
! mux. matroskamux name=mux ! filesink location=video.mkv

Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Pipeline is PREROLLED ...
Setting pipeline to PLAYING ...
New clock: GstAudioSrcClock
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Internal data stream error.
Additional debug info:
../libs/gst/base/gstbasesrc.c(3127): gst_base_src_loop (): /GstPipeline:pipeline0/GstV4l2Src:v4l2src0:
streaming stopped, reason not-negotiated (-4)
Execution ended after 0:00:00.001309727
Setting pipeline to NULL ...
Freeing pipeline ...

Preview works
gst-launch-1.0 -v \
v4l2src device=/dev/video2 ! video/x-h264,framerate=30/1,width=1920,height=1080 ! decodebin ! autovideosink

Audio works
gst-launch-1.0 -v alsasrc device=hw:1 ! queue ! audioconvert ! fdkaacenc ! fdkaacdec ! autoaudiosink

A: h264parse needed before mux
gst-launch-1.0 -v \
v4l2src device=/dev/video2 ! queue ! video/x-h264,framerate=30/1,width=1920,height=1080 \
! h264parse ! mux. \
alsasrc device=hw:1 ! queue ! audioconvert ! fdkaacenc ! mux. \
matroskamux name=mux ! filesink location=video.mp4


text:
Q: subprocess.call exit code in python I have a use case where I execute a java jar through python subprocess. How can I get to know if the subprocess completed successfully or terminated because of some exception. Subprocess does return an exit code but the jar does not handle returning appropriate exit codes.
Is there some other way to do this?
class Test(object):
     #constructor
     .
     .
     def execute(self):
         exit_code = subprocess.call(['jar_path'])
         if not exit_code:
             return True
         else:
             return False

A: Since you say -

Ques : does the jar report correct exceptions to stdout or stderr ?
Ans : yes it does support.

You can use subprocess.Popen() along with .communicate() and subprocess.PIPE to get the data from stdout/stderr and parse that appropriately to determine whether there was any exception.
Example -
 def execute(self):
     proc = subprocess.Popen(['jar_path'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     pout,perr = proc.communicate()
     if not perr:  #or however you want to check stderr/stdout
         return True
     else:
         return False


text:
Q: Convert a date format in epoch I have a string with a date format such as
Jun 13 2003 23:11:52.454 UTC

containing millisec... which I want to convert in epoch.
Is there an utility in Java I can use to do this conversion?

A: You can also use the Java 8 API
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class StackoverflowTest{
    public static void main(String args[]){
        String strDate = "Jun 13 2003 23:11:52.454 UTC";
        DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
        ZonedDateTime     zdt  = ZonedDateTime.parse(strDate,dtf);
        System.out.println(zdt.toInstant().toEpochMilli());  // 1055545912454
    }
}

The DateTimeFormatter class replaces the old SimpleDateFormat. You can then create a ZonedDateTime from which you can extract the desired epoch time.
The main advantage is that you are now thread safe.
Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.

A: Unfortunately,
the solution provided in all existing answers will fail if you run them on a system with Non-English Locale because the given date-time string is in an English. Never use SimpleDateFormat or DateTimeFormatter without a Locale as they are Locale-sensitive.
The accepted answer uses legacy date-time API which was the correct thing to do using the standard library in 2011 when the question was asked. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.
Demo using java.time API:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        long epochMillis = ZonedDateTime.parse(
                    "Jun 13 2003 23:11:52.454 UTC",
                    DateTimeFormatter.ofPattern(
                        "MMM d uuuu HH:mm:ss.SSS z",
                        Locale.ENGLISH
                    )
                )
                .toInstant()
                .toEpochMilli();
        System.out.println(epochMillis);
    }
}

Output:
1055545912454

Learn more about the modern Date-Time API from Trail: Date Time.

A: tl;dr
ZonedDateTime.parse(
                        "Jun 13 2003 23:11:52.454 UTC" ,
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
                    )
              .toInstant()
              .toEpochMilli()

1055545912454

java.time
This Answer expands on the Answer by Lockni.
DateTimeFormatter
First define a formatting pattern to match your input string by creating a DateTimeFormatter object.
String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime
Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).
ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

Count-from-epoch
I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).
But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.
Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ;

1055545912454

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 brought some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android (26+) bundle implementations of the java.time classes.

*For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.

*

*If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

A: This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:
String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

A: Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}

A:   String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10
   DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
        LocalDateTime zdt  = LocalDateTime.parse(dateTime,dtf);
        LocalDateTime now = LocalDateTime.now();
        ZoneId zone = ZoneId.of("Asia/Kolkata");
        ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
        long a= zdt.toInstant(zoneOffSet).toEpochMilli();
        Log.d("time","---"+a);

you can get zone id form this  a link!


text:
Q: Auto-renewable subscription receipt date format I'm struggling to figure out the formatting for the following date:
2011-05-24 19:02:32 Etc/GMT
This date is returned from Apple's receipt validation service and I need to turn it into a NSDate for some comparison operations.  The real trouble is related to the timezone.
Here's some code I've already written:
        NSDictionary *receiptData = [info valueForKey:@"expires_date"];

        NSDateFormatter *f = [[NSDateFormatter alloc] init];

        [f setLocale:[NSLocale currentLocale]];
        [f setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        [f setDateFormat:@"yyyy-MM-dd HH:mm:ss vvvv"];

        NSLog(@"%@", [f stringFromDate:[NSDate date]]);

        NSDate *subPurchaseDate = [f dateFromString:[receiptData valueForKey:@"original_purchase_date"]];

        [f release];

I've tried all combinations of 'v's and 'Z's that I can think of.  Any insight?

A: After doing some more research, the code I'm using here works, but is suspect;
   NSString *purchaseDateString = [@"2011-05-24 19:02:32 Etc/GMT" stringByReplacingOccurrencesOfString:@" Etc/GMT" withString:@""];
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   NSLocale *POSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
   [formatter setLocale:POSIXLocale];
   [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
   [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

   NSDate *purchaseDate = [formatter dateFromString:purchaseDateString];

I don't like the assumptions I am making about the incoming date string and so I am assuming this code may break for other stores (I'm testing against the UK one). So although this kind of works for my own situation, I'd really like to see a more robust solution that actually parses the timezone string correctly as per the original question.
I can't quite believe Apple have used a deprecated timezone (all the Etc/* ones are officially deprecated) in these important date strings!
EDIT:
I note you are using
NSDictionary *receiptData = [info valueForKey:@"expires_date"];

This is not actually a string according to the documentation it should be "The expiration date of the subscription receipt, expressed as the number of milliseconds since January 1, 1970, 00:00:00 GMT"
However the question is still valid as you have to use the purchase_date field when working with restored subscriptions and this field is in the text format you have described.

A: By looking at the date format documentation I got the correct format, is works well for me:
        NSDateFormatter * formatter = [NSDateFormatter new];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss VV";

        NSDate * purchaseDate = [formatter dateFromString:latestTransaction[@"original_purchase_date"]];
        NSDate * expirationDate = [formatter dateFromString:latestTransaction[@"expires_date"]];

No need to set the time zone on the formatter since it's embedded in the string.
Manipulating the date string to parse it is not a good idea.

Source: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

A: The following code can be used to parse RFC 3339 dates found in App Store receipts:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
formatter.timeZone = TimeZone(secondsFromGMT: 0)

let date = formatter.date(from: "2020-06-17 10:59:33 Etc/GMT")

Note that it is necessary to set the timeZone as well as the locale. Also setting locale before dateFormat is important according to Technical Q&A QA1480.
Apple recommends using the newer ISO8601DateFormatter API on iOS 10+ and macOS 10.12+.

A: This is what I do on Swift 3 to convert the date from an auto-renewable date from a receipt.
let expirationDate = "2017-08-16 23:10:35 Etc/GMT"
let receiptDateFormat = "yyyy-MM-dd HH:mm:ss VV"
let theDateFormat = DateFormatter.Style.medium
let theTimeFormat = DateFormatter.Style.medium
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = receiptDateFormat
let firstDate = dateFormatter.date(from: stringDate)
dateFormatter.dateStyle = theDateFormat
dateFormatter.timeStyle = theTimeFormat

let result = dateFormatter.string(from: firstDate!)


text:
Q: Error when trying to extend a class using 'mixin' The following snippet of code is one that I have used from a tutorial I found online:
package com.jktech.minend.common.events;
import net.minecraft.entity.ItemEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;

@Mixin(ItemEntity.class)
public abstract class itemevents extends ItemEntity {
    public itemevents(World world, double x, double y, double z, ItemStack stack, doublevelocityX, double velocityY, double velocityZ) {
        super(world, x, y, z, stack, velocityX, velocityY, velocityZ);
    }
}

Although the code compiles, it still shows errors on runtime, yet the game doesn't crash. However, my functions don't execute and nothing happens (as if they weren't applied in the first place).
[14:16:45] [main/ERROR] (mixin) minend.mixins.json:itemevents: Super class 'net.minecraft.entity.ItemEntity' of itemevents was not found in the hierarchy of target class 'net/minecraft/entity/ItemEntity'

org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException: Super class 'net.minecraft.entity.ItemEntity' of itemevents was not found in the hierarchy of target class 'net/minecraft/entity/ItemEntity'

A: There is multiple ways to do it:

*

*Use Entity
You can fix it by extends Entity instead of ItemEntity.

*Use a specific entity type

For example, AnimalEntity can solve your issue.
Finally, if for example you need to get entity's stack, you can thos like that:
public ItemStack getStack(){
   return ((ItemEntity) this).getStack();
}


text:
Q: What is the difference between Kafka Template and kafka producer? As I have seen the Kafka template internally used Kafka producer. I just want to know what is the exact difference.
Also, I found many send() methods available in the Kafka template as compared to Kafka producer.
Please help me with it. If anyone knows more.

A: The producer is the pattern, while the KafkaTemplate wraps a Producer instance and provides convenience methods for sending messages to Kafka topics. (source)
The Kafka Producer is defined in Apache Kafka. The KafkaTemplate is Spring's implementation of it (although it does not implement Producer directly) and so it provides more methods for you to use. So you can use KafkaTemplate to get started or implement your own solution through implementing the Producer yourself.

A: Kafka Producer is the term for producer in PubSub Pattern.
If you want to implement Apache Kafka using Spring, Spring has provided a wrapper around this producer which we call as Kafka Template.
Kafka template is a class which spring provides to produce messages into the Kafka Topic.
How Kafka Template works::
There are different layers in which Kafka Template does its tasks -

*

*SERLIALIZER Any record that we intend to send to the Kafka topic, needs to be serialised to bytes. ( 2 techniques involved - a) key.serializer b) value.serializer )

*Partitioner It determines in which partition the message is going to go.

*Record Accumulator It buffers all the records sent by Kafka template and these records only sent to the Kafka Topics when this buffer gets full.(However, linger.ms file is there where we can set the time limit)


text:
Q: Finding the inverse of an integral I'm looking for a computational approach here, since I don't think there is a closed-form solution.
I have the following:
$$ s(x) = \rho + \int_{\rho}^{x} \sqrt{ 1 + (\alpha \cos t - k)^2 } \, dt $$
$ k = \frac{\rho \sin \alpha - \alpha \sin(\rho \cos \alpha)}{\frac{\pi}{2} - \rho \cos \alpha} $ for $x<\frac{\pi}{2}$, otherwise $k=0$.
The following are all constants: $0 < \rho < \frac{\pi}{2}$, $0 < \alpha < \frac{\pi}{2}$ (and thus $k$).
I'd like to find $x$ such that $s(x) = r$ for some constant $0 \le r \le \pi$.
The interesting thing is that $s(x)$ is an elliptic integral for $x \ge \frac{\pi}{2}$, because $k=0$.  However, my lower limit $\rho$ means that I need to handle $k \ne 0$.
My hunch is that I can use some kind of series expansion here. Any ideas?

A: The numerical approach I would use here is quite obvious: reducing the problem to an ODE. From the integral itself it's clear that:
$$\frac{ds}{dx} = \sqrt{ 1 + (\alpha \cos x - k)^2 }$$
$$s(\rho)=\rho$$
Now we simply invert the function:

$$\frac{dx}{ds} = \frac{1}{\sqrt{ 1 + (\alpha \cos x - k)^2 }}$$
$$x(\rho)=\rho$$

Now we use any suitable numerical scheme, for example, the simplest explicit Euler method.
$$x_0=\rho$$
$$x_{n+1}=x_n+\frac{\Delta s}{\sqrt{ 1 + (\alpha \cos x_n - k)^2 }}$$
To reach $r$ we take:
$$\Delta s=\frac{r-\rho}{N}$$
Then:
$$x_{N} \approx x(r)$$


text:
Q: php checking if a remote rtmp file exists
Possible Duplicate:
Check if file exists on remote machine

If I have a URI like this
rtmp://.../mp4:20122013/..._16x9_1.mp4

is there a way in php that can verify and return if that exists or not?  if not in php how can I achieve my purpose?

A: Next time do a deeper research on google and stackoverflow.
This article explains how to check if a rtmp stream is up or down using PHP and rtmpdump.
How to check RTMP source stream is live or not?
if you prefer/need doing this with php native you can use this library
php-rtmp-client
UPDATE
in your case it will need to run :
rtmpdump -v -v -r "rtmp://flash.onthefly.nhl.com/ondemand/NHLHighlights//mp4:20122013/02/0118/2_118_nsh_sjs_1213_h_continuous_1600K_16x9_1.mp4" -W "http://nhl.cdn.neulion.net/u/videocenter/flex/images/evp.swf"

Check rtmpdump for more info.


text:
Q: Does Windows 8 Have Limited Duration Licences? A family member bought a new laptop for personal use with Windows 8 preinstalled. It had been working without issues for the past two months or so, but has now started displaying warnings about its licence expiring in a month.
On the activation page it displays a key already entered, but I don't know anything about the key type. Pressing the activation button produces no feedback on whether the activation process failed or why.
What I want to know is whether there is such a thing as an activation key that grants a mere three months licence for Windows 8 - meaning we need to purchase a new, longer-lasting licence, or whether there could be some problem with the activation process.

A: When in doubt, I call the Microsoft activation center.  It's not a painful process.
You should be able to reach the right phone number using these instructions :
http://support.microsoft.com/kb/950929


text:
Q: why this jQuery animation loop doesn't work? <script>
function swim() {

    $("#ship").animate({left: "-=-540px"}, 3000, function() {

        $("#ship").css("-moz-transform", "scaleX(-1)");
        $("#ship").css("-o-transform", "scaleX(-1)");
        $("#ship").css("-webkit-transform", "scaleX(-1)");
        $("#ship").css("transform", "scaleX(-1)");
        $("#ship").css("filter", "FlipH");
        $("#ship").css("-ms-filter", "FlipH");
        $("#ship").animate({left: "-=540px"}, 3000);
        swim();

        })

    }

    swim();

</script>

When I use only document.ready works fine, but stops after an attempt to turn it to a loop. There must be a syntax bug somewhere but I can't figure out where.
EDIT: nvm. It was the case of putting the script to <head> instead of <body>.

A: There's a reason why it needs the document ready wrapper. A "normal" function isn't an equal replacement for it. If you call the function before the DOM is ready, the #ship selector doesn't match anything, the animation doesn't run, and the callback isn't executed.
Call the function in a document ready event:
$( swim );


text:
Q: Compare two RTF files using Python I have two folders with RTF files, the filenames are same in both folders
RTF files consists of Header and Footer in every page
I have to ignore the Header and Footer part in every page and compare the content of body part
I did something like this so far, Im not sure whether this is the right way but it works(reads and compare the exact content)

txt_1 = 'D:\\files\\1'
txt_2 = 'D:\\files\\2'

fol_1 = []
fol_2 = []
for fname in os.listdir(path=txt_1):
    fol_1.append(fname)
for fname in os.listdir(path=txt_2):
    fol_2.append(fname)

for i in fol_1:
    for j in fol_2:
        if i == j:
            file_1 = open(txt_1 + '\\' + i).read()
            file_2 = open(txt_2 + '\\' + j).read()
            if file_1 == file_2:
                print('Matches')
            else:
                print('Files didnt match: ' + i)

Is there any way to ignore the Header and Footer part in every page
Or is there any way to ignore a String/Line in the footer/header part
Is there any python modules i should look for,
Please give me some suggestions, thank you!

A: I dont think we can't directly read and compare RTF files based on your code.
You have to use additional RTF libraries in your code to read and manipulate your logic.
See if this link is helpful for you.


text:
Q: Angular JS Display String Array From Json

  {{address.addressLines}}

The problem is with my {{address.addressLines}}
This is currently a string array so my value on screen is printed out like
["address1","address2","address3","address4"]
But I just want it printed like
address1,address2,address3,address4

A: You can do this using join also :

          {{address.addressLines.join()}}

A: I thing somthing like this would work...

   {{a}},

A: There are fundamentally 2 ways:
1) By using native angular directives:

        {{f}},

2) By writing a simple filter (best way):
angular.module('app', []).filter('arrayToList', function(){
        return function(arr) {
            return arr.join(',');
        }
    });

{{foo|arrayToList}}

This is the working example on jsfiddle: http://jsfiddle.net/g0dmazzk/

A: To avoid dealing with the comma in the last item on the list, I used a class (label from Bootstrap) like this:
 {{ a }}


text:
Q: Oracle Primavera P6 refreshing the screen issue I have installed Oracle Primavera P6 V17 and when I move the divider line between Gantt chart and activities some black lines appeared.
When I refresh the screen or click on the screen these black lines disappear.
How can I resolve this problem?

A: We all have the same issue. Usually clicking on a new activity is enough to right the screen. No fixes that I'm aware of.

A: Very familiar issue.
a) Upgrade to a newer version or
b) Install more memory or
c) Close memory hungry applications - eg. Teams.


text:
Q: Configuring Homestead error When I use vagrant up command I have this error message:
Bringing machine 'name' up with 'parallels' provider...
==> name: Checking if box 'laravel/homestead' is up to date...
==> name: Clearing any previously set forwarded ports...
==> name: Preparing network interfaces based on configuration...
name: Adapter 0: shared
name: Adapter 1: hostonly
==> name: Clearing any previously set network interfaces...
==> name: Forwarding ports...
name: 80 => 8000
name: 443 => 44300
name: 3306 => 33060
name: 5432 => 54320
name: 8025 => 8025
name: 27017 => 27017
==> name: Running 'pre-boot' VM customizations...
==> name: Booting VM...
==> name: Waiting for machine to boot. This may take a few minutes...
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

On Parallels the VM is created and when I launch I arrive to login page.
I'm using PhpStorm on Mac and followed this tutorial: http://www.pascallandau.com/blog/laravel-with-phpunit-on-vagrant-in-phpstorm/
How can I fix the issue?


text:
Q: how to i add custom field in checkout page magento 2
I want to add a custom field in the checkout page Magento 2
how I will add and also store that field values
anyone could help?

A:
Reference Link :-

creating-custom-fields-using-magento-2-ui-components
enter link description here
magento2-checkout-custom-form

A: This is the perfect solution to your need. Bit lengthy process but this is how the implementation is processed.

Check out this link https://magento.stackexchange.com/a/187848/45214 .


text:
Q: Adaptive payments funding type Trying to setup a parallel payment in paypal but need to give the user specific options on funding type
I would like to only give them "debitcard" or "creditcard" or "Balance" in seperate calls.
is this possible?
looking at this link it has them in "fundingsource fields" and are seperated with "allowed" being true or false
https://developer.paypal.com/docs/classic/api/adaptive-payments/Pay_API_Operation/
is this possible or would i need the extended permissions?
thanks

A: From the Developer Guide (Page 14) there are only two permission levels. Standard and Advanced.
The page you linked says "Note: FundingConstraint is unavailable to API callers with standard permission levels; for more information, refer to the section Adaptive Payments Permission Levels."
Yes this will work to limit which funding sources can be used (eCheck,CreditCard,Balance), however, you need the advanced permissions for this.


text:
Q: Error - NoReverseMatch I am stuck with this :  revWaves
Error message is : "NoReverseMatch"
Reverse for 'home()' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I have created namespace for 'newapp' and url path is also correct i.e. /static/newapp/home.html and above  revWaves goes into header.html
So i am not able to figure out what is the error. Kindly help.
Main Urls.py
from django.conf.urls import url , include
from django.contrib import admin

urlpatterns = [
    url(r'^newapp/', include('newapp.urls', namespace='newapp')),
]

newapp urls.py
from django.conf.urls import url , include
from . import views

urlpatterns = [
    url(r'^$',views.home) ,
    url(r'^about$',views.about) ,
    url(r'^services',views.service) ,
    url(r'^customers',views.customer),
    url(r'^contact',views.contact) ,
    ]

views.py
from django.shortcuts import render

# Create your views here.

def home(request) :
    return render(request, 'newapp/home.html')

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

def service(request):
    return render(request, 'newapp/services.html')

def customer(request):
    return render(request, 'newapp/customers.html')

def contact(request):
    return render(request, 'newapp/contact.html')

header.html
<!DOCTYPE html>

<title>Ady Rules</title>
<meta charset="utf-8"/>

{% load static %}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Satisfy" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="{% static "newapp/style.css" %}"/>