text:
Q: Can Win32 "move" heap-allocated memory? I have a .NET/native C++ application.  Currently, the C++ code allocates memory on the default heap which persists for the life of the application.  Basically, functions/commands are executed in the C++ which results in allocation/modification of the current persistent memory.  I am investigating an approach for cancelling one of these functions/commands mid-execution.  We have hundreds of these commands, and many are very complicated (legacy) code.
The brute-force approach that I am trying to avoid is modifying each and every command/function to check for the cancellation and do all the appropriate clean-up (freeing heap memory).  I am investigating a multi-threaded approach in which an additional thread receives the cancellation request and terminates the command-execution thread.  I would want all dynamic memory to be allocated on a "private heap" using HeapCreate() (Win32).  This way, the private heap could be destroyed by the thread handling the cancellation request.  However, if the command runs to completion, I need the dynamic memory to persist.  In this case, I would like to do the logical equivalent of "moving" the private heap memory to the default/process heap without incurring the cost of an actual copy.  Is this in any way possible?  Does this even make sense?
Alternatively, I recognize that I could just have a new private heap for every command/function execution (each will be a new thread).  The private heap could be destroyed if the command is cancelled, or it would survive if the command completes.  Is there any problem with the number of heaps growing indefinitely?  I know there is some overhead involved with each heap.  What limitations might I run into?
I am running on Windows 7 64-bit with 8GB RAM (consider this the target platform).  The application I am working with is about 1 million SLOC (half C++, half C#).  I am looking for any experience/suggestions with private heap management, or just alternatives to my solution.

A: You might be better off with separate processes instead of separate threads:

*

*use memory mapped files (ie not a file at all - just cross-processed shared memory)

*killing a process is 'cleaner' than killing a thread

*I think you can have the shared memory 'survive' the killing without a move - you map/unmap instead of move

although you might need to do some memory management on your own.
Anyhow, worth looking into.  I was looking into using inter-process memory for a few other things, and it had some unusual properties (can recall all of it clearly, it was a while ago), and you might be able to take advantage of it.
Just an idea!

A: From MSDN's Heap Functions page:
"Memory allocated by HeapAlloc is not movable. The address returned by HeapAlloc is valid until the memory block is freed or reallocated; the memory block does not need to be locked."
Can you re-link the legacy apps against your own malloc() implementation?  If so, you should be able to manage without modifying the rest of the code.  Your custom malloc library can track allocated blocks by thread, and have a "FreeAllByThreadId() function which you call after killing the legacy function's thread.   You could use private heaps inside the library.
An alternative to private heaps might be doing your own allocation from memory-mapped files.   See "Creating Named Shared Memory."   You create the shared memory while initializing the alloc library for the legacy thread.  On success, map it into the main thread so your c# can access it; on termination, close it and it is released to the system.

A: No. Memory cannot be moved between heaps.

A: Heap is a sort of big chunk of memory. It is a user-level memory manager. A heap is created by lower-level system memory calls (e.g., sbrk in Linux and VirtualAlloc in Windows). In a a heap, then you can request or return a small chunk of memory by malloc/new/free/delete. By default, a process has a single heap (unlike stack, all threads share a heap). But, you can have many heaps.

*

*Is it possible to combine two heaps w/o copying? A heap is essentially a data structure that maintains a list of used and freed memory chunks. So, a heap should have a sort of bookkeeping data called meta data. Of course, this meta data is per heap. AFAIK, no heap manager supports a merge operation of two heaps. I had reviewed entire source code of malloc implementation in Linux glibc (Doug Lea's implementation), but no such operation. Windows Heap* functions are also implemented in a similar way. So, it is currently impossible to move or merge two separate heaps.

*Is it possible to have many heaps? I don't think there should be a big problem to have many heaps. As I said before, a heap is just a data structure that keeps used/freed memory chunks. So, there should be some amount of overhead. But, it's not that severe. When you look at one of malloc implementation, there is malloc_state, which is a basic data structure for each heap. For example, you can create another heap by create_mspace (in Windows, it is HeapCreate), then you will get a new malloc state. It's not that big. So, if this tread-off (some heap overhead vs. implementation easiness) is fine, then you may go on.
If I were you, I'll try the way you describe. It makes sense to me. Having a lot of heap objects would not make a big overhead.
Also, it should be noted that technically moving memory regions is impossible. Pointers that pointed the moved memory region will result in dangling pointers.
p.s. Your problem seems like a transaction, especially Software Transactional Memory. A typical implementation of STM buffers pending memory writes, and then commits to the real system memory it the transaction had no conflict.


text:
Q: How to achieve KGroupTable use case in flink I am doing some poc on flink but I am not able to find documentation around how will I achieve use case similar to KGroupTable in kafka stream as shown below
KTable<byte[], Long> aggregatedStream = groupedTable.aggregate(() -> 0L,
(aggKey, newValue, aggValue) -> aggValue + newValue.length(),
(aggKey, oldValue, aggValue) -> aggValue - oldValue.length(),  Serdes.Long(),     "aggregation-table-store");

Use case I want to aggregate account balance from transactions I receive. If I get an update on existing transaction Id I want to remove old value and add new value. Lets say if a transaction gets cancelled I want to remove the old value from account balance.
eg
TransactionId AccountId  Balance
1             account1   1000         // account1 - 1000
2             account1   2000         // account1 - 3000
3             account2   2000         // account1 - 3000, account2 - 2000
1             account1   500          // account1 - 2500, account2 - 2000

In above example 4th update is, i got an update on existing transaction #1 so it will remove the old balance (1000) and add new balance (500)
Thanks

A: Here's a sketch of how you could approach that. I used Tuples because I was lazy; it would be better to use POJOs.
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class TransactionsWithRetractions {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Tuple3<Integer, String, Float>> rawInput = env.fromElements(
                new Tuple3<>(1, "account1", 1000.0F ),
                new Tuple3<>(2, "account1", 2000.0F),
                new Tuple3<>(3, "account2", 2000.0F),
                new Tuple3<>(1, "account1", 500.0F)
        );

        rawInput
                .keyBy(t -> t.f1)
                .map(new ManageAccounts())
                .print();

        env.execute();
    }

    public static class ManageAccounts extends RichMapFunction<Tuple3<Integer, String, Float>, Tuple2<String, Float>>{
        MapStateDescriptor<Integer, Float> transactionsDesc;
        ReducingStateDescriptor<Float> balanceDesc;

        @Override
        public void open(Configuration parameters) throws Exception {
            transactionsDesc = new MapStateDescriptor<Integer, Float>("transactions", Integer.class, Float.class);
            balanceDesc = new ReducingStateDescriptor<>("balance", (f, g) -> f + g, Float.class);
        }

        @Override
        public Tuple2<String, Float> map(Tuple3<Integer, String, Float> event) throws Exception {
            MapState<Integer, Float> transactions = getRuntimeContext().getMapState(transactionsDesc);
            ReducingState<Float> balance = getRuntimeContext().getReducingState(balanceDesc);

            Float currentValue = transactions.get(event.f0);
            if (currentValue == null) {
                currentValue = 0F;
            }
            transactions.put(event.f0, event.f2);
            balance.add(event.f2 - currentValue);

            return new Tuple2<>(event.f1, balance.get());
        }
    }
}

When run, this produces:
1> (account1,1000.0)
8> (account2,2000.0)
1> (account1,3000.0)
1> (account1,2500.0)

Note that this implementation keeps all transactions in state forever, which might become problematic in a real application, though you can scale Flink state to be very large.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows impersonation for WMI calls via python? I'm using PyWin32 to make WMI calls to the system in python from my django web application. My goal is to allow users to add printers to the system via a web interface. To do this, I'm using win32print.AddPrinterConnection.
This works well running the development server under my user account. I can add all the printers I want. However, eventually, this will need to run under apache which runs as the LocalSystem account.
This is problematic for two reasons:

*

*The LocalSystem account has no network privileges at all, and this is a network printer. The AddPrinterConnection WMI call eventually makes a COM call that will be disallowed.

*The LocalSystem account has no access to the domain these printers are on. They require a domain account to access.

Therefore, I've come to the conclusion that I need to impersonate domain user(s) to accomplish this task. I've done so using the code found here:
http://code.activestate.com/recipes/81402/
This seems to work as I'm able to verify that I've successfully impersonated the calling code. Unfortunately, after impersonation I always get this error from the win32print.AddPrinterConnection API call:
Exception Type: error
Exception Value: (2, 'AddPrinterConnection', 'The system cannot find the file specified.')

Do you have any idea why this may be?
Thanks a bunch! Pete
Update
Playing around, I noticed the the AddPrinterConnection API call completes successfully if the user that I'm impersonating is currently logged into the system. Once I log that user out and retry the command while impersonating that user, I get the error stated above.
What is going on here?

A: I can't help with the specific problem, but I do know that if I had to work with WMI stuff on Windows, with Python, I would definitely reach for Tim Golden's Python WMI module instead of pywin32.  Perhaps in the documentation/cookbook or Google searches using that module you can find a solution.


text:
Q: How to get and cast JNDI object correctly in Liberty I have a big problem on getting the correct instance or at least casting the instance I got with JNDI-lookup to correct interface at Web Sphere Liberty (16.0.0.4, running on Java 7, though using Oracle Java 1.8.0_45 in the back, developing on Eclipse Neon.2).
When I start the server and the ear containing the EJB, I get the following notification into the log:

The server is binding the xxx.interfaces.MyLocal interface of the MyEJB enterprise bean in the xxx-ejb.jar module of the xxx-ear application.  The binding location is: java:global/xxx/MyEJB!xxx.interfaces.MyLocal

Then I have a web application (ear) which has a service provider (with @Produces) for the previously started ejb-service, which will provide the JNDI resource as injectable (@Inject) for the rest of the application (a bit tricky thing, the main idea is to allow to change the lookup location from configuration file + do some other stuff also). It seems to work correctly for all it is supposed to, but when getting the JNDI-resource, it kind of works but not correctly.
If I put the ejb part as a dependency into my web-module, I can inject it directly (@Inject MyLocal myEjb;).
As the injected resource I get an object with the signature:
EJSMyLocal0SLMyEJB_a4549339@cc5d2cdd
with lookup I get an object with signature (at the same time as the inject):
EJSMyLocal0SLMyEJB_a4549339@cdda36a7
(Not the same instance afaik, but the "type" is correct?)
The injected resource is correctly (automatically of course) cast on 'MyLocal' interface and is ok.
When I try to check the resource got with JNDI, it does not qualify as an instance of 'MyLocal' nor as 'MyRemote'? Also the actual cast fails of course with ClassCastException. (MyRemote is basically the same as the MyLocal interface ... MyLocal extends MyRemote, both interfaces are accordingly annotated with @Local and @Remote)
The EJB looks like this at the time of testing...
@Stateless
@Named
@Default
@Local(MyLocal.class)
@Remote(MyRemote.class)
public class MyEJB implements MyLocal, MyRemote { ... }

I also tried to cast the JNDI resource like this.
InitialContext ic = new InitialContext();
Object lookedUpEjb = ic.lookup(lookup); // the 'java:global...' from log
MyRemote jndiEjb = (MyRemote) PortableRemoteObject.narrow(lookedUpEjb, MyRemote.class)
// Tried also casting/checking 'instanceof' to MyLocal...

No difference with that, the same ClassCastException occurs?!
I have the following features in server.xml
<featureManager>
    <feature>javaee-7.0</feature>
    <feature>ldapRegistry-3.0</feature>
    <feature>localConnector-1.0</feature>
    <feature>adminCenter-1.0</feature>
    <feature>wsSecurity-1.1</feature>
    <feature>ejbLite-3.2</feature>
    <feature>ejbRemote-3.2</feature>
    <feature>cdi-1.2</feature>
    <feature>jpa-2.1</feature>
    <feature>jsf-2.2</feature>
    <feature>jaxrs-2.0</feature>
    <feature>jaxws-2.2</feature>
</featureManager>

I found this documentation on the Liberty JNDI functionality:
https://www.ibm.com/support/knowledgecenter/SSAW57_liberty/com.ibm.websphere.wlp.nd.multiplatform.doc/ae/twlp_ejb_remote.html
I can't see where I go wrong. How do I cast that object from JNDI lookup to MyLocal or MyRemote interfaces?
---- Note ----
Using the @EJB annotation is not an option (it works though), since it will be hard coded reference to the resource. I want it to be optional though, thus JNDI lookup. @EJB will cause the app to crash when the resource is not available.

A: The problem is that each application has a different ClassLoader and the object that has been bound into JNDI was loaded with the ClassLoader of the application that defined the EJB.
This should not be an issue for Remote EJB interfaces as the ORB should have taken care of this for you. On a remote call that returns such an object, the ORB will serialize the object (from the target ClassLoader) and then deserialize using the client ClassLoader. For a lookup like this, the PortableRemoteObject.narrow should also take care of this. The failure here appears to just be a bug in the ORB.
In order to support cross application access to Local EJB interfaces, either the Local EJB interface needs to be moved to a shared library, that is used by both applications, or both applications configured to use a single global ClassLoader.  See this link for more information about using Local EJB interfaces across applications: Correct way to lookup local EJB in websphere - Getting ClassCastException (Note: this link is discussing traditional WebSphere, but the issue is the same with Liberty, as is the resolution to use a shared library for the interface).


text:
Q: Obtrusive and regular requests in Firefox I'm using Kaspersky Internet Security and haven't noticed this until today. While working on a local web project (localhost, port 3000) Firefox is doing external requests to ff.kis.v2.scr.kaspersky-labs.com. I am sure this legitimate, but interestingly - Firefox doesn't do these requests inside other (public) web pages like superuser.com. Also - I don't have any Kaspersky extension inside Firefox. I don't see how would I disable this in KIS either. Chrome is not affected. For some reason Edge cannot open the project but that's certainly due to specifics in the project itself.
These requests are really obtrusive and are like half a second apart.

A: You seem to have the Kaspersky add-on installed on Firefox.
The Kaspersky Labs post
What is "ff.kis.v2.scr.kaspersky-labs.com"
says this:

This is a fictitious address used by the Kaspersky AddOn to
  communicate with KIS/KTS. The address is resolved on your computer, it
  doesn't go outside. You can prevent the 'contact' by deactivating the
  script injection. Then the KL addon loses parts of its function.
Settings->Additional->Network', disable 'Inject script into web
  traffic...'.

I don't know if this "problem" merits any fix.


text:
Q: The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine I spent last two days trying to solve this error
The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine
no luck!!! :(
i am running windows xp sp2
please help me i am ..,..., frustrated!!
thanks

A: Are you running 64 Bit?  Here's the latest drivers which supports it:
http://support.microsoft.com/kb/239114
It took MS forever to get 64 Bit drivers for Jet 4.0.

A: I solved this by going to project properties | Build, and changing Platform Target to x86.

A: If it's the 32 bit windows, and it worked previously, maybe right click mdac.inf in c:\windows\inf and choose Install to reinstall/repair it. It may ask for your windows cd.

A: try
regsvr32 /u Msjet40.dll
regsvr32 Msjet40.dll

A: Yes, one way it can be resolved by making the value of the property Run64BitRuntime to be false in project property.
http://wpfgrid.blogspot.com/2013/01/sql-server-2012-ssis-excel-import-fail.html
SQL Server 2012 SSIS Excel import fail issue due to OLE Jet driver

SSIS project fails to build due to OLE Jet drive 64 bit version and you get the following error:
Microsoft.Jet.OLEDB.4.0 is not registered

Here is what you can do:
Right click on your SSIS project name and choose properties, go to:
Configuration Properties -> Debugging tab. (expand Configuration Properties if you do to see Debugging right way).

Make the value of the property Run64BitRuntime to be false.


text:
Q: Python script to write data into a CSV file I have the following code and the purpose of this code is to query the CPU, memory and disk from Prometheus and store them in CSV file. But this file is always storing all of the dataset in CPU column and it keeps repeating. I defined a list for this purpose. Can you please tell me what is my mistake?
import requests
import csv
import time
import json

# Define the Prometheus URL
prometheus_url = "http://localhost:9000/api/v1/query"

# Define the Prometheus queries for each metric
cpu_query = 'sum(rate(container_cpu_usage_seconds_total{namespace=~".+"}[1m])) by (namespace, pod, container)'
memory_query = 'sum(container_memory_usage_bytes{namespace=~".+"}) by (namespace, pod, container)'
disk_read_query = 'sum(rate(container_fs_reads_bytes_total{namespace=~".+"}[1m])) by (namespace, pod, container)'
disk_write_query = 'sum(rate(container_fs_writes_bytes_total{namespace=~".+"}[1m])) by (namespace, pod, container)'
network_in_query = 'sum(rate(container_network_receive_bytes_total{namespace=~".+"}[1m])) by (namespace, pod, container)'
network_out_query = 'sum(rate(container_network_transmit_bytes_total{namespace=~".+"}[1m])) by (namespace, pod, container)'

# Define headers for the CSV files
cpu_csv_headers = ['Namespace', 'Deployment', 'Container', 'CPU usage']
memory_csv_headers = ['Namespace', 'Deployment', 'Container', 'Memory usage']
disk_read_csv_headers = ['Namespace', 'Deployment', 'Container', 'Disk read']
disk_write_csv_headers = ['Namespace', 'Deployment', 'Container', 'Disk write']
network_in_csv_headers = ['Namespace', 'Deployment', 'Container', 'Network in']
network_out_csv_headers = ['Namespace', 'Deployment', 'Container', 'Network out']

# Define a function to query Prometheus and return the result as JSON
def query_prometheus(query):
    response = requests.get(prometheus_url, params={'query': query})
    data = json.loads(response.content)
    return data

# Define a function to write the metric data to a CSV file
def write_csv_file(results, headers, filename):
    with open(filename, 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(headers)
        for result in results:
            try:
                row = [result['metric']['namespace'], result['metric']['deployment'], result['metric']['container'], result['value'][1]]
            except KeyError:
                row = [result['metric']['namespace'], "N/A", result['metric']['container'], result['value'][1]]
            writer.writerow(row)

# Run the script continuously and write data to separate CSV files for each metric
while True:
    # Query Prometheus for each metric for all deployments and namespaces
    cpu_data = query_prometheus(cpu_query)
    memory_data = query_prometheus(memory_query)
    disk_read_data = query_prometheus(disk_read_query)
    disk_write_data = query_prometheus(disk_write_query)
    network_in_data = query_prometheus(network_in_query)
    network_out_data = query_prometheus(network_out_query)
    # Extract the results from the Prometheus response
    cpu_results = cpu_data['data']['result']
    memory_results = memory_data['data']['result']
    disk_read_results = disk_read_data['data']['result']
    disk_write_results = disk_write_data['data']['result']
    network_in_results = network_in_data['data']['result']
    network_out_results = network_out_data['data']['result']

    # Write the results to separate CSV files
    write_csv_file(cpu_results, csv_headers, 'cpu.csv')
    write_csv_file(memory_results, csv_headers, 'memory.csv')
    write_csv_file(disk_read_results, csv_headers, 'disk_read.csv')
    write_csv_file(disk_write_results, csv_headers, 'disk_write.csv')
    write_csv_file(network_in_results, csv_headers, 'network_in.csv')
    write_csv_file(network_out_results, csv_headers, 'network_out.csv')

    # Sleep for 5 minutes before running the script again
    time.sleep(60)```

I was expecting to record CPU, memory and disk in different columns.


text:
Q: 20k records are coming from database select query then in foreach loop its hang I am facing an issue is, i have to select a record from database with specific condition (where status=0), after that if around 20k rows are coming from select query then i added foreach loop to apply some conditions and on condition true i update the status of every fetched row from 0 to 1 and 1 to 2 and so on...
My problem is when large amount of data is coming from database then this process is hang and service stopped.
Please guide me what else i can do on place of foreach...if..else etc...

A: Use hash insted of foreach

// Common Usage:
$users = [
    ['id' => 1, 'name' => 'mark'],
    ['id' => 2, 'name' => 'jane'],
    ['id' => 3, 'name' => 'sally'],
    ['id' => 4, 'name' => 'jose'],
];
$results = Hash::extract($users, '{n}.id');
// $results equals:
// [1,2,3,4];


text:
Q: Ошибка "JFTP: :write: Некорректный ответ" Не могу сохранить изменения в шаблоне, когда нажимаю на сохранить, выскакивают 2 сообщения

JFTP: :write: Некорректный ответ.
Не удалось сохранить данные. Ошибка: Произошла ошибка. Файл index.php не удаётся сохранить.

Это происходит, когда я пытаюсь изменить страницу главного шаблона или файлы:
css/layouts.css
css/modules.css
css/template.css
A: Почитайте про chmod, тут в картинках. Более подробно - man chmod или тут.


text:
Q: Creating a heatmap by sampling and bucketing from a 3D array I have some experimental data that exists like so:
x = array([1, 1.12, 1.109, 2.1, 3, 4.104, 3.1, ...])
y = array([-9, -0.1, -9.2, -8.7, -5, -4, -8.75, ...])
z = array([10, 4, 1, 4, 5, 0, 1, ...])

If it's convenient, we can assume that the data exists as a 3D array or even a pandas DataFrame:
df = pd.DataFrame({'x': x, 'y': y, 'z': z})

The interpretation being, for every position x[i], y[i], the value of some variable is z[i]. These are not evenly sampled, so there will be some parts that are "densely sampled" (e.g. between 1 and 1.2 in x) and others that are very sparse (e.g. between 2 and 3 in x). Because of this, I can't just chuck these into a pcolormesh or contourf.
What I would like to do instead is to resample x and y evenly at some fixed interval and then aggregate the values of z. For my needs, z can be summed or averaged to get meaningful values, so this is not a problem. My naïve attempt was like this:
X = np.arange(min(x), max(x), 0.1)
Y = np.arange(min(y), max(y), 0.1)
x_g, y_g = np.meshgrid(X, Y)
nx, ny = x_g.shape
z_g = np.full(x_g.shape, np.nan)

for ix in range(nx - 1):
    for jx in range(ny - 1):
        x_min = x_g[ix, jx]
        x_max = x_g[ix + 1, jx + 1]
        y_min = y_g[ix, jx]
        y_max = y_g[ix + 1, jx + 1]
        vals = df[(df.x >= x_min) & (df.x < x_max) &
                  (df.y >= y_min) & (df.y < y_max)].z.values
        if vals.any():
            z_g[ix, jx] = sum(vals)

This works and I get the output I desire, with plt.contourf(x_g, y_g, z_g) but it is SLOW! I have ~20k samples, which I then subsample into ~800 samples in x and ~500 in y, meaning the for loop is 400k long.
Is there any way to vectorize/optimize this? Even better if there is some function that already does this!
(Also tagging this as MATLAB because the syntax between numpy/MATLAB are very similar and I have access to both software.)

A: Here's a vectorized Python solution employing NumPy broadcasting and matrix multiplication with np.dot for the sum-reduction part -
x_mask = ((x >= X[:-1,None]) & (x < X[1:,None]))
y_mask = ((y >= Y[:-1,None]) & (y < Y[1:,None]))

z_g_out = np.dot(y_mask*z[None].astype(np.float32), x_mask.T)

# If needed to fill invalid places with NaNs
z_g_out[y_mask.dot(x_mask.T.astype(np.float32))==0] = np.nan

Note that we are avoiding the use of meshgrid there. Thus, saving memory there as the meshes created with meshgrid would be huge and in the process hopefully gaining performance improvement.
Benchmarking
# Original app
def org_app(x,y,z):
    X = np.arange(min(x), max(x), 0.1)
    Y = np.arange(min(y), max(y), 0.1)
    x_g, y_g = np.meshgrid(X, Y)
    nx, ny = x_g.shape
    z_g = np.full(np.asarray(x_g.shape)-1, np.nan)

    for ix in range(nx - 1):
        for jx in range(ny - 1):
            x_min = x_g[ix, jx]
            x_max = x_g[ix + 1, jx + 1]
            y_min = y_g[ix, jx]
            y_max = y_g[ix + 1, jx + 1]
            vals = z[(x >= x_min) & (x < x_max) &
                      (y >= y_min) & (y < y_max)]
            if vals.any():
                z_g[ix, jx] = sum(vals)
    return z_g

# Proposed app
def app1(x,y,z):
    X = np.arange(min(x), max(x), 0.1)
    Y = np.arange(min(y), max(y), 0.1)
    x_mask = ((x >= X[:-1,None]) & (x < X[1:,None]))
    y_mask = ((y >= Y[:-1,None]) & (y < Y[1:,None]))

    z_g_out = np.dot(y_mask*z[None].astype(np.float32), x_mask.T)

    # If needed to fill invalid places with NaNs
    z_g_out[y_mask.dot(x_mask.T.astype(np.float32))==0] = np.nan
    return z_g_out

As seen, for a fair benchmarking, I am using array values with the original approach, as fetching values from a dataframe could slow things down.
Timings and verification -
In [143]: x = np.array([1, 1.12, 1.109, 2.1, 3, 4.104, 3.1])
     ...: y = np.array([-9, -0.1, -9.2, -8.7, -5, -4, -8.75])
     ...: z = np.array([10, 4, 1, 4, 5, 0, 1])
     ...:

# Verify outputs
In [150]: np.nansum(np.abs(org_app(x,y,z) - app1(x,y,z)))
Out[150]: 0.0

In [145]: %timeit org_app(x,y,z)
10 loops, best of 3: 19.9 ms per loop

In [146]: %timeit app1(x,y,z)
10000 loops, best of 3: 39.1 µs per loop

In [147]: 19900/39.1  # Speedup figure
Out[147]: 508.95140664961633

A: Here is a MATLAB solution:
X = min(x)-1 :.1:max(x)+1; % the grid needs to be expanded slightly beyond the min and max
Y = min(y)-1 :.1:max(y)+1;
x_o = interp1(X, 1:numel(X), x, 'nearest');
y_o = interp1(Y, 1:numel(Y), y, 'nearest');
z_g = accumarray([x_o(:) y_o(:)], z(:),[numel(X) numel(Y)]);


text:
Q: Let $f: G\to G'$ be a group homomorphism. There is a bijection from the $\ker(f)$ to the preimage of $h$ in the image $f (f^{-1}(h))$. This is difficult to wrap my head around.  If I am reading this right, there is a bijection from (elements in G that map to the neutral element in G') to (any element g in G whose image is h in G'.)  How can I show this or at least conceptualize it better?

A: As mentioned in the comments section, this is poorly worded.
What it is really asking for is a bijection between elements of the set $\text{ker}(f)=\{x\in G|f(x)=e'\}$ (where $e'$ is the identity in $G'$) and the set $f^{-1}(h)=\{y\in G|f(y)=h\}$ for some $h\in G'$.
Note - you actually need to specify $h\in \text{im}(f)$, or else $f^{-1}(h)$ might be the empty set, while the kernel must at least contain the identity element of $G$. Then you could never find a bijection!
Hopefully you can see how similar these sets are already!
The key is to find a way to move between these two sets - elements mapped to the identity, and elements mapped to $h$. Remember that we're dealing with a homomorphism here, so $f$ will respect all the operations of composition; does this suggest a way to send an element mapped to $h$ under $f$ to a corresponding element mapped to the identity?
Hint:

Use the inverse of $h$!


text:
Q: Views are failing when their underlying table is repopulated I am creating a view on a bigQuery Table.  The view works fine, until I truncate that table and put new data in it.  I get the following error:
"Query Failed Error: A view from this query references an old version of
a table that might be incompatible. Please delete and re-create
repcore-dev:views.listings."

If I run the query that defines the view, it works. If I re-create the view with the same query, it works.  But my question is why this is necessary.  For us the real value in the view is that it provides an abstraction of the table data (even when that data is re-populated).


text:
Q: White background for colorbar tick label Who do I apply a white background for the colorbar tick labels? (I use a jet colormap in which black text is hardly visual - changing the text color to white doesn't help either)
A typical workaround for text such as:
h = text(0.1,0.1,'some text','units','normalized','color','k','background','w');

isn't working; seems that background doesn't apply for colorbar.

A: One of the things I could think of is to set the figure background to white, so everything is seen better.
figure('Color',[1 1 1]);
[c, h] = contour(peaks/30);
clabel(c, h)
cb = colorbar


text:
Q: Programmaticaly configuring an RDS instance for Elastic Beanstalk I am trying to automate the creation of the temporary environment, I am struggling with the creation of a related RDS instance inside Elastic Beanstalk.
I would like that when I call eb create envName the environment also spawns an RDS database.
One solution would be to manually do it. Another solution seems to involve '.ebextensions' Using Elastic Beanstalk .ebextensions to specify an RDS database , though .ebextensions are to be run at each deployment, this could fit through a specific hook, but I would like to have my config in .elasticbeanstalk/config.yml because this is the file that seems to have preconfiguration for when I call eb commands.
One of the reason to not but it in .ebextensions is also that in the project configuration, those are not environment specific, they describe the requirements for the app in any environment.

A: I personally believe it is a bad idea to create the database as part of the environment, as it is a lot harder to deal with stopping and recreating the environment if you need to. I believe it is a lot easier and safer to keep the database running even if you want to completely destroy the environment and start all over. I believe most experience users will recommend you to manage the RDS on your own (outside EB). It is really easy anyway.
That said (and given you didn't ask for that), you can simply create a database as part of the eb create command itself:
eb create -db -db.engine postgres -db.version 9.4 -db.user dbroot -db.i ...

http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb3-create.html


text:
Q: I can't understand what's the"no closing instance of....." means? I am a freshman,I can't understand what's the"no closing instance of....." means?
public static void main(String[] args) {
    Map<Pk_person, Person> map = new HashMap<Pk_person, Person>();
    Pk_person pk_person = new Pk_person(); //Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    //No enclosing instance of type Simple1 is accessible.
    //Must qualify the allocation with an enclosing instance of type Simple1 (e.g. x.new A() where x is an instance of Simple1).
    pk_person.setPrefix("MR");
    pk_person.setNumber(22081);
    map.put(pk_person, new Person(pk_person, "马先生"));
    /*Pk_person pk_person2 = new Pk_person();
    pk_person2.setPrefix("MR");
    pk_person2.setNumber(22081);
    Person person2 = map.get(pk_person2);*/
    System.out.println(pk_person.getPrefix());
}

A: Pk_person is an inner class of class Simple1 .Just like member varibales cannot exist without an instance of Class,similarly inner class need an enclosing of an outer class's instance.They can have any access modifier just like other member varibales.
You need to do something like this:-
new Simple1().new Pk_person();

A: The Oracle Docs give quite a good explanation why things work / won't work that way. Also other threads as pointed out by Mick Mnemonic give some explanations. Instead of repeating them, consider the analogy with static variables:
You cannot refer to a non-static variable from a static context (like the main() method cannot access a variable in the same class that is not static). And likewise you cannot refer to a non-static nested class from a static context.
That's because from a nested inner ( = non-static) class you can access (non-static) member variables of the enclosing (outer) class, which makes it impossible to refer to an instance of an inner class from a static context.


text:
Q: Процедура mysql первый раз пишу процедуру в mysql пожалуйста поправьте меня
DELIMITER //
CREATE PROCEDURE `proc_IN` (IN var1 INT)
BEGIN
    DECLARE a INT;
    DECLARE TimeN TEXT;
    SET a = SELECT COUNT(old_idPersonalClothing) FROM PersonalClothing WHERE old_idPersonalClothing = var1;
    IF a = 1 THEN
        SET TimeN = Select `TimeN` from Clothing, PersonalCLothing WHERE `idClothing`=`idClothing1` and `IdPersonal` = var1;
        UPDATE PersonalClothing SET Fact=Fact+1 WHERE IdPersonal = var1;
        UPDATE PersonalClothing SET dateNext= SELECT INTERVAL TimeN MONTH + `date1` FROM `PersonalClothing` WHERE `IdPersonal` = var1;
    ELSE
        INSERT INTO `PersonalClothing`( `Old_IdPersonal`, `IdWorker1`, `IdClothing1`, `quantity`, `comment`, `date1`, `dateNext`, `purchasePrice`, `causeOfDelay`, `dateCause`, `transferCause`) VALUES (SELECT `Old_IdPersonal`, `IdWorker1`, `IdClothing1`, `quantity`, `comment`, `date1`, `dateNext`, `purchasePrice`, `causeOfDelay`, `dateCause`, `transferCause` FROM PersonalClothing WHERE IdPersonal` = var1;);
END IF;
END//


text:
Q: Jenkins ssh: Recover deleted ssh known host or recreate it? Recently I got an error doing ssh to another remote server from Jenkins pipeline. I forget to save all the log but here's a part of it
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!

In the error log, there's a suggestion to run this command to fix it
sudo ssh-keygen -f "/var/lib/jenkins/.ssh/known_hosts" -R "<<remote ssh ip>>"
so I ran it.
Previously some remote ssh command does run before it returns an error.
But now it seems can't connect to the remote at all, the remote ssh command fails from the beginning.
Failed to add the host to the list of known hosts (/var/lib/jenkins/.ssh/known_hosts).
from How can I get rid of " WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!" I tried running ssh-keygen -R <<remote ssh ip>> but the error still appear.
How can I recover the deleted line? or recreate a new one?

A: First, you have to understand what the message means before you "get rid of it".
The message means the destination server has changed its identity or someone is hacking you man-in-the-middle like and the server you are trying to reach, is not the server you think it is.
So first of all you must make sure there is no man-in-the-middle hack going on.
Then, you go into the known_hosts file and delete just the line with the server you are about to connect to.
After saving, you get asked wether you want to trust the server or not just as a connection to a yet unknown host.


text:
Q: is there a way of adding package/module to livetex (Latex) manually Note: I am using Linux ubuntu
And I am using latex for compiling a file to get pdf. The file contains

a pseudocode of an algorithm

but it requires a package to use those big O notations like symbols. Since I have downloaded that package separately so it needs to be added manually
How can I add it to livetex so it should load the package?
Any help is appreciated. If you still don't get any part of my question. I am ready to explain immediately. Thank you


text:
Q: Accessing XAML Text Box in Another Name Space I started the project with two different namespaces, which probably is not good practice but its nearly done.
I have a textbox
 <TextBox x:Name="txtStatus" HorizontalAlignment="Left" Height="23" Margin="55,272,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="241" TextChanged="TextBox_TextChanged"/>

In namespace one, that I want to access in anotherClass in NameSpace2.
Is it possible to make this reference?

A: Bind the textbox to a property on a class instance using the mode TwoWay. Then allow the other instance a reference to the the instance which has the property and change the property as needed; results shown on the screen regardless of who/what changes it.


text:
Q: jbogard/Respawn, how to reseed sql? Can't understand how to Reseed via Respawn. ReseedSql property is a private set.
How do I set this property? I don't see a constructor with parameters to set private setters.
Should I override the Checkpoint class?
public class Checkpoint
    {
        private GraphBuilder _graphBuilder;
        private IList<TemporalTable> _temporalTables = new List<TemporalTable>();

        public string[] TablesToIgnore { get; set; } = new string[0];
        public string[] TablesToInclude { get; set; } = new string[0];
        public string[] SchemasToInclude { get; set; } = new string[0];
        public string[] SchemasToExclude { get; set; } = new string[0];
        public string DeleteSql { get; private set; }
        public string ReseedSql { get; private set; }
        public bool CheckTemporalTables { get; set; } = false;
        internal string DatabaseName { get; private set; }
        public bool WithReseed { get; set; } = false;
        public IDbAdapter DbAdapter { get; set; } = Respawn.DbAdapter.SqlServer;

        public int? CommandTimeout { get; set; }

        }
    }

A: If by reseed you mean reseting identity columns seed values during the reset, then you simply need to set Checkpoint.WithReseed to true.
See this PR and this issue for implementation details and discussion.
But if reseed means restoring data to its initial state instead of just deleting it, you might want to checkout the Reseed library.


text:
Q: Upgrade testng version from 6.10 to 7.6 What do I need to keep in mind while upgrading the testng version in pom.
I am mostly interested in changes in retryAnalyzer logic.
[Edit Question]:

*

*Do. I need to use "AnnotationTransformer" to use 7.6 or it can still work by implementing IRetryAnalyzer

*After this change, I updated testng and tried adding retry logic in testng, instead of on the test. But if does not retry it at all.
I already had a class "RetryAnalyzer"
public class RetryAnalyzer implements IRetryAnalyzer {
  @Override
    public boolean retry(final ITestResult result) {
    //some logic
}
}

Now I added Annotation transformer
public class AnnotationTransformer implements IAnnotationTransformer {
    @Override
    public void transform(ITestAnnotation annotation,Class testClass,Constructor testConstructor, Method testMethod) {
        annotation.setRetryAnalyzer(RetryAnalyzer.class);
    }
}

I update the POM from version 6.10 to version 7.6.1


text:
Q: How do I force access by index rowid in Oracle? I need help forcing Oracle to always use table access by index row id on table "r_rapport" (~60k rows) to subsequently avoid full table scans on "r_attributfeld" (~8m rows) . I have a query resulting in the following plan:
---------------------------------------------------------------------------------------------------------
| Id  | Operation                      | Name           | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT               |                |   101 | 22220 |       | 63518   (2)| 00:12:43 |
|*  1 |  COUNT STOPKEY                 |                |       |       |       |            |          |
|   2 |   VIEW                         |                |  2870 |   616K|       | 63518   (2)| 00:12:43 |
|*  3 |    SORT ORDER BY STOPKEY       |                |  2870 |   313K|   696K| 63518   (2)| 00:12:43 |
|*  4 |     FILTER                     |                |       |       |       |            |          |
|*  5 |      HASH JOIN SEMI            |                |  2871 |   314K|       | 51920   (2)| 00:10:24 |
|*  6 |       HASH JOIN RIGHT SEMI     |                |  2871 |   299K|       | 26084   (2)| 00:05:14 |
|   7 |        VIEW                    | VW_NSO_1       |   214 |  1070 |       |     5  (20)| 00:00:01 |
|*  8 |         HASH JOIN              |                |   214 |  5350 |       |     5  (20)| 00:00:01 |
|*  9 |          INDEX RANGE SCAN      | TEST7          |   141 |  1269 |       |     2   (0)| 00:00:01 |
|* 10 |          INDEX RANGE SCAN      | TEST8          |   228 |  3648 |       |     2   (0)| 00:00:01 |
|* 11 |        HASH JOIN SEMI          |                |  5848 |   582K|       | 26079   (2)| 00:05:13 |
|* 12 |         HASH JOIN              |                |  6547 |   620K|       |   243   (2)| 00:00:03 |
|* 13 |          INDEX RANGE SCAN      | TEST5          |    47 |   470 |       |     2   (0)| 00:00:01 |
|  14 |          TABLE ACCESS FULL     | R_RAPPORT      | 60730 |  5159K|       |   240   (1)| 00:00:03 |
|  15 |         VIEW                   | VW_SQ_3        |   334K|  1633K|       | 25834   (2)| 00:05:11 |
|* 16 |          HASH JOIN             |                |   334K|    14M|    10M| 25834   (2)| 00:05:11 |
|  17 |           INDEX FAST FULL SCAN | TEST4          |   476K|  4656K|       |   368   (2)| 00:00:05 |
|* 18 |           HASH JOIN            |                |   343K|    11M|    11M| 24214   (2)| 00:04:51 |
|* 19 |            TABLE ACCESS FULL   | R_ATTRIBUTFELD |   343K|  7722K|       | 20483   (2)| 00:04:06 |
|  20 |            INDEX FAST FULL SCAN| TEST3          |  1670K|    17M|       |  1324   (1)| 00:00:16 |
|  21 |       VIEW                     | VW_SQ_2        |   334K|  1633K|       | 25834   (2)| 00:05:11 |
|* 22 |        HASH JOIN               |                |   334K|    14M|    10M| 25834   (2)| 00:05:11 |
|  23 |         INDEX FAST FULL SCAN   | TEST4          |   476K|  4656K|       |   368   (2)| 00:00:05 |
|* 24 |         HASH JOIN              |                |   343K|    11M|    11M| 24214   (2)| 00:04:51 |
|* 25 |          TABLE ACCESS FULL     | R_ATTRIBUTFELD |   343K|  7722K|       | 20483   (2)| 00:04:06 |
|  26 |          INDEX FAST FULL SCAN  | TEST3          |  1670K|    17M|       |  1324   (1)| 00:00:16 |
|* 27 |      INDEX RANGE SCAN          | TEST6          |     1 |     8 |       |     8   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------------------

By adding a FIRST_ROWS(1) hint, this changes to the much more desired plan:
----------------------------------------------------------------------------------------------------------
| Id  | Operation                         | Name                 | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                  |                      |     1 |   220 |    96   (0)| 00:00:02 |
|*  1 |  COUNT STOPKEY                    |                      |       |       |            |          |
|   2 |   VIEW                            |                      |     1 |   220 |    96   (0)| 00:00:02 |
|*  3 |    FILTER                         |                      |       |       |            |          |
|   4 |     NESTED LOOPS                  |                      |     1 |    97 |    16   (0)| 00:00:01 |
|   5 |      TABLE ACCESS BY INDEX ROWID  | R_RAPPORT            | 60730 |  5159K|     6   (0)| 00:00:01 |
|   6 |       INDEX FULL SCAN DESCENDING  | IDX_R_RAPPORT_3      |    10 |       |     2   (0)| 00:00:01 |
|*  7 |      INDEX RANGE SCAN             | TEST5                |     1 |    10 |     1   (0)| 00:00:01 |
|   8 |     NESTED LOOPS                  |                      |     1 |    25 |     2   (0)| 00:00:01 |
|*  9 |      INDEX RANGE SCAN             | TEST7                |   141 |  1269 |     2   (0)| 00:00:01 |
|* 10 |      INDEX UNIQUE SCAN            | TEST8                |     1 |    16 |     0   (0)| 00:00:01 |
|* 11 |       TABLE ACCESS BY INDEX ROWID | R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  12 |        NESTED LOOPS               |                      |     2 |    88 |    35   (0)| 00:00:01 |
|  13 |         NESTED LOOPS              |                      |    10 |   210 |     7   (0)| 00:00:01 |
|* 14 |          INDEX RANGE SCAN         | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 15 |          INDEX RANGE SCAN         | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 16 |         INDEX RANGE SCAN          | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 17 |        TABLE ACCESS BY INDEX ROWID| R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  18 |         NESTED LOOPS              |                      |     2 |    88 |    35   (0)| 00:00:01 |
|  19 |          NESTED LOOPS             |                      |    10 |   210 |     7   (0)| 00:00:01 |
|* 20 |           INDEX RANGE SCAN        | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 21 |           INDEX RANGE SCAN        | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 22 |          INDEX RANGE SCAN         | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 23 |         INDEX RANGE SCAN          | TEST6                |     1 |     8 |     8   (0)| 00:00:01 |
----------------------------------------------------------------------------------------------------------

Unfortunately this query is composed at runtime, and should there be three subrequests instead of the two here, it will ignore the FIRST_ROWS hint and again do multiple full table scans on 8 million rows. With the given data distribution access by rowid will always be faster (almost instant) while the plan Oracle prefers takes several seconds.
I tried using ROWID hints on both tables, before discovering those have been deprecated.
Any pointers will be appreciated.
=edit=
USE_NL & new Index
-----------------------------------------------------------------------------------------------------------
| Id  | Operation                          | Name                 | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                   |                      |   101 | 22220 |  3994   (1)| 00:00:48 |
|*  1 |  COUNT STOPKEY                     |                      |       |       |            |          |
|   2 |   VIEW                             |                      |   102 | 22440 |  3994   (1)| 00:00:48 |
|   3 |    NESTED LOOPS SEMI               |                      |     1 |   102 |    16   (7)| 00:00:01 |
|   4 |     NESTED LOOPS                   |                      |     1 |    97 |    11   (0)| 00:00:01 |
|   5 |      TABLE ACCESS BY INDEX ROWID   | R_RAPPORT            | 58985 |  5011K|    10   (0)| 00:00:01 |
|*  6 |       INDEX FULL SCAN DESCENDING   | TEST12               |     1 |       |     9   (0)| 00:00:01 |
|*  7 |        TABLE ACCESS BY INDEX ROWID | R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|   8 |         NESTED LOOPS               |                      |     2 |    88 |    35   (0)| 00:00:01 |
|   9 |          NESTED LOOPS              |                      |    10 |   210 |     7   (0)| 00:00:01 |
|* 10 |           INDEX RANGE SCAN         | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 11 |           INDEX RANGE SCAN         | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 12 |          INDEX RANGE SCAN          | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 13 |         TABLE ACCESS BY INDEX ROWID| R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  14 |          NESTED LOOPS              |                      |     2 |    88 |    35   (0)| 00:00:01 |
|  15 |           NESTED LOOPS             |                      |    10 |   210 |     7   (0)| 00:00:01 |
|* 16 |            INDEX RANGE SCAN        | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 17 |            INDEX RANGE SCAN        | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 18 |           INDEX RANGE SCAN         | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 19 |          INDEX RANGE SCAN          | TEST6                |     1 |     8 |     8   (0)| 00:00:01 |
|* 20 |      INDEX RANGE SCAN              | TEST5                |     1 |    10 |     1   (0)| 00:00:01 |
|* 21 |     VIEW                           | VW_NSO_1             |   105 |   525 |     5  (20)| 00:00:01 |
|* 22 |      HASH JOIN                     |                      |   214 |  5350 |     5  (20)| 00:00:01 |
|* 23 |       INDEX RANGE SCAN             | TEST7                |   141 |  1269 |     2   (0)| 00:00:01 |
|* 24 |       INDEX RANGE SCAN             | TEST8                |   228 |  3648 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------------------------------------------------

SQL:
select /*+ FIRST_ROWS */ * from (
select *
from   r_rapport a
where  rb_id in (
  select obj_id from obj_recht where obj_typ = 20 and obj_pid = 10065 and maske_id in (
      select  distinct maske_id
      from    obj_rechtmaske
      where   subj_pid = 10065
    ) )
and    rb_id in (
  select id from rb_buch where pid = 10065
)
and exists (
  select /*+ USE_NL( c d ) */ 1
  from   r_teilanlage b, r_attribut c, r_attributfeld d
  where  a.id = b.r_id
  and    b.id = c.r_teilanlage_id
  and    c.id = d.r_attribut_id
  and    d.attributfeld_typ not in ( 20, 25, 40, 78, 79, 90, 92, 123, 124, 125, 126, 127 )
  and    lower( d.wert ) like lower( '%ä%' )
)
and exists (
  select /*+ USE_NL( c d ) */ 1
  from   r_teilanlage b, r_attribut c, r_attributfeld d
  where  a.id = b.r_id
  and    b.id = c.r_teilanlage_id
  and    c.id = d.r_attribut_id
  and    d.attributfeld_typ not in ( 20, 25, 40, 78, 79, 90, 92, 123, 124, 125, 126, 127 )
  and    lower( d.wert ) like lower( '%ö%' )
)
and exists (
  select /*+ USE_NL( c d ) */ 1
  from   r_teilanlage b, r_attribut c, r_attributfeld d
  where  a.id = b.r_id
  and    b.id = c.r_teilanlage_id
  and    c.id = d.r_attribut_id
  and    d.attributfeld_typ not in ( 20, 25, 40, 78, 79, 90, 92, 123, 124, 125, 126, 127 )
  and    lower( d.wert ) like lower( '%ä%' )
)
and exists (
  select /*+ USE_NL( c d ) */ 1
  from   r_teilanlage b, r_attribut c, r_attributfeld d
  where  a.id = b.r_id
  and    b.id = c.r_teilanlage_id
  and    c.id = d.r_attribut_id
  and    d.attributfeld_typ not in ( 20, 25, 40, 78, 79, 90, 92, 123, 124, 125, 126, 127 )
  and    lower( d.wert ) like lower( '%ö%' )
)
and a.id not in (
  select r_id from r_gelesen where ma_id = 144
)
order by a.open_stamp desc
 ) where rownum <= 101;

and its plan:
----------------------------------------------------------------------------------------------------------
| Id  | Operation                         | Name                 | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                  |                      |     1 |   220 |  1195K  (1)| 03:59:08 |
|*  1 |  COUNT STOPKEY                    |                      |       |       |            |          |
|   2 |   VIEW                            |                      |     1 |   220 |  1195K  (1)| 03:59:08 |
|*  3 |    FILTER                         |                      |       |       |            |          |
|   4 |     NESTED LOOPS SEMI             |                      |  3213 |   320K|  1018K  (1)| 03:23:47 |
|   5 |      NESTED LOOPS                 |                      |  6547 |   620K| 82249   (1)| 00:16:27 |
|   6 |       TABLE ACCESS BY INDEX ROWID | R_RAPPORT            | 60730 |  5159K| 21493   (1)| 00:04:18 |
|   7 |        INDEX FULL SCAN DESCENDING | IDX_R_RAPPORT_3      | 60730 |       |   152   (1)| 00:00:02 |
|*  8 |       INDEX RANGE SCAN            | TEST5                |     1 |    10 |     1   (0)| 00:00:01 |
|*  9 |      VIEW                         | VW_NSO_1             |   105 |   525 |   143   (0)| 00:00:02 |
|  10 |       NESTED LOOPS                |                      |   214 |  5350 |   143   (0)| 00:00:02 |
|* 11 |        INDEX RANGE SCAN           | TEST7                |   141 |  1269 |     2   (0)| 00:00:01 |
|* 12 |        INDEX RANGE SCAN           | TEST8                |     2 |    32 |     1   (0)| 00:00:01 |
|* 13 |     TABLE ACCESS BY INDEX ROWID   | R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  14 |      NESTED LOOPS                 |                      |     6 |   264 |    97   (0)| 00:00:02 |
|  15 |       NESTED LOOPS                |                      |    30 |   630 |    13   (0)| 00:00:01 |
|* 16 |        INDEX RANGE SCAN           | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 17 |        INDEX RANGE SCAN           | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 18 |       INDEX RANGE SCAN            | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 19 |      TABLE ACCESS BY INDEX ROWID  | R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  20 |       NESTED LOOPS                |                      |     6 |   264 |    97   (0)| 00:00:02 |
|  21 |        NESTED LOOPS               |                      |    30 |   630 |    13   (0)| 00:00:01 |
|* 22 |         INDEX RANGE SCAN          | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 23 |         INDEX RANGE SCAN          | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 24 |        INDEX RANGE SCAN           | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 25 |       TABLE ACCESS BY INDEX ROWID | R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  26 |        NESTED LOOPS               |                      |     6 |   264 |    97   (0)| 00:00:02 |
|  27 |         NESTED LOOPS              |                      |    30 |   630 |    13   (0)| 00:00:01 |
|* 28 |          INDEX RANGE SCAN         | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 29 |          INDEX RANGE SCAN         | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 30 |         INDEX RANGE SCAN          | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 31 |        TABLE ACCESS BY INDEX ROWID| R_ATTRIBUTFELD       |     1 |    23 |     3   (0)| 00:00:01 |
|  32 |         NESTED LOOPS              |                      |     6 |   264 |    97   (0)| 00:00:02 |
|  33 |          NESTED LOOPS             |                      |    30 |   630 |    13   (0)| 00:00:01 |
|* 34 |           INDEX RANGE SCAN        | TEST4                |     9 |    90 |     3   (0)| 00:00:01 |
|* 35 |           INDEX RANGE SCAN        | TEST3                |     3 |    33 |     2   (0)| 00:00:01 |
|* 36 |          INDEX RANGE SCAN         | IDX_R_ATTRIBUTFELD_1 |     6 |       |     2   (0)| 00:00:01 |
|* 37 |         INDEX RANGE SCAN          | TEST6                |     1 |     8 |     8   (0)| 00:00:01 |
----------------------------------------------------------------------------------------------------------

A horrible, horrible cost estimate as this query completes instantly.

A: If you want to avoid table access full on r_attributfeld, you should try a nested loop on this table.
Maybe you'll have to had a leading(r_rapport r_attributfeld) (or ordered hint) if Oracle "don't understand" what you want

A: Not always what you think is better plan is realy better plan. To return you first rows fast is right way to use nested loops and rowid acces. But if you want return all result set fast it is more efficient to use hash join even if you are joining by rowid("select * from tab where rowid in (...)" or "... join tab on tab.rowid = ...'). So I think Oracle picked right plan for you.


text:
Q: How does resistor affect drift velocity? After reading many question and answers on stack, i got totally confused about how does resistor affect drift velocity.
Consider a simple circuit, a battery and a resistor, connected to each other with wire ( wire with area $A$ and resistivity $\rho_w$ (very small), resistor with area $A$ and resistivity $\rho_r$ ;  $\rho_w \ll \rho_r$). From the formula $v=\frac{I}{enA}$, we can conclude that overall drift velocity in circuit decreases by using a larger resistor (as it reduces the current).
Having constant current density $J$, electrical field in wire is $E_w = J \rho_w$ and resistor $E_r = J \rho_r$. As $\rho_w < \rho_r$, it says that electrical inside resistor is stronger than in wire. So the greater the electrical field, the more force on electrons and thus an increase in their speed (drift velocity). ( The increase in drift velocity can be concluded in another way : For both wire and resistor, all parameters in formula $v=\frac{I}{enA}$ are equal except $n$, charge carrier density. So drift velocity in resistor with less charge carrier density must be larger. )
Now some questions :

*

*It is correct to say that having a resistor in a circuit, slows down the overall drift velocity comparing to another circuit with a lower resistor, but inside a circuit itself, drift speed in resistor is more than in wire ?

*It is correct to say that in any element with nonzero resistor, as electrons move in opposite direction of electrical field, they lose electrical potential energy and it's get converted to kinetic energy and heat?

*Considering the simple circuit, if wires have zero resistance, does electrons flow through ? (Noting that there is no potential difference, so electrons have no electrical potential energy to convert to kinetic energy and start moving toward other terminal of battery)

*Does voltage drop mean that electrons have lost some electrical potential energy or it means that there are more electrons on one side of the resistor compared to the other side?

A: I will assume a constant current in the circuit in my answers.

*

*a) If you compare two circuits with the same properties, up to a different resistor, which have the SAME VOLTAGE applied, then in the circuit with the lower resistor there will be a higher current. Since all the other properties of the circuit didn't change, the overall drift velocity $v_d$ will also be higher.
b) It depends on your resistor wether the drift velocity is bigger in the wire than in the resistor (everything has just to satisfy your formula $ I = v_d n A e$. If you find a Resistor with $n_{Resistor}$ being bigger than $n_{Wire}$, and give it the same area $A$ the wire has, then the drift-velocity will be lower in the resistor. This is also pointed out in the answer you've linked, in the last section. Still, usualy resistors have lower charge densities, so they require a higher drift velocity.

*If by "opposite to the electric field" you mean "in direction of the force that acts uppon them" (eletrons have negative charge), then yes. The situation in the resistor is an equilibrium situation, where the electric field accelerates the electrons (converting its potential energy to kinetic energy) while at the same rate collisions of electrons convert the kinetic energy of the electron into heat.

*Of course they still move through, they just need a shorter amount of time: Even without resistance of the wire, saying that there is NO potential difference throughout the WHOLE wire is a property of the equilibrium situation, and as long as there is a net flow of charge, this equilibrium situation will not be reached:
Let's say the resistor has infinite resistance, and you connect wire and battery. What will happen? In the beginning, there is a potential difference throughout the wire. Electrons become accellerated. They will flow through the wire until they reach the resistor. With the electrons comes the charge, and with the charge comes potential. Since there now are more electrons in the wire, the potential difference has shrinked. As long as there will be a potential difference, electrons will become accelerated, until somewhen the potential is really constant throughout the entire wire.
This won't happen if your resistor has finite resistance, in that case there will be electrons drained out of the wire all the time, which creates a slightly little potential gradient at that part of the wire, and at the same time there are electrons pushed into the wire out of the battery, which also creates a tiny potential gradient.
The resistance being zero will just make the electron movement faster, and therefore they can balance out the potential difference between the start of the resistor and the battery faster. But as long as there is a current flowing, the potential difference between start of the resistor and the battery will not be zero, but a little bit more.
You are right, forces can only act on the electron when there is a potential gradient, but since there is no resistance throughout the wire, it is sufficient if the electron is accelerated at the start of the wire and slowed down at the end (for example).

*Voltage drop means that electrons have lost potential energy throughout the resistor. This doesn't neccesarrily mean that there are more electrons on one side of the resistor compared to the other side, it just can mean that. The question here is the geometry of the resistor: The charges in the wire before and after, and the ones in the resistor have to create a potential (via 1. Maxwell equation) that has the mentioned potential difference throughout the resistor.
However, I usualy would also think that there is a potential gradient pushing electrons through a wire when there is more of them on the first side than on the second. So in principle the answer is "yes", but I don't know if it always has to be like that.


text:
Q: Only get the latest build from a branch on deployment When doing a deployment job with a CI trigger and resources.pipelines that are defined like
resources:
  pipelines:
    - pipeline: thumbnailGenerator
      project: myServices
      source: thumbnail-generator CI
      trigger:
        branches:
          include:
            - master

The deployment job downloads the latest build of the pipeline (which may be a PR) rather than the last build from master.  Is there a way of making it only download the specific branches when doing a CI build?
I haven't explored it yet, but I am thinking based on this behaviour it will always do the latest builds for all the pipelines regardless.

A: There's a property called branch on the pipeline object
resources:
  pipelines:
    - pipeline: thumbnailGenerator
      project: myServices
      source: thumbnail-generator CI
      branch: master
      trigger:
        branches:
          include:
            - master


text:
Q: Is async/await pattern irrelevant without threading or asynchronous devices? Edit - After reading the three answers below, I've realized that I'm asking nonsense ! Apologies for wasting some of your precious time, and thanks for clarifying alot of misunderstandings, really! :)
I were assuming apples and pipe wrenches were the same thing in the way async/await and threads are solution for similar concerns. Async/await and Threads both addresses UI responsiveness, but not in the same way. The former is a pattern to be used when several desired results can be gathered asynchronously (in order to improve user experience for example), hence why it's called "async". Heavy works, those that take several seconds to hours has to be off loaded on another thread to keep UI responsive. Those two are completely different concerns.
No matter how I may edit this question, there is no way to ask such async/await with or without threading concern as they are completely different things, can be used together (in so many ways) or separately. The statement .2 below said it all (apart a "invocation" misconception) but I didn't truely understood its true meaning from the start.
I guess I should have deleted the question from the moment I had doubts, but I couldn't understand how far it was a dumb one before actually reading some answers. However, this may also help other to have a better understanding of what async/await is about.
By the way, I don't know what answer to mark as answer as they all have valuable informations.

Original post:
It's fair to note that I'm "yet another async/await beginner". However, What I've understood so far are:

*

*async/await doesn't create threads ! Never ! They run on the same thread as the caller.

*async/await are not parallel tasks. They just defines a pattern where an async block of code get executed the moment an await is invoked at caller level (or so - I know my understanding is slightly wrong, but that's how I can clearly picture it in mind)

*No code block is executed asynchronuously if that block doesn't contain an await keyword.

*async/await appears to work well with some I/O tasks, but seems not that wonderful on most high CPU computations.

*async/await seems to fail with Thread.Sleep (should use Task.Delay instead) or in case of Exception with Finally block.

Based on the above, and to simplify things, I think async/await is just an improved form of goto, capable of jumping from a method step to another method step, because the goto call can "fly" (be delayed) until an await is encountered ! (sorry to simplify things that far)
I've tested both I/O and CPU codes without additional threads, both heavy, and both produced unresponsive UI until everything was completed.
My observaton is:
Without asynchronous capable things like :

*

*threads explicitely defined using one of the numerous .net objects in the framework, or their members that create threads on their own

*or IO devices that are designed to work asynchronously from the start at hardware level (CPU)

async/await are just plain synchronous patterns; meaning, there is no asynchronous-like thing anywhere with just async/await keywords.

The question is: is the above observation true, or am I missing some important thing about async/await ?

Side notes :
I've read this blog post (There Is No Thread, Stephen Cleary's Blog). He states that there is no thread (totally agree) but it doesn't contradict with my observation that, at pure programmer code level without asynchronous devices involved, you can't have a responsive UI unless you delegate the heavy tasks in another thread. My concern is not the awaitable aspect of the pattern, as I said, it's like a flying goto; I want to make sure I'm not using async/await blindly just for the sake of using something new.
.ConfigureAwait(false) : seems to involve a ThreadPool to me, which is why the UI thread is still responsive...

A: Async-await is a pattern that allows you to write code that closely resembles synchronous code but can actually execute asynchronously. This relies on a lot of work done by the compiler. That's all.
Async-await doesn't create asynchronous operations, it just allows you to use them in a simple way and still be asynchronous, unlike before using BeginXXX/EndXXX.
It's true that async is mostly useful with I/O, because most asynchronous operations are I/O operations, but there are different ones like Task.Delay, asynchronous synchronization mechanisms or asynchronously waiting for an event.
About your specific points:

*

*Async-await doesn't create threads. Async methods start running on the caller thread, don't use any thread for the actual asynchronous operation and resume on a ThreadPool thread or one defined by the SynchronizationContext or TaskScheduler.

*Await isn't invoked. When an async method reaches an await on an uncompleted task the rest of the method is scheduled as a continuation that will run when that task is completed.

*Pretty much. You need to await an asynchronous operation for your async method to be asynchronous.

*Async-await works with both. If your operation isn't asynchronous though, there's no point in using async-await.

*Async-await doesn't fail with Thread.Sleep. It's just wasteful to use Thread.Sleep as it blocks a thread. That's why you use Task.Delay. You can now await in finally with C# 6.

And finally:

meaning, there is no asynchronous-like thing anywhere with just async/await keywords.

Yes, marking a method with the async keyword doesn't make anything run asynchronously. It only allows you to use await and wrap the result in a Task.

A: You may find my async intro helpful.
I would say that async and await are the most elegant way to consume asynchronous operations. As a side product, async also creates a higher-level asynchronous operation (if the method returns a Task/Task<T>). However, they are not a good way for creating asynchronous operations out of nothing.
So I would disagree with this statement:

async/await are just plain synchronous patterns

However, I would agree with the statement that await just breaks up an async method into multiple synchronous parts.
If you have CPU-bound code and you don't want to block the UI thread, then you could use something like Task.Run to push that code onto a thread pool thread. The UI code can then await the task returned from Task.Run.

A: There are two distinct concepts here that you are mixing up. Being asynchronous and parallel are not the same thing. While asynchronous operations can hide multithreading under the hood, they don't necessarily do.
The async / await keywords in C# are just syntactic sugar for expressing thoughts like "when operation A is done, do operation B". Whether or not operation A runs on another thread is an implementation detail you don't care about.
Basically, you let the compiler and the framework figure it out for you.
If you think of it, async / await can be conceptionally somewhat similar to how events and event loops work. Perhaps the event syntax was not flexible enough and that's why they introduced these new keywords. Personally I believe that it's kind of in the same legaue as promises in JavaScript or how the event loop works in Node.js. I'm not saying that it works similarly but it does solve very similar problems.


text:
Q: Segmentation fault (core dumped) Error in C program with dynamic arrays I can't seem to figure out where this error is coming from, but I am assuming it is something to do with the allocation of the arrays/passing the arrays as parameters. Apologies, I am fairly new to C. If someone could help me figure out where this error is resulting from, it would be tremendously helpful.
#include <stdio.h>
#include <stdlib.h>

void getSize(int *sizePtr) {
    printf("Please enter the size of the class: ");
    scanf("%i", sizePtr);
}

void allocateMemory(float *scoresPtr, int size) {
    scoresPtr = malloc(size * (sizeof(float)));
}

void readScores(float *scores, int size) {
    int i;
    printf("Enter each score as a floating point value, each on a separate line, followed by enter: \n");
    for (i = 0; i < size; i++) {
        scanf("%f", &scores[i]);
    }
}

void makeArrayCopy(float *original, float *copy, int size) {
    int j;
    for (j = 0; j < size; j++) {
        copy[j] = original[j];
    }
}

void findMin(float *scores, int size) {
    int min = scores[0];
    int i;

    for (i = 1; i < size; i++) {
        if (scores[i] < min) {
            min = scores[i];
        }
    }
    printf("%.1f", min);
}

void findMax(float *scores, int size) {
    int max = scores[0];
    int i;

    for (i = 1; i < size; i++) {
        if (scores[i] > max) {
            max = scores[i];
        }
    }
    printf("%.1f", max);
}

void findSum(float *scores, int size) {
    int i;
    int sum = 0;

    for (i = 0; i < size; i++) {
        sum += scores[i];
    }

    printf("%.1f", sum);
}

void findMean(float *scores, int size) {
    int i;
    double mean = 0;

    for (i = 0; i < size; i++) {
        mean += scores[i];
    }

    mean /= size;
    mean = (float)mean;
    printf("%.1f", mean);
}

void findMedian(float *sortedScores, int size) {
    int mod = size % 2;
    int sizeDivTwo = size / 2;
    float median;

    if (mod = 0) {
        median = (sortedScores[sizeDivTwo] + sortedScores[sizeDivTwo + 1]) / 2;
    } else {
        median = sortedScores[sizeDivTwo + 1];
    }
    printf("%.1f", median);
}

void printAllScores(float *scores, int size) {
    int i;
    printf("%s", "Class Scores: \n");

    for (i = 0; i < size; i++) {
        printf("%.1f", scores[i]);
        printf("%c", "\n");
    }
}

void sortAscending(float *scores, int size) {
    int i, j;
    float temp;

    for (i = 0; i < size;  i++) {
        for (j = 0;  j < size - 1; j++) {
            if (scores[j] > scores[j + 1]) {
                temp = scores[j];
                scores[j] = scores[j+1];
                scores[j + 1] = temp;
            }
        }
    }
}

int main() {
    float scores;
    int size;
    float sortedCopy;
    int op;

    getSize(&size);
    allocateMemory(&scores, size);
    readScores(&scores, size);

    allocateMemory(&sortedCopy, size);
    makeArrayCopy(&scores, &sortedCopy, size);
    sortAscending(&sortedCopy, size);

    while (op != 0) {
        printf("%s", "Please choose an option: \n 1: Calculate sum \n 2: Calculate mean \n 3: Calculate median \n 4: Find minimum score \n 5: Find maximum score \n 6: Print all scores \n 7: Print all scores in ascending order \n8: Exit");
        scanf("%i", op);

        switch(op) {
            case 1:
                findSum(&scores, size);
                break;
            case 2:
                findMean(&scores, size);
                break;
            case 3:
                findMedian(&sortedCopy, size);
                break;
            case 4:
                findMin(&scores, size)
                break;
            case 5:
                findMax(&scores, size);
                break;
            case 6:
                printAllScores(&scores, size);
                break;
            case 7:
                printAllScores(&sortedCopy, size);
                break;
            case 8:
                op = 0;
                break;
        }
    }

}

A: You've got quite a few issues here.
First, you should initialize values like op, otherwise the comparison op != 0 is undefined. Also, you pass op to scanf() instead of its address.
The immediate cause of your issue is that you're using pointers to stack variables to allocate memory using malloc.
In your findMin(), findMax(), findSum(), you use the int data type for the respective values, while you should be using float.
The edits below should start to help (as well as turning on warnings for your compiler)
// in main()
float *scores;
float *sortedCopy;
int   op = -1;

// remove & from before scores and sorted copy in all other function calls
allocateMemory(&scores, size);
allocateMemory(&sortedCopy, size);

// in the while loop
scanf("%d", &op);

// at the end of main(), don't forget to free mem
free(scores);
free(sortedCopy);

// in allocateMemory
void allocateMemory(float **scoresPtr, int size) {
    *scoresPtr = malloc(size * (sizeof(float)));
}

// in findMedian()

if (mod == 0) { // == is for comparison, = is for assignment

A: Begin by using gdb with "gdb a.out" (or the name of your compiled program)
(gdb) start
Temporary breakpoint 1 at 0xd0f
Starting program: a.out

Temporary breakpoint 1, 0x0000555555554d0f in main ()
(gdb) next
Single stepping until exit from function main,
which has no line number information.
Please enter the size of the class: 5
Enter each score as a floating point value, each on a
separate line, followed by enter:
4.5
4.7
4.7
4.6
4.8

Program received signal SIGSEGV, Segmentation fault.
  0x00005555555548a8 in makeArrayCopy ()

Then add printf("size = %d\n", size); to makeArrayCopy (before the loop):
Please enter the size of the class: 3
Enter each score as a floating point value, each on a
separate line, followed by enter:
2.5
2.6
2.7
size = 1076258406

You will be quick to find the solution, but it will be even more valuable for you to understand how gdb work and how you can debug

A: The following code cause memory corruption.
...
scanf("%f", &scores[i]); // line 18, write to the outside of scores.
...
float scores; // line 116
...

The following is the reported error. The link to reproduce this error.
=========== Start of #0 stensal runtime message ===========
Runtime error: [writing to the outside of a memory space]
  Continuing execution can cause undefined behavior, abort!
-
- Writing 4 bytes to 0xffc067d0 will clobber the adjacent data.
-
- The memory-space-to-be-written (start:0xffc067cc, size:4 bytes) is bound to 'scores' at
-     file:/prog.c::116, 9
-
-  0xffc067cc               0xffc067cf
-  +------------------------------+
-  |the memory-space-to-be-written|......
-  +------------------------------+
-                                  ^~~~~~~~~~
-        the write starts at 0xffc067d0 that is right after the memory-space end.
-
- Stack trace (most recent call first) of the write.
- [0]  file:/musl-1.1.10/src/stdio/vfscanf.c::302, 5
- [1]  file:/musl-1.1.10/src/stdio/vscanf.c::7, 9
- [2]  file:/musl-1.1.10/src/stdio/scanf.c::25, 8
- [3]  file:/prog.c::18, 5
- [4]  file:/prog.c::123, 3
- [5]  [libc-start-main]
-

============ End of #0 stensal runtime message ============


text:
Q: NSURLsession not working in loop Im trying to make request to multiple URLs to download the HTML and later turn it into a JSON format. Where I'm running into trouble is when i try to make request to multiple URLs in the for loop. I'm no master on this with async requests so, this might be a obvious mistake to you guys, but I can't find a answer to the question.
If I try to run it without the loop (just referencing a single object in the TFHppleElement-array) it seems to work, but as soon as I'm looping it, the request won't seem to be made.
Does not work:
func getData(data: [TFHppleElement]) {

   for index in data{

        let thisurl="https://theurl.org\(index.firstChild.objectForKey("href"))"

        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: thisurl)!)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request){
            (data : NSData?, response : NSURLResponse?, error : NSError?) -> Void in

            if error == nil{

                let parser = HTMLParser()
                parser.parseNode(data!, xPathString: "//span[@class='odd']", callback: self.createJSON)

            }else{
                print("Request not working")
            }

        }

        task.resume()
    }

}
Works:
func getData(data: [TFHppleElement]) {

  // for index in data{

        let thisurl="https://theurl.org\(data[0].objectForKey("href"))"

        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: NSURL(string: thisurl)!)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request){
            (data : NSData?, response : NSURLResponse?, error : NSError?) -> Void in

            if error == nil{

                let parser = HTMLParser()
                parser.parseNode(data!, xPathString: "//span[@class='odd']", callback: self.createJSON)

            }else{
                print("Request not working")
            }

        }

        task.resume()
    //}

}
I haven't been programming for a while, so I'm sorry if it might be an obvious mistake.


text:
Q: Where to start to learning Mojolicious? I am new to the Mojo framework... I went through some of the wiki pages on the Mojolicious website, however couldn't comprehend many things. The documentation seemed to be for someone who already has a background with the Mojo framework.
So, I'm wondering whether there is any place for a newbie to start?
Thanks in advance.

A: The wiki isn't necessarily trustworthy, since anyone can change it, and it isn't always up to date.
Start with the mojocasts at http://mojocasts.com; then move on to the docs.
The docs are accessible for new users; just make sure you read the guides in the order they are listed on http://mojolicio.us/perldoc.

A: the mojocasts cited by tempire are a good start, I find the docs a bit fragmentary, and prefer
to dig the code of other projects...
Here you can find some code to read here
https://github.com/kraih/mojo/wiki/Example-applications
This one is pretty good:
https://github.com/tempire/MojoExample


text:
Q: Determining whether the polynomials span $P_2$
Determine whether the following polynomials span $\mathbb P_2$
$p_1 = 1+x+2x^2$
$p_2 = 3+x$
$p_3 = 5-x+4x^2$
$p_4 = -2- 2x +2x^2$

Attempt:
I created the following augmented matrix:
$$
    \begin{bmatrix}
    1 & 3 & 5 & -2 & a \\
    x & x & -x & -2x&bx\\
    2x^2 & 0 & 4x^2 & 2x^2 & cx^2\\
    \end{bmatrix}
$$
which reduces to:
$$
    \begin{bmatrix}
    1 & 3 & 5 & -2 & a \\
    0 & 1 & 3 & 0 &(a-b)/2\\
    0 & 0 & 1 & 1/2 &  (c+a-3b)/2\\
    \end{bmatrix}
$$
Now, I believe that the system is consistent and has infinitely many solutions so the polynomials span $\mathbb{P_2}$.
Is this approach correct?

A: If $P_2$ is the vector space of real polynomials of order smaller or equal to 2, then you can think of the given polynomials as vectors in $\mathbb {R^3}$ as;
$p_1=(1,1,2)$, $p_2=(3,1,0)$, $p_3=(5,-1,4)$, $p_4=(-2,-2,2)$ (Why?). Then check the rank of the following matrix: \begin{pmatrix}
1 & 1 & 2\\
3 & 1 & 0\\
5 & -1 & 4\\
-2 & -2 & 2
\end{pmatrix}
If the rank is equal to 3, then the answer is affirmative.


text:
Q: What's the difference between `def` and `defp` I'm going through the Programming Phoenix book and I am wondering what the difference between def and defp is.
There are several functions in my controller - most of them are actions like this:
def new (conn, _params) do
...
end

The book had me create another function in this controller that is not a typical controller action like this:
defp user_videos(user) do
...
end

So my question is how do I know when to use defp and when to use def when defining a function in Elixir?

A:
So my question is how do I know when to use defp and when to use def when defining a function inside a controller in the Phoenix Framework.

def functions of a module can be called from other modules, whereas defp functions are private, or not callable from other modules. How do you know when to use def and when to use defp? It depends on what other modules may or may not need to know about. A common design pattern is for a module to provide a parent def function that wraps all the behavior of its defpfunctions:
defmodule MyModule do

  def function do
    # call all the defp functions below to do something
  end

  defp function2 do
    # do something that no other module cares about or needs to know about
  end

  defp function3 do
    # do something that no other module cares about or needs to know about
  end

  defp function4 do
    # do something that no other module cares about or needs to know about
  end
end

Here is an example of this with a parser for SEC filings: SEC Company Filings Parser. The main def method wraps all the private functions which no other module really needs to know about.

A: From Elixir's documentation on functions within modules:

Inside a module, we can define functions with def/2 and private functions with defp/2. A function defined with def/2 can be invoked from other modules while a private function can only be invoked locally.

So defp defines a private function.


text:
Q: Call Qml code (with a WebView item: QtWebView 1.0) from a local html (source of the WebView) I have a Qt application where I create and display a QQuickView object, using a QML file as source.
This QML has a 'WebView' item (QtWebView 1.0), which displays a local .html file.
I need to access to html code from Qt code (Qt --> Qml --> Html) and viceversa (Html --> Qml --> Qt)
My Qt code and Qml code are connected, but I have the problem in Qml <--> Html...
Searching on the internet I have tried several options, but no suceess. The last one is with a .js file, as proxy (which should be called from Html, and should call to Qml)
My codes now are like that:
MyWebView.qml

    Rectangle {
    id: rectMyWebView

    width: 1000
    height: 800

    WebView {
        id: myWebView

        objectName: "webView"

        anchors.fill: parent
        url: "file:///d:\\test.html"

        function fromHtmlToQML1(text)
        {
            console.log("Text from html" + text)
        }
    }

    // Called from Qt code: OK!!
    function fromQtToQml(text)
    {
        console.log("Text from qt: " + text)
        runJavaScript("jsCall2", function(result) { console.log(result); });
    }

    // 2nd option

    function fromHtmlToQML2(text)
    {
        console.log("Text from html" + text)
    }
}

test.html:
<!doctype html>

        ...

 <button onclick='myFunction1()'>Call Qt</button>

    ...

test.js (where must be located??)
function myFunction1() {
    myWebView.fromHtmlToQML1();
    myWebView.fromHtmlToQML2();
}

When I use the Html button, and error appears:
"js: Uncaught ReferenceError: myFunction1 is not defined"
Is it a problem of the location of test.js?
Is it the way to call Qml from the Html (used as source of the WebView in the Qml)
Thanks a lot in advance,
Diego


text:
Q: Compare two csv files in C# I want to compare two csv files and print the differences in a file. I currently use the code below to remove a row. Can I change this code so that it compares two csv files or is there a better way in c# to compare csv files?
  List<string> lines = new List<string>();
        using (StreamReader reader = new StreamReader(System.IO.File.OpenRead(path)))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.Contains(csvseperator))
                {
                     string[] split = line.Split(Convert.ToChar(scheidingsteken));

                    if (split[selectedRow] == value)
                    {

                    }
                    else
                    {
                        line = string.Join(csvseperator, split);
                        lines.Add(line);
                    }
                }

            }
        }

        using (StreamWriter writer = new StreamWriter(path, false))
        {
            foreach (string line in lines)
                writer.WriteLine(line);
        }
    }

A: Here is another way to find differences between CSV files, using Cinchoo ETL - an open source library
For the below sample CSV files
sample1.csv
id,name
1,Tom
2,Mark
3,Angie

sample2.csv
id,name
1,Tom
2,Mark
4,Lu

METHOD 1:
Using Cinchoo ETL, below code shows how to find differences between rows by all columns
var input1 = new ChoCSVReader("sample1.csv").WithFirstLineHeader().ToArray();
var input2 = new ChoCSVReader("sample2.csv").WithFirstLineHeader().ToArray();

using (var output = new ChoCSVWriter("sampleDiff.csv").WithFirstLineHeader())
{
    output.Write(input1.OfType<ChoDynamicObject>().Except(input2.OfType<ChoDynamicObject>(), ChoDynamicObjectEqualityComparer.Default));
    output.Write(input2.OfType<ChoDynamicObject>().Except(input1.OfType<ChoDynamicObject>(), ChoDynamicObjectEqualityComparer.Default));
}

sampleDiff.csv
id,name
3,Angie
4,Lu

Sample fiddle: https://dotnetfiddle.net/nwLeJ2
METHOD 2:
If you want to do the differences by id column,
var input1 = new ChoCSVReader("sample1.csv").WithFirstLineHeader().ToArray();
var input2 = new ChoCSVReader("sample2.csv").WithFirstLineHeader().ToArray();

using (var output = new ChoCSVWriter("sampleDiff.csv").WithFirstLineHeader())
{
    output.Write(input1.OfType<ChoDynamicObject>().Except(input2.OfType<ChoDynamicObject>(), new ChoDynamicObjectEqualityComparer(new string[] { "id" })));
    output.Write(input2.OfType<ChoDynamicObject>().Except(input1.OfType<ChoDynamicObject>(), new ChoDynamicObjectEqualityComparer(new string[] { "id" })));
}

Sample fiddle: https://dotnetfiddle.net/t6mmJW

A: If you only want to compare one column you can use this code:
                List<string> lines = new List<string>();
    List<string> lines2 = new List<string>();

    try
    {
        StreamReader reader = new StreamReader(System.IO.File.OpenRead(pad));
        StreamReader read = new StreamReader(System.IO.File.OpenRead(pad2));

        string line;
        string line2;

        //With this you can change the cells you want to compair
        int comp1 = 1;
        int comp2 = 1;

        while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
        {
            string[] split = line.Split(Convert.ToChar(seperator));
            string[] split2 = line2.Split(Convert.ToChar(seperator));

            if (line.Contains(seperator) && line2.Contains(seperator))
            {
                if (split[comp1] != split2[comp2])
                {
                    //It is not the same
                }
                else
                {
                    //It is the same

                }
            }
        }
        reader.Dispose();
        read.Dispose();
    }
    catch
    {

    }


text:
Q: How can you stop an app from refreshing if it enters the background? I'm building a social network with the usual functions like a feed. When I am closing the app via home button it sometimes just needs a minute to get refreshed when I am re-entering the app.
Obviously that is bad, when you are scrolling down the feed, you want to get back to the spot where you were the last time. It even refreshes the "new Post" screen when I wrote the title and go to safari to copy a link.. You get the gist of the problem.
Apps like Reddit do it very well and quite long.
Research just showed me functions to fetch in the background, which will let the app stay in its current state, I suppose, but I don't want to fetch anything, just expand the time before it refreshes.
func applicationDidEnterBackground(_ application: UIApplication) {

   UIApplication.shared.setMinimumBackgroundFetchInterval( 60 ) )
}

...
Any help to get a longer "active" state is appreciated, I'm just clueless!
Thank You

A: First of all , usually it happens when we are on the last index we call the refresh api with loader and wait for response and append in previous response . index will be maintained
Second if you want to refresh when appbecomeActive from background state you make app the all the list refresh and index won't be maintained
or
when app enter backgroundstate get the index number and when app is inthe foreground or active state just scroll to that index
if my anwswer is according to your question please elaborate your question
Thank you


text:
Q: How to avoid calling select query twice for difference in only one condition The below mentioned queries(outer and inner query) are similar except for one clause T2.COL2=(Temporary/Permanent). To accommodate this clause the select is executed twice, leading to performance degrade. Can we merge the inner query with the outer one and avoid using exists and also avoid calling select twice.
The below query returns only one record where T1.COL2='Temporary'. Modified query should also return only one result.

SELECT * FROM TABLE1 T1 WHERE T1.COL1='Rajesh' AND T1.COL2='Temporary'
AND EXISTS (
     SELECT 'Y'
      FROM TABLE1 T2 WHERE T2.COL1='Rajesh' AND T2.COL2='Permanant')

Thanks in advance for your suggestions.

A: You can use window functions:
SELECT T1.*
FROM (SELECT T1.*, MIN(COL2) OVER (PARTITION BY T1.COL1) as MIN_COL2
      FROM TABLE1 T1
      WHERE T1.COL1 = 'Rajesh' AND T1.COL2 IN ('Permanent', 'Temporary')
     ) T1
WHERE MIN_COL2 = 'Permanent' AND T1.COL2 = 'Temporary';


text:
Q: Creating .dll from a Python file
Possible Duplicate:
py2exe to generate dlls?

I'm searching for a way to make a .dll-file out of a python file. I also wonder if I can use the functions in the dll from an another language like C++ oder Assembler?
I have been looking at py2exe and pyapp, but it doesn't provide porting to dll.
I'm sorry for this question. I feel sorry because I didn't search StackOverflow before for similar questions / possible duplicates .

A: You can compile multiple python scripts into an assembly using clr.
import clr
clr.CompileModules("modules.dll", "module.py", "module2.py")

This is IronPython, but to reference these modules from other languages (ex. C++ or C#) IronPython would be preferable in my opinion because it runs as a .NET interpreter that can be understood by other languages that implement .NET
To reference the compiled dll from another IronPython script, for example:
import clr
clr.AddReference("modules.dll")


text:
Q: Is there a way to write `regex` without repeating some parts? I want to match Internet. or Internet at the end of string.
I can write:
$str =~ m/Internet\.|Internet$/

Is there a way to write regex without repeating Internet?

A: You can use parens to group things together, and the pipe works locally within the group.
This means, you can turn ab|ac into a(b|c). Note that this also automatically creates a capturing group1; if you don't want that, you can use a(?:b|c).
So, in your case, you could write2:
$str =~ /Internet(\.|$)/

(Or /Internet(?:\.|$)/ to use a non-capturing group, but it seems it doesn't matter here.)

1: This means that the contents of the matched group would go into $1 (or $2, etc. depending the how-many-th group it is), so with a(b|c) you would get either b or c in $1.
2: I removed the m because it is the default mode for pattern matching anyway.
Side note: As mentioned by commenter JvdV below, depending on your use case you may also consider adding a word boundary before the word Internet. Then, it would only match something like The Internet. or (Internet.) but not IIIIInternet.. You would do this using \b, e.g. /\bInternet(\.|$)/

A: First of all, $ doesn't match (just) the end of the string. You want \z for that.

(?:...) can be used as parentheses are used in mathematics. This enables us to factor out the common prefix as follows:
/Internet(?:\.|\z)/

In general, we can use interpolation or DEFINE.
For example, let's look at the following match which uses a long repeated pattern we can't simply factor out:
/ ^ [a-zA-Z][a-zA-Z0-9_]* (?: \. [a-zA-Z][a-zA-Z0-9_]* )* \z /x

Using interpolation:
my $ident = qr/[a-zA-Z][a-zA-Z0-9_]*/;
/ ^ $ident (?: \. $ident )* \z /x

Using DEFINE (better):
/
   ^ (?&IDENT) (?: \. (?&IDENT) )* \z

   (?(DEFINE)
      (?<IDENT> [a-zA-Z][a-zA-Z0-9_]* )
   )
/x

There's still repetition, but instead of repeating a complex pattern, we are repeating a simple word, and spelling errors will result in a fatal error rather than potentially-subtle misbehaviour.

A: Based on your input, it may come in the Start/middle/end of the content. So it would be better to use the below code to avoid case:
$str =~ m/[Ii]nternet(\.|$)/
or
$str =~ m/Internet(\.|$)/i

Also, if you want to store in the group, use parenthesis.


text:
Q: Blocks are invisible after hosting drupal7 I am facing with a problem in drupal7, I am new to drupal7 too. When I run my website in localhost everything fine, blocks and menu are visible. But after I host my website in GoDaddy, that blocks and menu are invisible, where they gone. I am also hoping someone can help me to solve this problem. Thanks.

A: Go to admin/structure/block page and assign the search block and the navigation menu to the left side bar.

A: Sometime this problem occurs when version mismatch between GoDaddy supported drupal and your drupal.