text:
Q: How can I configure an action that creates a variable number of objects? I am looking to create an action type that can be used to create a variable number of objects of a given object type. In other words, a user should be able to use this action to create 3 objects at once, 5 objects at once, etc.
I tried to accomplish this using the action configuration UI in OMA, but ran into the following issues:

*

*I noticed that in the "Rules" section, it is only possible to define a static number of objects to be created. In the example shown in the screenshot below, you'd only be able to create 2 objects rather than a variable number.

*Similarly, there is no way to specify a variable number of parameters in the "Form" section, which would be necessary to capture the primary keys for each object the user would like to create. I thought of specifying a string parameter that takes in multiple values as an alternative, but that wouldn't work because there is no way to assign a single value from this parameter to an object property.

How should I go about accomplishing this?

A: It would be possible to create a variable number of objects using a function backed action! In particular, you could take the following steps:

*

*Create a new function that takes in a list of primary keys as input and creates an object for each primary key in the list. The code for this function could look something like this:

@Edits(ObjectA)
@OntologyEditFunction()
public createMultipleObjects(primaryKeys: string[]): void {
   // Loop through pkeys and create a new object for each pkey
   primaryKeys.forEach(k => {
        Objects.create().objectA(k)
   });
}

You can also reference the following documentation for more guidance on how to define Ontology edit functions.

*Create an action in OMA that calls the function that you defined in step 1. You will need to define a multi-value string parameter for this action, which will be passed as an input to the function.

You can refer to the following documentation (https://www.palantir.com/docs/foundry/action-types/function-actions-getting-started/) for a step by step guide on how to configure a function backed action.


text:
Q: Mongodb schema for trello I'm trying to make something similar to Trello.com.  There will be many boards, and each board can have many lists, and each lists can have many items.  The order of the lists and items can change often by the user, so I came up with something like this that would minimize queries. I just read some of the mongo documentation last night so I would appreciate any feedbacks and suggestions
Here is a list of boards:
 {
        boards: [
            {
                _id: 901292190
                name: 'board1'
            }
        ]
    }

Here is when you view a single board:
 {
        _id: 901292190
        name: 'board 1',
        lists: [
            {
                _id: 932092,
                name: 'todo',
                items: [
                    {
                        _id: 9320903,
                        name: 'go shopping',
                        priority: 1,
                        createdby: 'user1',
                        assignedto: 'user2'
                    },
                    {
                        _id: 3902901,
                        name: 'go to school',
                        priority: 2,
                        createdby: 'user1',
                        assignedto: 'user2'
                    }
                ]
            },
            {
                name: 'finished',
                items: [
                    {
                        _id: 91209,
                        name: 'programming',
                        priority: 1,
                        createdby: 'user1',
                        assignedto: 'user2'
                    }
                ]
            }
        ]
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to navigate to another viewcontroller from UITabBar? How to navigate to another viewcontroller from UITabBar?
I am working on UITabBarController. Who have 4 TabBar Button and I have added a large Button on middle of UITabBar. So I want to navigate to new viewController when click on large Middle Button.

Actully I have added large button here Subclassing UITabBar(). I am giving you all code of UITabBar()
So Please tell me how can I do it. Rightnow everything is Working fine but only Navigateto new viewcontroller is Not working.
import UIKit

class MainTabBar: UITabBar {

    private var middleButton = UIButton()

    override func awakeFromNib() {
        super.awakeFromNib()
        setupMiddleButton()
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        if self.isHidden {
            return super.hitTest(point, with: event)
        }

        let from = point
        let to = middleButton.center

        return sqrt((from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)) <= 39 ? middleButton : super.hitTest(point, with: event)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
    }

    func setupMiddleButton() {
        middleButton.frame.size = CGSize(width: 70, height: 70)
        middleButton.backgroundColor = .blue
        middleButton.layer.cornerRadius = 35
        middleButton.layer.masksToBounds = true
        middleButton.setTitle("+", for: .normal)
        middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
        middleButton.addTarget(self, action: #selector(largeButtonAction), for: .touchUpInside)
        addSubview(middleButton)
    }

    @objc func largeButtonAction(_ sender:UIButton) {
        print("Write your Navigation Code here.......")
       jumpToHomeVC()
    }

    func jumpToHomeVC(){
        let story = UIStoryboard(name: "Main", bundle:nil)
        let vc = story.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
        let nav = UINavigationController(rootViewController: vc)
        nav.navigationController?.pushViewController(vc, animated: true)

    }

}

I subclassed my UITabBar() to my custom MainTabBar().

I want when I click on Large button go to new UIViewController and When click on Back again Come to UITabBarController means on Dismiss or PopViewController.
Or If is there any other solution to create a large button on middle of UItabBarController. click on anywhere in button to jump to new ViewController and on dismiss come back to previous controller.


text:
Q: Exporting more than 1 default in Next _app.tsx I came to this tricky situation, where I need to "export 2 defaults in my Next _app file (using typescript).
I started to export it for Redux, which I am using in my app
export default wrapper.withRedux(MyApp);

But now I need to translate my app with using next-i18next, where I am importing appWithTranslation and I also need to export it
import { appWithTranslation } from 'next-i18next';
export default appWithTranslation(MyApp);

Is it possible to have 2 export defaults somehow ?

A: It's impossible, but you can do either wrapper.withRedux(appWithTranslation(MyAppp)) or appWithTranslation(wrapper.withRedux(MyApp)) (not sure which order you need), so you will  get one default export both - with redux and with translation.


text:
Q: Spring Boot + Integration Test I'm trying to write an integration test for a spring boot project. Unfortunately, I'm confused with the implementation.
Below sample code snippet tried
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class)
@AutoConfigureMockMvc
public class PropertyControllerIT {

  @Autowired
  private MockMvc mockMvc;

  @Test
  public void sample_test() throws Exception {
    this.mockMvc.perform(post("/property")).andExpect(status().is2xxSuccessful());
  }
}

Question

*

*Do I need to have a separate MainClass with
@SpringBootApplication annotated to support the integration test?

*Do we create a mock database or override the database configuration. If yes, how do we override the configuration

*Should we maintain a separate directory for integration-test similar to java or test like integration-test

A: *

*You don't need to create any other classes annotated with
SpringBootApplication.

*It's a good practice to run integration tests using in memory database for example H2. You can create a new application-test.properties file in resources folder inside of test directory. In order to use override properties you can run test with test profile. In order to run tests with test profile @ActiveProfiles can be used.

*You can keep your integration tests in the same test directory like unit test but they can be located in a separate package


text:
Q: My Windows 10 tablet is broadcasting a 'direct' WiFi network without me enabling it. What can it be? I have an old Dell Venue 8 Pro tablet which I've upgraded to Windows 10. Today I noticed it started advertising a new hotspot called DIRECT-OR<MY_MACHINE_NAME>ms3W. It appeared out of nowhere - I haven't seen it until now and I'm sure I would given that I often scan for networks with my other devices when the tablet is on and the tablet's system name is quite distinct. I wasn't able to find a system setting for WiFi Direct or mobile hotspot as the option is greyed out in the little network settings tile area (the tablet doesn't have access to GSM).
I'm puzzled by this behaviour and a little concerned. Does anyone now of any Windows features which might enable a hotspot functionality? Or is it likely to be a some malicious presence on my machine? A few weeks ago I was messing around with the radio drivers as the ones provided by Dell drain battery in standby mode. Could I have accidentally installed something weird?

A:
'm puzzled by this behaviour and a little concerned. Does anyone now of any Windows features which might enable a hotspot functionality?

Windows 10 supports creating a Hotspot.  Windows 10 also supports Wi-Fi Direct.  Based on the name of the access point, the only thing it could be is a Wi-Fi Direct access point.

Or is it likely to be some malicious presence on my machine?

It is harmless.  It is absolutely NOT a malicious application.

A few weeks ago I was messing around with the radio drivers as the ones provided by Dell drain battery in standby mode. Could I have accidentally installed something weird?

Windows 10 supports a Wi-Fi Direct API but there must also be hardware support.  It sounds like you enabled a device driver feature by accident.


text:
Q: Search box that highlight words and divs I am trying to make a search box which highlights the words from different divs, now i want that after the word is highlighted only those divs are shown which has that word, rest divs should hide. The words are being highlighted but am not able to find a way about div.
$(function() {
  $("input").on("input.highlight", function() {
    // Determine specified search term
    var searchTerm = $(this).val();
    // Highlight search term inside a specific context
    $(".cd-item").unmark().mark(searchTerm);
  }).trigger("input.highlight").focus();
});

    mark {
      background: orange;
      color: black;
    }

Want to share anything?!

  <form action="/blog/search" method="get">
  <input type="text" name="search" placeholder="Search.." id="search" value="{{search}}">
    <button type="submit">search</button>
  </form>

    {% for post in posts %}

Category

{{post.subject}}

          View More

{% endfor %}

A: My idea:
For Highlight Word:

*

*Get .html() for each div (assuming they have same className='need-to-highlight')

*Then use Regex to replace keyword with keyword. Below regex expression is just one demo, it is not perfect.. because it doesn't consider some exceptions like child elements have attributes, the attributes contains keywords, you need to customize it by yourself.

*At below codes, I just simply compare oldHtml==newHtml, if ture, hide the div, if false, replace with new Html. The better solution should be use regex.match() to check whether match count > 0.
For Reset Highlight:
similiar with Highlight word, uses regex expression to match ()+keyword()+, then replace it with keyword. (Tips: Above Highlight Word function will cause keyword be wrapped with  multiple times when click Highlight Word multiple times, so uses ()+ to remove all).

function hgihtwords(keyword){
  $('.need-to-highlight').each(function(index, elem){
    let oldHtml = $(elem).html()
    //console.log(oldHtml.match(new RegExp('(<[a-z1-9]+>.*?)('+keyword+')(.*?<\/[a-z1-9]+>)', 'ig')))
    let newHtml = oldHtml.replace(new RegExp('(<[a-z1-9]+>.*?)('+keyword+')(.*?<\/[a-z1-9]+>)', 'ig'), '$1$2$3')
    if(oldHtml == newHtml){
      $(elem).hide()
    }
    else{
      $(elem).show().html( newHtml)
    }

  })
}

function resetHighlight(){
  $('.need-to-highlight').each(function(index, elem){
    let oldHtml = $(elem).html()
    let newHtml = oldHtml.replace(new RegExp('()+(.*?)()+', 'ig'), '$2')
    $(elem).show().html( newHtml)
  });
}

function showAll(){
  $('.need-to-highlight').show()
}
.mark {
  background-color:red;
}

<input type="text" id="search"/>
<button onclick="hgihtwords($('#search').val())">Highlight Words</button>
<button onclick="resetHighlight()">Reset Highlight</button>
<button onclick="showAll()">Show All</button>

A Header Test 1

A Description Test 1

  A View More Test 2

B Header Tes1t1

B Description Te1st 1

  B View More Te1st 2


text:
Q: How to make a wget and mysql bash script I want to make a bash script that will get a bunch of urls from a mysql table and pass all the urls one by one to the wget --spider , and update the mysql with the response code from wget: "HTTP request sent, awaiting response... 200 OK"
I really don't know where to start from ..
Thank you

A: #!/bin/bash

DBNAME=DB_NAME
USER=USER
PASS=PASS
HOST=localhost
STATEMENT="select name from environment;"

COUNTER=$(mysql $DBNAME -h $HOST -u$USER -p$PASS  -e "$STATEMENT")

for entry in $COUNTER; do
  echo wget $entry
done

Here is the output
 ./mql.sh
wget name
wget Prod
wget uat


text:
Q: maven change properties on the fly (runtime) I am having the following problem:
I want to be able to change maven properties on the fly using a plugin.
for instance if i have a property configured such as:
<properties>
   <someProperty>value</someProperty>
</properties>

i want to have a way to change it to "value-2" during the maven run itself (not before! for instance, i do not want to use -DsomeProperty=value-2 at command line)
I will try to explain my use case to clarify:
My pom.xml has some default properties set. However, i am running a task that creates a property file with name=value pairs to match my properties (for instance, if i have a property such as someProperty=value in my pom.xml the run.properties file has someProperty=value-2 property). during some maven run i would like to pass it the location of my properties file and have it change the default properties in my pom.xml.
I have tried using the "properties-maven-plugin" to achieve this goal but this only seems to work if i do not have the property configured in the pom.xml itself. That is, if the  section in my pom.xml does not have the "someProperty" property then the change works successfully. If i do have it, however then no change is made and i want to be able to change it even if some property is defined in the pom.xml
Any suggestions?
thanks in advance

A: I've been playing with gmavenplus-plugin which replaces the older gmaven-plugin.  In this example, I'm trying to conditionally direct the upload of docker images to either a SNAPSHOT and RELEASE docker registry similar to how the maven-deploy-plugin works.  With this code, I parse the version and set a property pointing to the correct repo.  Once you get into groovy you can mess around with maven like you are a regular java implemented maven plugin.
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.10</version>
    <executions>
      <execution>
        <id>parse-version</id>
        <goals>
          <goal>parse-version</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.5</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.4.4</version>
        <scope>runtime</scope>
      </dependency>
      <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.13</version>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>add-dynamic-properties</id>
        <phase>initialize</phase>
        <goals>
          <goal>execute</goal>
        </goals>
        <configuration>
          <scripts>
            <script>
<![CDATA[
import java.text.SimpleDateFormat;

Date now = new Date()
SimpleDateFormat timestamp = new SimpleDateFormat("yyyyMMdd.HHmmss");

myver  = "${project.version}"
myqual = "${parsedVersion.qualifier}"
myrepo = (myqual == "SNAPSHOT") ? "${docker.repo.snapshot}" : "${docker.repo.release}"
mytag  = (myqual == "SNAPSHOT") ? myver + "-" + timestamp.format(now) : myver

project.properties.setProperty('docker.repo.name', myrepo)
project.properties.setProperty('docker.image.tag', mytag)

log.info("Docker repository name is " + project.properties['docker.repo.name'])
log.info("Docker image tag is " + project.properties['docker.image.tag'])
]]>
            </script>
          </scripts>
        </configuration>
      </execution>
    </executions>
  </plugin>

A: As you found out, you cannot use dynamically changed value of property defined in POM's properties section. If you want to know why, read this answer to the end.
In order to use dynamic values and default values you have to set default values dynamically. You can use GMaven plugin for this and configure it probably as a first plugin in build. See Guillaume Darmont's answer.
And here is the explanation why this is needed. Maven replaces property values two times:

*

*at the beginning (probably during assembling of effective POM) it replaces static properties (declared in properties sections)

*before each run of a plugin it replaces properties again so dynamic values used now

What the above means is that if you have static declaration <myProperty> and later you use this property like ${myProperty} the value is injected before you have a chance to dynamicaly change it. Later you can dynamicaly change the value but the placeholder is already replaced so the dynamic value is nowhere to be injected.
I also answered this behavior here, maybe it is better explained there for someone.

A: I don't know if I fully understand your question, but you could try the Groovy Maven Plugin
<plugin>
    <groupId>org.codehaus.groovy.maven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <version>1.4</version>
    <executions>
      <execution>
        <id>add-dynamic-properties</id>
        <phase>initialize</phase>
        <goals>
          <goal>execute</goal>
        </goals>
        <configuration>
          <source>
            if (someCondition) {
                project.properties.myDynamicProperty = 'myDynamicValue'
            }
          </source>
        </configuration>
      </execution>
    </executions>
  </plugin>

Then, simply use ${myDynamicProperty}.
Hope this helps.

A: this works for me
exept I had to change property to different name:
<source>
    import org.apache.commons.lang.StringUtils;
    project.properties["my.enc"] = StringUtils.lowerCase(project.properties["db_user_base.enc"]);
</source>

Because with same name it did not work - value was not overwritten.


text:
Q: apache https to http Nginx My configuration is as follows - 1 unix server with two http servers running at the same time:

*

*apache server on ports 80 and 443

*Nginx server on port 8200   (www.myserver.com:8200)

The problem is that when I log in to Nginx site I need to authorize there. Doing this over internet with no SSL is not wise... I would like to connect to my apache server with SSL, be transparently redirected to another site and authorize still having encrpyted connection.
Nginx works via http so no ssl there... I would like to have url
https://www.myserver.com/duplicati to be proxied to http://www.myserver.com:8200
Effectively I want to have:

*

*encrypted connection from the web client to www.myserver.com

*proxy connection from https://www.myserver.com/duplicati to http://www.myserver.com:8200 (unencrypted), but limited to 1 physical machine which I don't care much about encryption (or actually lack of it)

What I did was the following
What I did was the following Apache config:
ProxyRequests Off
<Proxy *>
  Order deny,allow
  Allow from all
</Proxy>

ProxyPass /duplicati/ http://127.0.0.1:8200/ngax/
ProxyPassReverse /duplicati/ http://127.0.0.1:8200/ngax/
<Location /duplicati/>
  ProxyPassReverse /
  Order deny,allow
  Allow from all
</Location>
Header edit Location ^http://127.0.0.1:8200/ngax/ https://127.0.0.1:8200/ngax/

still no luck with that config....
It looks like a simple thing to do but after 5h of struggle I need to send my very first post to Stackoverflow community ;-)
Could you kindly help me with it?


text:
Q: Confidence Intervals And Probability Mean Is Not Closer To Tails I'm curious if there's a good way to estimate the probability that the true mean of a population falls closer to the observed sample mean than the tail ends of the margin of error. That is, I believe that there is unequal probability that the true mean may be greater or less than (to the right or left) of the sample mean.
But, if a survey is conducted and there is a large margin of error, how can we estimate whether it's likely that the true me is closer to the observed sample mean than at the tail end of the margin of error. That is, if the margin of error is -/+10 points, how could you calculate that there's a say 50% probability that the mean is probability -/+ 5points from the observed mean.
Ideally, I'd love a way to calculate this in R, if anyone is also familiar with that programming language.
Thank you and please let me know if i can make this question any clearer

A: If you want to calculate the probability a parameter (the mean in this case) falls within a certain distance from a point estimate for that parameter (observed mean) you are basically calculating the confidence level for a specific confidence interval.
The margin of error (ME) is calculated from the critical statistic and the samples standard error (SE):
$ME = critical\_statistic * SE$
Therefore, you can calculate the critical statistic based on the desired margin:
$critical\_statistic = \left(\frac{ME}{SE}\right)$
You can then obtain the p-value of that critical statistic using tables or GraphpPad's p-value calculator. The actual statistic used will depend on the characteristics of your survey (usually a t-statistic).
This p-value would be the probability that the parameter falls outside the desired margin of error, so the confidence level would be $1-p$


text:
Q: How to install PHP 7 on EC2 t2.micro Instance running Amazon Linux Distro I want to install the latest PHP 7.0 on an AWS EC2 T2.Micro Instance. So far I have read that currently AWS do not support PHP 7. But hey.. This is just a virtual server in the cloud with me having the full control over its configuration, so there must be some way to get PHP 7 running on this one.
Any help much appreciated.
My box is as below
$ cat /etc/*-release
---------------------------------------
NAME="Amazon Linux AMI"
VERSION="2015.09"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2015.09"
PRETTY_NAME="Amazon Linux AMI 2015.09"
ANSI_COLOR="0;33"
CPE_NAME="[*not significant*]"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"
Amazon Linux AMI release 2015.09

$ uname -a
---------------------------------------
Linux ip-xxx-xxx-xxx-xxx 4.1.13-18.26.amzn1.x86_64 #1 [date] x86_64 x86_64 x86_64 GNU/Linux

$ uname -mrs
---------------------------------------
Linux 4.1.13-18.26.amzn1.x86_64 x86_64

$ cat /proc/version
---------------------------------------
Linux version 4.1.13-18.26.amzn1.x86_64 (mockbuild@gobi-build-64010) (gcc version 4.8.3 20140911 (Red Hat 4.8.3-9) (GCC) )

A: You can now use the official php7 packages. Here an easy to follow guide.
1. Install Apache 2.4 and PHP 7.0 on Amazon Linux AMI
# Remove current apache & php
sudo yum remove httpd* php*

# Install Apache 2.4
sudo yum install httpd24

# Install PHP 7.0
# automatically includes php70-cli php70-common php70-json php70-process php70-xml
sudo yum install php70

# Install additional commonly used php packages
sudo yum install php70-gd
sudo yum install php70-imap
sudo yum install php70-mbstring
sudo yum install php70-mysqlnd
sudo yum install php70-opcache
sudo yum install php70-pdo
sudo yum install php70-pecl-apcu

2. Modify DirectoryIndex to include index.php
sudo nano /etc/httpd/conf/httpd.conf

find this:
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

and modify it to look like this:
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>

If a directory contains an index.html and an index.php, the server will serve the index.html with this setup. If you do not want that to happen, you have the following options:
Reverse the order, so index.php is served when both files exist:
 <IfModule dir_module>
    DirectoryIndex index.php index.html
 </IfModule>

Only use index.php as the DirectoryIndex:
<IfModule dir_module>
    DirectoryIndex index.php
</IfModule>

3. Start the Apache web server
sudo service httpd start

4. Configure the Apache web server to start at each system boot
sudo chkconfig httpd on

5. Test your installation
Create phpinfo.php:
echo '<?php print phpinfo();' | sudo tee --append /var/www/html/phpinfo.php

Open your browser and enter your instance's public IP in the address bar followed by /phpinfo.php
Example: http://xxx.xxx.xxx.xxx/phpinfo.php

Note: Don't forget to allow incoming connections for HTTP (port 80) in the Security Groups of your instance, else your request will time out.

A: It's simple. Just:
sudo amazon-linux-extras install -y php7.2

A: I got this running on my instance. You need http2.2 for it to work with the webtatic repo.  I had so many repos there were a bunch of different version incompatibilities.  I didn't keep great notes but looking at my history I basically did this:
# Remove current php & apache
sudo service httpd stop
sudo yum remove httpd* php*

# Remove any third party repos that aren't relevant
sudo yum repolist
sudo yum remove remi-safe

# Install Standard Apache for Amazon AMI
sudo yum install httpd   #specify http22 if you get a different version

# Download webtatic
mkdir -p /tmp/php7
cd /tmp/php7
wget https://mirror.webtatic.com/yum/el6/latest.rpm

# Install webtatic repo
sudo yum install latest.rpm
sudo vi /etc/yum.repos.d/webtatic.repo  'set repo enables
sudo yum clean all

# Install base php7
sudo yum install --enablerepo=webtatic php70w
php -v   #Should say something like  PHP 7.0.2 (cli) (built: Jan  9 2016 16:09:32) ( NTS )
sudo yum install php70w-opcache
sudo yum install php70w-xml
sudo yum install php70w-pdo
sudo yum install php70w-mysqlnd
sudo yum install php70w-gd
sudo yum install php70w-apcu
sudo yum install php70w-pecl-apcu
sudo yum install php70w-mbstring
sudo yum install php70w-imap

# Restart apache
sudo service httpd restart

A: Current answer to problem (not original version in question) - worth knowing since this is a bit simpler and php7 isn't available in the standard repos for Amazon Linux 2, and this didn't come up until I searched a bit harder:
amazon-linux-extras install php7.2

The version of extras can be checked with a list command if v7.2 is no longer current:
amazon-linux-extras list

A: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-LAMP.html
can follow this step-by-step guide for LAMP installation
sudo yum update -y

sudo yum install -y httpd24 php70 mysql56-server php70-mysqlnd

sudo service httpd start

A: If you want a quick copy-paste install:
wget http://mirrors.mediatemple.net/remi/enterprise/remi-release-6.rpm
sudo yum install -y remi-release-6.rpm
sudo yum update -y
sudo yum install -y --enablerepo=epel php70

Test with:
php70 -v

And if you want the executable to be php:
ln -s /usr/bin/php70 /usr/local/bin/php
php -v

A: This thread helped me get close enough to finish it off, I'm sharing the commands and output that worked for me.
On Amazon Lightsail with Amazon Linux (amzn1.x86_64), the following command list helped me rid the system of Apache 2.2 and PHP 5.3 to get to Apache 2.4 and PHP:

*

*Remove the current version of php and related tools:

sudo yum remove php*

==============================================================================================================================================
Package                           Arch                        Version                                  Repository                       Size
==============================================================================================================================================
Removing:
 php                               x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      7.4 M
 php-cli                           x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      6.4 M
 php-common                        x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      6.3 M
 php-devel                         x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      9.9 M
 php-gd                            x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      669 k
 php-mbstring                      x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      4.1 M
 php-mcrypt                        x86_64                      5.3.29-1.8.amzn1                         @amzn-main                       92 k
 php-mysql                         x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      445 k
 php-pdo                           x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      381 k
 php-xml                           x86_64                      5.3.29-1.8.amzn1                         @amzn-main                      625 k

Transaction Summary
==============================================================================================================================================
Remove  10 Packages

*Remove the current version of Apache (note you should backup your conf and conf.d folder before doing this, imho; in my case, it was a new system setup so there was nothing of interest there):

sudo yum remove http*

==============================================================================================================================================
 Package                           Arch                         Version                                Repository                        Size
==============================================================================================================================================
Removing:
 httpd                             x86_64                       2.2.31-1.8.amzn1                       @amzn-main                       3.0 M
 httpd-devel                       x86_64                       2.2.31-1.8.amzn1                       @amzn-main                       534 k
 httpd-tools                       x86_64                       2.2.31-1.8.amzn1                       @amzn-main                       135 k

Transaction Summary
==============================================================================================================================================
Remove  3 Packages

*Install Apache 2.4 (and start Apache)

sudo yum install httpd24.x86_64
sudo service httpd start

*Install PHP 7

sudo yum install php70

==============================================================================================================================================
 Package                           Arch                       Version                                  Repository                        Size
==============================================================================================================================================
Installing:
 php70                             x86_64                     7.0.13-1.19.amzn1                        amzn-updates                     3.3 M
Installing for dependencies:
 php70-cli                         x86_64                     7.0.13-1.19.amzn1                        amzn-updates                     4.7 M
 php70-common                      x86_64                     7.0.13-1.19.amzn1                        amzn-updates                     1.2 M
 php70-json                        x86_64                     7.0.13-1.19.amzn1                        amzn-updates                      65 k
 php70-process                     x86_64                     7.0.13-1.19.amzn1                        amzn-updates                      79 k
 php70-xml                         x86_64                     7.0.13-1.19.amzn1                        amzn-updates                     309 k

Transaction Summary
==============================================================================================================================================
Install  1 Package (+5 Dependent packages)

Total download size: 9.6 M
Installed size: 31 M
Is this ok [y/d/N]: y
Downloading packages:
(1/6): php70-7.0.13-1.19.amzn1.x86_64.rpm                                                                              | 3.3 MB     00:00
(2/6): php70-cli-7.0.13-1.19.amzn1.x86_64.rpm                                                                          | 4.7 MB     00:00
(3/6): php70-common-7.0.13-1.19.amzn1.x86_64.rpm                                                                       | 1.2 MB     00:00
(4/6): php70-json-7.0.13-1.19.amzn1.x86_64.rpm                                                                         |  65 kB     00:00
(5/6): php70-process-7.0.13-1.19.amzn1.x86_64.rpm                                                                      |  79 kB     00:00
(6/6): php70-xml-7.0.13-1.19.amzn1.x86_64.rpm                                                                          | 309 kB     00:00
----------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                14 MB/s | 9.6 MB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : php70-json-7.0.13-1.19.amzn1.x86_64                                                                                1/6
  Installing : php70-process-7.0.13-1.19.amzn1.x86_64                                                                                2/6
  Installing : php70-xml-7.0.13-1.19.amzn1.x86_64                                                                                3/6
  Installing : php70-cli-7.0.13-1.19.amzn1.x86_64                                                                                4/6
  Installing : php70-common-7.0.13-1.19.amzn1.x86_64                                                                                5/6
  Installing : php70-7.0.13-1.19.amzn1.x86_64                                                                                6/6
  Verifying  : php70-7.0.13-1.19.amzn1.x86_64                                                                                1/6
  Verifying  : php70-common-7.0.13-1.19.amzn1.x86_64                                                                                2/6
  Verifying  : php70-json-7.0.13-1.19.amzn1.x86_64                                                                                3/6
  Verifying  : php70-process-7.0.13-1.19.amzn1.x86_64                                                                                4/6
  Verifying  : php70-xml-7.0.13-1.19.amzn1.x86_64                                                                                5/6
  Verifying  : php70-cli-7.0.13-1.19.amzn1.x86_64                                                                                6/6

Installed:
  php70.x86_64 0:7.0.13-1.19.amzn1

Dependency Installed:
  php70-cli.x86_64 0:7.0.13-1.19.amzn1            php70-common.x86_64 0:7.0.13-1.19.amzn1        php70-json.x86_64 0:7.0.13-1.19.amzn1
  php70-process.x86_64 0:7.0.13-1.19.amzn1        php70-xml.x86_64 0:7.0.13-1.19.amzn1

Complete!

A: There are now official php7 packages for aws linux as of July 14, 2016. See the announcement at https://forums.aws.amazon.com/ann.jspa?annID=3902

To list available packages, run yum list php70*

A: The other answers seem to only work with Apache 2.2 but not 2.4.
Here's how I installed php7 on Amazon Linux running Apache 2.4:
First, if php is already installed, then remove it:
sudo yum remove php5*

Take note of the php5 packages that are being removed as you'll need to install the php7 versions of them. The php7 package names have a fairly direct and unambiguous mapping from their php5 counterparts as you'll see below. The rest of the instructions cover a classic LAMP stack and may be sufficient for your use-case.
Using instructions from http://www.spidersoft.com.au/2015/php-7-on-ami-linux-ec2/
wget http://mirrors.mediatemple.net/remi/enterprise/remi-release-6.rpm
sudo yum install remi-release-6.rpm

edit /etc/yum.repos.d/epel.repo and set enabled=1
sudo yum upgrade -y
sudo yum install php70 php70-php-fpm php70-php-xml php70-php-pdo php70-php-mysqlnd php70-php-gd php70-php-pecl-apcu php70-php-mbstring php70-php-mcrypt php70-php-opcache

Now you should have php70-php-fpm installed, which you can use in conjunction with apache:
Start the fpm daemon:
sudo service php70-php-fpm start

Switch Apache from prefork to mpm event worker (this is required because mod_php isn't thread safe) in /etc/httpd/conf.modules.d/00-mpm.conf:
LoadModule mpm_event_module modules/mod_mpm_event.so

Instruct apache to pass all php requests to php-fpm by adding the following lines in /etc/httpd/conf/httpd.conf
<FilesMatch \.php$>
         SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
DirectoryIndex /index.php index.php

Restart apache using sudo service httpd restart. If everything went ok you should be able to verify the installation by requesting a php file containing phpinfo().
If you have existing shell scripts that use php's cli interpreter and thus start with #!/usr/bin/php, you have to set up a symlink to /usr/bin/php since the binary is now named /usr/bin/php70. You can do this as follows:
sudo ln -s /usr/bin/php70 /usr/bin/php

For more info on how to configure php-fpm see https://wiki.apache.org/httpd/PHP-FPM

A: I was installing PHP 7.0 on a production box that already has apache 2.4 and PHP 5.5. I wanted to install PHP 7.0 alongside it in a way that would have no Server outage. This is what I did.
# Install PHP 7.0
# automatically includes php70-cli php70-common php70-json php70-process php70-xml
sudo yum install php70

# Install additional commonly used php packages
sudo yum install php70-gd
sudo yum install php70-imap
sudo yum install php70-mbstring
sudo yum install php70-mysqlnd
sudo yum install php70-opcache
sudo yum install php70-pecl-apcu

This happily installed PHP 7 alongside PHP 5.5. The trick was to tell apache to use 7.0. I'm not sure if this was the best way, but I achieved this by changing these 2 permalinks:
ln -sf /etc/httpd/conf.d/php-conf.7.0 /etc/alternatives/php.conf
ln -sf /etc/httpd/conf.modules.d/15-php-conf.7.0 /etc/alternatives/10-php.conf

At this point apache is still happily running 5.5. Then when you restart apache it should be working with 7.0 (maybe 7.0.1). This is the no downtime way. I'd still recommend doing what I did, which is to rebuild PROD on another instance  (create a TEST server) and test it all once before actually doing it on PROD. Good luck!
Oh, and right now the php command will still run 5.5. You can either change any scripts or CRON jobs to point to php7 or change the default version by running
alternatives --config php

A: The php 7 package name is php70w. So what you can do is, install a Webtatic repo on you linux machine and install it from there.
rpm -ivh https://mirror.webtatic.com/yum/el6/latest.rpm
yum clean all
yum install --enablerepo=webtatic php70w

A: By default, just few Yum Repo is enabled on RedHat EC2.
To enable all, just type
yum-config-manager --enable rhui-REGION-rhel-*

and do a yum list now, you should be able to see this:
yum list |grep php7

A: Several answers should work here; however, when I was installing mine, it would not render pages and would display text instead of rendered PHP.
To fix that, I ran
sudo yum install php70-php-fpm
After that, everything started working.

A: Here is how I installed PHP 7.1 on Amazon Linux:
wget http://rpms.remirepo.net/enterprise/remi-release-6.rpm
rpm -Uvh remi-release-6.rpm epel-release-latest-6.noarch.rpm
yum-config-manager --enable remi-php71

wget ftp://195.220.108.108/linux/epel/6/x86_64/Packages/s/scl-utils-20120229-1.el6.x86_64.rpm
rpm -Uvh scl-utils-20120229-1.el6.x86_64.rpm

yum install php71

https://gist.github.com/ihor/581d169886c29e7e17d01b0041167b01


text:
Q: type parameter `U` of call of method `then`. Missing annotation I have an object which might contain a promise property declared thus:
type PromiseAction = {
  +type: string,
  promise: ?Promise<any>,
};

The action argument to a function is declared to be of type PromiseAction:
(action: PromiseAction) =>

Later on I check whether the received action object does have a promise property and if action.promise has a then:
if (action.promise && typeof action.promise.then === 'function') {

If it does then I hook onto the promise chain:
return promise.then(

At which point I get the error: "type parameter U of call of method then. Missing annotation"
I can see in the source for flow that the then property of a Promise has a U parameter which, I assume, is the one being asked for.
How can an provide that U annotation if I only have only one parameter Promise<+R> in the type declaration?

A: You do not need to define the value of U.
The flow source you linked to means, essentially, "Promises returned by then fulfill with a value that is the same as either the return value of the handlers, or the fulfilled value of the returned Promise of those handlers." That sounds confusing (because Promises can be very confusing) but the bottom line is that it's not something you "fill out". It creates a relationship between the types that then returns and the types of the return values of onFulfill and onReject passed to then.
The error you're getting means that Flow can't figure out what that relationship is because it doesn't have enough information. Annotate the then callbacks with types:
return promise.then((a:string)=>...)
That will either fix the error, or at least disambiguate U enough to give you a more specific error.


text:
Q: What is the difference between continuous ans discrete variables in an optimization problem? Natural and real numbers? It is a rather theoretical question to better understand some definitions.
Can descision variables in descrete optimization problems be only integers?
If I have a set of real numbers which are not only natural numbers is it a continious optimization problem?
An example of a problem:
If there is a set of variables:

animal
value

frog
0.54

cat
-9.12

duck
0.001

dog
4

snake
-300.09

is that a continious or descrete problem?
From the Wiki definition: A continuous variable is a variable whose value is obtained by measuring, i.e., one which can take on an uncountable set of values. For example, a variable over a non-empty range of the real numbers is continuous, if it can take on any value in that range. The reason is that any range of real numbers between a and b with a , b ∈ R ; a ≠ b  is uncountable. A variable is a discrete variable if and only if there exists a one-to-one correspondence between this variable and N, the set of natural numbers.
Theoretically I could say that the example is a non-empty range of real numbers between -300.09 and 4 and see it is a continuous problem. From the Wikipedia definition I understand that descrete variables must belong to a set of natural numbers, so it is not my case. Or do I undestand it wrong?


text:
Q: Forecasting in R with a growth function? How would I go about forecasting future population with a growth function in R?
I'm trying to fit a growth function to the sales of EVs in the world. One assumption I might want to make would be one such as max potential sales would be 110 million. Current vehicle sales in the world are 96,804,38 with 3,109,050 being EVs in 2017. This is for both BEV and PHEV.
The source I've used are:
Logistic substitution model and technological forecasting by Dmitry Kucharavy and Roland De Guio

Application of S-shaped curves by Dmitry Kucharavy and Roland De Guio

Data is from the iea EV outlook.
 EVAnnualWorldSales<-structure(list(Country = structure(c(21L, 21L, 21L, 21L, 21L,
 21L, 21L, 21L, 21L, 21L, 21L, 21L, 21L), .Label = c("Australia",
 "Brazil", "Canada", "Chile", "China", "Finland", "France", "Germany",
 "India", "Japan", "Korea", "Mexico", "Netherlands", "New Zealand",
 "Norway", "Others", "Portugal", "South Africa", "Sweden", "Thailand",
 "Total", "United Kingdom", "United States"), class = "factor"),
Year = c(2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012,
2013, 2014, 2015, 2016, 2017), TotalSales = c(1.89, 2.23,
2.69, 5.15, 7.48, 14.26, 61.33, 179.03, 381.3, 703.65, 1239.45,
1982.04, 3109.05)), row.names = c(NA, -13L), .Names = c("Country",
 "Year", "TotalSales"), class = "data.frame")

How would I go about forecasting EV sales through 2040?
Here is what I've tried:
myfunction <- function(GrowthRate, time, Beta){
    AsymptoticLimitOfGrowth =88000
    Value = AsymptoticLimitOfGrowth / (1+exp(-GrowthRate*time-Beta))
    return(Value)
 }
nls(TotalSales ~ myfunction(GrowthRate, time, Beta),
 data=EVAnnualWorldSales,
start=list(GrowthRate=0.5, time=2030, Beta=1))

with error:
 Error in qr(.swts * gr) :
 dims [product 3] do not match the length of object [13]
 In addition: Warning message:
 In .swts * gr :
  longer object length is not a multiple of shorter object length

and
EV.ss <- nlsLM(TotalSales ~ SSgompertz(Year, Asym, b2, b3), data = EVAnnualWorldSales)

Error:
      Error in qr.qty(QR.rhs, .swts * ddot(attr(rhs, "gradient"), lin)) :
       NA/NaN/Inf in foreign function call (arg 5)
and
 EV.ss <- nls(TotalSales ~ SSlogis(Year, phi1, phi2, phi3), data = EVAnnualWorldSales)
 summary(EV.ss)

The last one generates an output but the limit if far below what would be expected. Therefore, not a logical result.
Would someone be able to point me in the correct direction?

A: The following worked for me
y <- EVAnnualWorldSales$TotalSales/88000
x <- EVAnnualWorldSales$Year-2004

my_model <- nls(y ~ 1/(1+exp(a*x +b)),start=list(a=-0.5,b=-0.5))
plot(EVAnnualWorldSales$Year,y)
lines(EVAnnualWorldSales$Year,predict(my_model),col="red",lty=2,lwd=3)

simply by choosing the correct starting values and not working with data.frame object and scaling time to prevent under- overflow when evaluating exponential function during estimation.

A: not so easy ... I took your SCALED data  and introduced it to AUTOBOX ( a piece of forecasting software that I have helped to develop )  and requested an automatic ARIMA model to be built which included outlier detection.
AUTOBOX automatically detected the need for a power transform (logs) and delivered the following model .
The forecasts for the next 23 periods are here  and The Actual and Forecast graph is here
If the forecasts exceed some upper limit that you have in mind , simply truncate the forecasts to that value.
Now AUTOBOX has an R version but if you are not interested in that version you simply need to find/use an automatic box-jenkins /ARIMA algorithm that will  determine/identify an appropriate power transformation while dealing with anomalies per When (and why) should you take the log of a distribution (of numbers)?


text:
Q: How to enable Electron to use chrome://flags/#enable-force-dark We found the chrome flag chrome://flags/#enable-force-dark that forces all websites to use dark mode and it's quite nice actually!
We cannot get this flag to work in Electron, however. Here's what we tried:
app.commandLine.appendSwitch('enable-force-dark');
app.commandLine.appendSwitch('force-dark-mode');
app.commandLine.appendSwitch('enable-features', 'enableForceDark');
app.commandLine.appendSwitch('enable-features', 'WebUIDarkMode');

Sadly, none of them work. Any pointers would be appreciated.

A: The Electron docs specify a list of supported command line switches (some of which do come from Chromium). Unfortunately, --enable-force-dark is not on that list.

A: That's because it should be:
app.commandLine.appendSwitch('enable-features', 'WebContentsForceDark');

You can find it out by enabling it and going to chrome://version and looking at the command line.
However in this case you should use themeSource instead.
Edit: Actually I guess that isn't the same as forcing dark mode (not sure you should do that) but if you want to I think maybe you're meant to do this instead:
    new BrowserWindow({
      webPreferences: {
        enableBlinkFeatures: "WebContentsForceDark",
      },
      ...

I haven't tried it though, and it seems to be hella janky. I can't make it work through any method for CSSColorSchemeUARendering.


text:
Q: how to append Multiple sheets from multiple workbooks I have 5 workbooks with hundreds of sheets with same name and same columns in each workbook, I want to append the data of each sheet of all workbooks separately and export to CSV or XLS, i am appending one by one
dir_path = r'D:\Input\\'

res = []
for path in os.listdir(dir_path):
    if os.path.isfile(os.path.join(dir_path, path)):
        res.append(path)

FilePath_1=dir_path+ res[0]
FilePath_2=dir_path+ res[1]

Data1 = pd.read_excel (FilePath_1,sheet_name='Data',header=None)
Data1.drop(Data1.head(1).index, inplace=True)
Data2 = pd.read_excel (FilePath_2,sheet_name='Data',header=None)
Data2.drop(Data2.head(2).index, inplace=True)
Data=pd.concat([Data1, Data2])
Data.to_excel(r'D:\Data.xlsx', index = False,header=None)


text:
Q: How can I fix "no module named blog"? After creating a Django project, I right click the project name and choose open in terminal. I was able to run the server using python manage.py runserver.
Now after creating a blog app in the project using python manage.py startapp blog, I tried to run the server again but it did not work.
The following error message pops up:
File "C:\Users\Sam Iam \AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog.urls'

How can that module be found?


text:
Q: What peer-to-peer protocol has the shortest specification? I want to implement a P2P protocol in C for personal education purposes.
What would be the protocol with the shortest specification that is still used today?
I have already implemented a web and IRC client and server.

A: Serial. The answer is serial. You're not going to get any leaner than simple RX/TX communication but you'll lack a lot of convenience methods. If you want to explore more than simple bidirectional comms, I2C or modbus open up a lot of options.

A: I agree with Mark, that point to point over a serial link would be a good exercise.
In particular, I would recommend the following programme of stuff...

*

*Implement basic transmission over a "Serial Port" (using RS-232 if you have some Arduinos/embedded processors lying around, or using a null modem emulator if you don't (see com0com on Windows, or this on linux/mac).

*

*I.e. send lower case letters from A->B, and echo them back as upper case from B->A

*Implement SLIP as a way to reliably frame messages

*

*i.e. you can send any string (e.g. "hello") and it is returned in upper case with "WORLD" appended ("HELLOWORLD").

*Implement the "Read Multiple Holding Registers" and "Write Multiple Holding Registers" part of the Modbus protocol, using SLIP to frame the messages.

*

*I.e. you have one follower (slave) device, and one leader (master) device. The follower has 10 bytes of memory that are exposed over modbus with the initial value "helloworld".

*Just hard-code the follower / leader device Ids for now.

*The leader reads the value, and then sets it to be "worldhello".

At the end of this you would start to have an understanding of the roles of network layers, ie:

*

*The physical layer - Serial/RS-232

*A "link layer" of sorts - SLIP

*An "application" layer - Modbus


text:
Q: C# ASP.NET Selecting multiple column from same mysql command and use them in code behind I woul make this thing:
"select nome,cognome from Utenti where CodiceCliente = @codice"

and then use the value in "nome" and the value in "cognome" in code behind. With PHP there are associative array, in C# ASP.NET?
'till now I have always used two different commands, but now it's annoying.
example:
MySqlCommand getNome = new MySqlCommand("select Nome from Utenti where CodiceCliente = @codice", userConnection);
    MySqlCommand getCognome = new MySqlCommand("select Cognome from Utenti where CodiceCliente = @codice", userConnection);
    MySqlCommand getEmail = new MySqlCommand("select IndirizzoEmail from Utenti where CodiceCliente = @codice", userConnection);
    getNome.Parameters.AddWithValue("@codice", codice);
    getCognome.Parameters.AddWithValue("@codice", codice);
    getEmail.Parameters.AddWithValue("@codice", codice);
    userConnection.Open();
    string nome = Convert.ToString(getNome.ExecuteScalar());
    string cognome = Convert.ToString(getCognome.ExecuteScalar());
    string email = Convert.ToString(getEmail.ExecuteScalar());

Can you help me?
Thanks before,
Daniele

A: Simple usage:
using(var connection = new MySqlConnection(myConnString))
{
   var cmd = connection.CreateCommand();
   cmd.CommandText = "select nome,cognome from Utenti where CodiceCliente = @codice";
   cmd.Parameters.AddWithValue("@codice", value);
   var reader = cmd.ExecuteReader();
   while(reader.Read())
   {
       // here could be problems if database value is null
       var nome = reader["nome"];
       var cognome = reader["cognome"];
   }
}

A: You may try this :
using(var connection = new MySqlConnection(myConnString))
{
   var cmd = connection.CreateCommand();
   cmd.CommandText = "select nome,cognome from Utenti where CodiceCliente = @codice";
   cmd.Parameters.AddWithValue("@codice", value);
   var reader = cmd.ExecuteReader();
  if(reader.HasRows) {
   while(reader.Read())
   {

       var nome = reader[0];
       var cognome = reader[1];
   }
reader.Close();
}
}

You must check if the DataReader has rows to avoid exception and finally don't forget to close it


text:
Q: WPML - how to get the permalinks to display also the default language Currently WPML adds /fr/ to permalinks to identify a url as French. The default language of the site is English, however WPML does not add /en/ by default for the default lannguage (English) permalinks. Is there a way to have the default language also show up in the permalinks?

A: EDIT: This feature has been added to the latest version of the plugin.
https://wpml.org/documentation/getting-started-guide/language-setup/directory-default-language/


text: Q: Jquery Bootstrap Label Display once in a column I have a dictionary search.I have to do designing.Here if there is  a noun word ,the noun label should be displayed once not everywhere . For labels I designed using bootstrap.But When the word is  an adjective then the 1st column contains the adjective label.What I am saying is if a  word is noun then noun label should be displayed once in the label in a table column.So, I created the label but it is iterating thorughout or the label is displayed throughout.That should not be the case.Please help me.This should be same for adjectives,adverbs.I have to use using Jquery


text:
Q: Authenticating user in MVC 5 I'm new to MVC and the User.Identity that comes with it.
I've just gotten the login functionality done on my site, but I'm missing something.
after the authentication.SignIn(identity), the isAuthenticated flag of the User.Identity object is false, and the isAnonymous flag is true.
here's the code I'm using. let me know what I've missed.
ClaimsIdentity identity =
                            new ClaimsIdentity(new[]
                            {new Claim(ClaimTypes.Name, user.Name), new Claim(ClaimTypes.Email, user.Email)});
                        IOwinContext ctx = Request.GetOwinContext();

                        IAuthenticationManager authManager = ctx.Authentication;

                        authManager.SignIn(identity);

                        return RedirectToAction("Index", "Home");


text:
Q: Convert 'int' to pytorch 'Variable' makes problems First project with pytorch and I got stuck trying to convert an MNIST label 'int' into a torch 'Variable'. Debugger says it has no dimension?!
# numpy mnist data
X_train, Y_train = read_data("training")
X_test , Y_test  = read_data("testing")

arr = np.zeros(5)
for i in range(5):
    # in your training loop:
    costs_ = 0
    for k in range(10000):
        optimizer.zero_grad()                            # zero the gradient buffers
        a = torch.from_numpy(np.expand_dims(X_train[k].flatten(), axis=0)).float()
        b = torch.from_numpy(np.array(Y_train[k], dtype=np.float)).float()
        input = Variable(a)
        output = net(input)
        target = Variable(b)                             # PROBLEM!!
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()                                 # Does the update

        costs_ += loss.data.numpy()
    arr[i] = costs_
    print(i)

Thrown error is: "RuntimeError: input and target have different number of elements: input[1 x 1] has 1 elements, while target[] has 0 elements at /b/wheel/pytorch-src/torch/lib/THNN/generic/MSECriterion.c:12"

A: The error is telling you exactly what is happening. Your target variable is empty.
Edit (after the comment below):
if Y_train[k] = 5, then np.array(Y_train[k], dtype=np.float).shape = (), and in turn Variable(b) becomes a tensor with no dimension.
In order to fix this you will need to pass a list to np.array() and not a integer or a float.
Like this:
b = torch.from_numpy(np.array([Y_train[k]], dtype=np.float)).float()


text:
Q: !array.length triggered even though there is a record in array I do not understand this one.
invoiceList shows one record.
LENGTH: shows 1
But it still triggers if (!invoiceList.length) {
    show({invoiceList})

    show("LENGTH: " + invoiceList.length)

    if (!invoiceList.length) {
        reject({code:"MULTI INVOICE ERROR", err:"You need to make an invoice"});
        return;
    }

How come that !invoiceList.length is triggered when length is 1?
I just tried this:
    var invoiceList = [
        {
            "foo": "bar",
        },
        {
            "foo": "bar",
        },
        {
            "foo": "bar",
        }
    ]

    console.log(invoiceList)

    console.log("LENGTH: " + invoiceList.length)
    console.log("LENGTH: " + invoiceList.length)

    if (!invoiceList.length) {
        reject({code:"ERR 1", err:"You need to make an invoice"});
    }
    if (invoiceList.length<1) {
        reject({code:"ERR 2", err:"You need to make an invoice"});
    }
    if (!invoiceList.length) {
        reject({code:"MULTI INVOICE ERROR", err:"You need to make an invoice"});
    }
    return;

And console.log gives me the following:
[ { foo: 'bar' }, { foo: 'bar' }, { foo: 'bar' } ]
LENGTH: 3
LENGTH: 3
{ code: 'MULTI INVOICE ERROR',
  err: 'You need to make an invoice with the word PRICE in one of the lines' }
getInvoice: [object Object]

So now I am really confused?!?!


text:
Q: How many unlabelled oriented trees with $n$ vertices? Is there a known upper bound of the form $a^n$ on the number of unlabelled oriented trees with $n$ vertices?

A: Yes: the Catalan numbers count unlabeled ordered trees with $n$ vertices (where an ordered tree is an oriented tree in which the order of the children of a node matters) and therefore the $n^{\text{th}}$ Catalan number $C_n$ is an upper bound on the number of unlabeled oriented trees. But $C_n = \frac1{n+1}\binom{2n}{n} \le 4^n$.


text:
Q: How to exclude certain messages by TAG name using Android adb logcat? Logcat allows filtering logs but it works like that: You define filters and logcat only displays messages which matches filters. But is there a way to display all logs EXCEPT some TAGs defined by filters?

A: If you want to exclude or filter certain messages by tag name in Android studio, goto the LogCat window=>Edit Filter configuration, and enter the following under "by Log Tag(regex): "
^(?!(tag1|tag2|tag3|tag4))

Note that there are no spaces, this is important

A: There is also the option to make your own filter in Android Studios logcat GUI.
E.g. I was very annoyed by OpenGLRenderer and ViewRoot messages in logcat.
In the logcat click on Edit Filter Configuration and create a new filter.
In the Log Tag Input you can type in something like ^(?!.*(OpenGLRenderer|ViewRoot)) and add several other Tags that are annoying you.

A: With new LogcatV2 you should use this example:
-tag~: chatty|WifiHAL|HwBinder|Light|lsc_nvram|SensorService|thermal_repeater

and so on

A: If you are using adb logcat you could pipe it through grep and use it's inverted matching:
From the grep manpage:

v, --invert-match
          Invert the sense of matching, to select non-matching lines.

For example:
$adb logcat | grep --invert-match 'notshownmatchpattern'

You can extend this by using regular expressions.
Here is an example of such an expression:
"/^(?:emails|tags|addresses)"

This one would check for either of the given to occur, grep would then not list them.

A: Here's a list of filters that I've been using to ignore Samsung system logs. would work with other devices too.

Logcat -> Edit Filter Configuration -> Log Tag

^(?!(PowerUI|PowerPlanningReceiver|BatteryService|SamsungPhoneWindowManager|MotionRecognitionService|AudioService|APM_AudioPolicyManager|SensorService|StorageManager|SignalClusterView|BatteryService|TelephonyManager|UsbDeviceManager|KeyguardUpdateMonitor|BatteryController|ActivityManager|LauncherAppsService|AppsModel|DataLoader|PackageManager|LauncherApps|ContactsImsCommon|ImsUtil|ImsSettingsProvider|DeviceConfigManager|WifiService|BackupManagerService|PersonaManagerService|DefaultDialerManager|ResourceType|NetworkUIGlobals|NetworkProxy|FileWriteThread|ReflectUtil|PhoneApp|SamsungAlarmManager|display|DeviceStorageMonitorService|wrapperGPS|io_stats|GnssLocationProvider|KeyguardServiceBoxContainer|ConnectivityService|SSRM|TLC_TIMA_PKM_initialize|mc_tlc_communication|TeeDriverClient|TLC_TIMA_PKM_measure_kernel|AutomaticBrightnessController|BatteryUtils|WifiConnectivityManager|Launcher|IconView|ApplicationPackageManager|LiveIconLoader|WifiScanningService|WifiHAL|WifiScanController|ApplicationPolicy|SELinux|TimaKeyStoreProvider|ActivityThread|zygote|GservicesProvider|GoogleHttpClient|cr_ChildProcessConnect|WificondControl|Netd|Tethering|ContactsImsCommon|ImsConstants|tnet-jni|BatteryStatsService|SignalClusterView|LiveIconManager|BitmapCacheContainer|com.samsung.android.app.powerplanning.utils.BatteryUtils|ReflectField|cr_ChildConnAllocator|TinLoadingFailTracker|WifiPermissionsUtil|EventHandler_FLP|android.hardware.wifi@1.0-service|BluetoothAdapter|bt_btm|WifiPermissionsUtil|GeofencerStateMachine|Places|GCoreUlr|BeaconBle|Sensors|SLocation|ContactsProvider_EventLog|WificondScannerImpl|AlarmManager|AlarmManagerEXT|MultiDex|NetworkSecurityConfig|DnsProxyListener|dalvik-internals|mobileconfig|SsacManager|ImsPhoneStateManager|VolteServiceModule|PdnController|PowerManagerService|GameManagerService|NoSync|SensorManager|DisplayPowerController|NetworkController|SamsungAnalytics111040|tlcFidoAuthnr|InputReader|FlashlightController|KeyguardWallpaperController|OpenGLRenderer|EasyMuteController|Vibrator|VibratorService|PowerManagerUtil|LightsService|WindowManager|InputDispatcher|InputReader|CustomFrequencyManagerService|SystemUIAnalytics|SamsungAnalytics|swipe|PanelView|BadgeCache|MARsPolicyManager|MARsDBManager|KeyguardClockPage|ScanManager|RegiMgrBase|secImsManager|GeolocationController|MultiSimUtils|CarrierText|Mms|NetworkNotificationUI2|CommandListener|ReschedulableTimer|RCS-ContactsImsCommon|Settings|DmConfigModule|NotificationMgr2|PhoneMultiSimUtils|PhoneProxy|VideoCapabilities|AudioCapabilities|SAIV_FACE|FaceController|FaceService|SamsungAnimationCreator|ImageWallpaper|Finsky|VirtualScreen|PagedView|DragLayer|HomeContainer|ImsServiceStub|DmConfigHelper|TZ))

A: From the shell, you can use a command like:
adb logcat AlarmManagerService:S PowerManagerService:S *:V

which will include all logs apart from those with the AlarmManagerService and PowerManagerService tags.
(The :S stands for "silent", which means nothing will be printed for those tags; the :V stands for "verbose" which means everything will be printed for all other tags. The Android documentation for logcat has more details of other options you can use in the filters.)
You can also use the ANDROID_LOG_TAGS environment variable to set up default filters, e.g. (in bash):
export ANDROID_LOG_TAGS="AlarmManagerService:S PowerManagerService:S *:V"

A: ^(?!.*(WindowManager|dalvik|Environment|DataRouter|AlarmManager)).*$
This will exclude texts having contents WindowManager,dalvik,...
tag:^(?!.*(WindowManager|dalvik|Environment|DataRouter|AlarmManager)).*$
This will exclude tags WindowManager,dalvik,... from logcat

A: An easy way to do this is by simply filtering in only the tags you want to see.
adb logcat -s "Tag1" -s "Tag2" -s "Tag3"

Will bring up only those tags.

A: You can do this from within DDMS Monitor (and also Eclipse or Android Studio) with the regular expression input box and negative look-ahead assertions, for example I am excluding a lot of noise from my log with the following:
tag:^(?!(WifiMulticast|WifiHW|MtpService|PushClient))

(The "tag:" isn't part of the regular expression, but tells LogCat to only apply the regex to the Tag field. If you use this trick in a saved filter then put just the regular expression in the "Tag" input box, and omit the "tag:" prefix)
In Android Studio's logcat monitor pane, you can set up a saved filter for this by opening the dropdown in the upper right (it may have "Show only selected application" selected) and selecting Edit Filter Configuration. Create a new logcat filter and put ^(?!(WifiMulticast ...etc. )) in the Log Tag box, with the Regex checkbox checked.

A: This is The Most common Annoying Tags i gathered
^(?!.*(OpenGLRenderer|ViewRoot|ForceDarkHelper|Looper|PlayCore|AudioTrack|SurfaceUtils|cr_ChildProcessConn|FA|ActivityThread|DynamiteModule|Perf|DynamitePackage|EgretLoader|cr_LibraryLoader|BpBinder|chatty|FeatureParser|MediaCodec|ExtendedACodec|MapperHal|OMXClient|VideoCapabilities|Gralloc3|MetadataUtil|AdrenoGLES|chromium|DpmTcmClient|WebViewFactory|cr_CachingUmaRecorder|AdrenoUtils|cr_media|AudioManager|cr_SpareChildConn|Chrome_InProcGp|Choreographer|AdInternalSettings|Keep-Alive|Vary|pool-15-thread-|WifiMulticast|WifiHW|MtpService|PushClient|EGL_emulation|OpenGl*|InputReader|art|dalvik|Environment|DataRouter|AlarmManager|WindowManager|PhoneStatusBar|ActivityManager|ResourceType|PackageManager|gralloc|Gnss|NetRec|ResolverController|GAv4|AsyncOperation|AppOps|WificondControl|aofp|wifi|netmgr|ctxmgr|BestClock|FirebaseInstanceId|android.os.Debug|memtrack|netd|system_server|StrictMode|bluetooth|NetworkMonitor|FA|BroadcastQueue|ConnextivityService|WakeLock|HttpClientWrapper|RAWR|Tenor|BgTask|WifiService|BluetoothAdapter|UpdateStatsService|AppIdleHistory|Connectivity|VelvetNetworkClient|WorkerManager|EGL_emulation|chatty|gralloc|InputReader|ActivityThread|ActivityTaskManager|UsageStatsService|ocess.gservice|DropBoxManagerService|EventLogChimeraService|PContextMetricsRunner))

A: Combine both positive and negative lookahead for more powerful filtering.
Example:
(?=(AndroidRuntime|Main|RandomTag))(?!(Audio))

Tags in the first nested parentheses are included.
Tags in second are excluded.

A: Within the Eclipse Logcat view there's not such an option. However you can make use of the log level to exclude any message whose log level is too low. E. g. setting it to I(nfo) doesn't display D(ebug) and (V)erbose messages.


text:
Q: Postgres - Dynamically referencing columns from record variable I'm having trouble referencing record variable type columns dynamically. I found loads of tricks online, but with regards to triggers mostly and I really hope the answer isn't "it can't be done"... I've got a very specific and simple need, see my example code below;
First I have an array containing a list of column names called "lCols". I loop through a record variable to traverse my data, replacing values in a paragraph which exactly match my column names.
DECLARE lTotalRec RECORD;
DECLARE lSQL text;
DECLARE lCols varchar[];

p_paragraph:= 'I am [names] and my surname is [surname]';

lSQL :=
    'select
        p.names,
        p.surname
    from
        person p
    ';

FOR lTotalRec IN
    execute lSQL
LOOP
    -- Loop through the already created array of columns to replace the values in the paragraph
    FOREACH lVal IN ARRAY lCols
    LOOP
        p_paragraph := replace(p_paragraph,'[' || lVal || ']',lTotalRec.lVal); -- This is where my problem is, because lVal is not a column of lTotalRec directly like this
    END LOOP;

    RETURN NEXT;
END LOOP;

My return value is the paragraph amended for each record in "lTotalRec"

A: You could convert your record to a json value using the row_to_json() function. Once in this format, you can extract columns by name, using the -> and ->> operators.
In Postgres 9.4 and up, you can also make use of the more efficient jsonb type.
DECLARE lJsonRec jsonb;

...

FOR lTotalRec IN
    execute lSQL
LOOP
    lJsonRec := row_to_json(lTotalRec)::jsonb;
    FOREACH lVal IN ARRAY lCols
    LOOP
        p_paragraph := replace(p_paragraph, '[' || lVal || ']', lJsonRec->>lVal);
    END LOOP;

    RETURN NEXT;
END LOOP;

See the documentation for more details.

A: You can convert a row to JSON using row_to_json(), and then retrieve the column names using json_object_keys().
Here's an example:
drop table if exists TestTable;

create table TestTable (col1 text, col2 text);
insert into TestTable values ('a1', 'b1'), ('a2', 'b2');

do $$declare
    sql text;
    rec jsonb;
    col text;
    val text;
begin
sql := 'select row_to_json(row) from (select * from TestTable) row';
for rec in execute sql loop
    for col in select * from jsonb_object_keys(rec) loop
        val := rec->>col;
        raise notice 'col=% val=%', col, val;
    end loop;
end loop;
end$$;

This prints:
NOTICE:  col=col1 val=a1
NOTICE:  col=col2 val=b1
NOTICE:  col=col1 val=a2
NOTICE:  col=col2 val=b2
DO


text:
Q: How can I debug a Borland BCC55 compiled EXE using visual studio? I have two visual studio projects (A, B) which create dlls. This dlls are loaded by program C which is compiled using BCC55. I have the source code for all the projects. How can I debug A,B and C together ?

A: In all likelihood, you can't.
Being able to debug, by which you probably mean using breakpoints and having the IDE stop on a certain line in the source code when there's an exception or other error etc. is not just about having the source, but having the debug symbols. This data can either be embedded in the binary, which is usually the case with a debug build, or in a separate file, but either way it is generated (or not generated) at compile time. And Microsoft has its own format which is different from Borland's format and so on.
And on top of all that, BCC 5.5 is quite dated, to say the least. If I were you, I'd take care of the VS build errors, build everything in VS and take it from there.


text:
Q: asp.net linkbutton properties I have an app that, based on the .text property in a linkbutton (which is set programmatically, typically "Add" or "Save") the system adds or saves to the database. The linkbutton is standalone and not within a gridview or anything like that.  Now the customer just wants to see "Save" in all cases, which invalidates my logic.  I would prefer to use the app's existing logic as much as possible.  Unfortunately the linkbutton doesn't have a property such as
.nonvisibletext, so I'm wondering if it does have a property which I could put a string in that I don't use, and I'm looking at CommandName.  I do use that in gridview processing, but not in linkbuttons.
Can I safely use CommmandName instead of Text? Or is there is internal usage of this property? I'm not finding anything in research so far that indicates one way or the other.
Thanks!

A: As per my knowledge, you can use the CommandName/Command Argument properties of the LinkButton without any problem. The only change would be that the "OnClick" event should be removed and "OnCommand" should be added.
Hope this Helps!!


text:
Q: Regex - how to get windows service state in Java? When running the command sc query <serviceName>, the next output is getting back:
TYPE               : 10  WIN32_OWN_PROCESS
    STATE              : 4  RUNNING
                            (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
    WIN32_EXIT_CODE    : 0  (0x0)
    SERVICE_EXIT_CODE  : 0  (0x0)
    CHECKPOINT         : 0x0
    WAIT_HINT          : 0x0

How can I extract the service state (in this case is RUNNING) using regex with Java?

A: You could match:

*

*\b a word boundary

*the word STATE followed by

*one or more whitespace characters \s+

*one \d or one or more digits \d+

*one or more whitespace characters \s+

*Capture in a group (group 1) one or more non-whitespace characters (\S+) which in this case will be RUNNING
\bSTATE\s+:\s+\d+\s+(\S+)
In Java
\\bSTATE\\s+:\\s+\\d+\\s+(\\S+)
Test

A: You can try the below regex
(.*?STATE\s*:\s*\d*\s*)(\w+)

and match group 2. See this link Regex Solution

A: You can use this regex:
STATE.*?(\S+)\n

The matched group should be RUNNING. You can see details and example here.
The important part is the use of a lazy star operator *? that allows matching the whole word at the end of the line instead of a single letter.
P.S: depending on whether you match multiline regex or not, you might want to switch the \n for a $.

A: There is another way to quickly get this value using .replaceFirst():
String result = s.replaceFirst("(?s).*?STATE[\\d\\s:]*(\\w+).*", "$1");

See the regex demo. Since the string is always in this format, and is not that long, this approach is quite convenient to implement in Java.
See the online Java demo.
Details

*

*(?s) - a DOTALL modifier making . match any char including line break chars

*.*? - any 0+ chars, as few as possible

*STATE - substring STATE

*[\d\s:]* - 0+ digits, whitespaces and :

*(\w+) - Capturing group 1 (what we want to keep, later, we can refer to the value using $1 placeholder from the replacement pattern): 1+ word chars

*.* - any 0+ chars as many as possible (up to the string end).


text:
Q: How to obtain the variable except the options in bash scripts? I made a script and the usage should be:
bash test.sh -r chr1:1000-2000 -n 123 test_1.fq test_2.fq

I want to get the input test_1.fq test_2.fq at the end of input.
But when I used $* in the script, input=$*, I just got the whole input -r chr1:1000-2000 -n 123 test_1.fq test_2.fq.
Other options (-r -n) were obtained normally using getopts.
How could I keep only the last two words?

A: Just shift all the parameters until you just have two:
while (( $# > 2 )); do
   shift
done

echo "$@"

From the linked page:

The shift builtin command is used to "shift" the positional
  parameters by the given number n or by 1, if no number is given.

Note also that the way to use the given parameters is with $@, not $*.

A: Use shift:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html
It removes the left most parameters.   If you know the number you need to remove then this is the solution.  If you know how many you need after shifting then the other answer will work :)
$ ./a.sh 1 2 3 4 5 6 7
+ shift 4
+ echo 5 6 7
5 6 7


text:
Q: The lower input the higher output I want it so when user gives higher input, the output is smaller. I am making a gambling minigame, and this is what i need in table below. I dont know if there is any Math. function or something to make that.
INPUT | OUTPUT

94    |   1.01
47.5  |   2
0.01  |   9500

Doesnt need to be exact, just rough.

A: Your requirement seems to be an inverse proportion. That is, the output is inversely proportional to the input. A general equation that meets this behaviour is
output ∝ 1/x => output = k/x

So, a reciprocal of the input should do the trick. But, you might want to add a weighted factor to fine tune further.
For example,
output = 1/input;

or
output = 100/input // if you need a tuning factor for your needs.


text:
Q: Symfony2: Access the container in the repository I'm trying to show an user oriented choice list in a form and I don't manage to access to the container to get the current User.
I don't see how to get it in the Repository neither than in the Type.
Any Idea?

A: Let say you created a FormType class. You don't know how to pass the container in this object.
Create now your own type extended from FormType and pass the container through the constructor
class MyType extends FormType
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
}

In your config.yml, define your new type
mytype:
  class: ...\MyType
  arguments: ["@service_container"]
  tags:
      - { name: form.type }

Now, use MyType instead of FormType in all your controllers

A: Perhaps you can request the User object in the controller, and pass it on to the repository in the constructor?


text:
Q: Computed field result in odoo 10 I am working on student registration module. I want to to auto generate registration code and save it into database where as computed method having some issue.
1.. can't save Computed result in database.
2.. when i use store attribute with field and depends api then there is not increment in variable.
here is my code below.
reg_code = fields.Char(compute='code', string='Code', readonly=True)

@api.multi
def get_code(self):
    count = 0
    reg = "Reg #"
    for record in self:
        count += 1
        record.reg_code = reg + " " + str(count)
        if record.reg_code:
            count += 1
            record.reg_code = reg+" "+str(count)
        else:
            count += 1
            record.reg_code = reg+" "+str(count)

A: You can use sequence in Odoo.
find sequence in

Enable Active developer mode

Settings --> Sequence

Then add this code in your module:
change field as
reg_code = fields.Char(string='Code',required=True, copy=False, readonly=True, index=True, default= lambda self: self.env['ir.sequence'].next_by_code('student.registration'))

Create another xml file like if you want to create sequence by code.

shipping_sequence.xml

and add this code
<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data noupdate="1">

        <!-- Sequences for student.registration -->
        <record id="seq_student_registration" model="ir.sequence">
            <field name="name">Student Registration</field>
            <field name="code">student.registration</field>
            <field name="prefix">Code-</field>
            <field name="padding">1</field>
            <field name="company_id" eval="False"/>
        </record>

    </data>
</odoo>


text:
Q: PHPStorm code completion fails for array within array I have this basic code:
    $test = array(
    'nested' => array('test' => 'nada');
);

    function doit()
    {
        global $test;
        $test['nested'][''];
    }

PHPStorm correctly suggests me 'nested' when I press Ctrl+Space
However, I found no way to make it suggest 'test' as member of the 'nested' array.
PHPStorm does not seem to be aware that nested is an array and also has members.
Is that a bug, did I do something wrong ?
According to comment I tried another solution to get completion support:
With no luck either
    class test
    {
      public static $nested = array('test' => 'nada');
}

    function doit()
    {
        $completeme = test::$nested;
        $completeme['']; // no completion working

        /** @var test::nested $completeme */
        $completeme = test::$nested;
        $completeme['']; // no completion working
    }

Same issue for me at the IDE, this time it is an array inside a class.
test::nested[''] << this works, I get completion. But as soon as I make a copy of it I found no way to get completion again or to specify the type using phpdoc.

A: This feature is not implemented (original array keys support ticket).
AFAIK even remembering keys for first level array adds some noticeable overhead (memory + CPU -- depends on actual project and how heavily arrays/variables are used). Considering this + the fact that in majority of cases first level is enough, the implementation for other levels was simply put on hold.
https://youtrack.jetbrains.com/issue/WI-6845 -- star/vote/comment to get notified on progress.


text: Q: Subclassing AssetsManager.AssetInputStream to read it with BitmapFactory.decodeStream I want to override read() in AssetsManager.AssetInputStream to make some cross-read work (simple xor), but as it is inner class I can't just extend it, what should I do? And can I then create an instance of such class with existing instance of its outter class - Asset Manager?


text:
Q: Cumulative application of a gsub sequence in R I'm working on a project dealing with chess games. After some processing of the data I need to get the FEN (https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) notation of a particular position. I've already written the code for each piece FEN encoding, but I'm having a hard time encoding the character that represents the number of consecutive squares that are not occupied.
As an example, take the following FEN code:
"rnbq1rk1/pppp1ppp/1b11pn11/11111111/11PP1111/11111NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"

Each 1 represents an unoccupied square inside the chess board. So, for example: 11111111 is telling us that this row inside the board is not occupied by pieces.
Problem is, R packages that plot chess boards using FEN as input don't like this notation and they want the more suscint, original notation where all the 1s are represented by one character: the sum of all this consecutive 1s. For the previous example, that would be:
"rnbq1rk1/pppp1ppp/1b2pn2/8/2PP4/5NP1/PP2PPBP/RNBQ1RK1 w KQkq c6 0 2"

Note that, for example, the 11111111 sequence was replaced by 8, the sum of all consecutive 1s
I've tried use mapply with gsub to get the replacements done, but it iterates over the strings applying the pattern-replacement pair one at a time. The result is the following:
Code:
pattern <- c("11111111","1111111","111111","111111","1111","111","11")
replacement <- c("8","7","6","5","4","3","2")
FENCodeToBeChanged  <-  "rnbq1rk1/pppp1ppp/1b11pn11/11111111/11PP1111/11111NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
mapply(gsub,pattern,replacement,FENCodeToBeChanged)

Result:
                                                                              11111111
  "rnbq1rk1/pppp1ppp/1b11pn11/8/11PP1111/11111NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
                                                                           1111111
 "rnbq1rk1/pppp1ppp/1b11pn11/71/11PP1111/11111NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
                                                                            111111
"rnbq1rk1/pppp1ppp/1b11pn11/611/11PP1111/11111NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
                                                                            111111
"rnbq1rk1/pppp1ppp/1b11pn11/511/11PP1111/11111NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
                                                                              1111
       "rnbq1rk1/pppp1ppp/1b11pn11/44/11PP4/41NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
                                                                               111
   "rnbq1rk1/pppp1ppp/1b11pn11/3311/11PP31/311NP1/PP11PPBP/RNBQ1RK1 w KQkq c6 0 2"
                                                                                11
       "rnbq1rk1/pppp1ppp/1b2pn2/2222/2PP22/221NP1/PP2PPBP/RNBQ1RK1 w KQkq c6 0 2"

As you can see, it does the replacements but one at a time and for the next pattern-replacement pair it starts from the original string, it does not accumulate them in the sequence that I've specified in the pattern - replace vectors.
I´ve tried the strategies described here and here, but they also didn't work. As it mention in the last link, I'm trying to avoid at all cost to loop over gsubs to get the job done, as it seems quite inefficient.
Any thoughts on how to proceed?
Thanks!

A: The issue with mapply is that it is looking at a fresh copy of the FEN string for each replacement, which is not what you need. I think you can use a Reduce mindset:
(BTW, your pattern for "5" has 6 ones, this fixed that.)
pattern <- c("11111111","1111111","111111","11111","1111","111","11")
Reduce(function(txt, ptn) gsub(ptn, as.character(nchar(ptn)), txt), pattern, init=FENCodeToBeChanged)
# [1] "rnbq1rk1/pppp1ppp/1b2pn2/8/2PP4/5NP1/PP2PPBP/RNBQ1RK1 w KQkq c6 0 2"

To be able to reduce over multiple arguments takes a little bit of work, usually iterating along a list of pairs or such. With this problem, it's easy enough to replace a pattern with its length instead of including another vector of strings, ergo nchar(ptn). (Technically as.character(.) is not required as gsub will implicitly convert it, but I wanted to be a bit "declarative" in that that's what I want. There are many tools in R that are less deterministic in this way (e.g., ifelse). Style.)


text:
Q: How can I define a code using the Hamming algorithm? I've got this request: Using any alphabetical and numerical symbols, define a code in which each symbol of interest is associated with the corresponding binary configuration. The code must use 5 bits, be redundant, and be characterized by a Hamming distance of 1. Identify the cardinality of the defined code. Eventually, does the code exist?
I don't have a clear idea about how to do this, could anyone help?
Thank you!


text:
Q: autodesk translate to svf failed I was following the steps from this tutorial to convert a file to svf format in order to be able to view it using the autodesk viewer.
https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/prep-file4viewer/
I was trying to convert a dwg file to svf. I got to task 3 step 1 with no problem, but in step 2, when I make the request, I get the following response :
{"urn":"dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6YnVja2V0MTJzL3Zpc3VhbGl6YXRpb25fLV9hZXJpYWwuZHdn",
"derivatives":[{"hasThumbnail":"false","name":"visualization_-_aerial.dwg","progress":"complete",
"messages":[{"type":"error","code":"AutoCAD-InvalidFile",
"message":"Sorry, the drawing file is invalid and cannot be viewed.
\n- Please try to recover the file in AutoCAD, and upload it again to view."},
{"type":"error","message":"Unrecoverable exit code from extractor: -1073741831",
"code":"TranslationWorker-InternalFailure"}],
"outputType":"svf","status":"failed"}],
"hasThumbnail":"false","progress":"complete","type":"manifest","region":"US","version":"1.0",
"status":"failed"}

I tried to view the file using their online viewer and was able to view it perfectly so I know that there's nothing wrong with the file. What could be the possible reason for this error?
Edit :
After I obtained access token and created bucket, I used this request to upload file to the bucket (Step 2 of Task 2) :
curl -X PUT -v 'https://developer.api.autodesk.com/oss/v2/buckets/{bucketname}/objects/visualization_-_aerial.dwg' -H 'Authorization: Bearer {TOKEN}' -H 'Accept-Encoding: gzip, deflate' --data-binary '{PATH_TO_FILE}/visualization_-_aerial.dwg'

The response to this is 200OK.
Then I used the online tool given in the tutorial to convert urn to base 64 encoded urn.
Here's the job post request (Step 1 of task 3) I sent :
curl -X POST  'https://developer.api.autodesk.com/modelderivative/v2/designdata/job' -H 'Authorization: Bearer {TOKEN}' -H 'x-ads-force: true' -H 'Content-Type: application/json' -d '{ "input": { "urn": "{URN}", "compressedUrn": true, "rootFilename": "visualization_-_aerial.dwg" }, "output": { "destination": { "region": "us" }, "formats": [{ "type": "svf", "views": ["2d", "3d"], "advanced": {"generateMasterViews": true} } ] } }'

the response to this is "success"
and the get request to check the status of the translation :
curl -X GET 'https://developer.api.autodesk.com/modelderivative/v2/designdata/{URN}/manifest' -H 'Authorization: Bearer {TOKEN}'

the response to this is what I included above.
The file is actually uploaded to the bucket and I was able to view it at https://oss-manager.autodesk.io/# but even there, it shows translation failed.
Edit 2:
Here's an image of the response from https://oss-manager.autodesk.io/ get manifest request (used dev tools to get this)
enter image description here

A: Based on the comments added to the previous answer it seems like the issue is with the upload part. As you can see in the tutorial it's using
--data-binary '@PATH_TO_DOWNLOADED_ZIP_FILE'

The @ symbol is important, without it you'll get a reply like this
{
"bucketKey" : "adam",
"objectId" : "urn:adsk.objects:os.object:adam/test.dwg",
"objectKey" : "test.dwg",
"sha1" : "cb54c0750e9201bbfa6da6adad6b496bec11a111",
"size" : 27,
"contentType" : "application/x-www-form-urlencoded",
"location" : "https://developer.api.autodesk.com/oss/v2/buckets/adam/objects/test.dwg"
* Connection #0 to host developer.api.autodesk.com left intact
}

Look at the size: 27 - that's definitely not right. And so when I try to translate the file I get the same error messages that you got.
However, if I add the @ symbol then all is good:
curl -X PUT -v 'https://developer.api.autodesk.com/oss/v2/buckets/{bucketname}/objects/test.dwg' -H 'Authorization: Bearer {TOKEN}' -H 'Accept-Encoding: gzip, deflate' --data-binary '@/Users/nagyad/Downloads/test.dwg'

Note: I'm on a Mac, on Windows the path will look a bit different
Reply I got this time:
{
"bucketKey" : "adam",
"objectId" : "urn:adsk.objects:os.object:adam/test.dwg",
"objectKey" : "test.dwg",
"sha1" : "d17e9156c948caed3a98788836e6c1f3d5fddadc",
"size" : 55727,
"contentType" : "application/x-www-form-urlencoded",
"location" : "https://developer.api.autodesk.com/oss/v2/buckets/adam/objects/test.dwg"
* Connection #0 to host developer.api.autodesk.com left intact
}

And this time when I tried to translate the file, it succeeded.

A: Change the compressedUrn to false if you working with single file or if you working with zip file so, set to true also mention rootFilename file name(root file name) in response body.


text:
Q: CORS policy error when trying to call custom search analyzer of azure search from ajax or browser CORS policy error when trying to call custom search analyzer of azure search from ajax or browser
I have azure search service enabled on azure account. Trying to search queries with azure search from client call or ajax and which is happening very smoothly. I have some requirement to analyze search query before searching actual search text, so I have created a custom analyzer which when I am trying to call from browser or ajax I am getting CORS policy error on browser.
Tried already:
I have enabled CORS for index in which i have created the custom analyzer
I have used npm library that is azure-search.min.js having function to call for analyzer (client.testAnalyzer): https://www.npmjs.com/package/azure-search-client

   //Sample 1:
  var index2 = AzureSearch({
                          url: k2,
                          key: k1,
                          version: "2019-05-06"
                 });
    var analyzerdata = {
        "text": searchTextData,
        "analyzer": sessionStorage.getItem('analyz')
      }
    index2.testAnalyzer("fastampsearchindex", analyzerdata, function (err,
    tokens) {
        if (!isNullorEmpty(tokens)) {
            //phrases = data.map(x=>x.token);
        }
     });

   //Sample 2:
     var urlTokenizer="https://mysearchurl.search.windows.net/indexes/indexname/analyze?api-version=2019-05-06";
     var analyzerdata = {
        "text": searchTextData,
        "analyzer": sessionStorage.getItem('analyz')
    }
      $.ajax({
        type: "POST",
        url: url2,
        dataType: 'json',
        crossDomain:true,
        data: analyzerdata,
        headers: {
            "api-key": k1,
            "Content-Type":"application/json"
        },
        success: function (response) {
            console.log(response);
        },
        error: function (xhr, status, message) {
            $('.loader').css('display', 'none');
            var err = "Error " + " " + message;
            if (xhr.responseText && xhr.responseText[0] == "{")
                err = JSON.parse(xhr.responseText).Message;
            toastr.warning(err);
        }
      });

analyzer should be called from browser instead of application to avoid round trip to azure search service via web app service where application is hosted


text:
Q: Как работать со вложенными JSON объектами postgreSQL? Занимаюсь тем, что переписываю свою базу с SQL на PostreSQL. Имею вот такой синтаксис:
SELECT JSON_VALUE(wr.jsonDetails, '$.risk.score') FROM WalletRisks wr;
И это работает, я получаю значения поля score:
50
50
50
50

Как мне написать этот же запрос, но на PostreSQL? Единственное, что у меня пока получилось это:
select WalletRisks.jsonDetails ->> 'risk' from WalletRisks;
И как результат:
{"level":2,"score":50,"verdict_time":1610803292}
{"level":2,"score":50,"verdict_time":1609775813}
{"score":50,"verdict_time":1623061355,"level":2}
{"level":2,"score":50,"verdict_time":1608741456}

Дело в том, что это получается вложенный объект, и мне надо получить доступ к полю объекта внутри другого объекта. Как мне это сделать на PostgreSQL?

A: select WalletRisks.jsonDetails -> 'risk' ->> 'score' from WalletRisks;


text:
Q: Is it possible to access an iPhone over SSH on 3G? I am trying to see if I can SSH to my iPhone using the 3G network. So, given my IP, I am trying to make contact through SSH, using the defined port (which is no longer 22, I changed it).
It all works fine on my private wifi network.
For some reason, it doesn't on 3G...
Any ideas ?
Thanks

A: a) Unless you have jailbroken your device, iOS doesn't have an SSH server to run.
b) If you have jailbroken your device, it will not be possible to SSH into your iPhone over cellular. You are behind one of the most complex NAT setups there is. When you move between towers, and lose signal, you lose your lease to a unique ID with the cellular network (like an IP). However, every time your connection is re-established with your carrier, you're connected to a new tower and your connection is routed differently through another NAT and finally out somewhere, probably in another state.
In researching this alone, over the course of 10 minutes, my iPhone returned 2 different IPs from the internet, one in Florida, one in Pennsylvania.
Short answer: Wi-Fi = yes | Cellular = no

A: Yes, you can, if you use a VPN service, that assigns you a real, unmasked IP address (which will be accessible from the internet) or a VPN to your local network.