text:
Q: rethinkdb java api outofmemoryerror exception i have a big document file ( ~1.5 gb ~430.000 line). The program read document file line by line and insert each row into rethinkdb. But I get this error between 11000-12000 lines. What would be the reason?

java.lang.OutOfMemoryError: unable to create new native thread    at
  java.lang.Thread.start0(Native Method) ~[na:1.8.0_171]    at
  java.lang.Thread.start(Thread.java:717) ~[na:1.8.0_171]   at
  java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:957)
  ~[na:1.8.0_171]   at
  java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1367)
  ~[na:1.8.0_171]   at
  java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
  ~[na:1.8.0_171]   at
  java.util.concurrent.Executors$DelegatedExecutorService.submit(Executors.java:678)
  ~[na:1.8.0_171]   at
  com.rethinkdb.net.Connection.connect(Connection.java:105)
  ~[rethinkdb-driver-2.3.3.jar:na]  at
  com.rethinkdb.net.Connection.reconnect(Connection.java:94)
  ~[rethinkdb-driver-2.3.3.jar:na]  at
  com.rethinkdb.net.Connection.reconnect(Connection.java:83)
  ~[rethinkdb-driver-2.3.3.jar:na]  at
  com.rethinkdb.net.Connection$Builder.connect(Connection.java:422)
  ~[rethinkdb-driver-2.3.3.jar:na]  at
  com.erdem.rethinkdb.inserter.config.RethinkDBConnectionFactory.createConnection(RethinkDBConnectionFactory.java:17)
  ~[classes/:na]    at
  com.erdem.rethinkdb.inserter.service.InserterService.insertData(InserterService.java:33)
  ~[classes/:na]    at
  com.erdem.rethinkdb.inserter.service.InserterService.insertData(InserterService.java:38)
  ~[classes/:na]    at
  com.erdem.rethinkdb.inserter.InserterApplication.batchInsert(InserterApplication.java:168)
  [classes/:na]     at
  com.erdem.rethinkdb.inserter.InserterApplication.fileModeIndex(InserterApplication.java:97)
  [classes/:na]     at
  com.erdem.rethinkdb.inserter.InserterApplication.run(InserterApplication.java:57)
  [classes/:na]     at
  org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:788)
  [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]     at
  org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:778)
  [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:335)
  [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
  [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
  [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]     at
  com.erdem.rethinkdb.inserter.InserterApplication.main(InserterApplication.java:37)
  [classes/:na]

RethinkDBConnectionFactory.java
public class RethinkDBConnectionFactory {

    private final RethinkDB r = RethinkDB.r;

    private String host;

    public RethinkDBConnectionFactory(String host) {
        this.host = host;
    }

    public Connection createConnection() {
        return r.connection().hostname(host).connect();
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

}

InserterService
@Service
public class InserterService {

    protected final Logger log = LoggerFactory.getLogger(InserterService.class);

    private final RethinkDB r = RethinkDB.r;

    @Autowired
    private RethinkDBConnectionFactory connectionFactory;

    private ObjectMapper oMapper = new ObjectMapper();

    @SuppressWarnings("unchecked")
    public void insertData(Activity activity) {
        oMapper.setSerializationInclusion(Include.NON_NULL);
        Map<Object, Object> map = oMapper.convertValue(activity, Map.class);
        r.db("test").table("twitter").insert(map).run(connectionFactory.createConnection());
    }

}

RethinkDBConfiguration
@Configuration
@ComponentScan(basePackages = { "com.erdem.rethinkdb.inserter.*" })
@PropertySource("classpath:application.yml")
public class RethinkDBConfiguration {

    @Value("${rethinkdb.host}")
    private String DBHOST;

    @Bean
    public RethinkDBConnectionFactory connectionFactory() {
        return new RethinkDBConnectionFactory(DBHOST);
    }

    @Bean
    public DbInitializer dbInitializer() {
        return new DbInitializer();
    }
}

A: I don't see, where or how the file is read; I'd presume, that the error is there.  You can always try using Eclipse MAT, and a -XX:+HeapDumpOnOutOfMemoryError to get the heapdump, and just check, what's wrong.

A: Try inserting those objects line per line, at this point you're mapping 430k lines and keeping them in memory which might cause issues when you're inserting them into the DB
Or increase JVM memory allocation


text:
Q: React-Native image seems to load but it shows blank I'm using an S3 bucket as origin for my app's images. Storage.get seems to be working fine, as when I copy and paste the link on the browser, it loads the image correctly. However, the Image tag seems not to be working...
It seems to load the image correctly, as it shows its space in the app, but it doesn't show the actual image.
Here is the code:
  render() {
        return(
            <View style={Styles.vContainerF}>
                { this.state.gmpLogoURL ?
                    <Image  style={{flex:1}}
                            resizeMode='contain'
                            source={{uri: this.state.gmpLogoURL }}
                     />
                : null }

This is the view style config:
  vContainerF: {
    flex: 1,
    padding: 10,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },

Any hints on what could be the issue?
Thanks in advance folks!

A: As described in react-native image doc :

Note that for network and data images, you will need to manually specify the dimensions of your image!

So add height and width to your image style :
<Image
  style={{ flex: 1, height: 100, width: 100 }}
  resizeMode='contain'
  source={{ uri: this.state.gmpLogoURL }}
/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieving data in status of active with a wild card criteria (Mysql) I have problem retrieving data in database.
Question: Why I still retrieve the data of having store_status DELETED but my condition is store_status = 'Active' only
This is my script look like
SELECT * FROM store_locator WHERE store_status = 'Active' AND store_address LIKE '%Q%'
OR branch_name LIKE '%Q%' OR city LIKE '%Q%'

And the sample image
sample image

A: It's likely happening because either your branch_name has a Q in it or the city has a Q in it.
The OR conditions ensure that records can still be shown even though the AND conditions are false.
Your query is essentially running this:
SELECT *
FROM store_locator
WHERE (store_status = 'Active'
  AND store_address LIKE '%Q%')
OR (branch_name LIKE '%Q%')
OR (city LIKE '%Q%')

So if any of these conditions are true, the record will be shown:

*

*store_status = 'Active' AND store_address LIKE '%Q%'

*branch_name LIKE '%Q%'

*city LIKE '%Q%'

If this is not the logic you wanted, then you can adjust your query to include brackets () around the AND/OR criteria that you want to use. If you only want to see active records where any of those fields have a Q in it, you may want this query:
SELECT *
FROM store_locator
WHERE store_status = 'Active'
AND (store_address LIKE '%Q%'
OR branch_name LIKE '%Q%'
OR city LIKE '%Q%')

Note that the brackets have enclosed all of the three LIKE '%Q%' criteria in a single condition.

A: It's because you didn't group your OR condition,
IMO this should be your right query to use:
SELECT *
FROM store_locator
WHERE store_status = 'Active'
    AND (store_address LIKE '%Q%' OR branch_name LIKE '%Q%' OR city LIKE '%Q%');


text:
Q: How do I reverse a running animation? When the Button is touched, it starts a zoom animation.
Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoomin);
view.startAnimation(zoomIn);

The zoomin.xml code:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillEnabled="true"
    android:fillAfter="true">
    <scale
        android:fromXScale="1.0"
        android:toXScale="1.3"
        android:fromYScale="1.0"
        android:toYScale="1.3"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="200"
        android:interpolator="@android:anim/accelerate_interpolator"/>
</set>

But if the Button is released during this still running animation, it should reverse the animation from this point in time.
How can i achieve that?

A: You could use ViewPropertyAnimator to achieve something like this.
For example:
Button button = (Button) findViewById(R.id.yourButton);

button.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        // adjust the scale and duration values according to your needs

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            v.animate().scaleX(2).scaleY(2).setDuration(2000);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            v.animate().scaleX(1).scaleY(1).setDuration(2000);
        }
        return false;
    }
});


text:
Q: Time required for the formation of ice of some thickness in a lake
The air above a large lake is at –2°C, while the water of the lake is at 0°C. Assuming that only thermal conduction is important and using relevant data selected from the given below find how many hours it would take for a layer of ice 10 cm thick to form on the lake's surface.
Data(where $w$=water and $i$=ice):
$K_w=5.6Wm^{-1}k^{-1},$ $K_i=2.3Wm^{-1}k^{-1}$
$L_i=3.3*10^5J{kg}^{-1},$ $\rho_w=10^3kg m^{-3}$
$\rho_i=920kgm^{-3}$

This is how I solved.
Let the area of crossection of lake be A and same throught its depth.
Let the layer of ice formed at time $t$ be $x$ where $t$ is in seconds and $x$ is in meters.

Now in time $dt$, $dm$ mass of water will be converted to ice but $dm=Adx\rho_w$.
So heat lost by water is $$dmL_i=A\rho_wL_idx$$
That amount of heat is transferred to the atmosphere through ice.
But heat transfer through ice is $$\frac{dq}{dt}=\frac{K_iA\Delta\theta}{x}$$
So heat lost by water is equal to heat transferred by ice.
$$A\rho_wL_idx=\frac{K_iA\Delta\theta}{x}dt$$
Now on solving the differential equatio we get $$t=\frac{x^2\rho_wL_i}{2K_i\Delta\theta}$$
On substituing the values answer comes out to be 99.6 hours.
Where as the solution of the question has taken $\rho_i$ instead of $\rho_w$ which I took to solve the question.
This is here where I am stuck and unable to comprehend and understand why. After giving it an enough thought both seems to be correct.
Hence the final answer comes out to be 92 hours.

A:
Assuming that only thermal conduction is important [...]

That's a very dicy assumption. There certainly is convection at the ice/air interface but assuming the water and ice are at the same temperature, convection at that boundary is $0$.
We can deal with that with a so-called overall heat transfer coefficient $U$:
$$\frac{\mathrm{d}q}{\mathrm{d}t}=UA\Delta\theta$$
$U$ is found using the principle of parallel heat resistors. $h_{ia}$ is the ice-to-air convection heat transfer coefficient:
$$\frac{1}{U}=\frac{1}{h_{ia}}+\frac{x}{K_i}$$
$$A\rho_iL_i\mathrm{d}x=UA\Delta\theta \mathrm{d}t$$
$$\frac1U=\frac{K_i+h_{ia}x}{h_{ia}K_i}$$
$$U=\frac{h_{ia}K_i}{{K_i+h_{ia}x}}$$
It then follows that:
$$\rho_iL_i\mathrm{d}x=\frac{h_{ia}K_i}{{K_i+h_{ia}x}}
\Delta\theta \mathrm{d}t$$
$$\rho_iL_i\left(K_i+h_{ia}x\right)\mathrm{d}x=h_{ia}K_i\Delta \theta \mathrm{d}t$$
Integrate as appropriate.

A: Note that the distance $x$ that you considered is the thickness of ice, not water. Hence $dx$ will be the elemental increase in thickness of ice, so we will use $\rho_i$ and not $\rho_w$.
The rest of your calculation is correct.


text:
Q: What's the origin of "hung for a toad"? Where is it used? The phrase I have heard most often from my father usually went like this:

Well I'll be hung for a toad!

Where did this saying come from and has anyone else heard it?  My dad's dad & mother were respectively Scots & Irish if that helps.
He would exclaim that saying when something was a surprise.
It's not mentioned in online dictionaries such as Merriam Webster.

A: meta: Look up the word toad in a good dictionary, not the phrase.
*"Hung for a toad" is not a set phrase or idiom.

A toad is a [2 A] contemptible or detestable person (used as a general term of abuse)

"Well I'll be hung for a toad!"
should likely mean that one will get severely punished for behaving in a contemptible or detestable manner.


text:
Q: How much space do large thrusters require? Space Engineer's wiki suggests that Small Thruster on a Small Ship destroys an area of 3x3x4 (width, height, depth) behind the exhaust, assuming the space is completely enclosed and filled. A small thruster is capable of dealing damage of up to 5 blocks depth over open space.
However, the wiki doesn't specify whether large thrusters work the same way, and damage the same area. Since a large block is 5x5x5 of a small block, it's reasonable to assume a destruction zone of 15x15x20.
Does anyone know for sure if the destruction zone works that way? I can always test manually, but figured I'd see if stackoverflow knew first.

A: You're not entirely clear on what your asking, but given the numbers you're throwing out it appears you're asking about the Small Thruster for Large Grids.  If that is the case the Official Space Engineer's Wiki claims that specific engine will do damage 2 (large) blocks (5m) deep directly behind the engine and, if that area is blocked, splash damage to adjacent blocks.  If an Engine is one of those adjacent blocks, "Fun" ensues.
Alternatively Large Thrusters do damage 5 blocks deep (2.5m for small grids, 12.5m for large grids).  The information is in a table on the bottom of the page I've linked.
I've also heard that you might want to give extra space around the exhaust path for particularly nimble ships to avoid swinging a trailing part of your craft into recently ejected exhaust.

P.S. I generally avoid wikia.com sites when there is a viable alternative, as they are generally slow to plagiarize their content from more authoritative or up-to-date sources.


text:
Q: How to enable synchronization 2 when using Vulkan API 1.2? Up until now, I used the the latest Vulkan API available on my development machine (1.3.201).
VK_CHECK(vkEnumerateInstanceVersion(&_apiVersion)); // returns 1.3.201
After some struggles I managed to use synchronization 2 as a core feature (functions without KHR).
But now, I wish to work with API version 1.2 to be compatible with more devices.
So when initializing VkApplicationInfo I set a lower version to the apiVersion field:
appInfo.apiVersion = VK_MAKE_API_VERSION(0, 1, 2, 0);
In order to use synchronization 2 extension, I pass the following extensions & layers to vkCreateInstance:
Extensions:

*

*VK_KHR_surface

*VK_KHR_win32_surface

*VK_KHR_get_physical_device_properties2

*VK_KHR_get_surface_capabilities2

*VK_EXT_debug_utils

Layers:

*

*VK_LAYER_KHRONOS_synchronization2

*VK_LAYER_KHRONOS_validation

And these are the extensions and layers I pass to vkCreateDevice:

*

*VK_KHR_create_renderpass2

*VK_KHR_synchronization2

*VK_KHR_swapchain

Layers:

*

*VK_LAYER_KHRONOS_validation

This is my device Initialization code:
    VkPhysicalDeviceFeatures deviceFeatures{ };
    VkPhysicalDeviceVulkan12Features features12{};
    features12.sType = VkStructureType::VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
    features12.timelineSemaphore = true;

    VkDeviceCreateInfo deviceCreateInfo
    {
        .sType = VkStructureType::VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
        .pNext = &features12,
        .flags = VkDeviceCreateFlags{},
        .queueCreateInfoCount = static_cast<uint32_t>(createDesc.queu_create_info.size()),
        .pQueueCreateInfos = createDesc.queu_create_info.data(),
        .enabledLayerCount = static_cast<uint32_t>(config.required_layers.size()),
        .ppEnabledLayerNames = config.required_layers.data(),
        .enabledExtensionCount = static_cast<uint32_t>(config.required_extentions.size()),
        .ppEnabledExtensionNames = config.required_extentions.data(),
        .pEnabledFeatures = &deviceFeatures
    };

Yet, when calling vkCmdPipelineBarrier2KHR I get a validation error:
Validation Error: [ VUID-vkCmdPipelineBarrier2-synchronization2-03848 ] Object 0: handle = 0x20b77c136f0, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0xa060404 | vkCmdPipelineBarrier2KHR(): Synchronization2 feature is not enabled The Vulkan spec states: The synchronization2 feature must be enabled (https://vulkan.lunarg.com/doc/view/1.3.236.0/windows/1.3-extensions/vkspec.html#VUID-vkCmdPipelineBarrier2-synchronization2-03848)


text:
Q: Hitting time probability in a Random Walk with possibility to die. A Random Walker can move of one unit to the right with probability $p$, to the left with probability $q$ and it can jump again to the starting point with probability $r$ and die. Naturally $p+q+r=1$. The walker starts moving from $x=0$ at time $t=0$. Two barriers are located in  $x=n$ and $x=-n$.
Let's call $\tau (n)$ the first time the random walk hits one of the two barriers. Is there a way to determine how does $E[ \tau ] (n)$, (i.e. the expected time the walker hits one of the two barriers) depend on $n$?
I would be happy if for some values of the parameters $p$, $q$, $r$, the expectation $E[ \tau ] (n)$ grows exponentially with $n$, but probably it's not like this...

A: First, let me elaborate on my comment. If $X$ occurs with probability $\rho$, then the expected waiting time before you first see a streak of length $\ell$ $X$s in a row in independent trials is exponential in $\ell$, $\frac{\rho^{-\ell}-1}{1-\rho}$. If you get $2n-1$ right steps in a row, then you must have hit the barrier, which gives an exponential upper bound for the expected first hitting time, $\frac{p^{1-2n}-1}{q+r}$. On the other hand, to reach a barrier, you need a streak of at least $n$ non-deaths. Again, the waiting time before you first see such a streak is exponential for $r\gt 0$, $\frac{(p+q)^{-n}-1}{r}$. If $q=0$ or $p=0$, the lower bound is sharp.
Imagine we release a particle at $0$ once, and watch it until it reaches a barrier or dies. Let the average number of steps it takes be $s$, and let the probability that it dies be $d$. Then the expected number of steps before some particle hits a barrier is $s(1+d+d^2+...) = \frac{s}{1-d}$. Both $s$ and $d$ can be calculated analytically, but I think it's easier to let Mathematica do it. Here are Mathematica commands which find them:
ProbReachesBarrier[k_] := Evaluate[a[k] /.
    RSolve[{a[k] == p a[k + 1] + q a[k - 1], a[n] == 1, a[-n] == 1},
           a[k], k][[1]] ]
ProbDies = Simplify[1 - ProbReachesBarrier[0]]

Let $\alpha = \frac{1+\sqrt{1-4pq}}{p}, \beta = \frac{1-\sqrt{1-4pq}}{p}$.
$$d = - \frac{(2^n-\alpha^n)(2^n-\beta^n)}{2^n(\alpha^n + \beta^n)}$$
ESteps[k_] := Evaluate[b[k] /.
      RSolve[{b[k] == 1 + p b[k + 1] + q b[k - 1], b[n] == 0, b[-n] == 0},
             b[k], k][[1]] ]
s = Simplify[ESteps[0]]

$$ s = - \frac{(2^n - \alpha^n)(2^n-\beta^n)}{r 2^n (\alpha^n + \beta^n)} = \frac{d}{r}$$
$$\frac{s}{1-d} = - \frac{(2^n-\alpha^n)(2^n-\beta^n)}{r (4^n + \alpha^n \beta^n)}.$$


text:
Q: Does a .net bool[] use one bit or one byte per item? In .net, does a bool[] use one bit or one byte per array item? ie, does it automatically pack the bool values? I know a single bool uses 1 byte, but maybe the CLR has a special case for bool[]...

A: Concerning size, it stores an array of bools as an array of bytes, no special case there.
You might want to check the BitArray class if you want to pack data.

A: What you want is a BitArray. bool[] gets no special treatment by the CLR.

A: One byte per value. I'm trying to find where this is actually specified (if indeed it is) but it's true for the current .NET CLR.
EDIT: This is sort of confirmed by printing sizeof(bool) which prints 1 - although the sizeof operator in C# doesn't end up calling the sizeof IL instruction...


text:
Q: prevent a variable form being edited by child based on condition class AppController extends Controller {

/**
 * @var $IsAjax weather request is ajax or not
 */
public $RequestType = 'NORMAL'; //make this read only by child

    function __construct()
    {
      if(isAjax())
        $RequestType ='AJAX';
        $layout = 'ajax'; //this var should not be editable further i.e read only by child
    }

}

If request is ajax I want it not to be editable. If it fails $layout should be editable by children.
Also is there a way to make the variable readonly for child.

A: You can control access to the member variable though set/get methods and make the variable private:
class ParentClass
{
    private $requestType = "Normal";

    protected function getRequestType()
    {
        return $this->requestType;
    }

    protected function setRequestType( $newType )
    {
        if ( $this->requestType != "AJAX" )
        {
            $this->requestType = $newType;
        }
    }
};

A: One method to get readOnly properties is to set their visibility to private and then use magic methods __get and __set to access them. for ex:
class A{
  private $readOnly = 'readOnly';
  function __get($key){
    if( $key === 'readonly')
      return $this->{$key};
  }
}

then readonly may be accessible for reading by anyone but only the A class may write to it


text:
Q: Not able to detect the CheckBox checked method in GridView I am adding the checkbox in gridview.I want to get the third cell value from each row.I am using the button click to post back to server which is outside of the gridview.
My Code:
(ASPX Part)
<asp:TemplateField HeaderStyle-Width="8px">
 <ItemTemplate >

                      <asp:CheckBox runat="server" ID="chkRow"/>
 </ItemTemplate>
 </asp:TemplateField>
'It is outside of the Gridview
<asp:Button ID="btnGetSelected" runat="server" Text="Get selected records"  OnClick ="GetSelectedRecords" />

(Vb.net Part)
Protected Sub GetSelectedRecords(sender As Object, e As EventArgs)
    Dim dt As New DataTable()
    Dim colSelRowKeys As New Collection
    colSelRowKeys.Clear()
    Dim s As String
    For Each row As GridViewRow In GridADFMain.Rows
 If (CType(row.FindControl("chkRow"), CheckBox)).Checked Then
            s = row.Cells(3).Text
            colSelRowKeys.Add(s)
 End If
    Next
    Session.Add("colSelRowKeys", colSelRowKeys)
End Sub

I am not able to enter the if checked condition.

A: Your posted code works well in test. Make sure that you are not rebinding your Gridview at post back. In rebinding check boxes values will be overwritten. Check where you databind the gridview, normally in Page_Load, wrap the code in If Not IsPostBack like below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        'Code to get data
        '    ..........
        ' BindGridView()
        GridADFMain.DataBind()
    End If
End Sub

Hope it helps!


text:
Q: In Watson conversation service, how to prevent from matching to the wrong intent, example is included I have a simple flow where I want to give the response based on the input to an entity ( in my case @language). Why is the response mapping to an intent ?

A: The issue is with the second condition you have created.
@language:java AND #how_to_develop

When the user enters in the text "Java", the intent of the text is checked again. Because the intent is different, it will never hit that node.
You can solve this by just setting your condition to:
@language:java

As you have already detected the earlier intent.
In your application, you can stop the second response from doing an intent check by passing back the intents[] object from the previous call.


text:
Q: Scraping using beautiful soup not working for a particular URL as expected I was trying to scrape some data off from a site using beautifulsoup on python 3.5(i'm working on eclipse) and requests from the site 'http://www.transfermarkt.com/arsenal-fc/startseite/verein/11/saison_id/2015'
which has some stats for footballers.
my code:
from bs4 import BeautifulSoup
import requests
r=requests.get('http://www.transfermarkt.com/arsenalfc/startseite/verein/11/saison_id/2015')
soup = BeautifulSoup(r.content, 'html.parser')
print (soup.prettify())

I expect a neat and pretty looking html code but all i get as output is this:

  <title>
   404 Not Found
  </title>

    404 Not Found

    nginx

For a different url it works. I have tried a couple of other url's and it worked. But not for this one. Am I doing something wrong. Any suggestion is appreciated. Thanks

A: You should use a user-agent to make the website think the request comes from a browser. This worked for me:
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
r=requests.get('http://www.transfermarkt.com/arsenalfc/startseite/verein/11/saison_id/2015', headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
print(soup.prettify())


text:
Q: scroll to particular category position in recyclerview I want to scroll to item id ==5 after loading recyclerview and I directly set item id in setTargetPosition....Please help me if any one has better clue for it.As per response I want to directly scroll to  Sandwich Category after loading recyclerview....
this my setAdapter code;
                try {
                JSONArray jsonArray = arrayList.get(0);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jObj = jsonArray.getJSONObject(i);
                    String catName = jObj.getString("CategoryName");
                    String catId = jObj.getString("CategoryID");
                    Category cat1 = createCategory(catName, Integer.parseInt(catId));
                    JSONArray jProductDetails = jObj.getJSONArray("ProductDetails");
                    ArrayList<HashMap<String, String>> productdetaildata = new ArrayList<HashMap<String, String>>();
                    for (int j = 0; j < jProductDetails.length(); j++) {
                        JSONObject jP = jProductDetails.getJSONObject(j);
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(HitUtilities.product_id, jP.getString("ProductID"));
                        map.put(HitUtilities.product_name, jP.getString("ProductName"));
                        map.put(HitUtilities.product_image, jP.getString("PhotoImagePath"));
                        map.put(HitUtilities.product_price, jP.getString("CurrentPrice"));
                        map.put(HitUtilities.product_isFavorite, jP.getString("Favorited"));
                        productdetaildata.add(map);
                    }
                    cat1.setItemList(createItems(productdetaildata, jProductDetails.length()));
                    catList.add(cat1);
                }

                restaurantMenuAdapter = new RestaurantMenuAdapter(catList);
                rvMenu.setAdapter(restaurantMenuAdapter);

                smoothScroller.setTargetPosition(getPositionWithName("Sandwich"));
                mLayoutManager.startSmoothScroll(smoothScroller);

            } catch (Exception e) {
                e.printStackTrace();
            }

below is my code;
  smoothScroller = new LinearSmoothScroller(RestaurantMenuActivity.this) {
        @Override
        protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_ANY;
        }
        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return null;
        }
    };

smoothScroller.setTargetPosition(catList.get(5).getId());
mLayoutManager.startSmoothScroll(smoothScroller);

Below is api response;
   {
  "Status":"Success",
  "StatusCode":"200",
  "Message":"data fetch successfully.",
  "Data":{
  "RestaurantID":"1",
  "ProductCategory":[
     {
        "CategoryID":"1",
        "CategoryName":"Restaurant Offers",
        "No_of_Product":2
     },
     {
        "CategoryID":"2",
        "CategoryName":"Cold Drinks",
        "No_of_Product":4
     },
     {
        "CategoryID":"3",
        "CategoryName":"Pizza",
        "No_of_Product":2
     },
     {
        "CategoryID":"4",
        "CategoryName":"Burger",
        "No_of_Product":1
     },
     {
        "CategoryID":"5",
        "CategoryName":"Sandwich",
        "No_of_Product":2
     },
     {
        "CategoryID":"6",
        "CategoryName":"Chinese",
        "No_of_Product":1
     },
     {
        "CategoryID":"7",
        "CategoryName":"Maxican",
        "No_of_Product":1
     }
  ]
  }
  }

A: try this code
recyclerView.smoothScrollToPosition(position);

A: Please find working code as below:
    import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView;

import org.json.JSONArray; import org.json.JSONObject;

import java.io.IOException; import java.io.InputStream; import java.util.ArrayList;

public class DemoActivity extends Activity {

private RestaurantMenuAdapter restaurantMenuAdapter;
RecyclerView rvMenu;
private RecyclerView.LayoutManager mLayoutManager;
int sandwichPos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_demo);
    rvMenu = findViewById(R.id.rvMenu);
    mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
    rvMenu.setHasFixedSize(true);
    rvMenu.setLayoutManager(mLayoutManager);

    try {
        JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
        JSONArray jsonArray = jsonObject.getJSONObject("Data").getJSONArray("ProductCategory");
        ArrayList<Category.CatData> productdetaildata = new ArrayList<Category.CatData>();

        for (int i = 0; i < jsonArray.length(); i++) {
            Category.CatData d = new Category().new CatData();
            JSONObject jObj = jsonArray.getJSONObject(i);
            String catName = jObj.getString("CategoryName");
            String catId = jObj.getString("CategoryID");
            int number = jObj.getInt("No_of_Product");
            d.setCategoryID(catId);
            d.setCategoryName(catName);
            d.setNo_of_Product(number);
            productdetaildata.add(d);
            if(catName.equalsIgnoreCase("Sandwich"))
            {
                sandwichPos = i;
            }
        }

        restaurantMenuAdapter = new RestaurantMenuAdapter(this,productdetaildata);
        rvMenu.setAdapter(restaurantMenuAdapter);
// According to your need you need to change Offset position, Currently it is 20 ((LinearLayoutManager) rvMenu.getLayoutManager()).scrollToPositionWithOffset(sandwichPos, 20); // smoothScroller.setTargetPosition(getPositionWithName("Sandwich")); // mLayoutManager.startSmoothScroll(smoothScroller);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getAssets().open("data.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
}

///Your adapter is
import android.content.Context; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView;

import java.util.ArrayList;

public class RestaurantMenuAdapter extends RecyclerView.Adapter {

private ArrayList<Category.CatData> objects = new ArrayList<>();

private Context context;
private LayoutInflater layoutInflater;

public RestaurantMenuAdapter(Context context, ArrayList<Category.CatData> objects) {
    this.objects =objects;
    this.context = context;
    this.layoutInflater = LayoutInflater.from(context);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemCount() {
    return objects.size();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = layoutInflater.inflate(R.layout.adapter_restaurant, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    final Category.CatData model = objects.get(position);
    if (position % 2 == 1) {
        holder.view1.setBackgroundColor(Color.BLUE);
    } else {
        holder.view1.setBackgroundColor(Color.CYAN);
    }
    holder.id.setText(""+model.getCategoryID());
    holder.name.setText(""+model.getCategoryName());
    holder.number.setText(""+model.getNo_of_Product());

}

protected class ViewHolder extends RecyclerView.ViewHolder{
    private TextView id;
    private TextView name;
    private TextView number;
    private LinearLayout view1;

    public ViewHolder(View view) {
        super(view);
        id = (TextView) view.findViewById(R.id.id);
        name = (TextView) view.findViewById(R.id.name);
        number = (TextView) view.findViewById(R.id.number);
        view1 = view.findViewById(R.id.view);
    }
}
}

// Model Class is
import java.util.ArrayList;

public class Category {

ArrayList<CatData> ProductCategory;

public ArrayList<CatData> getProductCategory() {
    return ProductCategory;
}

public void setProductCategory(ArrayList<CatData> productCategory) {
    ProductCategory = productCategory;
}

public class CatData {
    String CategoryID;
    String CategoryName;
    int No_of_Product;

    public String getCategoryID() {
        return CategoryID;
    }

    public void setCategoryID(String categoryID) {
        CategoryID = categoryID;
    }

    public String getCategoryName() {
        return CategoryName;
    }

    public void setCategoryName(String categoryName) {
        CategoryName = categoryName;
    }

    public int getNo_of_Product() {
        return No_of_Product;
    }

    public void setNo_of_Product(int no_of_Product) {
        No_of_Product = no_of_Product;
    }
}
}

A: change the SNAP_TO_ANY with SNAP_TO_START
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
  @Override protected int getVerticalSnapPreference() {
    return LinearSmoothScroller.SNAP_TO_START;
  }
};

get a position with category
public int getPositionWithName(String searchCatPos)
{
    int i=0;
    for(Category cat:catList)
    {
        if(cat.categoryName.equalsIgnoreCase(searchCatPos))
        {
             return i;

        }
        i++;
    }

    return 0;
}

get the position of adapter and setTargetPosition and scroll
smoothScroller.setTargetPosition(getPositionWithName("Sandwich"));
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(getPositionWithName("Sandwich"), 20);

A:
This help to increase the speed of recycler view scrolling and you
  can directly jump to required position.

SpeedyLinearLayoutManager linearLayoutManager = new SpeedyLinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
linearLayoutManager.scrollToPosition(myPosition);   // Position to scroll recycler view.
myRecyclerView.setLayoutManager(linearLayoutManager);

SpeedyLinearLayoutManager.class

 public class SpeedyLinearLayoutManager extends LinearLayoutManager {

        private static final float MILLISECONDS_PER_INCH = 2f; //default is 25f (bigger = slower)

        public SpeedyLinearLayoutManager(Context context) {
            super(context);
        }

        public SpeedyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public SpeedyLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {

            final LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {

                @Override
                public PointF computeScrollVectorForPosition(int targetPosition) {
                    return SpeedyLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);
                }

                @Override
                protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                    return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
                }
            };

            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        }
    }

A: change this code
String catName = jObj.getString("CategoryName");
String catId = jObj.getString("CategoryID");

Like this
String catName = jObj.getString("CategoryName");
if(catName.equals("Sandwich"){
  SandwichPosition=j
}
String catId = jObj.getString("CategoryID");

And then after setting recyclerview, call
mLayoutManager.scrollToPositionWithOffset (SandwichPosition,0)

A: Please use this code
Firstly you can the index where id=5 value is stored then scroll the recyclerview to that position.
recyclerView.scrollToPosition(5);

A: Try scrolling to position after the recyclerview is loaded properly by giving it some delay.
So your code would be:
recyclerview.postDelayed(new Runnable() {
        @Override
        public void run() {
            recyclerview.scrollToPosition(5);
        }
    },500);

I faced similar issue in scrolling to some position with offset in expandableListView.

A: you need to add below line
rvChat.scrollToPosition(chatAdapter.getItemCount() - 1);

worked for me in your case you need to add the position of required catagory

A: You need to include this customLinearLayoutManager class:
class CustomLinearLayoutManager(context: Context) : LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {

    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?, position: Int) {
        val smoothScroller = TopSnappedSmoothScroller(recyclerView.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private inner class TopSnappedSmoothScroller(context: Context) : LinearSmoothScroller(context) {

        override fun computeScrollVectorForPosition(targetPosition: Int): PointF? = this@CustomLinearLayoutManager.computeScrollVectorForPosition(targetPosition)

        override fun getVerticalSnapPreference(): Int = LinearSmoothScroller.SNAP_TO_START

        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = MILLISECONDS_PER_INCH / displayMetrics.densityDpi
    }

    companion object {
        private const val MILLISECONDS_PER_INCH = 80f
    }

}

Set your recyclerView layoutManager :
mRecyclerView.layoutManager = CustomLinearLayoutManager(ctx)

And now you are able to smoothScroll to any position you want ;) try it out.
mRecyclerView.smoothScrollToPosition(5)

A: I achieve my work by following way;
Take LinearLayoutManager
LinearLayoutManager mLayoutManager = new LinearLayoutManager(RestaurantMenuActivity.this);
rvMenu.setLayoutManager(mLayoutManager);

and scroll to position like below code;
   int scrollPosition = 0;
    for (int j = 0; j < pos; j++) {
        scrollPosition += menuItem.getData().getProductCategory().get(j).getProductDetails().size();
        scrollPosition++;
    }
    mLayoutManager.scrollToPosition(scrollPosition);
    final Handler handler = new Handler();
    final int finalScrollPosition = scrollPosition;
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            View rclItemView = rvMenu.getChildAt(0);
            mLayoutManager.scrollToPositionWithOffset(finalScrollPosition, rclItemView.getBaseline());
        }
    }, 100);


text:
Q: Question about "very" vs. "too" – with and without "much"
I feel sleepy very much.
  I feel very sleepy.
  I feel too sleepy.
  I feel sleepy too much.

Which is correct? Is there any difference between them? Thanks for your answers!

A: All of these sentences are grammatically correct, but you won't hear the last one very often, and probably never* encounter the first one. They mean different things.

☼¹ I feel sleepy very much.

I feel sleepy too much.

These are possible ways of referring to how often someone feels sleepy. That is, how frequently. There is some of the statement left off, which would make these sentences:

☼ I feel sleepy very much [of the time].

I feel sleepy too much [of the time].

When someone says "too" they are suggesting an excess beyond an acceptable level. In this case, the acceptable level would be feeling sleepy at regular times or just at the end of the day. The following dialog is possible:
"Why don't you like taking that medication?"
"I feel sleepy too much (of the time)."

"Too" is also used in one of your other examples:

I feel too sleepy.

Again, someone saying this is implying a tolerance limit that has been exceeded. Someone might make this declaration as they left the company of a group late at night, and the implication would be that they are too sleepy to continue doing what they are doing. More likely you'd hear it in situations like this:
"Why don't you go with us to the nightclub?"
"I'm too sleepy."

Most people would say that they are sleepy (not that they "feel" sleepy) unless they are describing something that is similar to sleepiness, especially something externally imposed. c.f.:
"Is the nitrous oxide flowing?"
"Yes. I feel very sleepy."

More likely people who are very sleepy in normal situations will just say "I am very sleepy."

 1 ☼ = descriptively ungrammatical (violates practice, but not rules).

A:
I feel sleepy very much.
I feel sleepy too much.

These are incorrect - 'much' is the wrong word for this. "Often" would work better - "I feel sleepy very/too often." As for the difference between them, 'too' implies that the amount of sleepiness is greater than some desired amount, whereas 'very' just says that it's a large amount, without saying whether that is good or bad.

I feel very sleepy.
I feel too sleepy.

These are correct, and are distinct from the other two in that 'often' is a description of frequency, whereas these describe the intensity of the feeling. The distinction between 'very' and 'too' is the same as above.


text:
Q: conditional logic based on type Given:
interface I
{
}

class B: I
{
}

class C: I
{
}

class A
{

    public void Method(B arg)
    {
    }

    public void Method(C arg)
    {
    }

    public void Method(I arg)
    {
       // THIS is the method I want to simplify.
       if (I is B)
       {
          this.Method(arg as B);
       }
       else if (I is C)
       {
          this.Method(arg as C);
       }
    }
}

I know that there are better ways to design this type of interactions, but because of
details which would take too long to explain this is not possible.
Since this pattern will be duplicated MANY times, I would like to replace the
conditional logic with a generic implementation which I could use just one line.
I can't see a simple way to implement this generic method/class, but my instincts tell me it should be possible.
Any help would be appreciated.

A: What you want is double dispatch, and visitor pattern in particular.

A: I would put the method inside the interface and then let polymorphism decide which method to call
interface I
{
   void Method();
}

class B : I
{
   public void Method() { /* previously A.Method(B) */}
}

class C : I
{
   public void Method() { /* previously A.Method(C) */ }
}

class A
{
   public void Method(I obj)
   {
     obj.Method();
   }
}

Now when you need to add a new class, you only need to implement I.Method. You don't need to touch A.Method.

A: This is kinda ugly but it gets the job done:
public void Method(B arg)
{
  if (arg == null) return;
...
}
public void Method(C arg)
{
  if (arg == null) return;
...
}

public void Method(I arg)
{
  this.Method(arg as B);
  this.Method(arg as C);
}

I don't think I would do it this way, though. It actually hurts looking at that. I'm sorry I forced you all to look at this as well.

A: interface I
{
}

class B : I
{
}

class C : I
{
}

class A
{
    public void Method(B arg)
    {
        Console.WriteLine("I'm in B");
    }

    public void Method(C arg)
    {
        Console.WriteLine("I'm in C");
    }

    public void Method(I arg)
    {
        Type type = arg.GetType();

        MethodInfo method = typeof(A).GetMethod("Method", new Type[] { type });
        method.Invoke(this, new I[] { arg });
    }
}

A: It doesn't exist in a convenient form withing C# - see here for an idea based on F#'s pattern matching, that does exactly what you want. You can do some things with reflection to select the overload at runtime, but that will be very slow, and has severe issues if anything satisfies both overloads. If you had a return value you could use the conditional operator;
return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0);

Again - not pretty.

A: Easy. In Visual Basic I do this all the time using CallByName.
Sub MethodBase(value as Object)
    CallByName(Me, "RealMethod", CallType.Method, value)

This will call the overload of RealMethod that most closely matches the runtime type of value.
I'm sure you can use CallByName from C# by importing Microsoft.VisualBasic.Interaction or by creating your own version using reflection.


text:
Q: Change the value in tableView Me need to change value on right labels. But first I need to change the first four rows and then the last three rows. So when i select first four rows i add in right label number 1200 for four rows, and then i select last three rows in right label number 1500 for last three rows.
For change data in right label i use button Задать цену at the end, all this data must be in the array.

At the end i want to see this result.

A: To replace Row Data in DidSelect Delegate of TableView
table View Class
import UIKit

class demoTableVC: UIViewController {

    let leftLabelArray : [String] = ["1","2","3","4","5","6","7"]
    var rightLabelArray : [String] = ["0","0","0","0","0","0","0"]

    @IBOutlet weak var demoTableView: UITableView!

    @IBAction func buttonAction(_ sender: Any)
    {
        //Get the updated Array
        print(rightLabelArray)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        demoTableView.delegate = self
        demoTableView.dataSource = self

    }
}

extension demoTableVC : UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        //Return Number of Rows
        return leftLabelArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        //Define cell
        let cell = self.demoTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableCellClass

        //Update Values
        cell.leftLabel.text = leftLabelArray[indexPath.row]
        cell.rightLabel.text = rightLabelArray[indexPath.row]

        //Return cell
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        //Switch case statement
        switch indexPath.row
        {
        //This Handle your first 4 case of Table Cell
        case 0,1,2,3:
            rightLabelArray[indexPath.row] = "1200"
            self.demoTableView.reloadRows(at: [indexPath], with: .none)
            break;

        //This Handle your next 3 case of Table Cell
        case 4,5,6:
            rightLabelArray[indexPath.row] = "1500"
            self.demoTableView.reloadRows(at: [indexPath], with: .none)
        default:
            break;
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }

}

Table Cell class
import UIKit

class TableCellClass: UITableViewCell {

    @IBOutlet weak var leftLabel: UILabel!
    @IBOutlet weak var rightLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Note This code is Written for 7 static Rows using switch case statements in case if number of Rows increases more than 7 then need to modify the switch case statement
This will work in flow to replace first 7 index
Storyboard

A: suppose you have a count for your number of rows in a variable devices = AnyObject
now make array with the arraysize
 var myInts = [Int](repeating: 0, count: devices.count)

in method,
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row <= 3 {
            let cell = tableView.cellForRow(at: indexPath) as? YourCell
            cell?.rightLabel.text = "1200"
            myInts[indexPath.row] = "1200"
        }
        else if (indexPath.row < devices.count) && (indexPath.row >= devices.count-3) {
            let cell = tableView.cellForRow(at: indexPath) as? YourCell
           cell?.rightLabel.text = "1500"
           myInts[indexPath.row] = "1500"
        }
}

now on button click
print(myInts)


text:
Q: Readable join for execution plan in Oracle I want to understand what join operations were done on my database by different users for future analysis and improvements. but I have issues with understanding the execution plan.
Example:
Consider this query:
SELECT f.year, f.geoid, a.age_band, sum(f.num_people), sum(f.num_insured)
FROM fact f
  JOIN age_bands a ON f.age_code = a.age_code
WHERE f.gender_code = 1
GROUP BY f.year, f.geoid, a.age_band

When I try to see the execution plan with this command:
SELECT s.sql_id, p.*
FROM v$sql s CROSS JOIN LATERAL (SELECT * FROM TABLE (
  dbms_xplan.display_cursor (s.sql_id, s.child_number, 'ALLSTATS LAST')
)) p
WHERE s.sql_text LIKE '%f.gender_code = 1%';

I get different values for the Predicate Information values (for different child numbers)
for instance - for child number 0:
Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("ITEM_1"="A"."AGE_CODE")
   6 - filter("F"."GENDER_CODE"=1)

for child number 1 (and 2):
Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("F"."AGE_CODE"="A"."AGE_CODE")
   4 - filter("F"."GENDER_CODE"=1)

My questions are

*

*what is "ITEM_1" and why does it replace "F"."AGE_CODE" ?

*is there a better way to understand what joins were made in the DB?

*is there a simple way to convert the alias in the Predicate Information to the full table name? (for instance convert "A" to "AGE_BANDS" in the above example)

A: *

*That is because of query transformations like for example Join Factorization.

Simply put, with JF, queries like this:
select t1.c1, t2.c2
    from t1, t2, t3
    where t1.c1 = t2.c1 and t1.c1 > 1 and t2.c2 = 2 and t2.c2 = t3.c2
  union all
    select t1.c1, t2.c2
    from t1, t2, t4
    where t1.c1 = t2.c1 and t1.c1 > 1 and t2.c3 = t4.c3;

Can be automatically rewritten by the optimizer to something like this:
select t1.c1, VW_JF_1.item_2
    from t1, (select t2.c1 item_1, t2.c2 item_2
                   from t2, t3
                   where t2.c2 = t3.c2 and t2.c2 = 2
                 union all
                   select t2.c1 item_1, t2.c2 item_2
                   from t2, t4
                   where t2.c3 = t4.c3) VW_JF_1
    where t1.c1 = VW_JF_1.item_1 and t1.c1 > 1;

You can see a step called VW_JF_... in your plan whan this happens.
There are other transformations as well that can cause this.

*This is too generic and unclear what you want.

*Not that I am aware of. You can however display an alias mapping with the format=>'alias' option:
SQL> explain plan for select count(*) from t1 a where a.object_id = 1;
Explained.
Default output:
SQL> select * from table(dbms_xplan.display);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
Plan hash value: 3900446664

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     5 |     1   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE   |      |     1 |     5 |            |          |
|*  2 |   INDEX RANGE SCAN| I1   |     1 |     5 |     1   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------

   2 - access("A"."OBJECT_ID"=1)

14 rows selected.

Same with alias mapping:
SQL> select * from table(dbms_xplan.display(format=>'alias'));

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
Plan hash value: 3900446664

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |     1 |     5 |     1   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE   |      |     1 |     5 |            |          |
|*  2 |   INDEX RANGE SCAN| I1   |     1 |     5 |     1   (0)| 00:00:01 |
--------------------------------------------------------------------------

Query Block Name / Object Alias (identified by operation id):

   1 - T1
   2 - T1 / A@T1

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("A"."OBJECT_ID"=1)

20 rows selected.

SQL>


text:
Q: Android: why does google places api return locations in other countries even when bounds is 500 meters? I'm trying to pass an autocomplete prediction request to google places api. Everything works, however I'm having problems with the bounds parameter. Even when bounds is 500 meters surrounding the user's current location (I verified that the lat/lngs were correct on a map) the api still insists on returning results located in other countries (as well as the relevant results that are actually located within 500 meters from the user).
Code:
PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, null);

what could be the cause of this unusual behavior? Specifically the unnecessary results are the names of cities/towns in other countries.

A: The bounds parameter on getAutocompletePredicitons signifies a bias towards a particular geographic area - see the documentation here. It is not possible to hard-restrict the result set to a particular country or geographic region today.


text:
Q: mySQL debit credit balances Is it possible to have a mySQL query to get these fields old balance (sum of my expenses), debit (here should I put total my expenses with same id in the current date), credit (not much in these query), new balance (same as debit).
Now when the day was ended, the new balance will be added to the old balance, and a new balance will be form for the current date. I have my code but it does not calculate my previous balances.
Table: rf_expenses
--------------------------------------
id_rf_expenses   rf_expense_desc
--------------------------------------
1                    salary
2                    bonus
3                    transportation

Table: expenses
-----------------------------------------------------------
id_expnses    id_rf_expenses     expense_amt   expense_date
------------------------------------------------------------
1                1                  100           current
2                1                  100           yesterday
3                2                   50           current
4                2                   50           current
5                3                  200           yesterday

OUTPUT:
-----------------------------------------------------------
EXPENSE      OLD BALANCE    DEBIT     CREDIT   NEW BALANCE
-----------------------------------------------------------
SALARY           100         100        0          100
BONUS             0          100        0          100
TRANSPO          200           0        0            0

This will happen every query of the current date..any dates previous the the current will be sum up in the old balance
SELECT
    r.rf_expense_desc,
    COALESCE(SUM(expense_amt), 0) - COALESCE(q1.amt2, 0) OLD,
    COALESCE(q1.amt2, 0) AS NEW
FROM
    rf_expenses r
LEFT JOIN
    expenses e ON r.id_RF_expense = e.id_rf_expense
LEFT JOIN
    (SELECT
         SUM(expense_amt) amt2, id_expense,
         rf_expenses.id_rf_expense
     FROM
         rf_expenses
     LEFT JOIN
         expenses ON rf_expenses.id_RF_expense = expenses.id_rf_expense
     WHERE
         expense_date = CURDATE( )
     GROUP BY
         rf_expense_desc, expense_date) q1 ON r.id_rf_expense = q1.id_rf_expense
GROUP BY
    rf_expense_desc

A: Hi I give two queries: one with date type column and another with string.
1 Query (with your sample data) SQLFIDDLE example:
    SELECT
rf.rf_expense_desc as EXPENSE
,(SELECT
  COALESCE(SUM(e.expense_amt),0)
  FROM expenses e
  WHERE e.id_rf_expenses= rf.id_rf_expenses
  AND expense_date != 'current'
 ) AS 'OLD BALANCE'
,(SELECT
  COALESCE(SUM(e.expense_amt),0)
  FROM expenses e
  WHERE e.id_rf_expenses= rf.id_rf_expenses
  AND expense_date = 'current'
 ) AS 'DEBIT'
,0 AS CREDIT
,(SELECT
  COALESCE(SUM(e.expense_amt),0)
  FROM expenses e
  WHERE e.id_rf_expenses= rf.id_rf_expenses
  AND expense_date = 'current'
 ) AS 'NEW BALANCE'
FROM
rf_expenses rf

2 Query (with data type date) SQLFIddle example2:
SELECT
rf.rf_expense_desc as EXPENSE
,(SELECT
  COALESCE(SUM(e.expense_amt),0)
  FROM expenses e
  WHERE e.id_rf_expenses= rf.id_rf_expenses
  AND expense_date != CURDATE()
 ) AS 'OLD BALANCE'
,(SELECT
  COALESCE(SUM(e.expense_amt),0)
  FROM expenses e
  WHERE e.id_rf_expenses= rf.id_rf_expenses
  AND expense_date = CURDATE()
 ) AS 'DEBIT'
,0 AS CREDIT
,(SELECT
  COALESCE(SUM(e.expense_amt),0)
  FROM expenses e
  WHERE e.id_rf_expenses= rf.id_rf_expenses
  AND expense_date = CURDATE()
 ) AS 'NEW BALANCE'
FROM
rf_expenses rf

Result:
|        EXPENSE | OLD BALANCE | DEBIT | CREDIT | NEW BALANCE |
---------------------------------------------------------------
|         salary |         100 |   100 |      0 |         100 |
|          bonus |           0 |   100 |      0 |         100 |
| transportation |         200 |     0 |      0 |           0 |

A: Yet another example of why mysql should enforce the SELECTs of all GROUP BY clauses to have only columns specified in the GROUP BY clause, or surrounded by an aggregate function. Mysql call's this bug a "feature".
What I mean is, take a look at the SELECT clauses for both of your GROUP BYs, both the inner query and the outer. You have columns that you are selecting that are not in the GROUP BY clause and aren't surrounded by a SUM, AVG, COUNT or other aggregate function. If you group rows, and you dont tell mysql how to "reduce" the rows in the group it will simply take any value at random.
For example, suppose we have this data in a table called "test":
PARENTID     ID     VALUE
-------------------------
1            1      2.05
1            2      3.50
1            3      1.58
2            1      4.65
2            2      0.65

The we query:
SELECT parentid, value FROM test GROUP BY parentid, value
Well we havent said what to do with the VALUE column, for example to SUM, so mysql will simply take any value in the group, for PARENTID=1 we may get any of 2.05, 3.50, or 1.58...but not the combined lot of them.
So this is correct:
SELECT parentid, SUM(value) as total FROM test GROUP BY parentid, value;

Now when mysql reduces each group we get the correct total sum, our results are:
PARENTID          VALUE
-------------------------
1                 7.13
2                 5.30

So in your example, you probably want to query:
SELECT r.rf_expense_desc, expense_date,
    COALESCE( SUM( expense_amt ) , 0 ) - COALESCE( sum(q1.amt2), 0 ) OLD, COALESCE( sum(q1.amt2), 0 ) AS NEW
FROM rf_expenses r
LEFT JOIN expenses e ON r.id_RF_expense = e.id_rf_expense
LEFT JOIN (
    SELECT SUM( expense_amt ) amt2, count(id_expense) as counts
    FROM rf_expenses
    LEFT JOIN expenses ON rf_expenses.id_RF_expense = expenses.id_rf_expense
    WHERE expense_date = CURDATE( )
    GROUP BY rf_expense_desc, expense_date
) q1 ON r.id_rf_expense = q1.id_rf_expense
GROUP BY rf_expense_desc


text:
Q: Use .csv as data source with PHP With PHP I want to pull in some text from a comma separated csv file (my array) on my server.  Dependent on the text (title) that is pulled into a page from a variable.
i.e.

<?php echo $item->title;?>

Prices from £[php price here]

Where 'title' in the echo (above) could be Spain.
So my csv would have:
Spain, 250
France, 350
Germany, 150

Spain being the 'title' and '250' being the [php price here] I want to pull in.
So if Spain were the 'title' being pulled in, it would grab the price of 250.
i.e.
Spain
Prices from £250

Hope this makes sense...
Thanks

A: Just an example. Assumning you have you file with data called pricelist.csv.
$pricelist = array();
if (($handle = fopen("pricelist.csv", "r")) !== FALSE)
{
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
        $pricelist[] = $data;
    }
    fclose($handle);
}

echo '
'; print_r($pricelist); echo '
';

Will give you output:
Array
(
    [0] => Array
        (
            [0] => Spain
            [1] =>  250
        )
    [1] => Array
        (
            [0] => France
            [1] =>  350
        )
    [2] => Array
        (
            [0] => Germany
            [1] =>  150
        )
)

Now you will be able to use this array data.

A: To question with so little detail, I can only answer with a link to http://php.net/manual/en/function.fgetcsv.php

A: Check out the fgetcsv function, you can use it to read in the csv file to an Array.


text:
Q: Integration by Trigonometric Substitution vs Table of Integral Solution I'm not sure how to phrase this question, but I find myself confused over the correctness of a particular solution in the table of integral, specifically:
$$\int\frac{dx}{\sqrt{x^2-a^2}}=\ln|\sqrt{x^2-a^2}+x|+C$$
I find that if you try to solve it with trigonometric substitution, you get a different answer:
So, for the example, since the form $\sqrt{x^2-a^2}$ is present, we use the substitution $x=asec \theta$, and $dx=asec\theta tan \theta d\theta$. Doing so:
$$\int\frac{asec\theta tan \theta d\theta}{\sqrt{(asec \theta)^2-a^2}}$$
$$\int\frac{asec\theta tan \theta d\theta}{\sqrt{a^2sec^2 \theta-a^2}}$$
$$\int\frac{asec\theta tan \theta d\theta}{a\sqrt{sec^2 \theta-1}}$$
Using the trigonometric identity $tan^2 \theta=sec^2 \theta -1$
$$\int\frac{asec\theta tan \theta d\theta}{atan \theta}$$
Cancelling like terms, we get $\int sec \theta$, which finally integrates to $ln|sec \theta + tan \theta|+C$
Undoing the substitution, using this triangle:
https://i.stack.imgur.com/6tkR7.png
With $sec \theta = \frac{x}{a}$ and $tan \theta = \frac{\sqrt{x^2-a^2}}{a}$, the final answer then is:
$$ln\biggl|\frac{x}{a} + \frac{\sqrt{x^2-a^2}}{a}\biggl|+C$$
Which is evidently different from the one from the table of integrals. Is my solution wrong or something?

A: You're right. Indefinite integrals represent a family of curves(functions) which vary by some constant.
$\ln \left|\dfrac{x+\sqrt{x^2-a^2}}{a}\right| +c= \ln |x+\sqrt{x^2-a^2}| - \ln|a| +c  = \ln(x+\sqrt{x^2-a^2}) +k$
$k = c-\ln |a| = $ constant


text:
Q: Scroll position of RecyclerView lost when returning back to activity from another activity I m using Firebase RecyclerView.Apdapter with Firebase UI in MainActivity.
When I'm opening another activity and returning back to main activity, scroll position moves to top. How to have same scroll position after closing of other activity using Firebase RecyclerView?

A: To solve this, you need to know that the component responsible one for holding the layout state (and restoring it) is the LayoutManager used in your RecyclerView. To achieve this, you can override the onSaveInstanceState() method and store the position directly in the Bundle object.
To get it back, just override the onRestoreInstanceState() method and get the position back fron the Bundle object.
In the end just simply use the following line of code in your onStart() method:
layoutManager.onRestoreInstanceState(yourListState);


text:
Q: java program to conditionally read lines from file I'm new to coding in Java. I put together this piece of code to read all lines between the "Start" and "End" tag in the following text file.
Start
hi
hello
how
are
you
doing?
End
My program is as follows....
package test;

import java.io.*;

public class ReadSecurities {
public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

      try {
        FileInputStream in = new FileInputStream("U:\\Read101.txt");
        FileOutputStream out = new FileOutputStream("U:\\write101.txt");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

        for (int i=1; i<=countLines("U:\\Read101.txt"); i++) {
            String line=br.readLine();
                 while (line.contains("Start")) {
                    for (int j=i; j<=countLines("U:\\Read101.txt"); j++) {
                        String line2=br.readLine();
                        System.out.println(line2);
                        if(line2.contains("End")) break;
                    else {
                             bw.write(line2);
                             bw.newLine();
                    }
                        bw.close();
                    } break;
                 }
               }
            br.close();
      }
      catch (Exception e) { }
      finally { }
      }
}

The program reads only the first two lines "hi hello" as though the if condition does not exist. I have a feeling the mistake is very basic, but please correct me.

A: String line;

do{ line = br.readLine(); }
while( null != line && !line.equals("Start"));

if ( line.equals("Start") ) { // in case of EOF before "Start" we have to skip the rest!
    do{
        line = br.readLine();
        if ( line.equals("End") ) break;
        // TODO write to other file
    }while(null != line )
}

Should be as easy as that. I left out creation / destruction of resources and proper Exception handling for brevity.
But please do at least log exceptions!
EDIT:
If EOF is encountered before Start, you have to skip the copy step!

A: You make one crucial mistake in your code: you don't handle the exceptions correctly. Two things:

*

*never catch Exception. Either catch just one type of Exception or specify a list of exceptions you want to catch. In your case, a simple IOException would suffice.

*Never leave a catch-block empty. Either throw a new exception, return a value or - in your case - print the exception with e.printStackTrace().
When you do these two things, you will notice that your code throws an IOException, because you close your bw-Stream too early. Move the bw.close() down to where br.close() is.
Now, when you have done that, your code is almost working. The only thing is - you now get a NullPointerException. This is because you don't change your line after all entries are read. The easy fix to this is change from
while(line.equals("Start")) { ...

to
if(line.equals("Start")) { ...

Also, there are some other not-so-neat things in your code, but I will leave it for now - experience comes with time.

A: For Java 8:
List<String> stopWords = Arrays.asList("Start", "End");
try (BufferedReader reader = new BufferedReader(input))) {
   List<String> lines = reader.lines()
     .map(String::trim)
     .filter(s -> !StringUtils.isEmpty(s) && !stopWords.contains(s))
     .collect(Collectors.toList());
}


text:
Q: Detecting and interacting with long running process I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to interact with the process. I would like this to work on Unix and Windows.
I am unsure how I do this. Specifically how do I detect if the process is already running and open a pipe to it? Should I use sockets (e.g. registering the server process on a known port and then check if it responds) or should I use "named pipes"? Or is there some easier way?

A: Sockets are easier to make portable between Windows and any other OS, so that's what I would recommend it over named pipes (that's why e.g. IDLE uses sockets rather than named pipes -- the latter require platform-dependent code on Windows, e.g. via ctypes [[or third-party win32all or cython &c]], while sockets just work).

A: Well here is an idea...

*

*place a status somewhere else, that
can be polled/queried.

*when the process starts, post the
'running' status.

*have the script check here to see if the process is running.

*I would also use a seperate place to
post control values.  e.g. set a
value to the 'control set' and have
the process look for those values
whenever it gets to decision points
in its runtime behavior.


text:
Q: Finding a termination measure for Search and Replace in Dafny? I'm coding a search and replace method that uses find, delete and insert methods. I'm calling these three methods inside a while loop and I'm not sure about which pre-conditions should I use.
Full Code:
      method searchAndReplace(line:array<char>, l:int,
        pat:array<char>, p:int,
        dst:array<char>, n:int)returns(nl:int)
        requires line != null && pat!=null && dst!=null;
        requires !checkIfEqual(pat, dst);
        requires 0<=l<line.Length;
        requires 0<=p<pat.Length;
        requires 0<=n<dst.Length;

        modifies line;
        {
          var at:int := 0;
          var p:int := n;

          while(at != -1 )
          invariant -1<=at<=l;
          {
            at := find(line, l, dst, n);
            delete(line, l, at, p);
            insert(line, l, pat, p, at);
          }

          var length:int := line.Length;

          return length;
        }

       function checkIfEqual(pat:array<char>, dst:array<char>):bool
        requires pat!=null && dst!=null;
          reads pat;
         reads dst;
{
  if pat.Length != dst.Length then false
  else forall i:nat :: i < pat.Length ==> pat[i] == dst[i]
}

     // l is length of the string in line
// p is length of the string in nl
// at is the position to insert nl into line
method insert(line:array<char>, l:int, nl:array<char>, p:int, at:int)
  requires line != null && nl != null
  requires 0 <= l+p <= line.Length // line has enough space
  requires 0 <= p <= nl.Length // string in nl is shorter than nl
  requires 0 <= at <= l // insert position within line
  modifies line
  ensures forall i :: (0<=i<p) ==> line[at+i] == nl[i] // ok now
{
  ghost var initialLine := line[..];

  // first we need to move the characters to the right
  var i:int := l;
  while(i>at)
    invariant line[0..i] == initialLine[0..i]
    invariant line[i+p..l+p] == initialLine[i..l]
    invariant at<=i<=l
  {
    i := i - 1;
    line[i+p] := line[i];
  }

  assert line[0..at] == initialLine[0..at];
  assert line[at+p..l+p] == initialLine[at..l];

  i := 0;
  while(i<p)
    invariant 0<=i<=p
    invariant line[0..at] == initialLine[0..at]
    invariant line[at..at+i] == nl[0..i]
    invariant line[at+p..l+p] == initialLine[at..l]
  {
    line[at + i] := nl[i];
    i := i + 1;
  }

  assert line[0..at] == initialLine[0..at];
  assert line[at..at+p] == nl[0..p];
  assert line[at+p..l+p] == initialLine[at..l];
}

        method find(line:array<char>, l:int, pat:array<char>, p:int) returns (pos:int)
  requires line!=null && pat!=null
  requires 0 <= l < line.Length
  requires 0 <= p < pat.Length
  ensures 0 <= pos < l || pos == -1
{
  var iline:int := 0;
  var ipat:int  := 0;
  pos := -1;

  while(iline<l && ipat<pat.Length)
    invariant 0<=iline<=l
    invariant 0<=ipat<=pat.Length
    invariant -1 <= pos < iline
  {
      if(line[iline]==pat[ipat] && (line[iline]!=' ' && pat[ipat]!=' ')){
          if(pos==-1){
              pos := iline;
          }
          ipat:= ipat + 1;
      } else {
        if(ipat>0){
          if(line[iline] == pat[ipat-1]){
            pos := pos + 1;
          }
        }
        ipat:=0;
        pos := -1;
      }
      if(ipat==p) {
          return;
      }
      iline := iline + 1;
  }
  return;
}

  method delete(line:array<char>, l:nat, at:nat, p:nat)
  requires line!=null
  requires l <= line.Length
  requires at+p <= l
  modifies line
  ensures line[..at] == old(line[..at])
  ensures line[at..l-p] == old(line[at+p..l])
{
  var i:nat := 0;
  while(i < l-(at+p))
    invariant i <= l-(at+p)
    invariant at+p+i >= at+i
    invariant line[..at] == old(line[..at])
    invariant line[at..at+i] == old(line[at+p..at+p+i])
    invariant line[at+i..l] == old(line[at+i..l]) // future is untouched
  {
    line[at+i] := line[at+p+i];
    i := i+1;
  }
}

A: This is a fairly difficult thing to prove. Here are some initial ideas, which might help you.
You need to find a termination measure for the loop. I would suggest using something like a tuple of the number of occurrences of the pattern, and the length of the string.
You must be very careful that the replacement doesn't contain the search term, otherwise your loop may not terminate. And even if it does terminate, its hard to find a termination measure that will reduce at each iteration.
For example, say I want to replace "fggf" with "gg" in the string "ffggff", the first time round the loop I will have 1 occurrence of "fggf", and replacing "fggf" with "gg" results in "fggf" - so I still have one occurrence!  The second time round I end up with just "gg".
You will need something like a function:
function occurences(line:array<char>, l:int, pat:array<char>, p:int) : int
  reads line
  requires line != null
  requires pat != null
  requires 0 <= l < line.Length
  requires 0 <= p < pat.Length

And then use that in the loop like
   ghost var matches := occurrences(line, l, dst, n);

   while(at != -1 )
      decreases matches
      invariant -1<=at<=l
      invariant matches == occurrences(line, l, dst, n)
   {
      at := find(line, l, dst, n);
      delete(line, l, at, p);
      insert(line, l, pat, p, at);
      matches := matches - 1;
   }

But, like I said, the number of occurrences by itself is not enough to prove termination. You can use any calculation as the termination measure. As long as it decrease in each loop iteration and has no infinite descending chains.


text:
Q: SQL Split Comma Separated Column on Delimiter Here is a split function, it can apply as dbo.Split('sf,we,fs,we',','), when I change the string to column name it doesn't work, such as dbo.Split(table.columnName,',').
Select * from dbo.Split('dirk@test.com','@')

is works but
Select * from dbo.Split((Select Email from Users),'@')

has an error message:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','

The Function is here:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Split] (@String varchar(8000), @Delimiter char(1))
   returns @temptable TABLE (items varchar(8000))
   as
   begin
       declare @idx int
        declare @slice varchar(8000)

        select @idx = 1
            if len(@String)<1 or @String is null  return

       while @idx!= 0
       begin
           set @idx = charindex(@Delimiter,@String)
           if @idx!=0
               set @slice = left(@String,@idx - 1)
           else
              set @slice = @String

           if(len(@slice)>0)
               insert into @temptable(Items) values(@slice)

           set @String = right(@String,len(@String) - @idx)
           if len(@String) = 0 break
       end
   return
   end

which it's refered to: SQL 2005 Split Comma Separated Column on Delimiter
Or someone can give me a similiar function which can split one column into two

A: That is because the function is returning a TABLE.
SELECT Split(myColumn) FROM myTable

will mean
SELECT myOutputTableFromSplit FROM myTable

It means, return a table from the table & SQL cannot do that.


text:
Q: In python, will subprocess.call produce an individual subprocess every time being invoked? If subprocess.call is invoked N times, I wonder if N subprocess will be created or not.
And when will the subprocess close? Should I kill it manually?
What about subprocess.Popen?

A: subprocess.call creates a process every time it gets called and waits for the command to complete. So due to the nature of waiting for the command to finish there is no real parallel processing.
subprocess.Popen also creates a process every time it gets called, but does not wait for the command to complete. You can use communicate to wait for the command to complete or call kill.
So sum it up. With subprocess.Popen you have more control about the process you created.
Described in the  python documentation

A: Yes, a new process is spawned every time you call subprocess.call() or any of its relatives, including Popen().  You do not need to explicitly kill the subprocesses normally--you'd just wait for them to exit.


text:
Q: tmux: How to get the expression (for config file) of the pressed key? Environment is Konsole + xterm-256color + tmux.
I like bind-key [Prefix] Alt+Backspace to next-window, so I wrote the following line in ~/.tmux.conf
bind-key M-BSpace next-window

It worked well. But now, it suddenly stop working after maybe the system upgrade or something whatever. I need to know how to get the correct expression for bind-key. (I mean, M-BSpace may be an invalid expression)
Is there any way to get the exact expression of the pressed key in tmux? For example, just like Emacs's C-h k, which can display the exact expression of a pressed key-binding.
This method is very useful because I can know whether Emacs accepted a correct key-binding, or the key-binding cannot interpreted/interpreted as something else by Konsole, xterm-256color, or tmux. (e.g. C-2 will be interpreted as C-@, C-i as TAB)


text:
Q: What does __weak it mean exactly? I am (trying to) learn Objective-C and I keep coming across a phrase like:
__weak IBOutlet NSLayoutConstraint *webViewLeftConstraint;

What does __weak it mean exactly in Objective-C?
Why we need to put __(underscore twice) in variable?
Can we use only one time? like( _ ) other declaration in other language..

A: If the outlet is referencing a UI Object in the View hierarchy then you should make it weak as the view hierarchy already has a strong reference.
Weak is specifically needed to avoid a retain cycle.


text:
Q: ActionScript - Get Function Of Event Dispatcher there are 2 functions in my code that dispatch a TweenEvent.  each function dispatches the same tween and adds the same TweenEvent.MOTION_FINISH event listener.  however, the event listening function must act according to which function dispatched the event.
is it possible to get the function of the event dispatcher from the event listener?  i could use a flag to make this work if there are no other elegant solutions.
public function FirstTweenAction():void
     {
     myTween = new Tween(/* tween stuff */);
     myTween.addEventListener(TweenEvent.MOTION_FINISH, myTweenEventMotionFinishHandler);
     }

public function SecondTweenAction():void
     {
     myTween = new Tween(/* tween stuff */);
     myTween.addEventListener(TweenEvent.MOTION_FINISH, myTweenEventMotionFinishHandler);
     }

private function myTweenEventMotionFinishHandler(evt:TweenEvent):void
     {
     evt.currentTarget.removeEventListener(TweenEvent.MOTION_FINISH, myTweenEventMotionFinishHandler);

     if (/* Event was fired from FirstTweenAction() */)
        trace("Dispatcher is FirstTweenAction()");
        else
        trace("Dispatcher is SecondTweenAction()");
     }

A: You can't find out from which method the tween was initialized.  Instead, make two tween member variables and check the event's target object:
if (evt.target == myFirstTween) doSomething();
else doSomethingElse();

or call two different event handlers:
public function FirstTweenAction():void
     {
     myTween = new Tween(/* tween stuff */);
     myTween.addEventListener(TweenEvent.MOTION_FINISH, myFirstTweenEventMotionFinishHandler);
     }

public function SecondTweenAction():void
     {
     myTween = new Tween(/* tween stuff */);
     myTween.addEventListener(TweenEvent.MOTION_FINISH, mySecondTweenEventMotionFinishHandler);
     }


text:
Q: In ajax i want compare json object and string // this is ajax response in json obj it print 'policyListing'
alert(response.result[i].screenName);

alert(response.result[i].screenName=='policyListing');// it return false

It should return true. I do not know where is the problem how to get true

A: The variable-type of screenName could be an object. You can check the type of a variable with alert( typeof(response.result[i].screenName) );
If the var is not a string-type, you can try to convert it into a string with .toString().
Example:
alert(response.result[i].screenName.toSting() == 'policyListing');


text:
Q: await Parallel.ForEachAsync in recursive function I have recursive function for tree.
Can I loop children node with Parallel.ForEachAsync?
private async Task<List<ResponseBase<BatchRowData>>> SaveDepartments(DepartmentTree node,
    string parentUnitGuid, List<ResponseBase<BatchRowData>> allResponses)
{
    if (parentUnitGuid == null)
    {
        return allResponses;
    }
    await Parallel.ForEachAsync(node.children, async (child, cancellationToken) =>
    {
        ResponseBase<BatchRowData> response = new ResponseBase<BatchRowData>();
        //...do something
        Unit unit = new Unit();
        unit.SerialNum = child.data.DepartmentNumber;
        unit.UnitName = child.data.DepartmentName;
        unit.ParentUnitGuid = parentUnitGuid;
        string unitGuid = await DBGate.PostAsync<string>("organization/SaveUnit", unit);
        if (unitGuid != null)
        {
            response.IsSuccess = true;
            response.ResponseData.ReturnGuid = unitGuid;
            await SaveDepartments(child, unitGuid, allResponses);
        }
        else
        {
            response.IsSuccess = false;
            response.ResponseData.ErrorDescription = "Failed to Save";
        }
        allResponses.Add(response);
    });
    return allResponses;
}

It works. but I wonder if the tree order levels is always saved with Parallel.ForEachAsync.
Because in my tree. it must be.
Or I should use simple sync foreach?
My application is ASP.NET Core 6.0.

A: First things first, the List<T> collection is not thread-safe, so you should synchronize the threads that are trying to Add to the list:
lock (allResponses) allResponses.Add(response);

Otherwise the behavior of your program is undefined.
Now regarding the validity of calling the Parallel.ForEachAsync recursively, it doesn't endanger the correctness of your program, but it does present the challenge of how to control the degree of parallelism. In general when you parallelize an operation you want to be able to limit the degree of parallelism, because over-parallelizing can be harmful for both the client and the server. You don't want to exhaust the memory, the CPU or the network bandwidth of either end.
The ParallelOptions.MaxDegreeOfParallelism property limits the parallelism of a specific Parallel.ForEachAsync loop. It does not have recursive effect. So you can't depend on this.
The easier way to solve this problem is to use a SemaphoreSlim as the throttler, and enclose the body of the Parallel.ForEachAsync loop in a try/finally block:
await semaphore.WaitAsync();
try
{
    // The body
}
finally { semaphore.Release(); }

The semaphore should be initialized with the desirable maximum parallelism for both of its arguments. For example if the desirable limit is 5 then:
SemaphoreSlim semaphore = new(5, 5);

Another way of solving this problem would be to have a single non-recursive Parallel.ForEachAsync loop, which is fed with the items of a Channel<(DepartmentTree, string)>, and inside the body of the loop you write the children of each department in the channel. This should be more efficient than nesting multiple Parallel.ForEachAsync loops the one inside the other, but it is also more complex to implement, and more prone to programming errors (bugs). So I'll leave it out from this answer.


text:
Q: Facebook API PHP SDK posts on a group are visible only in that group? I made through the FB API SDK a program that publishes posts in a Facebook group as if it were a page.
It all works, only these posts do not appear on the user's home, but only within the group. As a result, the visibility of these posts is practically nill.
I deduced this from the views, if I manually publish a post. I have some visibility, but if it's published via the API the visibility collapses.
These are my permission on Facebook app:

Do you have any advice about this?


text:
Q: Is there a way to implement hreflang on subfolder in Shopify Here my current custom code in shopify.

<link rel="alternate" hreflang="en-au" href="{{ canonical_url | replace: 'us', 'au' }}"  />

the output goes like this via source code
<link rel="alternate" hreflang="en-au" href="/en-au/pages/faqs"  />

The problem with the code above is that when visitors view it in other country like UK it won't /en-uk in the URL. I am trying to get to make it more dynamic after /en- so that I can implement on other countries. Here is the code I've tried but it gets error showing "liquid error" in Shopify
<link rel="alternate" hreflang="en-au" href="{{ canonical_url | replace: '{{ localization.country.iso_code }}', 'au' }}"  />

A: If you think that your last part will work, you simply have to extract the second liquid code in a variable and use it.
Here is what I mean:
Instead of
<link rel="alternate" hreflang="en-au" href="{{ canonical_url | replace: '{{ localization.country.iso_code }}', 'au' }}"  />

do like
{% assign iso_code = localization.country.iso_code %}
<link rel="alternate" hreflang="en-au" href="{{ canonical_url | replace: iso_code, 'au' }}"  />


text:
Q: django form wizard: global name 'request' is not defined in done() method I am using django form wizard, which requires a done method as such.
def done(self, form_list, **kwargs):
    #Making an instance of Location
    location = Location(
        manager = User.objects.get(username=request.user.username)
        #more stuff
    )

Except I am getting the following error:
global name 'request' is not defined on line (the line with manager assignment)

Not really sure what I could do to solve this problem. Should I just insert request into the done method? would that even make sense? How do other people handle this?

A: You can refer the request as self.request in class based views and form wizard.
Update your line to
location = Location(             #-------v
    manager = User.objects.get(username=self.request.user.username)
    #more stuff
)


text:
Q: Is there a simple way to add data to a relation table in Rails? I have a dish table, a ingredient table and a dish_ ingredient table to join dish and ingredient (see below). Every time I add a ingredient to dish, I want to increase or add the number of ingredients to the dish_ingredient table. I have manage to update the number by doing:
dish.dish_ingredients[counter].number_of_ingredients = new number

but by doing it this way I need to manage a counter. Is there a simple way to do this in Rails?
class Dish < ActiveRecord::Base
   has_many :dish_ingredients
   has_many :ingredients, :through => :dish_ingredients
end

class Ingredient < ActiveRecord::Base
   has_many :dish_ingredients
   has_many :dishes, :through => :dish_ingredients
end

class DishIngredient < ActiveRecord::Base
   belongs_to :dish
   belongs_to :ingredient
end

# in the database table dish_ingredient contains a field 'number_of_ingredients'
# that I want to update when ingredients are modified or added to dish.

A: Have you tried
class DishIngredient < ActiveRecord::Base
  belongs_to :dish
  belongs_to :ingredient, :counter_cache => true
end

? This requires you to have an ingredients_count attribute in the dish_ingredient table. Rails will automatically handle updates to the counter.

A: What's wrong with :
some_dish.ingredients.count


text:
Q: Creating a web application with full text search on dynamic data Even after thorough requirements engineering we end up with users wanting to attach 'notes' to their otherwise well-structured data records, in other words: arbitrary key-value pairs. Their primary interest is to find records later based on this meta data.
Example:
{
  fixedattr1: 10,
  fixedattr2: 11,
  fixedattr3: 12,
  foo: 'bar',
  lol: 2
}

and
{
  fixedattr1: 0,
  fixedattr2: 1,
  fixedattr3: 2,
  baz: 'rofl'
}

could be two such records. The primary interest is to be able to

*

*add new key-value pairs on the fly

*find records having certain key-value pairs

Obviously this is not going to fly with relational databases. Mongodb (for instance) can handly dynamic attributes (by storing them in the same document), and in general the MEAN stack could be used to build a web app.
Let's accept this idea for a moment, then the question is: what level of support is there in MEAN to index the documents based on the dynamic attributes? Or is there another technology platform that handles this?

A: PostgreSQL supports both JSON data type and GIN indexes out of the box so that will fly just fine with relational databases. You can also choose to model some of the fixed fields as normal columns and only use JSON for the dynamic fields. I would favor PostgreSQL over MongoDB especially if you also need proper ACID transactions and if your data fits on one node.

A: As far as I am concered. Mongo could index a document, but I am not sure if that index goes for "abitrary" records.
One technology that comes to mind if we talk json documents would be elasticsearch. That was build for ... searching.


text:
Q: Test execution dependency for py_test I am writing an integration-test (py_test) for a Python library. Now it only makes sense to run this one if a set of other py_test unit-tests have successfully completed.
I could not yet find a way of adding such a testing-dependency in Bazel.

A: Sorry it is not possible.
An action cannot declare a dependency on a test action.
Maybe you can work around by doing only one test or by adding tags (phase1, phase2):
bazel test --test_tag_filter -phase2 //... && bazel test --test_tag_filter phase2 //...


text:
Q: Get Logged user name I am using MS Access 2013 Web app with SharePoint lists.
I want to get user name of SharePoint logged user to retrieve the user's items in Access form.
I tried select current_user(); but it is always give me back an administrator!!
How to get current user name from MS Access form??


text:
Q: set a css class of element in partial from outside For example, I have a page with this content:

    Some web page
    <partial name="Path/To/Partial.cshtml" class="css-class-to-#ID-1" model="@SomeModel"/>

And I have a partial view with this content:

Some content

I know I could pass the css class through the model, but that would complicate the passing of other data, requiring for example wrapper classes.
The assumption would be, that I always have only one parent html element in the partial.
My question is: How could one achieve this?

A: You can use session to store the class:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });
        ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

       ...
        app.UseAuthorization();

        app.UseSession();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapRazorPages();
        });
    }
}

View:
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
    HttpContextAccessor.HttpContext.Session.SetString("class", "css-class-to-#ID-1");
}

    Some web page
    <partial name="Path/To/Partial.cshtml" model="@SomeModel"/>

Partial view:

Some content


text:
Q: Can't access GRASS GIS modules from within Python 2.7 Using the tutorials posted here, here and here, I am trying to setup a script that will make use of several GRASS GIS raster functions externally. For now I am just trying to get the tutorial script to run but I receive the following error:
CalledModuleError: Module run None ['g.gisenv', '-n'] ended with error Process ended with non-zero return code -1073741515. See errors in the (error) output.

When searching for this error it seems that others have issues trying to import grass.script. However, I am able to import this without issue. It is only afterwards when trying to run a module that I get this error. This happens when I try to use a 'gscript.run_command('g.gisenv') (see code block below).
I run:
- Windows 10 x64
- Python 2.7.13 x86
- GRASS GIS 7.2.0 x86
- x86 version of GDAL
I removed all other GRASS GIS installations (one was installed with QGIS) and reinstalled it with the required Microsoft Visual C++ Redistributable Packages.
import os
import sys
import subprocess

grass7bin = r'C:\Program Files (x86)\GRASS GIS 7.2.0\grass72.bat'
startcmd = [grass7bin, '--config', 'path']
try:
    p = subprocess.Popen(startcmd, shell=False,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
except OSError as error:
    sys.exit("ERROR: Cannot find GRASS GIS start script"
             " {cmd}: {error}".format(cmd=startcmd[0], error=error))
if p.returncode != 0:
    sys.exit("ERROR: Issues running GRASS GIS start script"
             " {cmd}: {error}"
             .format(cmd=' '.join(startcmd), error=err))
gisbase = out.strip(os.linesep)

os.environ['GISBASE'] = gisbase
grass_pydir = os.path.join(gisbase, "etc", "python")
sys.path.append(grass_pydir)

import grass.script.setup as gsetup

gisdb = r'C:\data\grass'
location = "Country"
mapset = "Topic"

rcfile = gsetup.init(gisbase, gisdb, location, mapset)

import grass.script as gscript
print'grass.script imported'

gscript.run_command('g.gisenv', 'n')

os.remove(rcfile)

EDIT:
After trying to reinstall GRASS GIS several times I decided to download a new GRASS GIS installation file and install that. Now the script runs without throwing the error.
EDIT 2:
I thought the issue was resolved but that is not the case. When I try to use a command as per the tutorial here:
gscript.run_command('r.in.gdal', input = inputVRT, output = outputName, overwrite = True)

It doesn't work and I again get a CalledModuleError:
Traceback (most recent call last):
  File "C:\scripts\10_1_grassGis.py", line 54, in <module>
    overwrite = True)
  File "C:\Program Files (x86)\GRASS GIS 7.2.0\etc\python\grass\script\core.py", line 410, in run_command
    return handle_errors(returncode, returncode, args, kwargs)
  File "C:\Program Files (x86)\GRASS GIS 7.2.0\etc\python\grass\script\core.py", line 329, in handle_errors
    returncode=returncode)
CalledModuleError: Module run None ['r.in.gdal', '--o', '--q', '-o', 'input=C:\\data\\rasters\\bykerneNet_03743.vrt', 'output=bykerne03743'] ended with error
Process ended with non-zero return code -1073741512. See errors in the (error) output.

However, if I try things like:
gscript.gisenv()

It runs fine.
What could be the issue?

A: Things have gotten much easier with GRASS GIS 7.4: there is now "grass-session" to call GRASS GIS functionality from Python.
To install the stable version use:
pip install grass-session

For the usage, see the GRASS GIS Wiki or this example GRASS-GIS-Python session.

A: Obviously, what you did to initiate the GRASS session from inside Python is correct. So simpler module g.gisenv and g.list should work. I can think of the following possibilities to try as this issue can be specific to installation:

*

*Try to see if the virtual raster is the issue. Use a real raster file (not a virtual raster) instead.

*If that is not the issue, reinstall GRASS in a folder without space in the folder name like: 'C:\GIS\GRASS_GIS_72\'

*Try defining the file path of your raster with os.path.join as resolved on this post by Micha

*Some similar modules were resolved in my system by uninstalling xerces-c package and all its dependencies (including GDAL) using conda command line, restarting the machine and reinstalling the xerces-c package with the dependencies given that you are using Anaconda.

Good luck!