text:
Q: Storing a Map collection of values in Enum class for better access I have the next enum class:
public class DataParameter {

    public enum Types {
        BIG(-1), SMALL(1), SMAL2(2), SMAL3(5), BIG1(-1), BIG2(1), BIG3(2), BIF4(
                5);

        private final int id;

        Types(int id) {
            this.id = id;
        }

        public int getValue() {
            return id;
        }

        public static <T> parseType(T type, int id) {
            int intType = Integer.parseInt(String.valueOf(type));

            if (intType == SIZE_XL.getValue()) {
                if (id == -1)
                    return BIG;
                if (id == 1)
                    return BIG2;
                if (id == 2)
                    return BIG3;
                if (id == 5)
                    return BIG4;
            } else if (intType == SIZE_LARGE.getValue()) {
                if (id == 5)
                    return BIG4;
                if (id == 2)
                    return SMALL2;
                if (id == 5)
                    return SMALL3;
            } else if (intType == SIZE_UKNOWN.getValue()) {
                if (id == -1)
                    return BIG;
                if (id == -1)
                    return BIG;
                if (id == -1)
                    return BIG1;
                if (id == 5)
                    return BIG4;
            } else if (intType == SIZE_UKNOWN_2.getValue()) {
                return SMAL3;
            }

            return returnDefault(intType);
        }
    }

    public DataParameter(GameTypes type) {
        mValue = type.getValue();
    }
}

The problem that this code is very messy a lot of if statements. I tried to create a map that will be the next structure:
SIZE_XL ---> BIG,BIG2,BIG4
SIZE_LARGE ---> BIG4,SMALL2 ,SMALL3
SIZE_UKNOWN ---> BIG , BIG1 , BIG4

and them when when I'll get key I will retrieve the element from the map
I get confused because in the enum class I get some unknown problems.
HashMap<Integer, HashMap<Integer, Integer> myMap = new HashMap<Integer, HashMap<Integer, Integer>();
myMap.put(SIZE_XL.getValue(),BIG2.getValue(),BIG2)
myMap.put(SIZE_XL.getValue(),BIG3.getValue(),BIG3)
myMap.put(SIZE_XL.getValue(),BIG4.getValue(),BIG4)

...
...
..
I'll appreciate a help in that issue

A: Instead of directly putting the values in Map you need to create a map and you would be required to put that Map against the Key from enum. You have currently put the values in a form which is not applicable in Map
i.e. Instead of using
HashMap<Integer, HashMap<Integer, Integer> myMap = new HashMap<Integer, HashMap<Integer, Integer>();
myMap.put(SIZE_XL.getValue(),BIG2.getValue(),BIG2)

use:
HashMap<Integer, HashMap<Integer, Integer> myMap = new HashMap<Integer,     HashMap<Integer, Integer>();
Map<Integer, Integer> valueMap = new HashMap<Integer, Integer>();//create a map for values
valueMap.put(BIG2.getValue(), BIG2);//put the value and enum field in the value map
myMap.put(SIZE_XL.getValue(), valueMap);//put the value map against the key in your map.

A: In your code, you left out the definition of SIZE_XL and similar constants, I propose that instead of defining them as some constant you put them in an enum of their own, for example:
enum Size {
  XL(2), LARGE(1), UNKNOWN(-1), UNKNOWN_2(-2);

  private final int value;
  Size(int val) {
    value = val;
  }

  public int getValue() {
    return value;
  }
}

In your parse method you are looking up a Types based on two parameters, essentially these are two keys which you need to combine to get your value. Table is a data structure defined in Guava with two keys (a row and a column) and one value. Storing the combinations of interest (as defined in your parse function) in an ImmutableTable allows you to perform a quick lookup for the right value. The code becomes:
public enum Types {
  SMALL(1), SMALL2(2), SMALL3(3),

  BIG(0), BIG1(1), BIG2(2), BIG3(3), BIG4(4);

  static final ImmutableTable<Integer, Integer, Types> TABLE =
    ImmutableTable.<Integer, Integer, Types>builder()
      .put(Size.XL.getValue(), BIG.getValue(), BIG)
      .put(Size.XL.getValue(), BIG2.getValue(), BIG2)
      .put(Size.XL.getValue(), BIG4.getValue(), BIG4)
      .put(Size.LARGE.getValue(), BIG4.getValue(), BIG4)
      .put(Size.LARGE.getValue(), SMALL2.getValue(), SMALL2)
      .put(Size.LARGE.getValue(), SMALL3.getValue(), SMALL3)
      .put(Size.UNKNOWN.getValue(), BIG.getValue(), BIG)
      .put(Size.UNKNOWN.getValue(), BIG1.getValue(), BIG1)
      .put(Size.UNKNOWN.getValue(), BIG4.getValue(), BIG4)
      .build();

  private final int id;

  Types(int id) {
    this.id = id;
  }

  public int getValue() {
    return id;
  }

  public static Collection<Types> getTypesWithSize(Size size) {
    return TABLE.row(size.getValue()).values();
  }

  public static Collection<Types> getTypesWithId(Types types) {
    return TABLE.column(types.getValue()).values();
  }

  public static <T> Types parseType(T type, int id) {
    final int intType = Integer.parseInt(String.valueOf(type));

    if (!TABLE.contains(intType, id)) {
      // return some default value or throw exception
    }
    return TABLE.get(intType, id);
  }
}

Now you can use this code as:
Types.getTypesWithSize(Size.LARGE); // returns [SMALL2, BIG4, SMALL3]
Types.getTypesWithId(Types.SMALL3); // returns [SMALL3]

Note that I had to change some of the values for the Types in order to avoid duplicate row and column combinations, for a given row and column there can be only one Types instance.


text:
Q: Python dict key Sorted by list as value I have a list of dict like this, the value of each dict key is a list,
[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}]

The number of dict in list will vary.
How i can get output like this,
Each dict value in ascending order
500:mike
600:luke
750:john
1000:mike
1100:luke
1250:john
1500:mike
2000:john
2750:mike
3000:mike

A: A one liner:
result = sorted(((item, key) for d in x for (key, value) in d.items() for item in value), key=lambda x: x[0])

for elem in result:
    print ({elem[0]}:{elem[0]}.format(elem=elem)

A multi liner:
x = [{"mike":[500,1000,1500,2750,3000]},{"john":[750,1250,2000]},{"luke":[600,1100]}]
result = []
for item in x:
    for key, value in item.iteritems():
        for v in value:
            result.append((v, key))
result.sort(key=lambda x: x[0])
for elem in result:
    print ({elem[0]}:{elem[0]}.format(elem=elem)

# outputs
500:mike
600:luke
750:john
1000:mike
1100:luke
1250:john
1500:mike
2000:john
2750:mike
3000:mike

A: Use list comprehensions to flat the list of dicts into a list of tuples (value, key), use sorted to sort them by the value, use str.join to format your output.
list_dicts = [  {'mike':[500,1000,1500,2750,3000]},
                {'john':[750,1250,2000]},
                {'luke':[600,1100]}]

# flat the list of dicts as a list of tuples (value, key), sort them
result = sorted([(item, k) for d in list_dicts for k, l in d.items() for item in l])

# format output
print('\n'.join([':'.join([str(i) for i in t]) for t in result]))
# Output
500:mike
600:luke
750:john
1000:mike
1100:luke
1250:john
1500:mike
2000:john
2750:mike
3000:mike

A: You use itertools for solving this problem:
from itertools import product, chain

LL = list(chain(*[list(product(i.keys(), i.values()[0])) for i in L]))
sorted(LL, key=lambda x: x[1])

Out[152]:
[('mike', 500),
 ('luke', 600),
 ('john', 750),
 ('mike', 1000),
 ('luke', 1100),
 ('john', 1250),
 ('mike', 1500),
 ('john', 2000),
 ('mike', 2750),
 ('mike', 3000)]

A: a,b=[],[]
for i in g:
    for k in i.values()[0]:
        a.append(k)
        b.append(i.keys())

print sorted(zip(a,b))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why cabal sandbox init does not change PATH like virtualenv does? Haskell newbie and Python guy here.
I think I may be missing something here but if you look at Yesod's quickstart, the autor install some packages before cabal sandbox init. I have seen the same pattern elsewhere. Questions:

*

*Am I missing something? Is this the real way to use cabal sandbox?

*Why can't (or shouldn't) I install yesod-bin inside a sandbox?

*What if I use different versions of yesod-bin throughout some projects?

*If there is some libraries that install binaries inside .cabal-sandbox/bin, why cabal sandbox init don't change PATH in order to match the sandboxed version?

Thank you very much in advance!

A: *

*Yes, this how to use a sandbox.
cabal sandbox init will create some files / directories for you that will keep track of the packages you have installed.
cabal install some_package will install that package into the sandbox.

*You are more than welcome to install yesod-bin into a sandbox.

*Read point 2

*cabal sandbox init doesn't change your path, because it doesn't really need to. Just add PATH=.cabal-sandbox/bin:$PATH in your .bash_profile.
Unlike virtual-env, you never need to 'enable' or 'disable' a sandbox. You just cd into a directory, and it is automatically enabled.
The only real downside I have found to cabal sandboxes, is that you need to be in the root directory in order to act upon a sandbox. Meaning, if you are in a sub-directory, running cabal install some_package will not install it into the sandbox that is up a level, instead it will install it into either the global or user database, depending on how you have cabal configured.

A: cabal exec lets you execute a program in the context of a sandbox. It changes the path to include the bin folder of the sandbox. You can see it by executing cabal exec printenv inside the sandbox.
Also, the latest versions of cabal let you create sandboxes in folders without .cabal files. Once you run cabal sandbox init, you can just cabal install the dependencies you need.
So, to use different versions of yesod-bin, install them in different sandboxes, and then invoke cabal exec yesod-bin on each one.
(Extra tip: cabal exec gchi is a useful command that makes ghci aware of the contents of the sandbox.)


text:
Q: for which $\sigma$-algebra this set function is a measure? Lets say we have $X=\mathbb{R}$, and we have the following function
$$\mu(A)=\cases{0, \text{if  $A=\emptyset$}\\ 1, \text{if $A\neq \emptyset$}}$$
I am asked to say for which $\sigma$-algebra the latter is a measure.
First, it's easy to see that $\mu(\emptyset)=0$, and I know that the measure must satisfy $\sigma$-additivity. My guess goes as follows:
Suppose $A_1,A_2\in X$, $A_1, A_2 \neq \emptyset$ and $A_1, A_2$ are disjoint.
Let $A=A_1\bigcup A_2$, hence $A\neq \emptyset$ and hence $\mu(A)=1$.
But if we use the $\sigma$-additivity we have that
$$\mu(A_1\bigcup A_2)=1+1=2$$
So I suppose that the $\sigma$-algebra must be something like $\{X,\emptyset\}$
Is this correct? If this is not the right approach, how could I face this kind of problems?


text:
Q: How many selections will contain the element? Given a set of $n$-elements, how many subsets of $m$ size selected from this set will contain a certain element in the original set.
For example, how many subsets will contain the number $1$ when selecting $2$-elements from the following set:
$1,2,3,4$,
and then from the following set:
$1, 2, 1, 1, 4$.

A: The first case is quite simple.
You have the set $A = \{1, 2, 3, 4\}$ and the set $B = \{2, 3, 4\}$.
Now, every subset of size $m$ of $A$ which contains $1$ can be formed by joining a generic subset of $B$ of size $m-1$ with the set $\{1\}$.
In other word, let $n=4$ and $m=2$ (as you propose), then
$\frac{(n-1)!}{(m-1)!(n-1-m+1)!} = \frac{3!}{1!2!} = 3$ is the number of the subset of size $1$ of $B$ and then this is the number of subset of $A$ of size $2$ which contains $1$.
I guess the second case can be solved with similar arguments.
Just to give an idea...
Let $A$ be a set (without repeated elements). For example $A = \{1, 2, 4\}$.
Suppose that each element of $A$ has a multiplicity, say $\mu(x)$ where $x$ is an element of $A$ . In the example, $\mu(1) = 3$, $\mu(2) = \mu(4) = 1$.
Suppose also that you remove an element $x$ from the set $A$ and you obtain the set $B = A \setminus \{x\}$.
Let $n_A = \mu(x)$ and $n_B = \sum_{y \neq x} \mu(y)$.  Clearly $n_A+n_B= n$.
When you have to form a group of $m$ element extracted from $A$ (with repeated elements) then you can say that:

*

*I extract $m$ elements from collection $B$ (if $m \leq n_B$)

*I extract $m-1$ elements from collection $B$ and $1$ from collection $\{x\}$ (if $m-1 \leq n_B$ and $1 \leq n_A$)

*I extract $m-2$ elements from collection $B$ and $2$ from collection $\{x\}$ (if $m-2 \leq n_B$ and $2 \leq n_A$)

*and so on...

and so on
Each case can be easily computed using binomial coefficients so the solution is straight forward!
NOTE I use collection to distinguish from set. A set has unique elements, a collection can have repeated elements. In my answer I use a set or a collection depending from the context.
$A$ as set: $A = \{1, 2, 4\}$
$A$ as collection: $A = \{1, 2, 1, 1, 4\}$
$B$ as set: $B = \{2, 4\}$
$B$ as collection: $B = \{2, 4\}$
$\{x\}$ as set: $\{x\} = \{1\}$
$\{x\}$ as collection: $\{x\} = \{1, 1, 1\}$


text:
Q: "Knowledge of" vs. "knowledge on"
She tried to figure out how much knowledge my class had of the real Pocahontas.

Should I use of or on there?

A: It could also be that "knowledge of" goes with a person or shows one's familiarity with someone or something (cf. the verb kennen in German) and "knowledge on" or "knowledge about" (cf. the verb wissen in German) goes with a field of study or a broad subject where one's personal attachment to it is irrelevant.
It also seems that "knowledge about" could be used in either case; it's just a longer form that may not be desired if someone's trying to write poetic verse or a terse newspaper headline, for example.

A: I think the best way to look at this would be to consider what one is trying to convey.
This could also read "knowledge my class had concerning the real Pocahontas." The word concerning often takes the genitive case in Greek and Latin, which relates to the word of. However, the expression "on the real Pocahontas" would take the ablative case in Latin and would not coincide with concerning. Therefore, the sentence

She tried to figure out how much knowledge my class had of the
  real Pocahontas.

is more likely to be correct.

A: The preposition of is generally used with knowledge: "knowledge of (something)".

her considerable knowledge of antiques
he denied all knowledge of the incidents

However, it is important to note here that the question relates not to some personal acquaintance with Pocahontas ("knowledge of Pocahontas"), but an understanding of the concept ("knowledge on Pocahontas").
If the pupils have studied and understood the story, they would have such an understanding.

Without a credible data sharing mechanism, building strategic knowledge on climate change is virtually impossible.
General Knowledge on the Use of Medicines

We need to use the preposition on in the example sentence.

She tried to figure out how much knowledge my class had on the real Pocahontas.

A: Only knowledge of and about are listed in the Longman Dictionary of Contemporary English. Hence, I think they are better.

MEANINGS
1.the information, skills, and understanding that you have gained through learning or experience
  • He did not have much knowledge of American history.
[+ about]
  • the need to increase knowledge about birth control


text:
Q: swiper setWrapperTranslate can not work when moving I am use swiper to achieve pull up to load next page on mobile using html5,and my page have a refresh button,when clicked it,it should load fisrt page data and the page should Recovery my first enter the page.
Now,the problem is: when I push up and load next page, I clicked the refresh button and invoke setWrapperTranslate(0),but it doesn't work, how to change wrapper translate when the slides is moving?


text:
Q: In Rails website, Google translate works fine on Localhost but fails on index page on Digital Ocean VPS My site is deployed to digital ocean with Unicorn server combined with nginx reverse proxy. Google translate works fine on digital ocean but fails on 1 and 2 pages. Tried everything from last two days but found nothing.
Translate code

I am setting session variable to keep track of choose of language.
Thank you in advance!

A: Try including the google translate code in every page, you want the translation. And I guess your application is not a single page application. The plugin is meant for single page application.


text:
Q: Is there a theorem relating sequences to its series or vice versa? I only have these in mind
Theorem:
If a series $\sum_n a_n$ of real numbers converges then $\lim_\limits{n \to \infty} |a_n|=0$
Divergence test:
If $\lim_\limits{n \to \infty} a_n \neq 0$, then the series  $\sum_n a_n$ diverges.
are there stronger/other statements?

A: There is the "ratio test":  The series $\sum a_n$ converges if  the limit of $\frac{a_{n+1}}{a_n}$ is less than 1 and diverges if it is larger than 1.
Or the "root test": the series $\sum a_n$ converges if the limit of $\sqrt[n]{a_n}$ is less than 1.


text:
Q: Return xml data from action - CakePHP I am trying to return some data retrieved from an xml file and then return it to a view page.
The xml file will be updated during a certain action a user will start, and then i have a dialog box that pops up and displays the contents of the xml file.  The xml file will be updated during this action.
In my view I want to display the data returned from the php action that reads the xml file.
Here is my action to get the updated xml file. This will be called every second to update the view.
public function getUpdate()
    {
        $myFile = '/srv/www/xml-status/update_status.xml';
        $file = fopen($myFile, 'r');
        $data = file_get_contents($myFile);
        //debug($data);
        //print_r($data);

        //echo json_encode($data);
        //echo $data;
        return json_encode($data);
    }

The contents of the xml file are retrieved and stored into the $data variable, but I keep getting a 500 internal server error. I tried a bunch of different things, but I don't know how to return the data correctly.
Here is my view code to display the info.

<?php
if(false != $xml = simplexml_load_file($xmlFile))
{
    foreach ($xml->LogEvent->sequence as $temp)
    {
        echo 'Step: ', $temp['step'], ' ', 'Step Name: ', $temp['stepName'], ' ', 'd1: ', $temp['d1'], ' ',
        'd2: ', $temp['d2'], ' ', 'd3: ', $temp['d3'], ' ', 'Status: ', $temp['status'],'
';
    }
}
else
{
    echo '
Error: Update status can\'t be displayed
';
}
?>

I can't figure out what I am doing wrong.  If I can get the data variable to be returned to the get request I can then parse through and display the info, but I am having trouble getting the data from php to the javascript get request.
Any help would be great.
Thanks

A: I think your action would be like that :
public function getUpdate()
{
    $myFile = '/srv/www/xml-status/update_status.xml';
    $file = fopen($myFile, 'r');
    $data = file_get_contents($myFile);
    //debug($data);
    //print_r($data);

    echo json_encode($data);
    exit;
}

OR
 public function getUpdate()
{
    $this->autoRender = false;
    $myFile = '/srv/www/xml-status/update_status.xml';
    $file = fopen($myFile, 'r');
    $data = file_get_contents($myFile);
    //debug($data);
    //print_r($data);

    echo json_encode($data);

}


text:
Q: Symfony2 get logged in user I have custom user provider in my symfony2 application.I tried to get users with this
$this->get('security.context')->getToken()->getUser();

And then i get the following error:
FatalErrorException: Error: Call to a member function getUser() on a non-object

Does anyone know how can I get logged user if I'm using custom user provider?

A: There is a section in the cookbook about implementing a custom user provider.
It's typically well described what you have to do to get it working:
http://symfony.com/doc/current/cookbook/security/custom_provider.html


text:
Q: No merge tables in MariaDB - options for very large tables? I've been happily using MySQl for years, and have followed the MariahDB fork with interest.
The server for one of my projects is reaching end of life and needs to be rehosted - likely to CentOS 7, which includes MariahDB
One of my concerns is the lack of the merge table feature, which I use extensively.  We have a very large (at least by my standards) data set with on the order of 100M records/20 GB (with most data compressed) and growing.  I've split this into read only compressed myisam "archive" tables organized by data epoch, and a regular myisam table for current data and inserts.  I then span all of these with a merge table.
The software working against this database is then written such that it figures out which table to retrieve data from for the timespan in question, and if the timespan spans multiple tables, it queries the overlying merge table.
This does a few things for me:

*

*Queries are much faster against the smaller tables - unfortunately, the index needed for the most typical query, and preventing duplicate records is relatively complicated

*Frees the user from having to query multiple tables and assemble the results when a query spans multiple tables

*Allowing > 90% of the data to reside in the compressed tables saves alot of disk space

*I can back up the archive tables once - this saves tremendous time, bandwidth and storage on the nightly backups

An suggestions for how to handle this without merge tables?  Does any other table type offer the compressed, read-only option that myisam does?
I'm thinking we may have to go with separate tables, and live with the additional complication and changing all the code in the multiple projects which use this database.

A: MariaDB 10 introduced the CONNECT storage engine that does a lot of different things.  One of the table types it provides is TBL, which is basically an expansion of the MERGE table type.  The TBL CONNECT type is currently read only, but you should be able to just insert into the base tables as needed.  This is probably your best option but I'm not very familiar with the CONNECT engine in general and you will need to do a bit of experimentation to decide if it will work.


text:
Q: How to detect if a USB port is 3.0 or 2.0? I have a Toshiba Canvio 3.0 external HDD. It has USB 3.0. It flashes blue if you connect it to a USB 3.0 port. If it is a 2.0 port, the light becomes white.
Yesterday, I plugged it in and the light was blue. Now, I plugged it in the same port and the light is white.
Can I somehow detect if the USB port I just plugged in is 2.0 or 3.0? I want to know if there is a problem with the device or the USB port I'm using.
Edit: I'm using Windows 8.1

A: I understand that the USB standard indicates that the USB 3 port will have a blue color plastic tab inside the plugin.

A: To check whether the USB device itself is USB 2.0 or 3.0, use USB Device Tree Viewer (on a computer). Then disconnect all your USB devices on the computer, and reconnect the USB in question. You'll see it appear on the sidebar on the left. Click it. On the right, scroll down about 1/4 of the page. In the section 'Connection Information', look at the Device Bus speed. These are what you should be looking for:
USB 2: Device Bus Speed         : 0x02 (High-Speed)
USB 3: Device Bus Speed         : 0x03 (Super-Speed)
Another way:

*

*Open the Charms Bar by dragging the cursor to top right of the screen
or by pressing Win + C.
2. Select Settings and then Change PC settings.

*Select the Devices under PC settings application.

As mdpc said, the device you plug the USB device into should have different signs or colours to show if the actual ports are USB 2 or 3:
USB 2:

USB 3 (the sign on the left image says 'SS' and the usb sign. SS = SuperSpeed as said above):

There are many more methods.
Check Microsoft's website for info on the different signs you can see.

A: *

*Just look at ports and plugs and if they are blue then it is USB3.

*USB 3.0 plugs with 5 additional pins (9 in total) to get Super Speed.

A: I am not a fan of posting commercial crap, but I was looking for the fast and easy way out, and you are probably also :)
I found a tool called USBDeview which can be downloaded free and will give u extensive information on all your USB ports (including exact version). As far as I can see the version column shows the version of the port and not the attached device (I know for a fact I put in a USB 3.0 stick, and it is showing version 2, so it is my computers port, which is quite likely 2.0 ) :)
My virus scan did not report any probs, and it doesn't require any install, just a simple exe.
Here's a download link.
http://www.nirsoft.net/utils/usb_devices_view.html

A: Many computer manufacturers do not clearly mark USB port versions. Use the Device Manager to determine if your computer has USB 1.1, 2.0, or 3.0 ports:
Open the Device Manager.
In the "Device Manager" window, click the + (plus sign) next to Universal Serial Bus controllers. You will see a list of the USB ports installed on your computer.
    If your USB port name contains "Universal Host", your port is version 1.1.
    If the port name contains both "Universal Host" and "Enhanced Host", your port is version 2.0.
    If the port name contains "USB 3.0", your port is version 3.0.

This is document aout in the Knowledge Base.

A: Sometimes, if you plug the USB3.0 device too slowly, it is recognized as 2.0.
Why ? Because the 3.0 line of pins is in a second row so if the protocol handshake is finished before your device is fully plugged in, it will never get USB3.0 speed.
This is particulary annoying when using USB keys like the Extrem series from sandisk as the plug is on springs and is frequently diving too slowly into the port.
If you own this specific model, be carefull to not touch or press the retractor button while inserting it. If you touch it, the USB plug will be on springs. If you don't touch the button at all, the USB plug will insert correctly.


text:
Q: New Mapquest tile server URL I have created a map using classic MapQuest tiles. I have got tile server URL from here: https://leaflet-extras.github.io/leaflet-providers/preview/
I noticed that changes I have made in Open Street Map editor are not showing in classic MapQuest. So I think they don't update the old version of MapQuest anymore.
Maybe I can move my map on the new MapQuest tiles, but I can't find tile server URL. Is there any possibility to use new MapQuest tiles?

A: There is no direct access to tiles any more. There is a Leaflet plugin provided to display MapQuest tiles in a Leaflet map along with geocode, route, and traffic plugins too.


text:
Q: how to use ExecutorChannel in spring integration? Firstly thanks for attention
i defined ExecutorChannel and task executor in my spring integration project, for async processing on messages with spring batch, as bellow :
<bean id="ftpSessionFactory" class="org.springframework.integration.ftp.session.DefaultFtpSessionFactory">
              <property name="host" value="${ftp.server.ip}"/>
              <property name="port" value="${ftp.port}"/>
              <property name="username" value="${ftp.username}"/>
              <property name="password" value="${ftp.password}"/>
              <property name="clientMode" value="2"/>
              <property name="fileType" value="2"/>
       </bean>
   <int-ftp:outbound-gateway id="gatewayGET"
                              local-directory-expression="'./backup/' +#remoteDirectory"
                              session-factory="ftpSessionFactory"
                              request-channel="toGetFilesChannel"
                              reply-channel="toRemoveChannel"
                              command="get"
                              command-options="-P"
                              expression="payload.remoteDirectory + '/' + payload.filename"/>
    <int:channel id="toRemoveChannel">
        <int:interceptors>
            <int:wire-tap channel="logger2"/>
        </int:interceptors>
    </int:channel>
 <int:transformer input-channel="toRemoveChannel" output-channel="outboundJobRequestChannel">
        <bean class="ir.ali.configuration.FileMessageToJobRequest">
            <property name="fileParameterName" value="fileName"/>
        </bean>
    </int:transformer>
 <int:channel id="outboundJobRequestChannel">
        <int:dispatcher task-executor="simpleExecutor"/>
</int:channel>
<task:executor id="simpleExecutor" pool-size="10-1000"
                   queue-capacity="5000"/>

it's work correctly , but thrown bellow exception:
org.springframework.messaging.MessagingException: ; nested exception is org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is java.net.SocketException: Connection reset
    at org.springframework.integration.dispatcher.AbstractDispatcher.wrapExceptionIfNecessary(AbstractDispatcher.java:133)
    at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:120)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:101)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:97)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:286)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:245)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
    at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:95)
    at org.springframework.integration.endpoint.SourcePollingChannelAdapter.handleMessage(SourcePollingChannelAdapter.java:130)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:219)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:55)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:149)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:146)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:298)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:52)
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:49)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:292)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is java.net.SocketException: Connection reset
    at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:343)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.doLs(AbstractRemoteFileOutboundGateway.java:416)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.handleRequestMessage(AbstractRemoteFileOutboundGateway.java:392)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:99)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
    at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
    ... 27 more
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:189)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at org.apache.commons.net.ftp.FTPFileEntryParserImpl.readNextEntry(FTPFileEntryParserImpl.java:53)
    at org.apache.commons.net.ftp.FTPListParseEngine.readStream(FTPListParseEngine.java:133)
    at org.apache.commons.net.ftp.FTPListParseEngine.readServerList(FTPListParseEngine.java:104)
    at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3302)
    at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3271)
    at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2930)
    at org.springframework.integration.ftp.session.FtpSession.list(FtpSession.java:68)
    at org.springframework.integration.ftp.session.FtpSession.list(FtpSession.java:41)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.listFilesInRemoteDir(AbstractRemoteFileOutboundGateway.java:582)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.listFilesInRemoteDir(AbstractRemoteFileOutboundGateway.java:598)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.listFilesInRemoteDir(AbstractRemoteFileOutboundGateway.java:598)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway.ls(AbstractRemoteFileOutboundGateway.java:551)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway$1.doInSession(AbstractRemoteFileOutboundGateway.java:420)
    at org.springframework.integration.file.remote.gateway.AbstractRemoteFileOutboundGateway$1.doInSession(AbstractRemoteFileOutboundGateway.java:416)
    at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:334)
    ... 32 more

A: That exception is unrelated to the channel type.

Caused by: java.net.SocketException: Connection reset

It just means your ftp server closed the connection while listing the files.


text:
Q: How to obtain the current url
Possible Duplicate:
How to get the URL of the current page in C#

If I am in a page say http://myweb/folder/obtain.aspx?thevalue=3 , how can i determine if the url contains obtain.aspx?thevalue in c#?. I just need to check whether the user landed on this particular page.
PS: I guess I dont really need to check for the ?thevalue but just the obtain.aspx

A: This will give you the exact file name ( obtain.aspx )
Request.Url.Segments[1]

A: Try this:
//gets the current url
string currentUrl = Request.Url.AbsoluteUri;

//check the url to see if it contains your value
if (currentUrl.ToLower().Contains("obtain.aspx?thevalue"))
    //do something

A: Request.Url should contain everything you need. In your case, you could use something like
if( Request.Url.PathAndQuery.IndexOf("obtain.aspx") >= 0 )...

A: I recommend using Request.Url. To get the exact file name, you may try also using System.IO.Path
var aspxFile = System.IO.Path.GetFileName(Request.Url.LocalPath);
var landed = aspxFile.Equals("obtain.aspx", StringComparison.InvariantCultureIgnoreCase);
if(landed) { // your code }

A: Request.Url will return the exact Uri being requested by the user.
If you want to check specifically for thevalue, you're probably better off looking for that in Request.QueryString

A: it's ugly but you cand try
if (HttpContext.Current.HttpRequest.Url.AbsolutePath.Contains("/obtain.aspx"))
 // then do something


text:
Q: How to install Pillow on Windows using pip? I'm trying to install Pillow 3.1 on Windows. Per the instructions, I should be able to just type in:
pip install Pillow
But I get: ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting
Because now (starting with versions after 3.0 I think?) libjpeg is required for pillow to be installed. I don't know how to do that magic on Windows. Maybe install Ming or something. But I was really hoping for a simple pip install.
I can disable these options through the intuitive command: pip install --upgrade pillow --global-option="build_ext" --global-option="--disable-jpeg" --global-option="--disable-zlib"
But then the build fails because I don't have Visual C++ installed.
Yes, I can install Pillow by downloading it from the unofficial repository list. But is there a way to do it with pip on Windows without a lot of extra installs?

A: By far the easiest thing to do on Windows is install Pillow using pre-built binaries rather than trying to build it yourself.
When there's a new Pillow release, it usually takes a day or so for the Windows binaries to be built and uploaded.
You ran into this problem during this window. The Windows binaries are now up so you can install with pip install pillow (or pip install -U pillow).
If you need Pillow during this window, you can install a given previous version with binaries like pip install pillow==3.0.0.

A: I install it By running command prompt as administrator
pip install Pillow  also we can mention specific version like pip install Pillow==2.6.1

A: I spent almost a day figuring out what is wrong with pillow installation. It was working fine till yesterday and suddenly stopped working from today. Finally got it figured out, Few of my team mates upgraded python to 3.6 version which is now available for download. Since Pillow is not yet made compatible with 3.6 and is supporting only till 3.5.2 this error popped up.

Resolution is to check if Pillow supports your version of python. Once
  I reverted python back to 3.5.2 the installation worked like a charm
  and no errors encountered.

Hope this help resolve your issue.

A: In django models, you can try:
python -m pip install Pillow


text:
Q: How to get activity log of release manager in Play Console? I have an issue with activity log on play console. Our company previous release manger log is showing on activity log but other release manger log not showing.
In item column show "Device catalog Terms of Service accepted".
In Changes column show "Accept".


text:
Q: Headless Chrome (Puppeteer) different behaviour running in local docker and remote docker (AWS EC2) I am trying to debug an issue which causes headless Chrome using Puppeteer to behave differently on my local environment and on a remote environment such as AWS or Heroku.
The application tries to search public available jobs on LinkedIn without authentication (no need to look at profiles), the url format is something like this: https://www.linkedin.com/jobs/search?keywords=Engineer&location=New+York&redirect=false&position=1&pageNum=0
When I open this url in my local environment I have no problems, but when I try to do the same thing on a remote machine such as AWS EC2 or Heroku Dyno I am redirected to a login form by LinkedIn. To debug this difference I've built a Docker image (based on this image) to have isolation from my local Chrome/profile:
Dockerfile
FROM buildkite/puppeteer

WORKDIR /app

COPY . .

RUN npm install

CMD node index.js

EXPOSE 9222

index.js
const puppeteer = require("puppeteer-extra");
puppeteer.use(require("puppeteer-extra-plugin-stealth")());

const testPuppeteer = async () => {
    console.log('Opening browser');
    const browser = await puppeteer.launch({
        headless: true,
        slowMo: 20,
        args: [
            '--remote-debugging-address=0.0.0.0',
            '--remote-debugging-port=9222',
            '--single-process',
            '--lang=en-GB',
            '--disable-dev-shm-usage',
            '--no-sandbox',
            '--disable-setuid-sandbox',
            "--proxy-server='direct://",
            '--proxy-bypass-list=*',
            '--disable-gpu',
            '--allow-running-insecure-content',
            '--enable-automation',
        ],
    });

    console.log('Opening page...');
    const page = await browser.newPage();
    console.log('Page open');

    const url = "https://www.linkedin.com/jobs/search?keywords=Engineer&location=New+York&redirect=false&position=1&pageNum=0";
    console.log('Opening url', url);
    await page.goto(url, {
        waitUntil: 'networkidle0',
    });
    console.log('Url open');

    // page && await page.close();
    // browser && await browser.close();

    console.log("Done! Leaving page open for remote inspection...");
};

(async () => {
    await testPuppeteer();
})();

The docker image used for this test can be found here.
I've run the image on my local environment with the following command:
docker run -p 9222:9222 spinlud/puppeteer-linkedin-test

Then from the local Chrome browser chrome://inspect it should be possible to inspect the GUI of the application (I have deliberately left open the page in headless browser):

As you can see even in local docker the page opens without authentication.
I've done the same test on an AWS EC2 (Amazon Linux 2) with Docker installed. It needs to be a public instance with SSH access and an inbound rule to allow traffic through port 9222 (for remote Chrome debugging).
I've run the same command:
docker run -p 9222:9222 spinlud/puppeteer-linkedin-test

Then again from local Chrome browser chrome://inspect, once added the remote public IP of the EC2, I was able to inspect the GUI of the remote headless Chrome as well:

As you can see this time LinkedIn requires authentication. We can see also a difference in the cookies:

I can't understand the reasons behind this different behaviour between my local and remote environment. In theory Docker should provide isolation and in both environment the headless browser should start with no cookies and a fresh (empty session). Still there is difference and I can't figure out why.
Does anyone have any clue?


text:
Q: Why can't I get past the Daytower after clearing all corrupted zones in the valley? As soon as I was able to leave the Sacred Grounds, I stopped doing the main quest and began exploring.
When I attempted to go to the second Tallneck, however, I ran into the Daytower and I was told that the gates would remain sealed until all corrupted zones in the valley had been cleared. After that, I went and cleared every corrupted zone I could find and explored every part of the map that I could, until there didn't seem to be any more corrupted zones.
However, the Carja guards still refuse to let me pass, despite having cleared all corrupted zones on the accessible area of the map. How do I get through the gates?

A: You actually aren't able to pass through this gate until you've completed the Main Quest "A Seeker At The Gates". Despite telling you that you need to clear all corrupted zones in the valley, you only actually need to clear two of them in order to progress the quest. After this, you'll have to

 defend the Daytower from more corrupted Machines.

After which point, you'll be allowed to pass through the gates into Carja.


text:
Q: Batoo JPA, Spring and JodaTime I've been checking out batoo JPA lately. I've managed to use it with Spring and it seems to work good with the standard JPA interface. Now I'm looking how to get JodaTime to get persisted transparently.
I know that I can write a converter but I was wondering if maybe guys from the batoo team done some work on this. I've cloned the source and grep-ed it through but with no luck.

A: Thank you for pointing out the issue.
As stated in the issue manager a snapshot has been released that should fix the issue.


text:
Q: How to run multiple commands using terraform local-exec I am trying to run a few az cli commands using terraform using local-exec provisioner but I keep running into an error that says:
Error: Invalid expression

On modules/eventgrid/main.tf line 68: Expected the start of an expression, but
found an invalid expression token.

Here's my code:
resource "null_resource" "eg-role-assignment" {
  provisioner "local-exec" {

    interpreter = ["/bin/bash", "-c"]
    command = <<EOT
              "az account set --subscription foo"
              "az eventgrid topic update --resource-group $RESOURCE_GROUP --name $EVENTGRID_NAME --identity systemassigned"
    EOT

    environment = {
      RESOURCE_GROUP = "RG_${var.platform_tag}_${var.product_code}_PUBLISH_${var.environment}_${var.location_code_primary}"
      EVENTGRID_NAME = "EG-${var.platform_tag}-${var.product_code}-${var.environment}-${var.location_code_primary}-domain"

    }

  }
}

Can anybody please guide me as to what's wrong ?

A: With your <<EOT statement, you're inside a string literal already, so you don't need the quotes. Also, <<-EOT (with a dash) is indentation aware, while <<EOT is not.
Finally, as the cause of the issue, you have a space after EOT.
command = <<-EOT
          az account set --subscription foo
          az eventgrid topic update --resource-group $RESOURCE_GROUP --name $EVENTGRID_NAME --identity systemassigned
EOT


text:
Q: How to create Observable from callbacks called in own threads I try to create rx-java wrapper for nu-process (non blocking process execution). And try create Observable for std out:
static Observable<byte[]> process(List<String> cmd) {
    return Observable.create(emitter -> {

        NuProcessBuilder b = new NuProcessBuilder(cmd);
        b.setProcessListener(new NuAbstractProcessHandler() {
            @Override
            public void onStdout(ByteBuffer buffer, boolean closed) {
                //calls on NuProcess thread
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                emitter.onNext(bytes);
            }

            @Override
            public void onExit(int statusCode) {
                //calls on NuProcess thread
                emitter.onComplete();
            }
        });
        //start asyncronous
        NuProcess p = b.start();
        System.out.println("Process started");
        emitter.setCancellable(() -> p.destroy(true));
    });
}

As you can see all nu-process events calls asyncronous in it's own thread. Basically it's worked. But what if I want run multiple processes serial?
In that case my implementation broken, because emission happens on other thread.
In code bellow all processes started same time:
public static void main(String[] args) throws InterruptedException {

    List<String> cmd = List.of("bash", "-c", "printf hello && sleep 1 && printf world");
    process(cmd).subscribeOn(Schedulers.single()).subscribe();
    process(cmd).subscribeOn(Schedulers.single()).subscribe();
    process(cmd).subscribeOn(Schedulers.single()).subscribe();
    process(cmd).subscribeOn(Schedulers.single()).subscribe();
    process(cmd).subscribeOn(Schedulers.single()).subscribe();
    process(cmd).subscribeOn(Schedulers.single()).subscribe();

    Thread.sleep(1000);
}

How to implement Observable with "right" threading?

A: You can do it with concatMap:
Observable.range(1, 10).concatMap(integer -> process(cmd)).subscribe();


text:
Q: Is there a way to listen to signals on Windows I'm writing a small shell for Windows in Rust, and want to kill the Command I spawned and prevent my shell from quitting.
Is there a way of capturing the Windows SIGINT equivalent in Rust?

A: There is a crate, chan-signal, that aims to help in handling this, by spawning a thread and having it wait for signals.
EDIT: It doesn't currently support windows.
There is an RFC asking for this functionality to be integrated into the language's standard library, but it is very young.
It seems your option is to go with FFI.


text:
Q: rails call action on collection_select change basically I want to immediately go to an action/path (new_budget_path) after selecting an option from a dropdown menu. I cant figure how solve it and how to order the statements.
= collection_select(:budget, :id, Member.list_available_budgets,:title, :title,
options= {prompt: t('view.member.select_budget_box')},
html_options= {onchange: remote_function(url: new_budget_path)})

I'm getting the following error message:
undefined method `remote_function' for #<#<Class:0x007ff5fc6fa0c8>:0x007ff602bba698>

Can anyone help?


text:
Q: Key Stroke logging: Records both pressed and released Here Is the keylogger Code:
''' from pynput.keyboard import Key, Listener
import logging

log_dir = r"/Users/user/Desktop/submit/Keylogger.txt "
logging.basicConfig(filename=(log_dir + "keyLog.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')

def on_press(key):
    logging.info(str(key))

def on_release(key):
    print('{}'.format(key))
    if str(key) == 'Key.esc':
        print('Exiting...')
        return False

with Listener(on_press=on_press) as listener:
    listener.join() '''

When ever I run it, it works fine but for one thing: It records in double, so ill see A A and B B for one word. How can I fix this? (python3, MacOS)


text:
Q: Can't compile after upgrade: Failed to find integrator bundle for class NSTextFinder I just upgraded to Lion and the latest build of monotouch and now I received the following when trying to build any project - even just an empty project from the templates.
Has anyone ever seen this before?
It doesn't look like I need to do anything different after upgrading to lion, at least not from the documentation. Am I missing something?
Any help or thoughts would be greatly appreciated.
Building: DUmmyTest1 (Debug|iPhoneSimulator)

Performing main compilation...
/Developer/MonoTouch/usr/bin/smcs /noconfig "/out:/DevTests/DUmmyTest1/DUmmyTest1/bin/iPhoneSimulator/Debug/DUmmyTest1.exe" "/r:/Developer/MonoTouch/usr/lib/mono/2.1/System.dll" "/r:/Developer/MonoTouch/usr/lib/mono/2.1/System.Xml.dll" "/r:/Developer/MonoTouch/usr/lib/mono/2.1/System.Core.dll" "/r:/Developer/MonoTouch/usr/lib/mono/2.1/monotouch.dll" /nologo /warn:4 /debug:+ /debug:full /optimize- /codepage:utf8 "/define:DEBUG"  /t:exe "/DevTests/DUmmyTest1/DUmmyTest1/Main.cs" "/DevTests/DUmmyTest1/DUmmyTest1/AppDelegate.cs" "/DevTests/DUmmyTest1/DUmmyTest1/RootViewController.cs" "/DevTests/DUmmyTest1/DUmmyTest1/RootViewController.designer.cs" "/DevTests/DUmmyTest1/DUmmyTest1/DetailViewController.cs" "/DevTests/DUmmyTest1/DUmmyTest1/DetailViewController.designer.cs"
Compilation succeeded - 1 warning(s)

/DevTests/DUmmyTest1/DUmmyTest1/RootViewController.cs(53,44): warning CS0414: The private field `DUmmyTest1.RootViewController.DataSource.controller' is assigned but its value is never used

Compiling interface definitions
/Developer/usr/bin/ibtool --errors --warnings --notices --output-format human-readable-text "/DevTests/DUmmyTest1/DUmmyTest1/RootViewController.xib" --compile "/DevTests/DUmmyTest1/DUmmyTest1/bin/iPhoneSimulator/Debug/DUmmyTest1.app/RootViewController.nib" --sdk "/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk"
2011-11-01 16:13:29.616 ibtoold[618:e07] [MT] DVTAssertions: ASSERTION FAILURE in /SourceCache/IDEInterfaceBuilder/IDEInterfaceBuilder-1938/Framework/WidgetIntegration/IBIntegratorManager.m:278
Details:  Failed to find integrator bundle for class NSTextFinder
Object:   <IBIntegratorManager: 0x400b778e0>
Method:   -registerIntegrator:remainingIntegratorsBySuperclass:
Thread:   <NSThread: 0x40010a1a0>{name = (null), num = 1}
Hints: None
Backtrace:
  0  0x000000010085ebd4 -[DVTAssertionHandler handleFailureInMethod:object:fileName:lineNumber:messageFormat:arguments:] (in DVTFoundation)
  1  0x000000010085eaa4 _DVTAssertionFailureHandler (in DVTFoundation)
  2  0x0000000100021b42 -[IBIntegratorManager registerIntegrator:remainingIntegratorsBySuperclass:] (in IDEInterfaceBuilderKit)
  3  0x0000000100021c69 -[IBIntegratorManager registerIntegrator:remainingIntegratorsBySuperclass:] (in IDEInterfaceBuilderKit)
  4  0x0000000100021804 -[IBIntegratorManager registerIntegrators:] (in IDEInterfaceBuilderKit)
  5  0x00000001000213b4 -[IBIntegratorManager loadAllIntegrators] (in IDEInterfaceBuilderKit)
  6  0x00000001000210cc -[IBInterfaceBuilderPlugin init] (in IDEInterfaceBuilderKit)
  7  0x0000000100020f91 +[IBInterfaceBuilderPlugin ide_initializeWithOptions:error:] (in IDEInterfaceBuilderKit)
  8  0x000000010047eb7c _IDEInitializeOnePlugInAndPrerequisites (in IDEFoundation)
  9  0x000000010047e38c IDEInitialize (in IDEFoundation)
 10  0x0000000100003e58 (in ibtoold)
 11  0x0000000100001a94 (in ibtoold)
ibtool exited with code 134
Build complete -- 1 error, 1 warning

---------------------- Done ----------------------

Build: 1 error, 1 warning

A: I think that you need to install the version of XCode built for Lion after you upgrade (hopefully you haven't done this already).


text:
Q: Progress update in Parallel.For() loops As you can guess the index of the Parallel.For() loop jumps from one value to the other. How can I estimate the amount of the work done?
Thanks.

A: By keeping a counter rather than looking at the index? For example:
int counter  = 0;
Parallel.For(4, 500, i => {
    // TODO: something useful...
    int progress = Interlocked.Increment(ref counter);
    Console.WriteLine("{0}: {1}", progress, i);
});

(the Interlocked usage is essential to avoid getting race-conditions on accessing counter)

A: int progress = 0;
Parallel.For( from, to, i => {
// do the job
Interlocked.Increment(ref progress);
});

now actual progress is (float)(to - from) / progress


text:
Q: Replicating @ElementCollection behavior Is there anyway I can have the effect of @ElementCollection without actually having this annotation? I am using Hibernate 3.3, while @ElementCollection and @CollectionTable is only supported for Hibernate 3.5 and beyond. But I really need to use these annotations, for a case like this:
http://www.concretepage.com/hibernate/elementcollection_hibernate_annotation
(Where we get the List of Strings rather than List of the full entity)

A: You can use the <element> tag to do the same operation, refer to this link from hibernate documentation:
7.2.3. Collections of basic types and embeddable objects
The example given in the link is :
<element
        column="column_name"                               (1)
        formula="any SQL expression"                       (2)
        type="typename"                                    (3)
        length="L"
        precision="P"
        scale="S"
        not-null="true|false"
        unique="true|false"
        node="element-name"
/>

1   column (optional): the name of the column holding the collection element values.
2   formula (optional): an SQL formula used to evaluate the element.
3   type (required): the type of the collection element.

Refer to this link for an example:
Collection Mapping
Star.java
private Set<String> planets = new HashSet<String>();

Star.hbm.xml
<set name="planets" table="star_planet">
    <key column="star_id" />
    <element type="text"/>
</set>

Update:
You have to use either xml mapping or annotations for a given entity class but not both at a time.
If you want to see examples only using annotations then there are so many available if you search in Google, please check and let me know if you have issues in implementing them.
Finally, yes it works with Set of Strings, integers or Long etc.
Update:
Here is a simple example that shows how to use element collections:
User.java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;

@Entity
@Table(name = "TB_User")
public class User {
    @Id
    @GeneratedValue
    private int id;
    private String name;

    @ElementCollection
    @CollectionTable(name = "Addresses", joinColumns = @JoinColumn(name = "user_id"))
    @AttributeOverrides({ @AttributeOverride(name = "street1", column = @Column(name = "fld_street")) })
    public Set<Address> addresses = new HashSet<Address>();

    public User() {
    }

    public User(String name, Address... addresses){
        this.name = name;
        this.addresses.addAll(Arrays.asList(addresses));
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(Set<Address> addresses) {
        this.addresses = addresses;
    }
}

Address.java
import javax.persistence.Embeddable;

@Embeddable
public class Address {
    private String street1;

    public Address() {
    }

    public Address(String street1) {
        this.street1 = street1;
    }

    public String getStreet1() {
        return street1;
    }

    public void setStreet1(String street1) {
        this.street1 = street1;
    }

    @Override
    public String toString() {
        return street1;
    }
}

Simple logic to test this:
private static void showUsers() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.getTransaction().begin();
    List<User> users = session.createQuery("from User").list();

    for (User user : users) {
        System.out.println(user.getName() + " -- > " + user.getAddresses());
    }

    session.getTransaction().commit();
}

private static void saveUsers() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.getTransaction().begin();
    User user1 = new User("U1", new Address("A1"), new Address("A11"));
    User user2 = new User("U2", new Address("A2"));
    session.save(user1);
    session.save(user2);
    session.getTransaction().commit();
}


text:
Q: Sorting a vector of strings by the first letter in non-ascii order in C++ I have a text file with a list of words.
I used ifstream to read these words into a vector and now I am trying to sort them in an order similar to:
A a B b C c [...]

I tried to implement this using a third for loop inside of a bubble search algorithm to look at the first character of each word (I know this is far from the most efficient way especially if I was using a large data set)
And then check whether the letter and the next letter were uppercase or lowercase and switching if the uppercase letter was the same letter as the current letter, but this didn't seem to work.
void bubble_Sort (vector <string> & words)
{
  for (unsigned i = words.size(); i >= 2; --i)
  {
    for (unsigned k = 0; k + 1 < i; k++)
    {
      int hi = k+1;
      string temp1 = words[hi];
      string temp2 = words[k];
      int smallsize = words[hi].size();
      int smallprecedence = 0;

      if (words[k].size() < words[hi].size())
        smallsize = words[k].size();

      for (unsigned j = 0; j < smallsize; j++)
      {
        if (temp1[j] >= 'A' && temp1[j] <= 'Z')
        {
          if (temp2[j] >='a' && temp2[j] <= 'z')
          {
            char lowercase1 = temp1[j] + 32;
            if (lowercase1 == temp2[j])
            {
              string temp = words[k];
              words[k] = words[hi];
              words[hi] = temp;
              break;
            }
          }

          else if (temp2[j] >= 'A' && temp2[j] <= 'Z')
          {
            if (temp1[j] < temp2[j])
            {
              string temp = words[k];
              words[k] = words[hi];
              words[hi] = temp;
              break;
            }
          }
        }

        if (temp1[j] >= 'a' && temp1[j] <= 'z')
        {
          if (temp2[j] >= 'A' && temp2[j] <= 'Z')
          {
            char uppercase1 = temp1[j] - 32;
            if (uppercase1 < temp2[j])
            {
              string temp = words[k];
              words[k] = words[hi];
              words[hi] = temp;
              break;
            }
          }

          else if (temp2[j] >= 'a' && temp2[j] <= 'z')
          {
            if (temp1[j] < temp2[j])
            {
              string temp = words[k];
              words[k] = words[hi];
              words[hi] = temp;
              break;
            }
          }
        }

        else if (temp1[j] == temp2[j] && temp1.size() < temp2.size())
          ++smallprecedence;
      }

      if (smallprecedence == smallsize)
      {
        string temporary = words[k];
        words[k] = words[hi];
        words[hi] = temporary;
      }
    }
  }
}

A: Don't reinvent the wheel. Just modify the default comparison function so aA < bB (regardless of case) and A < a.
EDIT I used the wrong comparison function. It should return true for <, and false for >=. This has been fixed
std::vector<std::string> vec;
//
std::sort(vec.begin(), vec.end(), [](const std::string& lhs, const std::string& rhs)
{
   const char* s1=lhs.c_str();
   const char* s2=rhs.c_str();
   while(true) {
     // first ignore case
     if ( std::toupper(*s1) < std::toupper(*s2) ) return true;
     if ( std::toupper(*s1) > std::toupper(*s2) ) return false;
     // end of both strings, exact match
     if ( *s1 == 0 && *s2 == 0 ) return false;
     // compare upper case vs lower case ('A' vs 'a')
     if ( *s1 > *s2) return false;
     if ( *s1 < *s2) return true;
     ++s1; ++s2;
  }
});

A: First, get rid of the hard-coded ASCII-isms. C and C++ have long had functions for determining whether a character is a letter, a digit, uppercase, lowercase, etc. Look them up.
Second, describe clearly what goes into determining the order that you want the result to be in.
Third, from that description, write a function that takes two strings, and tells you whether the first string should come before the second. Use that function in the sort.

A: You can sort a vector using std::sort and get a reference to the first character in a std::string using std::string::at() :
std::vector<std::string> vec;
//
std::sort(vec.begin(), vec.end(), [](const std::string& lhs, const std::string& rhs)
{
    char l_ch, r_ch;
    l_ch = lhs.at(0);
    r_ch = rhs.at(0);
    return l_ch < r_ch;
});

A: I think it's really enough to skip exactly equal prefixes and then compare once with uppercasing:
std::vector<std::string> vec;
//
std::sort(vec.begin(), vec.end(), [](const std::string& lhs, const std::string& rhs)
{
  const char* s1=lhs.c_str();
  const char* s2=rhs.c_str();
  while(*s1 && *s1 == *s2) {++s1; ++s2;}
  int rc = toupper(*s1) - toupper(*s2);
  if (rc) return rc;
  return *s1 - *s2;
});

If you need to compare by first letter only, simply remove while(*s1 && *s1 == *s2) {++s1; ++s2;}


text:
Q: I'm using Ajax, but the page is still refreshing when I click on submit button I am trying to use this code. But Ajax doesn't work and the page is refreshing when I press the submit button. I don't know where is my mistake.
I'm using json because I need to print multiple answers. For instance, I need to show if each answer is correct.
I'm loading jQuery in the header, that is OK.

Übung: Finde das Gegenteil:

        a) schön
        1 alt

        b) groß
        2 klein

        c) neu
        3 langweilig

        d) laut
        4 leise

        e) interessant
        5 hässlich

  <form action="" method="post">

        a)

          <select name="a">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>

        b)

          <select name="b">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>

        c)

          <select name="c">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>

        d)

          <select name="d">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>

        e)

          <select name="e">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
          </select>

        <input type="submit" value="Go" class="submit">

  </form>

And this is the php file:-
<?php
$a = $_POST["a"];
$b = $_POST["b"];
$c = $_POST["c"];
$d = $_POST["d"];
$e = $_POST["e"];
if ($a == '2') {
    $answer1 = "correct answer";
    echo $answer1;
} else {
    $answer1 = "wrong answer";
    echo $answer1;
}
if ($b == '4') {
    $answer2 = "correct answer";
} else {
    $answer2 = "wrong answer";
}
if ($c == '1') {
    $answer3 = "correct answer";
} else {
    $answer3 = "wrong answer";
}
if ($b == '5') {
    $answer4 = "correct answer";
} else {
    $answer4 = "wrong answer";
}
if ($b == '3') {
    $answer5 = "correct answer";
} else {
    $answer5 = "wrong answer";
}
echo json_encode(
  array(
    "message1" => "$answer1",
    "message2" => "$answer2",
    "message3" => "$answer3",
    "message4" => "$answer4",
    "message5" => "$answer5",
  )
)
?>

A: Use event.preventDefault() like below:-
$('form').submit(function(event) {
  event.preventDefault();

  //rest of the code

});

Reference:- https://api.jquery.com/event.preventdefault/

A: You need to have the following piece of JavaScript to prevent the form from submitting.
$( 'form' ).on({
    submit: function() {
         return false;
    }
});


text:
Q: Uitableview cell text got hidden on edit Button When i try to delete any row - while clicking the edit button - the delete button appears and the text on right side truncated from the end.
I want to compress it automatically while delete button appears.

A: You can try setting the textLabel property attributes to automatically truncate the middle of the string or set a smaller (minimum) font.
[[theCell textLabel] setMinimumFontSize:theSizeYouWant];

or
[[theCell textLabel] setLineBreakMode:UILineBreakModeMiddleTruncation];


text:
Q: Tensorflow 2.0 `tf.multiply` method gives unexpected results I am bit confused about output shape of this operation
>>> eps = tf.random.uniform((3))
>>> images = tf.random.normal((3, 28, 28, 1))
>>> output = eps * images
>>> output.get_shape()
(3, 28, 28, 3)

I want this to multiply every single scalar in eps with each image of shape (28, 28, 1)  in  images to get the output shape  (3, 28, 28, 1)
Something like this
>>> output = []
>>> output.append(eps[0] * images[0])
>>> output.append(eps[1] * images[1])
>>> output.append(eps[2] * images[2])
>>> output = tf.convert_to_tensor(output)
>>> output.get_shape()
(3, 28, 28, 1)

Please help.

A: That is due to broadcasting (the link is from NumPy documentation, but it works the same way in TensorFlow). If you want to "match" the single dimension of eps to the first dimension of images, you need to add extra singleton dimensions to eps so the broadcasting works as you expect:
eps = tf.random.uniform((3))
# Add dimensions for broadcasting
eps = tf.reshape(eps, [-1, 1, 1, 1])
output = eps * images
print(output.get_shape())
# (3, 28, 28, 1)

Alternatively, you can directly create eps with that shape:
eps = tf.random.uniform((3, 1, 1, 1))


text:
Q: java.lang.String cannot be cast to model.AtvLanguage I'm using the library Hawk to persist data. I'm facing a problem with the data retrieved.
When I do the next code to check the value of an object stored, but sais it can't cast the value.
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.test.app.model.AtvLanguage

The code:
 if(Hawk.contains("ATV_LANGUAGE")){
            atvLanguage = (AtvLanguage)Hawk.get("ATV_LANGUAGE");  // Fail point
        }else{
            atvLanguage.setLanguageCodes("", getString(R.string.str_en));
        }

The put method:
public void updateSelectedLanguage(String iso6391, String iso6392){

        AtvLanguage atvLanguageTmp = new AtvLanguage(iso6391, iso6392);
        Hawk.put("ATV_LANGUAGE", atvLanguageTmp);

    }

AtvLanguage pojo:
public class AtvLanguage implements Serializable {

    @SerializedName("iso6391")
    @Expose
    private String iso6391;

    @SerializedName("iso6392")
    @Expose
    private String iso6392;

    public AtvLanguage() {
    }

    public AtvLanguage(String iso6391, String iso6392) {
        setLanguageCodes(iso6391, iso6392);
    }

    public String getIso6391() {
        return iso6391;
    }

    public void setIso6391(String iso6391) {
        this.iso6391 = iso6391;
    }

    public String getIso6392() {
        return iso6392;
    }

    public void setIso6392(String iso6392) {
        this.iso6392 = iso6392;
    }

    // ISO 639-2 is the language code with 3 chars, like ENG or SPA.
    public void setLanguageCodes(String iso6391, String iso6392){

        if(iso6391.isEmpty() && !iso6392.isEmpty()){

            if(iso6392.equalsIgnoreCase("ENG"))
                setIso6391("en");
            else if(iso6392.equalsIgnoreCase("ESP"))
                setIso6391("es");

            setIso6392(iso6392);

        }else if(!iso6391.isEmpty() && iso6392.isEmpty()){

            if(iso6391.equalsIgnoreCase("en"))
                setIso6392("ENG");
            else if(iso6391.equalsIgnoreCase("es"))
                setIso6392("ESP");

            setIso6391(iso6391);

        }

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        AtvLanguage that = (AtvLanguage) o;

        return new EqualsBuilder()
                .append(getIso6391(), that.getIso6391())
                .append(getIso6392(), that.getIso6392())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(getIso6391())
                .append(getIso6392())
                .toHashCode();
    }

    @Override
    public String toString() {
        return "AtvLanguage{" +
                "iso6391='" + iso6391 + '\'' +
                ", iso6392='" + iso6392 + '\'' +
                '}';
    }
}


text:
Q: can one instance of google clouds compute engine have multiple external ip addresses I am using google cloud compute engin for running a small web server as well as some other servers I currently am using the free trial I will be upgrading to a paid account when that expires but I would like to have another server on a different wan IP address I know I can use a different port and do forwarding/redirects but my question is can one instance ger multiple external IPs or would I need to create/pay for another instance to get a 2nd external IP address?

A: Yes, you can create VM instance with multiple external IPs.
Have a look at the documentation Creating instances with multiple network interfaces:

By default, every instance in a VPC network has a single default
  network interface. Use these instructions to create additional network
  interfaces. Each interface is attached to a different VPC network,
  giving that instance access to different VPC networks in Google Cloud
  Platform (GCP). You cannot attach multiple network interfaces to the
  same VPC network.

and at the section Requirements:

*

*You can only configure a network interface when you create an instance.

*Each network interface configured in a single instance must be attached to a different VPC network, and each interface must belong to
  a subnet whose IP range does not overlap with the subnets of any other
  interfaces.

*The additional VPC networks that the multiple interfaces will attach to must exist before you create the instance. See Using VPC Networks
  for instructions on creating additional VPC networks.

*You cannot delete a network interface without deleting the instance.

and

*

*Every interface can optionally have an external IP address.

I've tried to create such VM:

*

*create custom VPC networks:
$ gcloud compute networks create test-vpc-network-1 --subnet-mode=custom
$ gcloud compute networks create test-vpc-network-2 --subnet-mode=custom

*create custom VPC subnets:
$ gcloud compute networks subnets create test-subnet-1 --network=test-vpc-network-1 --region=europe-west3 --range=172.16.1.0/24
$ gcloud compute networks subnets create test-subnet-2 --network=test-vpc-network-2 --region=europe-west3 --range=172.16.2.0/24

*reserve static external IPs (optional):
$ gcloud compute addresses create test-static-ip-1 --region=europe-west3
$ gcloud compute addresses create test-static-ip-2 --region=europe-west3

*create VM instance:
$ gcloud compute instances create test-instance-2ip --zone=europe-west3-a --machine-type=n1-standard-1 --network-interface subnet=test-subnet-1,address=34.89.215.180 --network-interface subnet=test-subnet-2,address=35.234.123.210 --tags=test-instance-2ip --image=ubuntu-1804-bionic-v20200430 --image-project=ubuntu-os-cloud --boot-disk-device-name=test-instance-2ip

and here it is VM instance with 2 external IPs:
NAME               ZONE            MACHINE_TYPE   PREEMPTIBLE  INTERNAL_IP            EXTERNAL_IP                   STATUS
test-instance-2ip  europe-west3-a  n1-standard-1               172.16.1.3,172.16.2.2  XXX.89.XXX.180,XXX.234.XXX.210  RUNNING

*don't forget to create firewall rules:
$ gcloud compute firewall-rules create test-instance-2ip-vpc-1 --direction=INGRESS --priority=900 --network=test-vpc-network-1 --action=ALLOW --rules=tcp,udp --source-ranges=0.0.0.0/0 --target-tags=test-instance-2ip
$ gcloud compute firewall-rules create test-instance-2ip-vpc-2 --direction=INGRESS --priority=900 --network=test-vpc-network-2 --action=ALLOW --rules=tcp,udp --source-ranges=0.0.0.0/0 --target-tags=test-instance-2ip

rules above are for example only.
In addition, have look at 3rd party example.
Also, as a possible alternative you can try Protocol forwarding:

You can set up multiple forwarding rules to point to a single target
  instance, allowing you to use multiple external IP addresses with one
  VM instance. You can use this in scenarios where you may want to serve
  data from just one VM instance, but through different external IP
  addresses. This is especially useful for setting up SSL virtual
  hosting.


text:
Q: List View Threshold issue i created one Doc library having more than 5000 items. when i tried to display these documents in list view web part, it is showing the message like "list exceeded the limit 5000".
Pls share the solution.

A: you have to:
1- Login to Central Administration.
2- Go to Application Management -> Manage Web Applications.
3- Find General Settings button on the ribbon, click on the text "General Settings" (not the icon) and select Resource Throttling in the drop-down.
4- On the appeared page change "List View Threshold" value from 5000 to your value.
Hope that helps.


text:
Q: AngularJS $http scope issue I have a bootstrap dialog box where the user can enter shipping tracking number. 2 buttons - one to cancel and one to ship. A controller is tied to this. Upon success I want to change the status of that order (in an ng-repeated list) to "shipped". But it's not working. What am I doing wrong here?
Controller with dialog sub controller:
function ManageOrderCtrl($scope, $http, $dialog) {

  // Setup some dialog options for shipping popup
  var dialogOptions = {
    controller: 'ShipOrderCtrl',
    templateUrl: '/partials/order/_ship.html'
  };

  // Shipping action - launches popup for tracking #
  $scope.shipOrder = function(order){
      var itemToEdit = order;
     $dialog.dialog(angular.extend(dialogOptions, {
        resolve: {
          order: angular.copy(itemToEdit)
        }
      }
    ))
    .open()
     .then(function(result) {
      if(result) {
       angular.copy(result, itemToEdit);
       }
       itemToEdit = undefined;
     })
  };
}

// Shipping controller (injected in ship dialog)
function ShipOrderCtrl($scope, $http, order, dialog){
  $scope.order = order;

  // Called when they click "mark as shipped" on dialog
  $scope.ship = function() {

    dialog.close($scope.order);

     //This works fine from here
     //$scope.order.status = 'shipped';

    $http.put('api/order/ship/' + $scope.order._id, {
      tracking: $scope.order.tracking
    })
    .then(function(response) {

      // This doesn't work
      $scope.order.status = 'shipped';
    });
  };
  // Cancel the dialog
  $scope.close = function(){
    dialog.close(undefined);
  };
}

View:

     {{ order.status }}

A: Ok - it's a bug in Angular Bootstrap dialog - fixed in 0.2.0 - I was using 0.1.0


text:
Q: UITableViewCell and customised accessoryDisclosureIndicator I made customised accessoryDisclosureIndicator at UITableViewCell.
I have a background color at alternate Table Cell and once the customised image view (detail) is inserted for the accessorydisclosureindicator, the right end of the table cell's background color is changed.
How can I have background color is same?
The problem is shown in the attached image.
The code is shown below.
    cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"measure_bar1.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] ];
    cell.contentView.backgroundColor = [UIColor colorWithRed:0.968 green:0.862 blue:0.925 alpha:0.5];

    UIImageView *detail = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [detail setImage:[UIImage imageNamed:@"detail_arrow.png"]];
    [cell setAccessoryView:detail];

A: You have to change:
cell.contentView.backgroundColor = [UIColor colorWithRed:0.968 green:0.862 blue:0.925 alpha:0.5];

to
cell.backgroundColor = [UIColor colorWithRed:0.968 green:0.862 blue:0.925 alpha:0.5];

the cell contentView stops right when the accessory view begins.
Take a look at this illustration:


text:
Q: Split up user creation and invitation I have an app where the admin invites new users with devise_invitable. This works fine, but I want to split things up. First I want to create the user and then later on I want to be able to invite them. How can I split up these actions?

A: You can use the skip_invitation option when using invite! to skip sending the actual invitation.
User.invite!(:email => "new_user@example.com", :name => "John Doe", :skip_invitation => true)
# the record will be created, but the invitation email will not be sent

You can then send the invitation by:
user = User.find(42)
user.deliver_invitation

https://github.com/scambra/devise_invitable


text:
Q: SSL/HTTPS issue (no padlock icon) on Safari when using ngixn+unicorn I have an application that runs on nginx+unicorn. This is how my server block looks like
upstream rtdev{
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a single worker for timing out).
server unix:/tmp/rtapp.sock fail_timeout=0;
}

server{

listen                443 ssl; # default;
server_name           devapp.resolutiontweet.com;
root                  /home/xxxxxxx/xxxxxxxxx/public;
client_max_body_size 12M;

ssl on;
ssl_certificate         xxxxxxxx/xxxxxxxxx.crt;
ssl_certificate_key     xxxxxxxx/xxxxxxxxx.key;

ssl_ciphers "AES256+EECDH:AES256+EDH";
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;

add_header Strict-Transport-Security "max-age=63072000; includeSubDomains";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;

ssl_stapling on; # Requires nginx >= 1.3.7
ssl_stapling_verify on; # Requires nginx => 1.3.7

location / {
    access_log          off;

    proxy_set_header        Host $host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;

    proxy_redirect    off;
    proxy_headers_hash_max_size 8192;
    proxy_headers_hash_bucket_size 256;

    proxy_pass          http://rtdev;

    #proxy_redirect      http://rtdev https://devapp.resolutiontweet.com;
   }
}

I'm running into a weird issue where Safari doesn't show
the "Lock" symbol for the secure site. All other browsers show it (tested on Chrome and Firefox). Attaching screenshots for reference.

Mozilla Firefox
Google Chrome
Safari
Modifying a few things in my server block fixes the issue, but the site doesn't load. For example changing,
proxy_pass          http://rtdev; --> proxy_pass          https://rtdev;
resolves the issue, but nginx throws  501 error.
I would appreciate if anyone can throw light on how to resolve/debug the issue. Thanks.
EDIT: The certificates are chained properly. I verified the settings with a couple of third party sites and everything seems fine.

A: I figured out the reason and it has got nothing to do with my server configuration.
Apparently, an unsafe script was injected dynamically by one of the libraries I was using. The script was using http not https.
Firefox and Chrome give an indication that the page contains unsafe scripts, Safari on the other hand, doesn't give user any feedback and shows the page as unsecure.
I don't know what to say, whether to applaud Apple for being overly cautious or to blame it for any lack of visual feedback.
References:
Find out what resources are not going over HTTPS
https://www.whynopadlock.com/


text:
Q: Vim: Replace n with n+1 How do I replace every number n that matches a certain pattern with n+1? E.g. I want to replace all numbers in a line that are in brackets with the value+1.
1 2 <3> 4 <5> 6 7 <8> <9> <10> 11 12

should become
1 2 <4> 4 <6> 6 7 <9> <10> <11> 11 12

A: In vim you can increment (decrement) the numeric digit on or after the cursor by pressing
NUMBER<ctrl-a>      to add NUMBER to the digit
(NUMBER<ctrl-x>      to substract NUMBER from the digit)

If only incrementing (decrementing) by one you don't need to specify NUMBER. In your case I would use a simple macro for this:
qaf<<ctrl-a>q

100<altgr-q>a

Here a brief explanation of the macro: It uses the find (f) commant to place the cursor on the opening < bracket. It is not necessary to position the cursor on the digit. When press  the number on the cursor or the nearest number after the cursor will get incremented.
If you want an even shorter series of commands you can position your curser ONCE by pressing f<, increment the number with ctrl-a and then just repeatedly press ;.. The ; command repeats the last cursor movement i.e. the find command. The . command repeats the last text changing command.
Check out this link for further information or use the built in documentation: h: ctrl-a.

A: %s/<\zs\d\+\ze>/\=(submatch(0)+1)/g
By way of explanation:
%s          " replace command
"""""
<           " prefix
\zs         " start of the match
\d\+        " match numbers
\ze         " end of the match
>           " suffix
"""""
\=          " replace the match part with the following expression
(
submatch(0) " the match part
+1          " add one
)
"""""
g           " replace all numbers, not only the first one

Edit:
If you only want to replace in specific line, move your cursor on that line, and execute
s/<\zs\d\+\ze>/\=(submatch(0)+1)/g

or use
LINENUMs/<\zs\d\+\ze>/\=(submatch(0)+1)/g

(replace LINENUM with the actual line number, eg. 13)


text:
Q: Controlling the executions of CPP Preprocessor I am using standard CPP to preprocess any C/CPP file.
I am using the below command for preprocessing:
cpp -idirafter <path_to_header_files> -imacros <sourcefile> <source_file> > <destination_file>

The above command is replacing all the macros with its corresponding implementations defined in header files.
If I want some specific MACROS containing a particular string (eg, ASSERT) should not replace by cpp preprocessor. ie, if  any macro defined by the name of TC_ASSERT_EQ or TC_ASSERT_NEQ defined in some header files should not replace by preprocessor.
Is there any ways I can control this?

A: You can use predefined macros to work around this. You can pass different defines to cpp and gcc/g++ using -D parameters
For example your assertion header can look like my_assert.h:
#ifndef __my_assert_h__
#define __my_assert_h__

#if defined  ASSERT_DEBUG
 #define my_assert(expr) my_assert(expr) /* please dont touch my assertions */
#else
 #define my_assert(expr) ((void)0U)      /* Your assertion macro here */
#endif /* ASSERT_xxx */

#endif /* #ifndef __my_assert_h__ */

And your source files can be as before. For example test.c:
#include "my_assert.h"
#include <stdio.h>

void foo (int p) {
   my_assert(p==1);
   puts("Tralala\n");
}

int main (void) {
   foo(1);
   return 0;
}

With the above trick you can run
cpp -DASSERT_DEBUG test.c
While the compilation still works as before.
gcc test.c

A: I have used #pragma poison TC_ASSERT_EQ statements to pass the line without preprocessing.


text:
Q: Black Hole Singularity and String Theory This question arises in a somewhat naive form because I am largely unfamiliar with String Theory. I do know that it incorporates higher space dimensions where I shall take the overall dimensionality to be 10 in this question, for concreteness. Now the traditional Hawking-Penrose Singularity results apply to the the General Relativity manifold of 3+1 dimensions; with the 4D Schwarzchild solution providing an example of a Singularity and Black Hole.
So the question is: do  singularities (and maybe associated Event Horizons) necessarily form in all 10 dimensions?
Examining this question for myself I see that  this paper for mathematicians introduces an $N$ dimensional Schwarzchild metric and in theorem 3.15 an $N$ dimensional Hawking-Penrose singularity theorem. However this cannot answer directly to the intentions of the String theory models. For example it is mathematically possible to extend 4D Schwarzchild to 10D differently by adding a 6D Euclidean metric. So one question is whether this modified 10D Schwarzchild even meets the conditions for the $N$ dimensional Hawking-Penrose theorem. Although such a modification is not likely acceptable as a String Theory extension, it shows that we can consider some cases:
a) All 4D singularities / Event Horizons are actually 10 D ones.
b) Some/all 4D singularities / Event Horizons are "surface phenomena" in String theory - the underlying Bulk Volume is singularity free.
EDIT: Expressed a bit more formally this is saying that the String Theory has a singularity free solution $\Phi$ in 10D, but when $\Phi$ is restricted or reduced to 3+1D it is one of the known singular solutions of GR.
c) Some Singularities in String Theory Bulk (the 6D part) can arise without a corresponding 4D singularity (akin to a "deep earth earthquake" in 10D space-time, perhaps)?

A: The Schwarzschild metric for $d$ dimensions is the standard form
$$
ds^2~=~-e^{2\phi}dt^2~+~e^{2\gamma}dr^2~+~r^2d\Omega^2
$$
These metric terms in the Einstein field equation gives
$$
R_{tt}~-~\frac{1}{2}Rg_{tt}~=~G_{tt}~=~ -e^{2\phi}\Big((d~-~1)\frac{e^{2\gamma}}{r} ~+~\frac{(d~+~1)(d~-~2)}{2r^2}(1~-~e^{2\gamma}\Big)
$$
A multiplication by $g^{tt}$ removes the $-e^{2\phi}$ and we equate this with a pressureless fluid $T^{tt}~=~\kappa\rho$.  So we think of the black hole as composed of "dust."   Some analysis on this is used to compute the $G_r^r$ gives the curvature term
$$
G_r^r~=~\Big((d~-~1)(\phi_{,r}~+~\gamma_{,r})\frac{e^{-2\gamma}}{r}~+~\kappa\rho\Big).
$$
which tells us $\phi~=~-\gamma$, commensurate with the standard Schwarzschild result, and that
$$
e^{-2\gamma}~=~e^{2\phi}~-~\Big(\frac{r_0}{r}\Big)^{d~-~2}.
$$
The entropy of the black hole is then computed by writing the density according to these metric elements and computing the Rindler time coordinates $S~=~2\pi(d~-~2)A/\kappa$.
The results more or less follow as with the standard $3~+~1$ spacetime result.  The Connection with strings is to work with the entropy of the black hole.  The $1~+~1$ string world sheet  has $d~-~1$ transverse degrees of freedom which contain the field data.  The entropy $S~=~2\pi(d~-~1)T$ may be computed with the string length, which reduces to the holographic results in $d~=~4$ spacetime.
The event horizon is $d~-~2$ dimensional, which for $10$ dimension means the horizon is $8$ dimensional.  The singularity is not considered in these calculations.  The factors $e^{-2\gamma}~=~e^{2\phi}$ become extremely large.  The metric approximates
$$
ds^2~\simeq~\Big(\frac{r_0}{r}\Big)^{d~-~2}dt^2~+~r^2d\Omega^2
$$
which is a $d~-~1$ dimensional surface where the Weyl curvature diverges for $r~\rightarrow~0$.  For $d~=~4$ this has properties similar to an anti-deSitter space.
The theory of black holes essentially follows in arbitrary dimensions.  It is interesting to speculate on what the singularity is from a stringy perspective.  The event horizon contains the quantum field information which composes the black hole.  This may then have some type of correspondence with the interior singularity, with one dimension larger. For a black hole that is very small $\sim~10^3$ Planck units, the horizon is a quantum fluctuating region, as is the singularity, and the QFT data on the two may have some form of equivalency.

A: Yes, the singularities have to form - under similar assumptions - in spacetimes of any dimension. This is not a problem: a singularity just means a place where the quantum-gravity, Planckian effects become important. In particular, the Penrose-Hawking theorem and its generalizations guarantees that black holes with singularities are formed even in 10D vacua.
The singularities that would be, if formed, problematic from the viewpoint of another Penrose's claim - the Cosmic Censorship Conjecture (the CCC) - are naked singularities, i.e. those that are not dressed in an event horizon. In 3+1 dimensions, naked singularities are most likely not formed (the CCC seems to hold) but I think that it has become pretty much established that in higher-dimensional GR, they may get formed (the CCC fails). They're not a real inconsistency - a consistent theory of quantum gravity may predict what happens even in the presence of naked singularities even if Dr Roger Penrose found it counterintuitive or dangerous.
a) Whether the 4D or 10D singularity theorem is relevant for string theory depends on the situation you consider. If there are 10 large dimensions, you need to use the 10D theorem; if there are only 4 large dimensions, physics is approximately equivalent to GR in 4D and the relevant singularity theorem is the 4D theorem. Obviously, if the compact dimensions are as small as the Planck length, we can't resolve them from a cosmological viewpoint, so the cosmological implications are identical. A singularity in a 3+1-dimensional GR description may secretly be extended in additional dimensions - either all the compactified dimensions or just some of them - but this fact doesn't affect the conclusions about the singularities for much longer distances than the Planck scale.
b) I don't fully understand what "surface phenomena" are but it is true that e.g. in the AdS/CFT correspondence, it is extremely difficult if not impossible to "see" inside the black holes, i.e. to the regions inside the event horizon. That's why the singularities inside the black holes remain largely invisible to the boundary CFT description. In some sense, all of physics may be imagined to reside outside the event horizons and the interior of the black hole contains just some subset of this information that is severely reshuffled: this principle rejecting the independent existence of the interior is known as the "black hole complementarity".
c) There can be singularities localized in the extra dimensions that are extended over the whole large 3+1-dimensional spacetime. In that case, we simply say that the compactified manifold is singular. Conifolds and orbifolds are two classes of simple examples. In those cases, the 4D effective description may remain non-singular. However, whenever you have any singularities whose character strongly depends on the position in the 3+1-dimensional spacetime (in particular, any singularities that are localized in at least one large dimension among the 3+1 dimensions), they will inevitably manifest themselves as singularities in the 4D description by GR as well. It's simply because one can show that the energy density around those singularities blows up and this energy density has to cause a huge curvature, even according to the effective 4D description. So singularities localized in the large dimensions can't hide themselves - not even if they try to localize themselves in the compact dimensions in any way.


text:
Q: Android stream to rstp server and convert to rtmp using nginx I trying to get my android device to stream its camera live to a webbrowser.
I read a great tutorial at androidhive about using wowza to do so. However, im looking for a free solution.
I decided to setup on my local machine a nginx server with rtmp module with access from outside the LAN.
Im able to stream my screen using OBS without problem.

MY SETTINGS:
In nginx, I'm using the following conf :
rtmp {
    server {
        listen 1935;
        allow play all;
        chunk_size 4000;

        application live {
            live on;
            allow publish all;
            allow play all;

            exec_pull c:/nginx/ffmpeg -i "rtsp://127.0.0.1:1935/live/test" -f flv -r -s -an "rtmp://127.0.0.1:1935/live/pc"

            #enable HLS
            hls on;
            hls_path "c:/nginx/www/hls";
            hls_fragment 3;
            hls_playlist_length 60;
        }
    }
}

Im really uncertain with the line about ffmpeg...
In my android application, its simple, I took the class from androidhive tutorial here : http://www.androidhive.info/2014/06/android-streaming-live-camera-video-to-web-page/
Im using the libstreaming for android : https://github.com/fyhertz/libstreaming
So, I simply create a RTSP client using the following line :
    Matcher m = uri.matcher("rtsp://127.0.0.1:1935/live/test");

It should create a RTSP client to connect to 127.0.0.1:1935 with RTSP protocol and stream the camera to the "live" application in the "test" channel.
So my nginx should receive something on port 1935 and convert the RTSP to RTMP using ffmpeg right ?
What iam missing to make the whole thing work ? Im getting really stuck and out of idea to try
Thank you !

A: Use 10.0.2.2 - special alias to your host loop back interface (127.0.0.1)
Change
Matcher m = uri.matcher("rtsp://127.0.0.1:1935/live/test");

to
Matcher m = uri.matcher("rtsp://10.0.2.2:1935/live/test");


text:
Q: Access to table cell using tr and td id's I have the following table structure:

            Id
            Val 1
            Val 2
            Val 3

            1
            1

            1

            1
            1

            1

            1
            1

            1

            1
            1

            1

What I'm trying to do is to set the value of an specific td dynamically. I'm able to get the td id values that I want. What I've tried so far is the following code:
$('#101#101-1-Some String').html('ABC');

But it's not working. What I saw is that the same code works okay if my id its 101-1-SomeString but the problem is that maybe I'll not be able to change that id. So, my question is if there is a way to access to that id with whitespace?


text:
Q: Reporting Services Connection to SharePoint I need to create reports on SQL Server Reporting Services 2005 (SSRS) on data coming from SharePoint Lists,
i was searching for ways to do that and i found,

*

*connecting to SharePoint web service
out put XML, the problem here is it
sometimes work and sometimes don't,
and also i couldn't do inner join
between different lists may be it is
there but it will be trouble to do
it i think (if there is easy way
tell me please)

*Creating a link table in MS Access
2007 that links to sharepoint lists,
and then connect to the MS ACCESS
link tables from SSRS 2005 : this
will work but i am kind of scared of
having ACCESS in the middle i always
want to avoid using access

*connecting to the views provided in
the sharepoints backend database
(there is a view for all lists and
another view for all list items) :
here column names will be troublsome
to create the query the clounm names
are like
(float1,float2,...,date1,date2,date3,....)
, also i am not sure if it is good
thing to make SSRS talk directly to
sharepoints backend database views

can you tell me which of these ways is best (or if there is a better way plz tell me)
i kind of like the third way but not sure if i should use it

A: I have summarized this problem on our wiki, but it is not complete.
http://wiki.threewill.com/display/enterprise/Reporting+on+List+Data+in+SharePoint.
Note that we have since tried out the CorasWorks DIT and it looks like a promising approach.

A: We are exporting all the data to a SQL database everynight ( we have also started to move items away from Sharepoint because of performance). Then we use standard Reporting Services to create the reports....

*

*(+) reporting doesn't hit the performance of day to day activities in Sharepoint

*(-) the data is "one day" old

A: Check out SharePoint List Assocation Manager, SLAM.
Allows you to do exactly what you're looking to do in real time and it's free and very well supported.
http://slam.codeplex.com