text:
Q: Python Pandas Reshape Data Frame It seems to be very basic knowledge, but I got stuck despite having some theoretical background in data processing (via other software). Worth to mention I'm new to python and pandas library.
So. I've got a data frame:

My task is to put values of 'Series Name' column as separate columns (transform from long to wide). I've spent ages trying different methods, but got only errors.
For example:
mydata = mydata.pivot(index=['Country', 'Year'], columns='Series Name', values='Value')

And I got an error:

... a lot of text...
  ValueError: Length of passed values is 2487175, index implies 2

Could anybody guide me through that process please? Thanks.
It's for the code
'mydata = mydata.pivot(index=['Country', 'Year'], columns='Series Name', values='Value')'
Error message:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-8169d6d374c7> in <module>
----> 1 mydata = mydata.pivot(index=['Country', 'Year'], columns='Series Name', values='Value')

~/anaconda3_501/lib/python3.6/site-packages/pandas/core/frame.py in pivot(self, index, columns, values)
   5192         """
   5193         from pandas.core.reshape.reshape import pivot
-> 5194         return pivot(self, index=index, columns=columns, values=values)
   5195
   5196     _shared_docs['pivot_table'] = """

~/anaconda3_501/lib/python3.6/site-packages/pandas/core/reshape/reshape.py in pivot(self, index, columns, values)
    412         else:
    413             indexed = self._constructor_sliced(self[values].values,
--> 414                                                index=index)
    415     return indexed.unstack(columns)
    416

~/anaconda3_501/lib/python3.6/site-packages/pandas/core/series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    260                             'Length of passed values is {val}, '
    261                             'index implies {ind}'
--> 262                             .format(val=len(data), ind=len(index)))
    263                 except TypeError:
    264                     pass

ValueError: Length of passed values is 2487175, index implies 2

A: Try maybe:
mydata = mydata.pivot_table(index=['Country', 'Year'], columns='Series Name', values='Value', aggfunc='sum')

(If you want to sum your Value) it seems that you need to somehow aggregate your data explicitly.
Although would be good, if you would share full error message.
I managed to reproduce your error. Like I said- you need to provide aggregating function:
import pandas as pd

df=pd.DataFrame({"a": list("xyzpqr"), "b": list("abbbaa"), "c": [4,3,6,2,7,5], "d": list("pqqppp")})

df2=df.pivot(index=["b", "d"], columns="a", values="c")
#ValueError: Length of passed values is 6, index implies 2

df2=df.pivot_table(index=["b", "d"], columns="a", values="c", aggfunc=set)
#works fine - you need aggregation function e.g. list/set to collect all/unique values or e.g. sum/max to do some numeric operation

A: Nearly there. The resulting table is
How is it possible to to put 'Country' and 'Year' to the same level as other column names to be able to export it normally to excel? If I export like it is now 'Country' and 'Year' not included in the table.


text:
Q: Current IP Of LDAP Host In Round Robin IP selection I have a LDAP server ( for example ldaps://abc.example.com).
I am using @ldap_connect() function and program in PHP for getting connection with ldap. This host has more than one ips configured for it and uses them in round robin fashion. So is there any way by which I can get the current ip with whom currently its connected from within these ips?
Code:
$host = "ldaps://abc.example.com";
$binddn = "cn=user,ou=My Accounts,ou=TestUsers,ou=Test System   access,dc=abc,dc=example,dc=com";
$password = "xyz"
for( $i = 0; $i < 3; $i++ )
{
    $conn = @ldap_connect( $host );
    if ( !$conn )
    {
        sleep(1);
        continue;
    }
    echo "Connected at $host (my attempt count is $i): ";
    print_r($conn, true);
    @ldap_set_option( $conn, LDAP_OPT_PROTOCOL_VERSION, 3 );
    @ldap_set_option( $conn, LDAP_OPT_REFERRALS, 0 );
    echo "Binding at $host (my attempt count is $i)";
    $Resource = @ldap_bind( $conn, $binddn, $password );
    if ( $Resource )
    {
        break;
    }
    echo "Bind failed to AD at $host (my attempt count is $i): " . trim (@ldap_error($conn);
    @ldap_close( $conn );
    sleep(1);
}

A: As you will only be connecting to the same A record, you could just use the gethostbyname() function to give you the IP of the connected server. You would then use gethostbyaddr() to perform a reverse lookup (IP to Hostname) to grab the PTR record. This variable assigned to gethostbyaddr() would be the hostname you would use for making the LDAP query as you are technically not querying the A record, but the IP address which in-turn bypasses round robin.
$ip = gethostbyname('www.google.com'); //Get the ip via hostname (Given IP from Round Robin)
$address = gethostbyaddr($ip); // Convert the IP to Hostname using reverse lookup/ PTR Lookup

echo $address; //Use this for your LDAP query

In my example above, Google has a different PTR record (Reverse Lookup Record) to the A record so in this instance, the result is different to my original query of www and shows the hostname as lhr35s01-in-f4.1e100.net. If you control your DNS (which I'm guessing you do), you could create a PTR record which matches the A record so your reverse lookup resolves correctly.
Output:
lhr35s01-in-f4.1e100.net

See:
http://php.net/manual/en/function.gethostbyname.php
http://php.net/manual/en/function.gethostbyaddr.php

A: If you really want to know to which server you are connecting, my solution would be to turn things around.
$dclist = gethostbynamel($host); // will get the list of IPs in round robin fashion (order changes)

$host = $dc[0]; // will contain different IP

// now you can connect to $host while knowing the IP...

(this might not work with ssl tho.. sorry about that, I just now noticed you do connect using ldaps...)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jenkins Job information How to get below mentioned job information by using Jenkins api or some other command line option.

*

*Time-stamp of last job that succeeded.

*Time-stamp of last job that failed.

I looked in to this API but its giving only build info but not the time stamp i.e at what time and date information when this build failed of succeeded.
http://javadoc.jenkins-ci.org/hudson/model/Job.html

A: You do this by using the method getLastSuccessfulBuild() and getLastFailedBuild() on Job and then asking each one for their timestamp. E.g. there is no methods for doing this directly on the Job node, instead you need multiple methods.
So, using, for example, the XML API, it would look something like this:
https://<JENKINS_URL>/job/<JOB_NAME>/api/xml?tree=lastSuccessfulBuild[timestamp],lastFailedBuild[timestamp]

In my case this gives me:
<freeStyleProject _class="hudson.model.FreeStyleProject">
  <lastFailedBuild _class="hudson.model.FreeStyleBuild">
    <timestamp>1484291786712</timestamp>
  </lastFailedBuild>
  <lastSuccessfulBuild _class="hudson.model.FreeStyleBuild">
    <timestamp>1486285440897</timestamp>
  </lastSuccessfulBuild>
</freeStyleProject>


text:
Q: How to connect to webservice using suds? I want to connect to a webservice called e-conomic to sync data from my webshop with the e-conomic bookkeeping system. But I'm stuck at the beginning how to start a connection.
I've got an e-conomic account, a username and a password and I installed the suds library to make the call:
>>> from suds.client import Client
>>> c = Client('https://www.e-conomic.com/secure/api1/EconomicWebService.asmx?WSDL')
>>>

Then what?
The documentation is here and what I want to do is create a new order like described here.
My code that is part of my app is only just started and I don't know how to specify my account in the SOAP request:
from suds.client import Client

class Economic(NewBaseHandler):

    def get(self):
        url = 'https://www.e-conomic.com/secure/api1/EconomicWebService.asmx?WSDL'
        client = Client(url)
        self.response.out.write('client: %s' % str(client))

Can you tell me how to proceed?

A: You have to call the webservice with the service method of the Client.
>>> from suds.client import Client
>>> c = Client('https://www.e-conomic.com/secure/api1/EconomicWebService.asmx?WSDL')
>>> c.service.Account_Create(10, '20', 'ProfitAndLoss')
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 240, in __call__
    return target.call(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 379, in call
    return method(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 240, in __call__
    return target.call(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 422, in call
    return client.invoke(args, kwargs)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 480, in invoke
    result = self.send(msg)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 511, in send
    result = self.failed(binding, e)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/client.py", line 562, in failed
    r, p = binding.get_fault(reply)
  File "/usr/lib/python2.7/site-packages/suds-0.3.6-py2.7.egg/suds/bindings/binding.py", line 226, in get_fault
    raise WebFault(p, faultroot)
WebFault: Server raised fault: 'Economic.Api.Exceptions.AuthenticationException(E02250): User is not authenticated. Access denied. {id=131496672}'

I got this error because user is not authenticated. There might be some service or some key by which they will authenticate the user. You need that key then you can call the services.

A: #Works only in 2.7 Python. Does not work in Python 3.0 version

from suds.client import Client
from suds.sax.text import Raw

client = Client('https://www.e-conomic.com/secure/api1/EconomicWebService.asmx?WSDL')
xml = Raw('--Paste your entire xml --')
Response_XML= (client.service.MethodName(__inject={'msg':xml}))

-- You will get all your xml response in Response_XML variable


text:
Q: Setting the date format in Atlassian Crucible When I set up a review in Atlassian Crucible, and I set a date, it displays it in DD/MM/YYYY
I'd like to switch that over to MM/DD/YYYY, but I don't see anywhere in the configuration to switch that.
The closest setting I see is for the timezone, which I have set to EST.
I have Crucible running on a CentOS 6.2 machine that's set to UTC
I'm using Crucible version 2.7.14 Build:20120612060728 2012-06-12
My locale is currently set to en_US.UTF-8
> locale | grep LC_TIME
LC_TIME="en_US.UTF-8"

Can someone point out how I can switch the date format in Crucible ?

A: According to JIRA CRUC-1941 they have not implemented this yet.
Update: closed as "Won't Fix".


text:
Q: Is there a way to change the url on langauge change? please does anyone know of a way i can change the url of the page once i change the language, i'm using react-i18next
E.g
if the language is in English of the login page(http://localhost:5000/login), and i click on the button that changes the language to Spanish, i want the url to change to http://localhost:5000/acceso

// Header.js
const {
  t
} = useTranslation();
const [lang, setLang] = useState(Cookies.get("i18next"));

const handleChange = (e) => {
  const {
    value
  } = e.target;
  i18n.changeLanguage(value);
  setLang(Cookies.get("i18next"));
};
// App.js
<Routes>
  <Route exact path="/" element={<Home />} />
  <Route path={`/${t( "login")}`} element={<Login />} />
  <Route path={`/${t( "contact")}`} element={<Contact />} />
  <Route path={`/${t( "about")}`} element={<About />} />
</Routes>

// Header.js
<div className="flags">
  <label className={ lang==="gb" ? "fi fi-gb icon active" : "fi fi-gb icon" } htmlFor="gb">
              <input
                type="radio"
                name="lang"
                value="gb"
                id="gb"
                defaultChecked={lang === "gb"}
                onChange={handleChange}
              />
            </label>
  <label className={ lang==="es" ? "fi fi-es icon active" : "fi fi-es icon" } htmlFor="es">
              <input
                type="radio"
                name="lang"
                value="es"
                id="es"
                onChange={handleChange}
                defaultChecked={lang === "es"}
              />
            </label>
</div>


text:
Q: How to see the content of tensorflow tensor keras Input layer? I want to see the content of the below tensorflow tensor given by Input class of keras
from keras.layers import Input
sequence_input = Input(shape=(128,), dtype='int32')
# How to see the content of sequence input
sequence_input
import tensorflow.compat.v1 as tf
with tf.Session() as sess:
  print(sequence_input.eval())

Exception ignored in: <bound method BaseSession.__del__ of <tensorflow.python.client.session.Session object at 0x7fa11ecac8d0>>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/client/session.py", line 763, in __del__
    if self._session is not None:
AttributeError: 'Session' object has no attribute '_session'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-eaa497285237> in <module>()
      5 import tensorflow.compat.v1 as tf
      6 import numpy as np
----> 7 with tf.Session(session=sess) as sess:
      8   print(sequence_input.eval())

TypeError: __init__() got an unexpected keyword argument 'session'

I have tried several solutions offered on how to see the content of the tensorflow tensor but I get errors and could not find a working code.I have included on solution proposed above with the error. What would you suggest?

A: you want to see the content of the tensor given a specific input? or just the general configuration of this tensor? anyway you can use keras Model class to define your model,  for example:
input = Input(shape=(128,), dtype='int32')
output = input
model = tf.keras.Model(inputs, output)

than you can access the model layers - model.layers[0] for example will be the input layer. However I'm not sure I understand you're purpose since the input tensor will have no value unless you provide some data to the model...


text:
Q: Why my function can't read passed parameters as expectation in React.js? I use a given postId to fetch all the comments for the post, and I expect to use a saveComments function to set the array of loaded comments into the post id.
So I passed two parameters, postId(should be a number value), and loadedComments(should be an array of comments).
  useEffect(
    () => {
      fetchCommentsForPostId(postId)
      .then( loadedComments => {
        saveComments(postId, loadedComments);
      });
    },
    []
  );

However, when I print the value to check if passed parameters correct. I realize that the first one is good, it's an id for post. But the second one, the comments, it's also an id value. I think it should be an array.
  function saveCommentsForPostId(postId, comments) {

    console.log(postId); // correct id number, eg. 1
    console.log(comments); // incorrect, I think it should be an array of comments, but it is same as postId
    ...
  }

And then, I tried another way. I make my two parameters as an object into calling function.
  useEffect(
    () => {
      fetchCommentsForPostId(postId)
      .then( loadedComments => {
        saveComments({postId, loadedComments});
      });
    },
    []
  );

Now, the postId is still correct. However, the comments is the whole object I passed in. It is like {postId: 1, loadedComments: Array(5)}. How could it be a whole object? I think it should be a pure array.
  function saveCommentsForPostId(postId, comments) {

    console.log(postId); // correct id number, eg. 1
    console.log(comments); // it is an object, eg. {postId: 1, loadedComments: Array(5)}. Why it is an object? I think it should be just an array.

    ...
  }

After tried out a lot of ways, the only working way is I make parameters as an object, and get the array I want use:
comments['loadedComments'] // this is the comment array I actually want

I'm super confused about it. Anyone could explain the logic behind it? Thanks in advance!
*** update
export function fetchCommentsForPostId(postId) {
  return new Promise( (resolve) => {
    // This inserts a 2 second delay so we can easily see a spinner at work
    setTimeout( resolve, 2000);
  })
  .then(
    () => fetch(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`, {
      method: 'GET',
    })
  )
  .catch( () => Promise.reject('networkError') )
  .then( response => {
    if(response.ok) {
      return response.json();
    }
    return Promise.reject('serviceError');
  });
}

A: Ok, not sure what else you are doing but this seems to work:

function fetchCommentsForPostId(postId) {
  return new Promise((resolve) => {
    // This inserts a 2 second delay so we can easily see a spinner at work
    setTimeout(resolve, 2000);
  }).then(() =>
      fetch(`https://jsonplaceholder.typicode.com/posts/${postId}/comments`, {
        method: "GET",
      })
    )
    .catch(() => Promise.reject("networkError"))
    .then((response) => {
      if (response.ok) {
        return response.json();
      }
      return Promise.reject("serviceError");
    });
}

function saveCommentsForPostId(postId, comments) {
  console.log("postId:", postId);
  console.log("comments:", comments);
}

function doStuff(postId) {
  fetchCommentsForPostId(postId).then((loadedComments) => {
    saveCommentsForPostId(postId, loadedComments);
  });
}

doStuff(1);


text:
Q: Constants for AVCaptureMetadataOutput's metadataObjectTypes property? When using AVFoundation to detect features (e.g. faces or barcodes) in an image, you must call a line such as:
AVCaptureMetadataOutput *metadataOutput = ...;
metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes;

Examining availableMetadataObjectTypes shows the following strings:
face,
"org.gs1.UPC-E",
"org.iso.Code39",
"org.iso.Code39Mod43",
"org.gs1.EAN-13",
"org.gs1.EAN-8",
"com.intermec.Code93",
"org.iso.Code128",
"org.iso.PDF417",
"org.iso.QRCode",
"org.iso.Aztec"

If I am writing a barcode scanning app, I don't want the framework to be looking for faces, so instead of passing metadataOutput.availableMetadataObjectTypes, I want to pass specific barcodes to look for. Rather than using these hard-coded strings, I was hoping they were defined as constants somewhere.
Do they exist anywhere in the framework, or must I use hard-coded strings?

A: There are constants for the various barcode types, just in the AVMetadataMachineReadableCodeObject class (full list here).
So you can do something like this:
metadataOutput.metadataObjectType = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code];


text:
Q: Multiple RewriteCond doesn't work I have in htaccess some like this:
RewriteCond %{HTTP_HOST} !^foo
RewriteCond %{HTTP_HOST} !^bar
RewriteCond %{HTTP_HOST} !^some
RewriteRule ^register,(.*)$ /register.html [R=301,L]
RewriteRule ^offer,(.*)$ /offer.html [R=301,L]

It redirect me if I write http://foo.domain.com/register,one.html I want it only on http://domain.com/register,one.html or http://www.domain.com/register,one.html
What is wrong?

A: In the example that you've given, you will most certainly not be redirected.
However, it looks like you're expecting the RewriteCond directives to apply to both of the RewriteRule directives - they do not.  They only apply to the RewriteRule that immediately follows them.
So, in your example, http://foo.domain.com/register,one.html will not redirect you - but http://foo.domain.com/offer,one.html will.
What you probably need is something more along these lines:
RewriteCond %{HTTP_HOST} !^(foo|bar|some)
RewriteRule ^register,(.*)$ /register.html [R=301,L]
RewriteCond %{HTTP_HOST} !^(foo|bar|some)
RewriteRule ^offer,(.*)$ /offer.html [R=301,L]


text:
Q: Why's my wifi-Hotspot connection failing to get established? What I did:

*

*Open system settings, Network, Wireless.

*Clicked "Create Hotspot"

*(Nothing happened). Clicked network icon in panel

*Create New wireless network

*Entered name and password

*Entered SSID "ubuntu"

*set IPV6 setting to Ignored (default)

*Tried Create-Hotspot again and failed!

*Error message : "WIFI Disconnected"

I'll update any necessary info here as you request.

A: This have bugged me for quite some time, especially after any fresh installs or updates. I found a solution which worked perfectly for me. For those of you who have the same trouble with their laptop wifi [Toshiba or HP laptop-wifi-drivers in particular] this will surely help you.

*

*Deactivate currently active Broadcom drivers from additional-drivers. Blacklist BCMA and BRCM80211 by typing in terminal:
echo "blacklist bcma" | sudo tee -a /etc/modprobe.d/blacklist.conf
echo "blacklist brcm80211" | sudo tee -a /etc/modprobe.d/blacklist.conf

*Reboot now and download Synaptic Package Manager (makes it easier to find our files).

*Search "bcm43" and download these 4 (they might prompt for some other dependency files - just accept them too)

*

*bcmwl-kernel-source

*broadcom-sta-common

*broadcom-sta-source

*firmware-b43-installer

*Reboot

*Now, you may check if your wifi is working (testing your hotspot or connecting to a network etc.)

*If it isn't, then go to additional-drivers and activate the newly downloaded drivers followed by a reboot.

Note: additional drivers are found in System-settings > Software sources > additional drivers

A: If you simply want a hotspot, you could try installing ap-hotspot. It works fine for connecting to almost all wifi devices, android phones, etc.
To install it:
$ sudo add-apt-repository ppa:nilarimogard/webupd8
$ sudo apt-get update
$ sudo apt-get install ap-hotspot

Next, to start the hotspot:
$ sudo ap-hotspot start

It asks you which adapter's internet you want to share, name of the network, password, etc. in an interactive manner.
To stop the hotspot :
$ sudo ap-hotspot stop

To configure it:
$ sudo ap-hotspot configure

If any problem, hope this link helps.


text:
Q: Files.readAllLine() not working after FileWriting hoping you're doing well, this is my first question
I have a trouble:
My goal is to create java files from pieces of code (fields, attributes, constructor)
I tried to do this by altering between reading and writing file.
Reading file to get the old value , delete closing "}"
Writing in file :  the new piece of code, plus closing "}"
The problem with my try is that Files.readAllLine() or FileWriter() is not working.
You can find my source code below.
public static void fillFile(String fileName, String name, String value) throws IOException {
        Path path = Paths.get(fileName);
        List<String> all = Files.readAllLines(path,StandardCharsets.UTF_8);
        System.out.println(" the path "+Paths.get(fileName));
        System.out.println(name + " :; "+ value);
        System.out.println("to write " + all.toString().replaceAll(", ", " ").substring(1, (all+"").replaceAll(", ", " ").length()-1)  + "\n" +  name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n } ddddddddddddddddddddddd");
        FileWriter test = new FileWriter(fileName,true);
        test.write(all.toString().replaceAll(", ", " ").substring(1, all.toString().replaceAll(", ", " ").length()-1) +  "\n" +  name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n }");
        //test.flush();
        test.close();
    }

Another question : there is an other easy way to reach my goal ?

A: The solution is that the FileWriter classe should have a different path that the one which File.readAllLine()use.
So we have to create a temporary file, which will be copied to the desired fileName file, then we delete the temporary file
Hope this will help people who need it. It is working !!!
public static void fillFile(String fileName, String name, String value) throws IOException {
        Path path = Paths.get(fileName);
        List<String> all = null;
        if (path.toFile().exists()) {
            all = Files.readAllLines(path,StandardCharsets.UTF_8);}
        if(all!= null) System.out.println(path + " the size of "+ all.toArray(new String[all.size()])+"");
        Path path2 = Files.createTempFile(path.getParent(),"test-file", ".java");
        Files.write(path2, ((all+"").replaceAll(", ", "\n").replaceAll("\\[", "").replaceAll("\\]", "").substring(1, ((all+"").replaceAll(", ", " ").replaceAll("\\[", "").replaceAll("\\]", "")).length()-1) +  "\n" +  name + value+ "\n" +"}").getBytes());
        Files.copy(path2, path, StandardCopyOption.REPLACE_EXISTING);
        Files.deleteIfExists(path2);
    }


text:
Q: How to lock the iPad's screen with a keyboard shortcut? Is it possible to lock the iPad's screen by using a keyboard shortcut, when using a BT keyboard, or the SmartKeyboard?
Cmd+Shift+Eject as on the Mac does not work. Holding down the Cmd key also does not show any shortcut.

A: I was able to figure out Control + Command + Q seems to work on the new iPad Pro keyboard to lock it.

A: In the past, this was not possible with a keyboard shortcut. Some third party keyboard has dedicated buttons for locking and more...
Now there are widely available key shortcuts and Accessability and switch control options to lock the screen on iPadOS.

A: Right now it may be possible if you have Fn key on your keyboard.
Just click Fn + L and the screen will be locked.
This works on my bluetooth keyboard(Logitech K375s), but I'm not sure whether it works on every keyboard.


text:
Q: Is adding a Masking layer before the prediction layers correct? I want to us a pre-trained model to classify images. Every image can have multiple classes (in this case up to 21). Of course not all classes occur in every image. Therefore, I want to add a Masking layer to the model which masks all zeros (given value if a class doesn't exist).
Now I've never used a Masking layer before, but in most online examples it is added directly after the Input layer. This is, however, not possible in the example below, because the Masking layer is not compatible with all layers (in this case a Conv2D layer.
It was possible to insert the Masking layer before the fully-connected output layer. But this did not really affect the loss of the model (loss is around 20!).
Am I doing it right or is adding the Masking layer at the top of the model totally useless?
My Model
from keras.layers import Input, GlobalAveragePooling2D, Masking, Dense, Dropout
from keras.applications.inception_v3 import InceptionV3
from keras.models import Model

#Define input tensor
input_tensor = Input(shape=(512, 512, 3))

# create the base pre-trained model
base_model = InceptionV3(input_tensor=input_tensor, weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a Mask fully-connected layer and a dropout
x = Masking(0.)(x)
x = Dense(1024, activation='relu')(x)
x = Dropout(0.2)(x)
# and a logistic layer with 21 classes
predictions = Dense(21, activation='sigmoid')(x)

# create final model
model = Model(inputs=base_model.input, outputs=predictions)

# compile model
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

Example labels
# input
np.array([[1,2,0,0,0,6,7,8,0,0,0,12,13,14,15,16,17,18,19,20,21],
          [0,2,0,4,5,6,7,8,9,10,11,0,0,14,15,16,17,18,19,20,21]])


text:
Q: How to add a file in a zip using SharpZibLib in c# I am trying to add a file to an existing zip using sharpZibLib in c#.
When run zip gets qverwrite i.e all files within zip gets deleted and only new file is there in a zip.
using (FileStream fileStream = File.Open("D:/Work/Check.zip", FileMode.Open, FileAccess.ReadWrite))
    using (ZipOutputStream zipToWrite = new ZipOutputStream(fileStream))
    {
        zipToWrite.SetLevel(9);

        using (FileStream newFileStream = File.OpenRead("D:/Work/file1.txt"))
        {
            byte[] byteBuffer = new byte[newFileStream.Length - 1];

            newFileStream.Read(byteBuffer, 0, byteBuffer.Length);

            ZipEntry entry = new ZipEntry("file1.txt");
            zipToWrite.PutNextEntry(entry);
            zipToWrite.Write(byteBuffer, 0, byteBuffer.Length);
            zipToWrite.CloseEntry();

            zipToWrite.Finish();
            zipToWrite.Close();
        }
    }

Can anyone tell me whats the issue in above code? Why the zip gets overwitten

A: Have a look here:
http://wiki.sharpdevelop.net/SharpZipLib_Updating.ashx
you need to call
zipFile.BeginUpdate();

//add file..

zipFile.CommitUpdate();


text:
Q: How to implement "do something when meeting " The token <EOS> is ubiquitously used in NLP. As I haven't used it, the implementation of conditioning on it is a bit unclear to me. Could anyone provide a snippet of Python code. (If statements may be used.)
Example 1: There is a sequence of words with some <EOS> tokens interpolated. This sequence goes through a RNN to get encoded. Whenever encounters <EOS>, the timestep outputs its state.
Example 2: a machine translation task. When meets <EOS>, it stops generating tokens.

A: The EOS token is important for the decoder as well: the explicit "end" token allows the decoder to emit arbitrary-length sequences. The decoder will tell us when it's done emitting tokens: without an "end" token, we would have no idea when the decoder is done talking to us and continuing to emit tokens will produce gibberish.
So for examples given, I have this snippet from image captioning which is relative to machine translation:
        # Which sequences are incomplete (didn't reach <end>)?
        incomplete_inds = [ind for ind, next_word in enumerate(next_word_inds) if
                           next_word != word_map['<end>']]
        complete_inds = list(set(range(len(next_word_inds))) - set(incomplete_inds))

Here the token <end> is similar to <EOS>. This snippet is looking for the <end> token when generating caption for an image. Of course, we want to know when to stop, and the length of the caption is predefined for the boundary of caption for an image is known in advance in training step.


text:
Q: Get specific value in in one of the values of .CSV file in PHP I just want to ask something about getting values from CSV file.
I have a CSV file and I can get a value from it. But now I would like to get a specific value inside that value.
For example.
I have "name", "address and postal code", "phone" inside the .CSV file. I can get the value from the address and postal code. But now I only want the value of the postal code. How can I separate the address from the postal code if they're in one cell using php?
Thanks!


text:
Q: Add R markdown footnote within table code I am struggling with how to use [^1] footnotes within r chunks for my r markdown document. I have a table that I need to add some footnotes to but I can't figure out how to add them. I want the 1 subscript to appear beside the end of the word "Pay" I have attempted the following code when trying to add a footnote to the first entry in the  'key_points' column:

mainPoints <- data.frame(key_points = c(paste0("Median Pay", [^1], "has increased by ", YearChangePct, "%"),
                                        paste0("Top decile Pay: £", TopDecile,"\nBottom decile Pay: £", BottomDecile),
                                        paste0(PayRisePct, "% of BLUB staff received a pay\nincrease between ", currentyear - 1, " and ", currentyear),
                                        paste0("Gender Pay gap is ", GenderPayGap, "%")),
                         Commentary = c(paste0("The average (median full-time equivalent) pay of BLUB staff is £", CurrentYearMedian, " which is an increase of ", YearChangePct, "% on the equivalent figure for ", currentyear -1, ". The overall pay award for the BLUB for ", currentyear -1, " was 1%."),
                                        paste0("Pay of £", BottomDecile, " would put someone in the bottom 10% of BLUB staff, whereas pay of £", TopDecile, " would put someone in the top 10% of BLUB staff."),
                                        paste0("The extent of the increase varied between grades: ", AApct, "% of AA staff received a pay increase between 0.1% and 1.9%. ", IND2pct,"% of Industrial 2 staff received a pay increase between 4.0% and 5.9%."),
                                        paste0("There continues to be a gap between male and female pay in the BLUB – the median pay for females is ", GenderPayGap, "% lower than the median pay for males.")))

names(mainPoints) <- c("Key Points", "Commentary")

A: The caret must be before the bracket: ^[footnote content]
You can include it inside you string: "Median Pay^[footnote content] has increased by "
Passing your table through knitr::kable(mainPoints) will do the job:
---
output: html_document
---

Footnote in cell:

```{r, echo = F}
mainPoints <- data.frame(Key_points = c("Median pay^[footnote content]", "Top decile"),
                         Commentary = c("Comment 1", "Comment 2"))

knitr::kable(mainPoints)
```


text:
Q: how to add javascript function to html tag? Just curious, and want to know. Can I add a javascript function to certain html tag? In example, if I have div tag like this:

Hello!

and want to add function that alert the value inside of every div like:
function divFunction(){
     alert(/*some div content*/);
}

so, it can be executed like:

Hello!

The point of my question is to add some new attribute or function to a certain tags. Like if there is:
document.getElementById("example").innerHTML;

can it be:
document.getElementById("example").newAttribute;

What makes me curious because jQuery can done something like this:
$( "#result" ).load( "ajax/test.html" );

A: DOM elements are like javascript objects with certain properties, so you could add a new property to, in your case a new function.
Here's an example:

var element = document.querySelector('#example');

function bindToNode(node, name, fn) {
  node[name] = fn.bind(node);
}

bindToNode(element, 'logValue', function() {
  console.log(this.textContent);
});

element.logValue();

  Hello!

But you shouldn't mess arround with DOM elements, a better way would be to wrap the elements like jQuery does.

A: This isn't possible because $ (jQuery) and document are defined objects that have there in built functions.
Because when you use . you call an object member.
Foo.bar() - Calling function bar() defined inside and object Foo.
So you would have to make your class/selector.
Here is a simple example:

class select {
 constructor(selector) {
   this._element = document.getElementById(selector);
  }

  // Functions

  colorMe() {
   this._element.style.backgroundColor = "red";
  }

  moveMe(x) {
    this._element.style.marginTop = x;
  }
}

var elem = new select("example");

elem.colorMe();
elem.moveMe("50px");

  This is an example

A: It's a little weird and inadvisable, but it's possible.

tag=document.querySelector('#myTag')
tag.test=tag=>{tag.innerText=tag.id};
tag.test(tag);

A: You can add events to the DOM elements. Read this page https://www.w3schools.com/js/js_htmldom_events.asp for more information or see a small example below

function divFunction(){
     alert(document.getElementById("example").innerText);
}

Hello!

A: You should pass the html element to your javascript function. Add an element argument in your function definition.
function divFunction(el){
     alert(el.innerHTML);
}

And use getElementById to reference the element to use as an argument.

Hello!

A: It's possible without the use of any library.
I use it to validate the content of a  modal element saved in another file
This is myModal.html

  some content

In the other file mainPage (it could be a .cshtml or a .php page) i'm including myModal.html.
I can access the function because it's a div's function:
This is MainPage. :

In this way the function is "portable" with the div and it's in the same file (no more copy and paste)

A: you can do this with custom-elements [1] [2]

*

*create custom-element

*add method to custom-element class

*you can call the method

export class CustomElementInput extends HTMLElement {

  log(){
    alert("log")
  }

  // you can even overwrite methods like so
  remove(){
    alert("removing this node")
    super.remove()
  }
}

customElements.define("custom-element-input", CustomElementInput)

// somewhere else...
// in your HTML something like:
// <custom-element-input></custom-element-input>

const el = document.querySelector("custom-element-input")
el.log() // creates alert()

:)


text:
Q: How do I mimic virtual methods only using composition? I am struggling with the concept of always using composition, there are many articles that mention virtually all uses of inheritance can be replaced with composition. I understand there are benefits of it such as testing... but how can I replace the use of inheritance in this case?
Basically I have 2 decorators, that add functionality to an existing file service class. Before copying the files, I want it to rename them and then delegate back to the original file service.
In this example, I have two methods. One loops though a theoretical list of files and then calls Copy File. Instead of duplicating the code, the decorator class simply calls the wrapped implementations version instead, similar to utilizing inheritance.
However, this doesn't work like inheritance because now it's never going to call the decorators CopyFile method because it is now in the previous base class implementation, it is not aware that the decorators CopyFile method exists.
If I use inheritance, by marking the method as virtual the base class would know when one of its functions has been overrided and call that version instead of its own.
How can I mimic this functionality only using composition?
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp5
{

public interface IFileService
{
    void CopyFile(string source, string destination);
    void CopyFiles(IEnumerable<string> source, string destination);
}

public class MainFileService : IFileService
{
    public void CopyFile(string source, string destination)
    {
        Console.WriteLine("Base Method of Copy File invoked");
    }

    public void CopyFiles(IEnumerable<string> source, string destination)
    {
        foreach (var file in source)
        {
            CopyFile(file,destination);
        }
    }
}

public class RenamingFileService : IFileService
{
    private IFileService _wrapper;

    public RenamingFileService(IFileService wrapper)
    {
        this._wrapper = wrapper;
    }

    public void CopyFile(string source, string destination)
    {
        RenameFileExtensionToPART();
        _wrapper.CopyFile(source, destination);
    }

    private void RenameFileExtensionToPART()
    {
        Console.WriteLine($"Now invoking {nameof(RenameFileExtensionToPART)}");
    }

    public void CopyFiles(IEnumerable<string> source, string destination)
    {
        _wrapper.CopyFiles(source, destination);
    }
}

public class FileLoggingService : IFileService
{
    private IFileService _wrapper;

    public FileLoggingService(IFileService wrapper)
    {
        this._wrapper = wrapper;
    }

    public void CopyFile(string source, string destination)
    {
        Console.WriteLine("Logged Request");
        _wrapper.CopyFile(source, destination);
    }

    public void CopyFiles(IEnumerable<string> source, string destination)
    {
        Console.WriteLine("Logging  requests.");
        _wrapper.CopyFiles(source, destination);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new FileLoggingService(new RenamingFileService(new MainFileService()));
        service.CopyFiles(Enumerable.Range(0,10).Select(x => Guid.NewGuid().ToString()),"Directory");
    }
}

}


text:
Q: Sending HTML email from Joomla! component I am developing a Joomla!3.0/3.1 component that allows people to book a golf lesson online. When they complete the booking and process paypal payment, I want to send them a receipt/confirmation email.
I can do this fine and send the information in html or plain text format. However I don't like the fact that I now have view (email content) data within my controller code.
Is it possible to have a sort of template view file which can be parsed and sent as the contents instead? or am I stuck with it in my code?
Thanks,
Chris

A: Add a configuration field to your component of type textarea or editor, and let the user write the email template.  You should explain which tokens are available or at least provide a default text, such as
Dear {USERNAME},

today I received {NUM_MESSAGES} messages on your behalf,
and your profile has been viewed {NUM_PROFILEVIEWS} times.

Then simply replace the {TOKENS} in your code with str_replace.

A: On admin side create a section for editing your email template with Joomla's default editor
you an create an editor on the backend and open an html file inside that, for changing the styles ,formats content etc for users.

keep your template file as an HTML file on server and email sending time something like below.
function send_mail_account_pages($email_title,$greeting_text,$subject,$email_content,$user_email){

            $config = JFactory::getConfig();
            $data['fromname']   = $config->get('fromname');
            $data['mailfrom']   = $config->get('mailfrom');
            $data['sitename']   = $config->get('sitename');

            $path = JPATH_BASE."/email_tmpl/";
            $fp = fopen($path."email_tmpl.html","r");
            $fsize = filesize($path."email_tmpl.html");
            $fcontent = fread($fp,$fsize);
            fclose($fp);

            $date_format     = date("M.d, Y");

            $fcontent = str_replace("{email_page_title}",$email_title,$fcontent);
            $fcontent = str_replace("{date}",$date_format,$fcontent);
            $fcontent = str_replace("{greeting_text}",$greeting_text,$fcontent);
            $fcontent = str_replace("{email_content}",$email_content,$fcontent);
            $fcontent = str_replace("{thanks_text}",THANKS_TEXT,$fcontent);

            $return = JUtility::sendMail($data['mailfrom'], $data['fromname'], $user_email, $subject, $fcontent,1);
}

This way you can make admin users to give access to change the template styles make sure admin users do not edit the {place holders}.
Hope its helps..


text:
Q: Export SharePoint List with Managed Metadata column as CSV using PowerShell I am using the script below to export a 6000+ item Sharepoint list to CSV. It works great, however, 1 of the columns on the list is a Managed Metadata column. When exported with the script below, the values are all 'Microsoft.SharePoint.Client.Taxonomy.TaxonomyFieldValue'.
I have tried a few variations but I am struggling. Please could anyone help me to change the script below to work with the Managed Metadata column?
Function GetAllListItems($ctx,$listUrl)
{
   #Get the List
    $List = $Ctx.Web.GetList($ctx.Web.ServerRelativeUrl + "/" + $listUrl)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()

    #Define Query to get List Items in batch
    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
    $Query.ViewXml = @"
    <View Scope='RecursiveAll'>
        <Query>
            <OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>
        </Query>
        <RowLimit Paged="TRUE">5000</RowLimit>
    </View>
"@

    $allListItems = @()
    #Get List Items in Batch
    Do
    {
        $ListItems = $List.GetItems($Query)
        $Ctx.Load($ListItems)
        $Ctx.ExecuteQuery()
        #$ListItems.count
        $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition

       foreach($listItem in $ListItems)
       {
            $allListItems += $listItem
       }

    }
    While($Query.ListItemCollectionPosition -ne $null)

    Return $allListItems

}

Function MainProcress()
{

    $siteUrl = "SITE URL HERE"
    $listUrl = "Lists/List Name Goes Here"
    $outputFilePath = "F:\exportedlist.csv"

    $includeHiddenField = $False
    $includeReadonlyField = $False

    Connect-PnPOnline -Url $siteUrl -Interactive

    $ctx = Get-PnPContext
    $ctx.Load($ctx.Web)
    $ctx.ExecuteQuery()

    $listFields = Get-PnPField -List $listUrl |? { $_.Hidden -eq $includeHiddenField -AND $_.ReadOnlyField -eq $includeReadonlyField} | Select -ExpandProperty internalname

    $count = 0

    $listItems= GetAllListItems -ctx $ctx -listUrl $listUrl

    $listItems.Count
    $hashTable=@()

    # Loop through the list items
    foreach($listItem in $listItems)
    {   $count = $count+1
        Write-Progress -Activity "Exporting" -Status "$($count/$listItems.Count*100)% Complete:" -PercentComplete $($count/$listItems.Count*100)
        $obj=New-Object PSObject

        $listItem.FieldValues.GetEnumerator() | Where-Object { $_.Key -in $listFields }| ForEach-Object{

                    if($_.Value.LookupValue){$obj | Add-Member Noteproperty $_.Key $_.Value.LookupValue}
                    else{$obj | Add-Member Noteproperty $_.Key $_.Value}

                }

        $hashTable+=$obj;
        $obj=$null;
    }
     $hashtable | export-csv $outputFilePath -NoTypeInformation

}

MainProcress


text:
Q: Escape string and split it right after i've the following code:
import re

key = re.escape('#one #two #some #tests #are #done')
print(key)
key = key.split()
print(key)

and the following output:
\#one\ \#two\ \#some\ \#tests\ \#are\ \#done
['\\#one\\', '\\#two\\', '\\#some\\', '\\#tests\\', '\\#are\\', '\\#done']

How come the backslashes are duplicated? I just want them once in my list, because i would like to use this list in a regular expression.
Thanks in advance! John

A: There is only one backslash each, but when printing the repr of the strings, they are duplicated (escaped) - just as you would need to duplicate them when using a string to build a regex. So everything is fine.
For example:
>>> len("\\")
1
>>> len("\\n")
2
>>> len("\n")
1
>>> print "\\n"
\n
>>> print "\n"

>>>

A: The \ character is an escape character, that is a character that changes the meaning of the subsequent character[s]. For example the "n" character is simply an "n". But if you escape it like "\n" it becomes the "newline" character. So, if you need to use a \ literal, you need to escape it with... itself: \\

A: The backslashes are not duplicated. To realize this, try to do:
for element in key:
    print element

And you will see this output:
\#one\
\#two\
\#some\
\#tests\
\#are\
\#done

When you have printed whole list, the python used representation where strings are printed not as they are, but they are printed as python expression (notice the quotes "", they are not in the strings)
To actually encode string containing backslash, you need to duplicate that backslash. That is it.

A: When you convert a list to a string (e.g. to print it), it calls repr on each object contained in the list. That's why you get the quotes and extra backslashes in your second line of output. Try this:
s = "\\a string with an escaped backslash"
print s       # prints: \a string with an escaped backslash
print repr(s) # prints: '\\a string with an escaped backslash'

The repr call puts quotes around the string, and shows the backslash escapes.


text:
Q: Ionic 2 Events, publish and subscribe not working I'm trying to use Publish and Subscribe from ionic-angular
But I am not receiving any data nor error. Here are my codes
Page 1
import {Events} from 'ionic-angular'

static get parameters(){
 return [[Events]];
}

constructor(Events)
{
 this.events = Events;

 this.events.publish("Msg", "Hello World");
}

Page 2
import {Events} from 'ionic-angular'

static get parameters(){
 return [[Events]];
}

constructor(Events)
{
 this.events = Events;

 this.events.subscribe("Msg", (data) => {
  console.log(data[0]);
 }
}

I'm using ionic-angular beta0.4.

I realize why it doesn't show on console.. Page 2 has to be loaded and ready before Page 1 initiate an event. If Page 1 were to initiate and publish before Page 2 is even loaded, Page 2 will not be able to grab that data.
SOLVED

A:
I would need to use event as I'm constantly listening to my internet
  status on my first page, and I would like something to happen when my
  network is off on my second page

In the app I'm working right now, we're doing exactly the same. Please take a look at this plunker.
As you can see there, I've created a ConnectivityService whose main goal is to be informed when the connection status has changed (by your first page), and then notify to all the subscribers about that (your second page -and every page if you want-)
ConnectivityService.ts
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ConnectivityService {

  private connectionObserver: any;
  public connection: any;

  constructor(){
    this.connectionObserver = null;
    this.connection = Observable.create(observer => {
        this.connectionObserver = observer;
    });
  }

  // Send that information to all the subscribers
  public connectionHasChanged(private isOnline: bool) {
      this.connectionObserver.next(isOnline);
  }
}

With that being done, we just need to register the 'online' and 'offline' events in your first page (or do it like you're doing it in your app) and notify the service when the connection status changes:
App.ts
import { Component } from "@angular/core";
import { ionicBootstrap, Platform } from 'ionic-angular/index';
import { HomePage } from './home.ts';
import { ConnectivityService } from 'connectivityService.ts';

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [ConnectivityService]
})
export class MyApp {
  constructor(private platform: Platform, private connectivityService: ConnectivityService) {
    this.addConnectivityListeners();
    this.rootPage = HomePage;
  }

  // Subscribe to online/offline events
  addConnectivityListeners(){

    // Handle online event
    document.addEventListener('online', () => {
      // Call the service, to indicate now there's connection (true)
      this.connectivityService.connectionHasChanged(true);
    }, false);

    // Handle offline event
    document.addEventListener('offline', () => {
      // Call the service, to indicate now there's no connection (false)
      this.connectivityService.connectionHasChanged(false);
    }, false);
  }
}

ionicBootstrap(MyApp);

And last but not least, then in your second page (or every page you need to) you can just subscribe to that service and handle the events
Home.ts
import { NavController } from 'ionic-angular/index';
import { Component } from "@angular/core";
import { ConnectivityService } from 'connectivityService.ts';

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public status: string = '';

  constructor(private nav: NavController, private connectivityService: ConnectivityService) {

    // We subscribe to the service, so if the connection status changes, we'll be notified.
    this.connectivityService.connection.subscribe((isOnline) => {
      this.handleConnectionStatus(isOnline);
    });
  }

  // Show a message when the connection changes
  public handleConnectionStatus(private isOnline: bool) {
    if(isOnline) {
      this.status = 'Online';
      console.log('Now is Online');
    } else {
      this.status = 'Offline';
      console.log('Now is offline');
    }
  }
}

A: Having read the posts here and other forums, seems like the part about subscribing to an event is rather tricky. I gather that understanding lifecycle hooks and how promises work is important to getting around the problem. The following works if you want a second page to be able to subscribe to a published event on an existing page:
this.navCtrl.setRoot(NextComponentPage, Parameters).then(()=>
{
    this.events.publish("user:created", userdetails);
});

A: Call the .subscribe inside constructor.
and insted of console.log(data[0]) have you tried with console.log(data) ?


text:
Q: How to efficiently ensure a decimal value has at least N decimal places I want to efficiently ensure a decimal value has at least N (=3 in the example below) places, prior to doing arithmetic operations.
Obviouly I could format with "0.000######....#" then parse, but it's relatively inefficient and I'm looking for a solution that avoids converting to/from a string.
I've tried the following solution:
decimal d = 1.23M;
d = d + 1.000M - 1;
Console.WriteLine("Result = " + d.ToString()); // 1.230

which seems to work for all values <= Decimal.MaxValue - 1 when compiled using Visual Studio 2015 in both Debug and Release builds.
But I have a nagging suspicion that compilers may be allowed to optimize out the (1.000 - 1).  Is there anything in the C# specification that guarantees this will always work?
Or is there a better solution, e.g. using Decimal.GetBits?
UPDATE
Following up Jon Skeet's answer, I had previously tried adding 0.000M, but this didn't work on dotnetfiddle.  So I was surprised to see that Decimal.Add(d, 0.000M) does work.  Here's a dotnetfiddle comparing d + 000M and decimal.Add(d,0.000M): the results are different with dotnetfiddle, but identical when the same code is compiled using Visual Studio 2015:
decimal d = 1.23M;
decimal r1 = decimal.Add(d, 0.000M);
decimal r2 = d + 0.000M;
Console.WriteLine("Result1 = " + r1.ToString());  // 1.230
Console.WriteLine("Result2 = " + r2.ToString());  // 1.23 on dotnetfiddle

So at least some behavior seems to be compiler-dependent, which isn't reassuring.

A: If you're nervous that the compiler will optimize out the operator (although I doubt that it would ever do so) you could just call the Add method directly. Note that you don't need to add and then subtract - you can just add 0.000m. So for example:
public static decimal EnsureThreeDecimalPlaces(decimal input) =>
    decimal.Add(input, 0.000m);

That appears to work fine - if you're nervous about what the compiler will do with the constant, you could keep the bits in an array, converting it just once:
private static readonly decimal ZeroWithThreeDecimals =
    new decimal(new[] { 0, 0, 0, 196608 }); // 0.000m

public static decimal EnsureThreeDecimalPlaces(decimal input) =>
    decimal.Add(input, ZeroWithThreeDecimals);

I think that's a bit over the top though - particularly if you have good unit tests in place. (If you test against the compiled code you'll be deploying, there's no way the compiler can get in there afterwards - and I'd be really surprised to see the JIT intervene here.)

A: The Decimal.ToString() method outputs the number of decimal places that is determined from the structure's internal scaling factor.  This factor can range from 0 to 28.  You can obtain the information to determine this scaling factor by calling the Decimal.GetBits Method.  This method's name is slightly misleading as it returns an array of four integer values that can be passed to the Decimal Constructor (Int32[]); the reason I mention this constructor is that its "Remarks" section of the documentation describes the the bit layout better than the documentation for the GetBits method.
Using this information you can determine the Decimal value's scale factor an thus know how many decimal places the default ToString method will yield.  The following code demonstrates this as an extension method named "Scale".  I also included an extension method named "ToStringMinScale" to format the Decimal to a minimum scale factor value.  If the Decimal's scale factor is greater than the specified minimum, that value will be used.
internal static class DecimalExtensions
    {
    public static Int32 Scale(this decimal d)
        {
        Int32[] bits = decimal.GetBits(d);

        // From: Decimal Constructor (Int32[]) - Remarks
        // https://msdn.microsoft.com/en-us/library/t1de0ya1(v=vs.100).aspx

        // The binary representation of a Decimal number consists of a 1-bit sign,
        // a 96-bit integer number, and a scaling factor used to divide
        // the integer number and specify what portion of it is a decimal fraction.
        // The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28.

        // bits is a four-element long array of 32-bit signed integers.

        // bits [0], bits [1], and bits [2] contain the low, middle, and high 32 bits of the 96-bit integer number.

        // bits [3] contains the scale factor and sign, and consists of following parts:

        // Bits 0 to 15, the lower word, are unused and must be zero.

        // Bits 16 to 23 must contain an exponent between 0 and 28, which indicates the power of 10 to divide the integer number.

        // Bits 24 to 30 are unused and must be zero.

        // Bit 31 contains the sign; 0 meaning positive, and 1 meaning negative.

        // mask off bits 0 to 15
        Int32 masked = bits[3] & 0xF0000;
        // shift masked value 16 bits to the left to obtain the scaleFactor
        Int32 scaleFactor = masked >> 16;

        return scaleFactor;
        }

    public static string ToStringMinScale(this decimal d, Int32 minScale)
        {
        if (minScale < 0 || minScale > 28)
            {
            throw new ArgumentException("minScale must range from 0 to 28 (inclusive)");
            }
        Int32 scale = Math.Max(d.Scale(), minScale);
        return d.ToString("N" + scale.ToString());
        }

    }


text:
Q: Looping clipboard and errorlevel evaluation not working as expected while clipboard =
    {
        SendEvent, ^{ins}                                   ;^c doesn't work
        sleep 50
    }
    clipWait, 2                                     ; Wait for the clipboard to contain text.
    if ErrorLevel
    {
        ;endEvent, ^{ins}
        MsgBox Failed to save the selection: %clipboard%
        ;exit
    }

Problem: ErrorLevel still gets evaluated as true, whereas the loop shouldn't finish unless something came inside the clipboard. How is this possible?
Clarification: This construction was made as an attempt to answer question: SendEvent ^{ins} isn't copying content to the clipboard
As such, yes I am aware that looping the clipboard is not regarded as a reliable practice. But I have no other alternative than employing such a construction.

A: While loops expect expressions, clipboard = is no expression. Try this one:
clipboard := ""
while( StrLen(clipboard) < 1 )
{
    Send, ^{ins}
    Sleep, 50
}
MsgBox % ClipBoard


text:
Q: How to position popover in swift dead center (it's a little off center) The following code displays an arrowless popover. I tried positioning it dead center in the view but it's a little off. I don't know what to do - I'm a total beginner.
@IBAction func PostPop(sender: AnyObject) {
    self.performSegueWithIdentifier("showPostPop", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender:   AnyObject?) {

    if segue.identifier == "showPostPop" {
        let vc = segue.destinationViewController
        let controller = vc.popoverPresentationController

        if let _controller = controller {
            //set anchor and remove arrow
            _controller.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds), 0, 0)
            _controller.permittedArrowDirections = UIPopoverArrowDirection(rawValue:0)

        }

        if controller != nil
        {
            controller?.delegate = self
        }
    }
}

Here's what it looks like:


text:
Q: How can I change my Lenovo Legion Y520 keyboard light from white to red? The pictures I see have red lights but mine has white lights. Can I change it or is it part of the model?
my model can only have white light.


text:
Q: Regex contain one of specific numbers Let say I have a text like this
11/2/2010 10
22/3/2009 20
30/4/2003 30
14/5/1994 40
5/6/2000 50

And I only want to choose numbers after a string of a day in April or February (in this case it means '10' and '30'). I have tried:
\d+\/(2|4)\/\d+ (\d+)

but it captures also number '2' and '4' as group 1, then '10' and '30' as group 2 in result.
Please help!
P/S: I used pcre(php) as regex flavor

A: Use this regex :
\d+\/(?:2|4)\/\d+ (\d+)

By adding ?: you specifiy you don't want to capture the group (2|4)
Or here simply :
\d+\/[24]\/\d+ (\d+)

A: If i understood you correctly:
^.*\/[24]\/.*?(?=\s)

Live demo
Out of:
11/2/2010 10
22/3/2009 20
30/4/2003 30
14/5/1994 40
5/6/2000 50

This will match:
11/2/2010
30/4/2003


text:
Q: Table of all combinations possible with combination id Here come a little ABAP challenge:
For an ABAP projet, i must build from an internal table with 2 columns (example1) another table containing all combinations possibles (example2).
"X" columns represent the parameter. "Y" represent the parameter value.
example1:
X(param)
    Y(value)
A   a1
A   a2
A   a3
B   b1
B   b2
C   c1
C   c2
In the result table (example2):
We must get all combinations with a numeric id (on 3 columns).
The new "z" column represent the combination id. For each combination there is a number of lines equal to the number of dictinct parameters(in our case 3 line for A,B and C).
"x" column still represent the parameter and "y" column the associated value.
example2:
z(combi num)
    x(param)
    y(value)
1   A   a1
1   B   b1
1   C   c1
2   A   a1
2   B   b1
2   C   c2
3   A   a1
3   B   b2
3   C   c1
4   A   a1
4   B   b2
4   C   c2
etc...
    etc...
    etc...
12  A   a3
12  B   b2
12  C   c2
Another remark is that the number of parameters and the number of values per parameters is not fixed (the initial internal table can evolve a lot and so the combinations possibles).
We maybe need recursion but i'm not sure of it.

A: Here is a non-recursive way to do it, you might have to rewrite the parts that use the new 740 syntax. The idea is pretty simple, first transform the data into an internal table with one entry per parameter containing a table with the possible values, the LOOP loop. From there it is a simple matter of going through all the combinations and adding these to another internal table, the WHILE loop.
REPORT z_algorithm.

TYPES: ty_param TYPE char1,
       ty_value TYPE char2,
       BEGIN OF ty_struct,
         x TYPE ty_param,
         y TYPE ty_value,
       END OF ty_struct,
       BEGIN OF ty_combi,
         z TYPE i,
         s TYPE ty_struct,
       END OF ty_combi.
TYPES: BEGIN OF ty_param_struct,
         x  TYPE ty_param,
         ys TYPE STANDARD TABLE OF ty_value WITH DEFAULT KEY,
         ix TYPE i,
       END OF ty_param_struct.

DATA: tab      TYPE STANDARD TABLE OF ty_struct,
      params   TYPE STANDARD TABLE OF ty_param_struct,
      done     TYPE abap_bool VALUE abap_false,
      z        TYPE i VALUE 0,
      overflow TYPE abap_bool VALUE abap_false,
      combis   TYPE STANDARD TABLE OF ty_combi.

START-OF-SELECTION.
  APPEND VALUE: #( x = 'A' y = 'a1' ) TO tab,
                #( x = 'A' y = 'a2' ) TO tab,
                #( x = 'A' y = 'a3' ) TO tab,
                #( x = 'B' y = 'b1' ) TO tab,
                #( x = 'B' y = 'b2' ) TO tab,
                #( x = 'C' y = 'c1' ) TO tab,
                #( x = 'C' y = 'c2' ) TO tab.

  LOOP AT tab ASSIGNING FIELD-SYMBOL(<tab>).
    READ TABLE params WITH KEY x = <tab>-x ASSIGNING FIELD-SYMBOL(<param>).
    IF sy-subrc NE 0.
      APPEND INITIAL LINE TO params ASSIGNING <param>.
      <param>-x = <tab>-x.
      <param>-ix = 1.
    ENDIF.
    APPEND <tab>-y TO <param>-ys.
  ENDLOOP.

  WHILE done EQ abap_false.

    ADD 1 TO z.
    overflow = abap_true.
    done = abap_true.

    LOOP AT params ASSIGNING <param>.

      READ TABLE <param>-ys INDEX <param>-ix ASSIGNING FIELD-SYMBOL(<y>).
      APPEND VALUE #( z = z s-x = <param>-x s-y = <y> ) TO combis.

      IF overflow EQ abap_true.
        ADD 1 TO <param>-ix.
      ENDIF.

      IF <param>-ix GT lines( <param>-ys ).
        overflow = abap_true.
        <param>-ix = 1.
      ELSE.
        overflow = abap_false.
        done = abap_false.
      ENDIF.

    ENDLOOP.

  ENDWHILE.


text:
Q: Tangent vector confusion I am a little confused, is a tangent vector $T$ a unit vector? I know there is a unit tangent vector defined as
$$T = \frac{r'}{|r'|}.$$
I think the most confusing thing is $T$ is being used for both Tangent vector and unit tangent vector?
Could someone clarify this?

A: We know the velocity vector $v = \frac{\mathrm dr}{\mathrm dt}$ is tangent to the curve $r(t)$ so it is a tangent vector, but the vector $T$ is its direction vector. Of course, this unit tangent vector (I mean $T$) is a differentiable function of $t$ whenever $v=r'(t)$ is a
differentiable function of $t$.


text:
Q: extjs getselectedcell() but not using Ext.grid.CellSelectionModel I hv an editorGridPanel and it's selmodel=new Ext.grid.CheckboxSelectionModel(), but I want to get the selected column by using getSelectedCell, is it possible?

A: Here is working sample: http://jsfiddle.net/qxpfJ/1/

function cellRenderer(value, column, record, row, col){
    return Ext.String.format('{4}',
       record.data.id, column.column.dataIndex, row, col, value);
}

Ext.create('Ext.grid.Panel', {
    title: 'Countries',
    selType : 'cellmodel',
    renderTo: Ext.getBody(),
    store: Ext.create('Ext.data.Store', {
                fields:['id', 'cName'],
                data:{'items':[ { id: 1, cName: 'Australia' },
                                { id: 2, cName:'Germany' },
                                { id: 3, cName:'Russia' },
                                { id: 4, cName:'United States' }]},
                proxy: {
                    type: 'memory',
                    reader: { type: 'json', root: 'items' }
                }
            }),
    columns: [{ text: 'id',  dataIndex: 'id', renderer: cellRenderer },
              { text: 'Country', dataIndex: 'cName', flex: 1, renderer: cellRenderer }],
    listeners:{
        selectionchange: function( me, selected, eOpts ){
            var sel = Ext.query('.x-grid-cell-selected span');
            if(sel[0]){
                var data = sel[0].getAttribute('key').split('_');
                container.update( Ext.String.format(
                    'id={0};
column="{1}";
rowIndex={2};
colIndex={3};',
                    data[0], data[1], data[2], data[3]));
            }
        }
    }
});

var container = Ext.create('Ext.container.Container', {
    renderTo: Ext.getBody()
});

EDIT
And here is same sample, but for checkboxmodel: http://jsfiddle.net/qxpfJ/2/
Ext.create('Ext.grid.Panel', {
    title: 'Countries',
    selType : 'checkboxmodel',
    renderTo: Ext.getBody(),
    store: Ext.create('Ext.data.Store', {
                fields:['id', 'cName'],
                data:{'items':[ { id: 1, cName: 'Australia' },
                                { id: 2, cName:'Germany' },
                                { id: 3, cName:'Russia' },
                                { id: 4, cName:'United States' }]},
                proxy: {
                    type: 'memory',
                    reader: { type: 'json', root: 'items' }
                }
            }),
    columns: [{ text: 'id',  dataIndex: 'id' },
              { text: 'Country', dataIndex: 'cName', flex: 1 }],
    listeners:{
        cellclick: function( me, td, cellIndex, record, tr, rowIndex, e, eOpts ){
            container.update( Ext.String.format(
            'id={0};
rowIndex={1};
cellIndex={2};',
             record.data.id, rowIndex, cellIndex));
        }
    }
});

var container = Ext.create('Ext.container.Container', {
    renderTo: Ext.getBody()
});


text:
Q: The php post is returning wrong value I have wrote the code like this
<?php
  echo "Add1:".$_POST['Address1'];
  echo "
";
  echo "Add2:".$_POST['Address2'];
 ?>
<FORM name="myForm" method='post'>

    Address 1
    <input type="text" name="Address1">

    Address2
    <input type="text" name="Address2">

<input type="submit">
</FORM>

When enter a value as some thing like this
Address1 = test <test1 and Address2=address2:

But in post i got only the Address1 value in both post variable like.
Add1:test
Add2:test1

Any one can help me.

A: Debug what you're getting via
<?php print_r($_POST);

and you'll see if it is PHP releated problem or the problem lays somewhere else

A: Based on your example, it doesn't look like it's not working (Add1 and Add2 are different). What happens if you do a var_dump($_POST)?

A: If $_POST['Address2'] wasn't filled through the form, it is empty, no output should be displayed.
Try var_dump($_POST); to check the whole POST-array and/or use tools like Firebug, to see which data was sent to the actually.

A: you can have exact idea by writing this code
<?php
    echo "
";print_r($_POST);echo "
";
    echo "Add1:".$_POST['Address1'];
    echo "
";
    echo "Add2:".$_POST['Address2'];
?>

that will emable you to check what exactly is coming in $_POST


text:
Q: Specifying one Dimension of Cells in UICollectionView using Auto Layout In iOS 8 the UICollectionViewFlowLayout supports automatically resizing cells based on their own content size. This resizes the cells in both width and height according to their content.
Is it possible to specify a fixed value for the width (or height) of all the cells and allow the other dimensions to resize?
For a simple example consider a multi-line label in a cell with constraints positioning it to the sides of the cell. The multi-line label could be resized different ways to accommodate the text. The cell should fill the width of the collection view and adjust it's height accordingly. Instead, the cells are sized haphazardly and it even causes a crash when the cell size is larger than the non-scrollable dimension of the collection view.

iOS 8 introduces the method systemLayoutSizeFittingSize: withHorizontalFittingPriority: verticalFittingPriority: For each cell in the collection view the layout calls this method on the cell, passing in the estimated size. What would make sense to me would be to override this method on the cell, pass in the size that is given and set the horizontal constraint to required and a low priority to the vertical constraint. This way the horizontal size is fixed to the value set in the layout and the vertical size can be flexible.
Something like this:
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    UICollectionViewLayoutAttributes *attributes = [super preferredLayoutAttributesFittingAttributes:layoutAttributes];
    attributes.size = [self systemLayoutSizeFittingSize:layoutAttributes.size withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
    return attributes;
}

The sizes given back by this method, however, are completely strange. The documentation on this method is very unclear to me and mentions using the constants UILayoutFittingCompressedSize UILayoutFittingExpandedSize which just represent a zero size and a pretty large one.
Is the size parameter of this method really just a way to pass in two constants? Is there no way to achieve the behavior I expect of getting the appropriate height for a given size?

Alternate Solutions
1) Adding constraints that will be specify a specific width for the cell achieves the correct layout. This is a poor solution because that constraint should be set to the size of the cell's collection view which it has no safe reference to. The value for that constraint could be passed in when the cell is configured, but that also seems completely counterintuitive. This is also awkward because adding constraints directly to a cell or it's content view is causing many problems.
2) Use a table view. Table views work this way out of the box as cells have a fixed width, but this would not accommodate other situations like an iPad layout with fixed width cells in multiple columns.

A: A simple way to do it in iOS 9 in a few lines of codes - the horizontal way exemple (fixing its height to its Collection View height) :
Init your Collection View Flow Layout with an estimatedItemSize to enable self-sizing cell :
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.estimatedItemSize = CGSizeMake(1, 1);

Implement the Collection View Layout Delegate (in your View Controller most of the time), collectionView:layout:sizeForItemAtIndexPath: . The goal here is to set the fixed height (or width) to the Collection View dimension. The 10 value can be anything, but you should set it to a value that doesn't break constraints :
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(10, CGRectGetHeight(collectionView.bounds));
}

Override your custom cell preferredLayoutAttributesFittingAttributes: method, this part actually calculate your dynamic cell width based on your Auto Layout constraints and the height you have just set :
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    UICollectionViewLayoutAttributes *attributes = [layoutAttributes copy];
    float desiredWidth = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].width;
    CGRect frame = attributes.frame;
    frame.size.width = desiredWidth;
    attributes.frame = frame;
    return attributes;
}

A: There's a cleaner way to do this than some of the other answers here, and it works well. It should be performant (collection views load fast, no unnecessary auto layout passes etc), and doesn't have any 'magic numbers' like a fixed collection view width. Changing the collection view size, e.g. on rotation, and then invalidating the layout should work great too.
1. Create the following flow layout subclass
class HorizontallyFlushCollectionViewFlowLayout: UICollectionViewFlowLayout {

    // Don't forget to use this class in your storyboard (or code, .xib etc)

    override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as? UICollectionViewLayoutAttributes
        guard let collectionView = collectionView else { return attributes }
        attributes?.bounds.size.width = collectionView.bounds.width - sectionInset.left - sectionInset.right
        return attributes
    }

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let allAttributes = super.layoutAttributesForElementsInRect(rect)
        return allAttributes?.flatMap { attributes in
            switch attributes.representedElementCategory {
            case .Cell: return layoutAttributesForItemAtIndexPath(attributes.indexPath)
            default: return attributes
            }
        }
    }
}

2. Register your collection view for automatic sizing
// The provided size should be a plausible estimate of the actual
// size. You can set your item size in your storyboard
// to a good estimate and use the code below. Otherwise,
// you can provide it manually too, e.g. CGSize(width: 100, height: 100)

flowLayout.estimatedItemSize = flowLayout.itemSize

3. Use the predefined width + custom height in your cell subclass
override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    layoutAttributes.bounds.size.height = systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    return layoutAttributes
}

A: Try fixing your width in the preferred layout attributes:
- (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    UICollectionViewLayoutAttributes *attributes = [[super preferredLayoutAttributesFittingAttributes:layoutAttributes] copy];
    CGSize newSize = [self systemLayoutSizeFittingSize:CGSizeMake(FIXED_WIDTH,layoutAttributes.size) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
    CGRect newFrame = attr.frame;
    newFrame.size.height = size.height;
    attr.frame = newFrame;
    return attr;
}

Naturally you also want to ensure that you setup your layout correctly to:
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *) self.collectionView.collectionViewLayout;
flowLayout.estimatedItemSize = CGSizeMake(FIXED_WIDTH, estimatedHeight)];

Heres something I put on Github that uses constant width cells and supports dynamic type so the height of the cells updates as the system font size changes.

A: It sounds like what you are asking for is a way to use UICollectionView to produce a layout like UITableView. If that's really what you want, the right way to do this is with a custom UICollectionViewLayout subclass (maybe something like SBTableLayout).
On the other hand, if you're really asking if there is a clean way to do this with the default UICollectionViewFlowLayout, then I believe there is no way. Even with iOS8's self-sizing cells, it is not straightforward. The fundamental problem, as you say, is that the flow layout's machinery provides no way to fix one dimension and let another respond. (In addition, even if you could, there would be additional complexity around needing two layout passes to size the multi-line labels. This might not fit with how self-sizing cells want to compute all sizing via one call to systemLayoutSizeFittingSize.)
However, if you still want to create a tableview-like layout with a flow layout, with cells that determine their own size, and respond naturally to the collection view's width, of course it is possible. There is still the messy way. I have done it with a "sizing cell", i.e., a non-displayed UICollectionViewCell that the controller keeps only for calculating cell sizes.
There are two parts to this approach. The first part is for the collection view delegate to calculate the correct cell size, by taking in the collection view's width and using the sizing cell to calculate the cell's height.
In your UICollectionViewDelegateFlowLayout, you implement a method like this:
func collectionView(collectionView: UICollectionView,
  layout collectionViewLayout: UICollectionViewLayout,
  sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
  // NOTE: here is where we say we want cells to use the width of the collection view
   let requiredWidth = collectionView.bounds.size.width

   // NOTE: here is where we ask our sizing cell to compute what height it needs
  let targetSize = CGSize(width: requiredWidth, height: 0)
  /// NOTE: populate the sizing cell's contents so it can compute accurately
  self.sizingCell.label.text = items[indexPath.row]
  let adequateSize = self.sizingCell.preferredLayoutSizeFittingSize(targetSize)
  return adequateSize
}

This will cause the collection view to set the width of the cell based on the enclosing collection view, but then ask the sizing cell to calculate the height.
The second part is to get the sizing cell to use its own AL constraints to calculate the height. This can be harder than it should be, because of the way multi-line UILabel's effectively require a two-stage layout process. The work is done in the method preferredLayoutSizeFittingSize, which is like so:
 /*
 Computes the size the cell will need to be to fit within targetSize.

 targetSize should be used to pass in a width.

 the returned size will have the same width, and the height which is
 calculated by Auto Layout so that the contents of the cell (i.e., text in the label)
 can fit within that width.

 */
 func preferredLayoutSizeFittingSize(targetSize:CGSize) -> CGSize {

   // save original frame and preferredMaxLayoutWidth
   let originalFrame = self.frame
   let originalPreferredMaxLayoutWidth = self.label.preferredMaxLayoutWidth

   // assert: targetSize.width has the required width of the cell

   // step1: set the cell.frame to use that width
   var frame = self.frame
   frame.size = targetSize
   self.frame = frame

   // step2: layout the cell
   self.setNeedsLayout()
   self.layoutIfNeeded()
   self.label.preferredMaxLayoutWidth = self.label.bounds.size.width

   // assert: the label's bounds and preferredMaxLayoutWidth are set to the width required by the cell's width

   // step3: compute how tall the cell needs to be

   // this causes the cell to compute the height it needs, which it does by asking the
   // label what height it needs to wrap within its current bounds (which we just set).
   let computedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)

   // assert: computedSize has the needed height for the cell

   // Apple: "Only consider the height for cells, because the contentView isn't anchored correctly sometimes."
   let newSize = CGSize(width:targetSize.width,height:computedSize.height)

   // restore old frame and preferredMaxLayoutWidth
   self.frame = originalFrame
   self.label.preferredMaxLayoutWidth = originalPreferredMaxLayoutWidth

   return newSize
 }

(This code is adapted from the Apple sample code from the sample code of the WWDC2014 session on  "Advanced Collection View".)
A couple points to notice. It's using layoutIfNeeded() to force layout of the entire cell, in order to compute and set the width of the label. But that's not enough. I believe you also need to set preferredMaxLayoutWidth so that the label will use that width with Auto Layout. And only then can you use systemLayoutSizeFittingSize in order to get the cell to compute its height while taking the label into account.
Do I like this approach? No!! It feels way too complex, and it does layout twice. But as long as performance doesn't become an issue, I'd rather perform layout twice at runtime than have to define it twice in code, which seems to be the only other alternative.
My hope is that eventually self-sizing cells will work differently and this will all get a lot simpler.
Example project showing it at work.
But why not just use self-sizing cells?
In theory, iOS8's new facilities for "self-sizing cells" should make this unnecessary. If you've defined a cell with Auto Layout (AL), then the collection view should be smart enough to let it size itself and lay itself out correctly. In practice, I haven't seen any examples that have gotten this to work with multi-line labels. I think this is partly because the self-sizing cell mechanism is still buggy.
But I'd bet it's mostly because of the usual trickiness of Auto Layout and labels, which is that UILabels require a basically two-step layout process. It's not clear to me how you can perform both steps with self-sizing cells.
And like I said, this is really a job for a different layout. It is part of flow layout's essence that it positions things that have a size, rather than fixes a width and lets them choose their height.
And what about preferredLayoutAttributesFittingAttributes: ?
The preferredLayoutAttributesFittingAttributes: method is a red herring, I think. That is only there to be used with the new self-sizing cell mechanism. So this isn't the answer as long as that mechanism is unreliable.
And what's up with systemlayoutSizeFittingSize:?
You're right the docs are confusing.
The docs on systemLayoutSizeFittingSize: and systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: both suggest that you should only pass UILayoutFittingCompressedSize and UILayoutFittingExpandedSize as the targetSize. However, the method signature itself, the header comments, and the behavior of the functions indicate that they are responding to the exact value of the targetSize parameter.
In fact, if you set the UICollectionViewFlowLayoutDelegate.estimatedItemSize, in order to enable the new self-sizing cell mechanism, that value seems to get passed in as the targetSize. And UILabel.systemLayoutSizeFittingSize seems to return the exact same values as UILabel.sizeThatFits. This is suspicious, given that the argument to systemLayoutSizeFittingSize is supposed to be a rough target and the argument to sizeThatFits: is supposed to be a maximum circumscribing size.
More Resources
While it is sad to think that such a routine requirement should require "research resources", I think it does. Good examples and discussions are:

*

*http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html

*http://devetc.org/code/2014/07/07/auto-layout-and-views-that-wrap.html

*code for WWDC2014 session 232, "Advanced User Interfaces with Collection Views"

A: YES it can be done using auto layout programmatically and by setting constraints in storyboard or xib. You need to add constraint for width size to remain constant and set height greater than or equal to.
http://www.thinkandbuild.it/learn-to-love-auto-layout-programmatically/
http://www.cocoanetics.com/2013/08/variable-sized-items-in-uicollectionview/
 Hope this will be helpful and solve your issue.


text:
Q: iCloud key value storage on multiple apps using same ubiquity container I know this type of question has been asked before in a similar fashion but no satisfactory answer could be found for those. Could some one please shed some light on it. Before I start my question I would like to add that App IDs are iCloud enabled and provisional profiles are created/downloaded/installed after that.
I followed the Apple documentation here https://developer.apple.com/library/mac/documentation/General/Conceptual/iCloudDesignGuide/Chapters/iCloudFundametals.html
Configuring a Common Ubiquity Container for Multiple Apps
In the Xcode target editor's Summary tab, you can request access to as many ubiquity containers as you need for your app. For example, say you provide a free and paid version of your app. You'd want users, who upgrade, to retain access to their iCloud documents. Or, perhaps you provide two apps that interoperate and need access to each other's files. In both of these examples, you obtain the needed access by specifying a common ubiquity container and then requesting access to it from each app.

To configure a common ubiquity container
Pick one of your iCloud-enabled apps to serve as the primary app for the common ubiquity container.

The app you pick can be the current one you are developing, or another app of yours submitted for distribution in the App Store and whose entitlements use the same team ID.

In the first row of the Xcode target editor's iCloud Containers list, enter the bundle identifier of your primary iCloud-enabled app.

If you then look in the .entitlements property list file, you'll see that Xcode has automatically qualified the identifier string by prefixing it with your team ID.

To retrieve a URL for a ubiquity container, you must pass the fully qualified string to the NSFileManager method URLForUbiquityContainerIdentifier:. That is, you must pass the complete container identifier string, which includes your team ID, that you see in the .entitlements property list file. You can pass nil to this method to retrieve the URL for the first container in the list.

For more information about how to configure entitlements, see "Configuring Store Technologies in Xcode and iTunes Connect" in App Distribution Guide

I have a MAC App and an iOS app. In capabilities section of MAC app iCloud is switched on. Ubiquity container contains the bundle identifier of my MAC app. I checked the .entitlement file and iCloud key value storage is TeamIdentifier.bundleidentifier. Everything works fine. Values are being stored in iCloud and I can fetch them without any problem.
Now on my iOS app. In capabilities section I have switched on iCloud and set the ubiquity container string to bundle identifier of my MAC app. Checked .entitlement file and iCloud key value storage string is set to TeamIdentifier.bundleidentifier. My iOS app is getting nil in the values when I fetch from iCloud. I have tested that on simulator and on my iPhone 5 but no luck.
Any help is greatly appreciated.


text:
Q: How to get scroll values of a select dropdown inside a modal I have a select box which will load more than 3k values in it. Due to more values performance has got affected. So I tried to load values based on the scroll. But nothing worked for me.
The below HTML code is inside modal
<div class="col-md-3">
<select select2 data-placeholder="Program Name(s)" class="form-control scroll" ng-
model="getProgramName" when-scrolled = "loadMore()" id="scroll" multiple>
<option value="{{progname}}" ng-repeat="progname in segmentList | limitTo:numberToDisplay">
{{progname | splitMak}}
</option>
</select>
</div

JS FIle:
$scope.openModelrepoName = function (ev, rowObj) {
try {
APIFactory.getAllFuncPackSrcArtifacts(repoNameObj, function (response) {
if (response.status) {
$mdDialog.show({
controller: dataFuntionalPartner,
templateUrl: 'html/templates/dataFunctionalPartner.template.html',
controllerAs: 'vmid',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: false,
fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
locals: {
"rowObj": rowObj,
"segmentList" : response.data,
"repoNameObj" : repoNameObj
 }
 })
 } else {
 Toaster.sayError(response.errorMessage)
 }
 })
 } catch (err) { }
 }

 function dataFuntionalPartner($scope, $mdDialog, rowObj,segmentList,repoNameObj) {
 $scope.numberToDisplay = 20;
 $scope.segmentList = segmentList

 $scope.loadMore = function (event) {
 if ($scope.numberToDisplay + 20 < $scope.segmentList.length) {
 $scope.numberToDisplay += 20;
 } else {
 $scope.numberToDisplay = $scope.segmentList.length;
 }
 }

My Directive:
 app.directive("whenScrolled", function(){
 return{
 restrict: 'A',
 link: function(scope, elem, attrs){
 console.log(elem)
    // we get a list of elements of size 1 and need the first element
 raw = elem[0];

    // we load more elements when scrolled past a limit
 elem.bind("scroll", function(){
 if(raw.scrollTop+raw.offsetHeight+5 >= raw.scrollHeight){
 scope.loading = true;

 // we can give any function which loads more elements into the list
 scope.$apply(attrs.whenScrolled);
 }
 });
 }
 }
 });

My problem here is the above directive working only while initializing. and it is not working on any scroll action is done.


text:
Q: Statistical model with $\Gamma(\alpha_i,1)$ sample We are given statistical sample of $X=(X_1,X_2,X_3)$, where $X_i\sim\Gamma(\alpha_i,1)$ and independent. Let $Z=X_1+X_2+X_3$ and $T$ three dimensional statistic $T:=(\frac{X_1}{Z},\frac{X_2}{Z},\frac{X_3}{Z})$.
We are asked to check are $T$ and $Z$ independent.
Hint: Find joint density function of $T$.
So far, I manage to find that:
$$Z\sim\Gamma(\alpha_1+\alpha_2+\alpha_3,1)$$
and that:
$$\frac{X_i}{Z}\sim\beta'(\alpha_i,\alpha_1+\alpha_2+\alpha_3)$$.
So:
$$f_T(y_1,y_2,y_3)=\prod_{i=1}^{3}f_{\frac{X_i}{Z}}(y_i).$$
However, now when I have to prove the independence of $T$ and $Z$ I get lost. How should I use this joint distribution function? Should I try to deduce something special about this distribution? Please, help.
By the way, I do see that $T_1+T_2+T_3=1$. Is there a way to use that?

A: This post has self study tag so I will just describe the way to solve this problem.
The joint distribution of $T$ is actually the joint distribution of $Y_1 = \frac{X_1}{Z}$, $Y_2 = \frac{X_2}{Z}$ because the third coordinate is automatically set to be $1-Y_1-Y_2$.
To get the distribution of $T$, I guess you should
firstly use transformation like : $Y_1 = \frac{X_1}{Z}$, $Y_2 = \frac{X_2}{Z}$, $Y_3 = Z$
and secondly get the joint distribution of these variables
and finally integrate it with $y_3$ to get the marginal distribution of $Y_1$ and $Y_2$ which is the distribution of $T$.
This can be done with a little effort.
You can use the fact that $X_1,X_2,X_3$ are independent of each others and the determinant of Yacobian matrix isn't complex.
And actually you don't have to integrate with $y_3$ to show the independence.
Before integration, you can figure out that the joint pdf  $g_{Y_1,Y_2,Y_3}$ can be expressed as the multiplication form like $g_{Y_1,Y_2}(y_1,y_2) g_{Y_3}(y_3)$ which means that $Z=Y_3$ is independent of $T$.
I am not a native English speaker so please don't mind my awkward expressions and it would be appreciated if you improve my sentences. Thank you.
This is the way to find the Drichlet distribution which is mentioned by the comments of @GordonSmyth.


text:
Q: Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver In netbeans I'm trying to connect the database with Netbeans with the help of oracle 10g. I have downloaded odjbc7.jar file and added it in the ORACLE THIN driver in db services. Still, I'm  getting this class not found exception. (I am using Apache netbeans).
enter code here

       import java.sql.*;

        public class jdbclass {
        public static void main(String args[]) throws ClassNotFoundException, SQLException
       {
             String url="jdbc:oracle:thin:@localhost:1521:orcl";
             String uname="sh";
             String passwd="ara";
             String query="select pizza_type from pizza";
             Class.forName("oracle.jdbc.driver.OracleDriver");
             Connection con=DriverManager.getConnection(url,uname, passed);
             Statement st=con.createStatement();
             ResultSet rs=st.executeQuery(query);
             String name=rs.getString("pizza_type");
             rs.next();
            System.out.print(name);
            st.close();
            con.close();

          }

        }

A: *

*You should use ojdbc14.jar as mentioned at https://docs.oracle.com/cd/E19830-01/819-4721/beanh/index.html

*Make sure you have added the jar in the classpath as mentioned at How do I set the classpath in NetBeans?


text:
Q: How to mirror an image horizontally using Java 2D Arrays? Greetings guys and girls I've stumbled into a problem I can't seem to figure out, and the similar posts have a different structure than what I'm using. Therefore I'd really appreciate some guidance. Let's take a look at my horizontal mirror method:
  public void  mirrorHorizontal(){
  Pixel[][] pixels = this.getPixels2D();
  Pixel topPixel = null;
  Pixel bottomPixel = null;
  int width = pixels[0].length;
  for (int row = 0; row < pixels.length / 2; row++){
      for (int col = 0; col < width; col++){
          bottomPixel = pixels[row][col];
          topPixel = pixels[row][col];
          bottomPixel.setColor(topPixel.getColor());
      }
  } }

Lets establish that this code was provided to use and modify so I will do my best to explain.
In this for loop what I did was cut the rows in half by diving the pixels.length by 2 so I can achieve the top picture at the top, and one on the bottom.
for (int row = 0; row < pixels.length / 2; row++){

So I believe here is my problem:
bottomPixel = pixels[row][col];
topPixel = pixels[row][col];

I do not know what to put inside the bottomPixel [row][col]
I believe it has to render something like this:

*

*1 2 3 4

*5 6 7 8

*5 6 7 8

*1 2 3 4

However I'm not sure how to modify it to achieve that.
This uses two modified for loops & different values to achieve similar effects to flipping a multi-dimensional array java by AngryDuck.

A: So in your exsample the bottomPixel and topPixel are exactly the same.
If I understood your question correctly, this will solve your problem:
for (int row = 0; row < pixels.length / 2; row++){
  for (int col = 0; col < pixels[0].length; col++){
      topPixel = pixels[row][col];
      bottomPixel = pixels[(pixels.length - 1) - i][col];
      bottomPixel.setColor(topPixel.getColor());
  }
}

I changed the row coordinate of bottomPixel so it will take the mirrored coordinate from the bottom. But this only works if your image has exactly pixels.length / 2 rows.