text:
Q: Convert string numeric values with comma as decimal separator to NUMERIC(10, 2) I have an SQL table of varchar columns which contain Greek formatted numbers (. as thousand separator and comma as decimal separator)
The classic conversion
CONVERT(numeric(10,2),REPLACE([value],',','.'))

does not work because the . (thousand separator) kills the conversion
E.g try
CONVERT(numeric(10,2),REPLACE('7.000,45',',','.'))

I want to convert such values to numeric(10,2)
Any suggestions of how to handle it?

A: What version of SQL Server are you using?  From SQL Server 2012 onwards you can use TRY_PARSE with its USING culture argument.  You can also use PARSE, the difference being PARSE will fail if the conversion fails and TRY_PARSE will return a NULL, eg
DECLARE @t TABLE ( x VARCHAR(10) )

INSERT INTO @t
VALUES ( '7.000,45' ), ( 'xxx' )

SELECT x,
    TRY_PARSE( x AS NUMERIC(10,2) USING 'El-GR' ) x
FROM @t

HTH

A: (If you are using SQL Server 2012 or newer, please see @wBob's answer for a cleaner approach. The approach outlined in my answer below is only required if you are using SQL Server 2008 R2 or older.)
You don't need (or want) the thousands' separator when converting to NUMERIC, regardless if it is comma, period, or space, so just get rid of them first. Then convert the comma into a period / decimal and you are done:
SELECT CONVERT(NUMERIC(10, 2),
               REPLACE(
                       REPLACE('7.000,45', '.', ''),
                       ',', '.'
                      )
              ) AS [Converted];

Returns:
7000.45

For the sake of completeness, I should mention that I also tried:

*

*SET LANGUAGE Greek;

*Looking at various format styles for CONVERT, but nothing applies here.

*The FORMAT function, but the input type must be a numeric or date/time/datetime value (that and it was introduced in SQL Server 2012, so not applicable to SQL Server 2008 R2 or older).
And nothing else seemed to work. I was hoping to find something more elegant than two REPLACE calls, but so far no such luck.

Also, just to mention, while not a pure T-SQL solution, this can also be accomplished via SQLCLR. And, there is a pre-done function that does this in the SQL# library (that I wrote) named String_TryParseToDecimal. This function is available in the Free version, and works in every version of SQL Server starting with SQL Server 2005:
SELECT SQL#.String_TryParseToDecimal('7.000,45', 'el-GR');

Returns:
7000.45000000000000000000

A: The following code worked in my case:
select convert(varchar,FORMAT(123456789.0258,'###,###,###.00','de-de'))

output: 123.456.789,03


text:
Q: Simple relocatable image format options I am writing firmware for an ARM platform in which I want to have the main bootloader relocatable in memory rather than always loaded at a fixed address during boot. This means that I need a relocatable format stored in Flash, like ELF.
If ELF is used then I need an ELF loader stored in the ROM code that first gets execution after reset. While this is okay, I also need that same relocation code in the bootloader .. so I will have a lot of code duplication and loss of Flash space if. My intent for the ROM is to just load the bootloader from Flash, so it really is going to be very simple.
I toyed around with creating simple ROM stub that jumped into the text section of the stored ELF image (linked at the address it is stored at in Flash). While this sort of works, I think it might be overkill for my intent.
tl;dr: All I want/need is a relocatable format to store my binary in Flash. Are there other options that are perhaps simpler than ELF that retain relocation tables?

redpajama_set_name: RedPajamaStackExchange


text:
Q: NodeJS - Caching of Dynamic Response Am facing design issue wherein I want to reduce latency of API Server where it does some heavy processing on requested file based on parameters passed.
This server need to serve processed files to lot of http clients.  Note that these dynamic content is result of raw file name and other parameters. At any single point of time it may happen that for many http clients raw file name and other parameters exactly match.  So in order to save redundancy this processing has to be done exactly once.
I am currently using Redis based distributed lock to achieve this.

*

*What's the better way to avoid this stalling?
Now in order to reduce bandwidth cost; I process  these files and upload them to CDN. And eventually pass on the processed-final-URL in redirect request to all interested parties i.e. http clients.

*

*How can I make this completely non-blocking?
Based on some reading I found nsq.io can solve this by creating dynamic topic for each unique combination of file and params. But how http clients would consume the result in non-blocking fashion. Note that I do not have any control over HTTP clients i.e. I can't change anything on client side to resolve this.

A: I'm not sure how you are using your lock.
Here's what I would do,
1. check redis for (file, params) (see if already processed)
  1.1 if not check redis for (processing - file, params) (see if processing)
    1.1.1 if so, wait for (file, params)
    1.1.2 if not, put (processing -file, params) and start making the (file, params) result

(since this is non-atomic, you could process multiple times in the time window, but maybe better than constant
  locking/unlocking, I think the important idea is that you would want
  to implement "lock" concept for each resource, so that requests to
  different requests wouldn't have to acquire the lock.)

  1.2 if so, serve the contents

blocking/non-blocking is what you apply in the server side, client has nothing to do with it.
You make your server socket(operation) non-blocking.
How you do it depends on what framework/library you are using for your server.
Now I see you are using node.js, isn't node.js already using nonblocking socket?


text:
Q: TransformBlock never completes I'm trying to wrap my head around "completion" in TPL Dataflow blocks. In particular, the TransformBlock doesn't seem to ever complete. Why?
Sample program
My code calculates the square of all integers from 1 to 1000. I used a BufferBlock and a TransformBlock for that. Later in my code, I await completion of the TransformBlock. The block never actually completes though, and I don't understand why.
static void Main(string[] args)
{
    var bufferBlock = new BufferBlock<int>();
    var calculatorBlock = new TransformBlock<int, int>(i =>
    {
        Console.WriteLine("Calculating {0}²", i);
        return (int)Math.Pow(i, 2);
    }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8 });

    using (bufferBlock.LinkTo(calculatorBlock, new DataflowLinkOptions { PropagateCompletion = true }))
    {
        foreach (var number in Enumerable.Range(1, 1000))
        {
            bufferBlock.Post(number);
        }

        bufferBlock.Complete();

        // This line never completes
        calculatorBlock.Completion.Wait();

        // Unreachable code
        IList<int> results;
        if (calculatorBlock.TryReceiveAll(out results))
        {
            foreach (var result in results)
            {
                Console.WriteLine("x² = {0}", result);
            }
        }
    }
}

At first I thought I created a deadlock situation, but that doesn't seem to be true. When I inspected the calculatorBlock.Completion task in the debugger, its Status property was set to WaitingForActivation. That was the moment when my brain blue screened.

A: TransformBlock needs a ITargetBlock where he can post the transformation.
 var writeCustomerBlock = new ActionBlock<int>(c => Console.WriteLine(c));
        transformBlock.LinkTo(
            writeCustomerBlock, new DataflowLinkOptions
            {
                PropagateCompletion = true
            });

After this it completes.

A: The reason your pipeline hangs is that both BufferBlock and TransformBlock evidently don't complete until they emptied themselves of items (I guess that the desired behavior of IPropagatorBlocks although I haven't found documentation on it).
This can be verified with a more minimal example:
var bufferBlock = new BufferBlock<int>();
bufferBlock.Post(0);
bufferBlock.Complete();
bufferBlock.Completion.Wait();

This blocks indefinitely unless you add bufferBlock.Receive(); before completing.
If you remove the items from your pipeline before blocking by either your TryReceiveAll code block, connecting another ActionBlock to the pipeline, converting your TransformBlock to an ActionBlock or any other way this will no longer block.

About your specific solution, it seems that you don't need a BufferBlock or TransformBlock at all since blocks have an input queue for themselves and you don't use the return value of the TransformBlock. This could be achieved with just an ActionBlock:
var block = new ActionBlock<int>(
    i =>
    {
        Console.WriteLine("Calculating {0}²", i);
        Console.WriteLine("x² = {0}", (int)Math.Pow(i, 2));
    },
    new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 8});
foreach (var number in Enumerable.Range(1, 1000))
{
    block.Post(number);
}
block.Complete();
block.Completion.Wait();

A: I think I understand it now. An instance of TransformBlock is not considered "complete" until the following conditions are met:

*

*TransformBlock.Complete() has been called

*InputCount == 0 – the block has applied its transformation to every incoming element

*OutputCount == 0 – all transformed elements have left the output buffer

In my program, there is no target block that is linked to the source TransformBlock, so the source block never gets to flush its output buffer.
As a workaround, I added a second BufferBlock that is used to store transformed elements.
static void Main(string[] args)
{
    var inputBufferBlock = new BufferBlock<int>();
    var calculatorBlock = new TransformBlock<int, int>(i =>
    {
        Console.WriteLine("Calculating {0}²", i);
        return (int)Math.Pow(i, 2);
    }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8 });
    var outputBufferBlock = new BufferBlock<int>();
    using (inputBufferBlock.LinkTo(calculatorBlock, new DataflowLinkOptions { PropagateCompletion = true }))
    using (calculatorBlock.LinkTo(outputBufferBlock, new DataflowLinkOptions { PropagateCompletion = true }))
    {
        foreach (var number in Enumerable.Range(1, 1000))
        {
            inputBufferBlock.Post(number);
        }

        inputBufferBlock.Complete();
        calculatorBlock.Completion.Wait();

        IList<int> results;
        if (outputBufferBlock.TryReceiveAll(out results))
        {
            foreach (var result in results)
            {
                Console.WriteLine("x² = {0}", result);
            }
        }
    }
}


text:
Q: How would you calculate the force of a hammer hitting an anvil? If I were to hit an anvil with a hammer (let's say a 1 kg hammer at 1 m/s) how would the force of the impact be calculated?
So, where I'm at with this is that I know the deal with f = mv, so the force would be equal to 1N/s. My problem is with the time that it takes for the energy to be transferred from the hammer to the anvil. If you could see the time it takes for the collision to happen (say 0.1s) that would be easy (10N).
The hammer with the anvil is purely just an example. I've heard people mention of using a dirac delta function, but that just feels unrealistic since it's obviously not instant. Is there an inherent limit to the amount of time that it takes for the force to be applied (say the speed of sound?)
(also like to note that I have absolutely 0 idea how to use a dirac delta function. From the looks of it it's just an integral but I do not understand it)
EDIT: Thanks for the answers. I've been googling for about a week now, watching every video I could find on impulsive force, all of them say to measure it physically. You can understand why this is a very unsatisfying answer, and none of the posts answer this particular question.
Energy is not transmitted instantly. If I were to have a stick 2 lightyears long, put a button at the end of the stick, and push the stick from earth, the button would not be pressed instantly. I was curious if there's anything that determines the rate of energy transfer.

A: I think you mean f=ma, rather than f = mv.
The force between hammer and anvil is, indeed, very difficult to calculate. There are two significantly different cases: 1) where the interaction is elastic (no permanent deformation of either the hammer or the anvil; and 2) where the interaction is inelastic (e.g., the hammer leaves a dent in the anvil). In both cases, the force is related to the momentum change:
$f = ma$  or equivalently $f = m (velocity change)/time$
Unfortunately there is no easy way to know how long it takes for the hammer to reverse direction when it strikes the anvil.  It is not quite instantaneous, because both the hammer and the anvil deform elastically when the hammer strikes.
When there is a dent, we can estimate the time by dividing the depth of the dent by the initial speed of the hammer.  A typical dent is on the order of a millimeter, and a typical hammer speed at impact is probably ~ 10 meters/sec. The duration of the impact would be approximately equal to 1/10,000 sec. The force would be on the order of:
$f = 2 kg * 20 m/sec / ((1 mm)/(10 m/sec))$ = 400,000 Newtons.
In the first case, I think I would try to measure the force indirectly, by measuring the acceleration of the hammer.  It is possible to measure the speed of the hammer head optically at nanosecond intervals.  If that measurement is done continuously during impact, acceleration at each moment is approximately equal to the speed of the hammer head at the moment, minus the speed in the previous moment, divided by the time between the moments.
I don't know what the calculated force would turn out to be in the elastic case, but we know it would be greater than the force during an inelastic collision; probably a million Newtons or more.
A Dirac delta function in this context would simply mean that the speed change is instantaneous, which would mean that the force is infinite.  Yes it's large, but it's not infinite!


text:
Q: Does Angular 2+ (Angular 7) have a code diff component Does Angular 2+ (Angular 7 to be exact) have a code diff component or plugin that can be used for comparing 2 separate text files.
Our current AngularJS app, which we're upgrading, uses Ace-Diff which works well. Yet I can't find anyone who's successfully used an Angular2 version of Ace-Diff, or PrettyDiff, etc.

A: You have currently have two options:

*

*You use ngx-diff See npm

*You implement your own Component using a 3rd-party-library like google-diff-match-patch
ngx-diff's Fetaures are pretty limited and im not sure how the styling works so you maybe wanna build your own for flexibility.
Be a Hero and publish it to npm so everyone can use it.


text:
Q: BlueSocket saying Connection Refused when connecting to Python Socket Socket For a iOS app I'm making, it needs to connect to a python socket server. For the iOS application i'm using Swift 3 and i'm using BlueSocket When I try to connect to the server with the correct IP and Port, it always returns Connection Refused and I don't see the connection on the server. BlueSocket is set to a TCP Client and the python server is also a TCP Server, so i'm confused on why its not working.
Does anyone know/understand why it won't connect to the server?
The iOS swift code is this:
import UIKit
import Foundation
import SystemConfiguration
import SystemConfiguration.CaptiveNetwork
import Socket

let ssid = "SSID"
let server = "192.168.0.24"
let port = 8000

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var ideaLabel: UILabel!

@IBAction func generateButton(_ sender: Any) {

    func isInternetAvailable() -> Bool
    {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
    func getSSID() -> String? {
        var ssid: String?
        if let interfaces = CNCopySupportedInterfaces() as NSArray? {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
                    ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                    break
                }
            }
        }
        return ssid
    }
    func generateIdea() -> String? {
        let RNumber = arc4random_uniform(23)

        var idea = ""

        //(A bunch of code to get a idea for offline mode)

        return String(idea)
    }

    let InternetConnect = isInternetAvailable()

    if (InternetConnect == isInternetAvailable()){
        print("Internet Connection Verified")
        if (getSSID() == ssid){
            print("SSID Verified")

            let s = try! Socket.create()
            try! s.connect(to: server, port: 8000)
            print("Connceted to server")

            try! s.write(from: "01")
            print("String send")

            let idea = try! s.readString()
            print("Idea Received")
            ideaLabel.text = idea

            s.close()
        }
        else{

            print("SSID Verification Failed")
            ideaLabel.text = generateIdea()
        }

    }
    else {

        ideaLabel.text = generateIdea()
        print("Internet Connection Verification Failed")

    }
}

}
Explanation of swift client:
When a button is clicked to generate a idea, the app first checks to see if it can connect to the internet, if it can it then checks to see if its on the set internet network by checking the SSID(The server is going to be a lan server, so it only works on the set network)If it can't connect to the internet or its not on the correct network, it chooses a from a limited amount of ideas that are stored on the app. If it can connect to the internet and its on the right internet network, it attempts to connect to the server and get a idea from the server.
The python socket server code:
import socket
import sqlite3
from random import randint

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8000)
print("Starting Server")
s.bind(server_address)
print("Waiting for client")
s.listen(1)
alive = True

while(alive == True):
    connection, client_address = s.accept()
    print(client_address)

    try:
        command = connection.recv(2)

        if (command == "01"):
            conn = sqlite3.connect('ideas.db')
            c = conn.cursor()
            file = open("maxID.txt", "r")
            maxID = (int(file.read()) + 1)
            ideaNumber = (randint(1,maxID),)
            c.execute('SELECT * FROM ideas WHERE id=?', ideaNumber)
            idea1 = c.fetchone()
            idea = str(idea1)
            conn.close()
            idea = idea.translate(None, "1234567890'(),u")
            print("Your idea is:")
            print(idea)
            connection.send(str(idea))

    finally:
        connection.close()

Explanation of python socket server:
When the server gets a client, it waits to get a command. In this server, there is only 1 command, which is to get an idea. That command is "01". When it gets that command the first thing it does is gets the amount of ideas stored in the database. That will be written in the maxID.txt file, so it reads it. Then randomly chooses a random idea ID, then it gets that idea from the database by using the ID. Then it takes that idea and sends it to the client.

A: The issue was on the python server. The issue was that I set the host to localhost, instead of leaving it blank.
This:
server_address = ('localhost', 8000)

Should've been:
server_address = ('', 8000)


text:
Q: Error creating bean with name 'securityConfiguration' when running test I'm creating a Spring Boot application with Spring Security. I've created a custom login page that uses an auth endpoint in our AuthController. My SecurityConfiguration class extends WebSecurityConfigurerAdapter.
At the moment, I'm trying to create tests for this without any results. Most of this is new to me and I'm still learning, specially testing. I'm not even sure if I've done this right at all.
Any help is appreciated.
SECURITYCONFIGURATION
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final ApplicationUserService applicationUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(  "/register", "/index*", "/static/**", "/*.js", "/*.json", "/*.ico").permitAll()
                .antMatchers(HttpMethod.POST,"/api/auth/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                //.loginProcessingUrl("/api/auth/authenticate")
                .defaultSuccessUrl("/home", true);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(applicationUserService);
        return provider;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

AUTHCONTROLLER
@RequiredArgsConstructor
@RestController
@RequestMapping("api/auth/")
public class AuthController {

    private final UserService userService;

    @PostMapping("authenticate")
    public ResponseEntity<?> verifyUser(@RequestBody User user) throws Exception {
        return userService.authenticateUser(user);
    }

}

USERSERVICE
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final AuthenticationManager authenticationManager;

    public ResponseEntity<?> authenticateUser(User user) throws Exception {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(user.getEmail(),user.getPassword()));
        if (!authentication.isAuthenticated())
            return new ResponseEntity<>(new ResponseObject("Error"), HttpStatus.UNAUTHORIZED);
        else {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return new ResponseEntity<>(user,HttpStatus.OK);
        }
    }

}

TESTCLASS
@WebMvcTest(AuthController.class)
class AuthControllerTest {

    User user;

    @MockBean
    UserService userService;

    @Autowired
    MockMvc mockMvc;

    @BeforeEach
    void setUp() {
        user = User.builder()
                .email("test@hotmail.com")
                .password("password")
                .id(1L).build();
    }

    @Test
    void verifyUser() throws Exception {
        given(userService.authenticateUser(any(User.class))).willReturn(new ResponseEntity<>(HttpStatus.OK));

        mockMvc.perform(post("/api/auth/authenticate")
                .contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(user)))
                .andExpect(status().isOk());
    }

}

ERRORS

Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration' defined in file [\SecurityConfiguration.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.crypto.password.PasswordEncoder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.crypto.password.PasswordEncoder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}


text:
Q: consuming an deployed Azure ML model in PowerBI I have issues while interfacing Azure ML with PowerBI. I deployed a model from Auto ML, and tried to consume it in PowerBI. I successfully completed the following tutorials create a predictive model by using auto ML and consume a model in PowerBI . But when it comes to implement my proper model, I  can choose the targeted model, and use the right inputs, with the right data type, but I get this error :
Unable to parse the response from the Azure ML Web Service

I have to add that my model forecasts time series. On the contrary, the model was a regression in the Microsoft tutorials. And I didn't use R or Python script, I used exactly the same method as the second tutorial about PowerBI.
Thank you very much for your help ! don't hesitate to ask me if you need more information.
Mary

A: Good practice to use error handling:
def run(data):
try:
        result = model.predict(data)
        return result.tolist()
    except Exception as e:
        result = str(e)
        return json.dumps({"error": result})
    return json.dumps({"result": result.tolist()})

If you instead used the pandas dataframe as the input schema, this should generate the swagger with the column names as separate input parameters with known data types which Power Bi can then use to map to columns in your data flow.


text:
Q: Download CSV file on click event of link button not working The below piece of code is not working. I want to download a CSV file from the folder on link button click event.
protected void LinkButton1_Click(object sender, EventArgs e)
{
  string filePath = "~/Data/Book1.csv";
  System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(filePath));
  if (file.Exists)
  {
    WebClient req = new WebClient();
    HttpResponse response = HttpContext.Current.Response;
    //string filePath = "";
    response.Clear();
    response.ClearContent();
    response.ClearHeaders();
    response.Buffer = true;
    response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension");
    byte[] data = req.DownloadData(Server.MapPath(filePath));
    response.BinaryWrite(data);
    response.End();
  }
}

A: Instead of reading the file by using a WebClient, you can transmit it to the client directly. As long as the file is located in the local file system, you do not need to get it using a web request but can read it directly. This is much more efficient.
protected void LinkButton1_Click(object sender, EventArgs e)
{
  string filePath = "~/Data/Book1.csv";
  System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(filePath));
  if (file.Exists)
  {
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.ClearContent();
    response.ClearHeaders();
    response.AddHeader("Content-Disposition", "Attachment;Filename=" + file.Name);
    response.TransmitFile(file.FullName);
    response.Flush();
    response.End();
  }
}

I'd also recomment to disable buffer and to flush the content before ending the response.
As also @BobSwager pointed out, there are some problems in the Content-Disposition header.


text:
Q: MySQL: Create stored procedures dynamically I have a database to which several real users have access using JDBC. The separation of these users is very crucial, such that they are neither able see nor manipulate each other's data.
To separate the users' data, I decided to create the few corresponding tables for every user, and only give the owning user the permissions on this table. This is all done automatically in a stored procedure.
Besides this table separation, I want a user only to execute stored procedures to work with his tables, not arbitrary SQL queries.
Let's consider an example procedure like
DELIMITER //
CREATE PROCEDURE MyProcedure(IN p_identifier VARCHAR(30), IN p_key INT(10))
BEGIN
SET @p_identifier = p_identifier;
SET @p_key = p_key;

SET @s = CONCAT('DELETE FROM ', p_identifier, '_mytable WHERE key =?;');
PREPARE stmt FROM @s;
EXECUTE stmt USING @p_key,
DEALLOCATE PREPARE stmt;

END //
DELIMITER ;

And use it like CALL MyProcedure('ad3e981b', 2);.
So far, so good.
Problems arise since this procedure is used by all users (the first paraeter is the table-prefix). This is bad, because once a user gets execution privileges for MyProcedure, he is able to to provide any table-prefix at will and mess with other user's data - so my user separation is gone. This is the problem I need to solve.
I currently see two solutions:

*

*Don't use stored procedures: Just give INSERT/DELETE/SELECT privileges on the user's table only to the user. This is simple and works - but I'd prefer to only call stored procedures over JDBC, not arbitrary SQL queries.

*Make a stored procedure for EVERY user, in which the table prefix is invariant (e.g, table-prefix_MyProcedure(), which is only executable by one user). Then, assign the execution privilege only to the corresponding user. However, this should be done automatically on request - hence, I need to be able to create a stored procedure with a parameterized name to set this up (phew). As the title suggests, this is the way I want to go - but I really struggle with the syntax of dynamically creating a stored procedure (in a stored procedure) and thus, I'm really not sure if this is how I should proceed.

Any ideas how I got approach this problem?
Regards,
raute


text:
Q: Jetbrains Pycharm 2019.2 & Win10 WSL: can't not sync actual python package I'm here to look for help. Recently I need to do some linux-based development so I try a brand new way to archive this:using WSL instead of SSH interpreter. Vmware performance is not so good on my 8GB laptop, so I try to WSL. When talking about SSH Interpreter, I think SSH Interpreter has been a little heavy when you meet WSL for the first time just like me.
WSL has many benefits, such as automatic fill local path as remote path and need no virtual machine or VPS.
But something funny happens: I'm using Kali-Linux as my Windows subsystem of Linux and python3.7 is installed as default. WSL has two account:girl and root, and I add interpreter by choose WSL:

Then show the package status:

As shown from the above, there is no package name bs4 BUT when I type from bs4 import BeautifulSoup, pycharm did not warn me that I do not have the package:

Even run this script will return an error:

And I don't know why. Once upon a time I install rsync on the subsystem and it appears to be health. However I still have some doubut so I try to confirm whether the problem is solved or not. I uninstall another package and try to import it. The same circumstance occurs again.
Jetbrains did not give any answer, will anyone here know why is that? Thank you very much.
(ps:have not try other WSL version yet, pycharm version is professional and registered)


text:
Q: Sending a string from C# to insert into a PHP file to be immediately used in a mysql select query with the results returned So I have this php file with the following query
$query = "select Customer.CustID, LastName,FirstName,DOB,CustPhone,
Max(TransDate) as LatestTransaction from Customer, History where
Customer.AuthKey='A111' and Customer.AuthKey=History.AuthKey and
Customer.CustID=History.CustID  Group by CustID;";

$result = mysqli_query($con,$query);

$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
  echo json_encode($rows);

  mysqli_close($con);

And then I do this C# here to get the results and put them into a datagridview
            WebClient wc = new WebClient();
            var json = wc.DownloadString(URL);
            List<Customer> customers =
            JsonConvert.DeserializeObject<List<Customer>>(json);
            CustomerDataViewGrid.DataSource = customers;

There are no problems with this, however I would like to take
Customer.AuthKey = 'A111'

From the above select query in the php And instead pass the value from my C# code to it
$aKey = $_POST['Authkey'];
Customer.AuthKey = '$aKey'

I have tried to do this within the same button click event but I am not quite understanding how I can send this string and then immediately get the Downloading string.  When I hard code the Customer.Authkey it returns my results, but when I try to send this string it does not return anything.  How can I do this from the same event?
Thanks

A: NameValueCollection formData = new NameValueCollection() {
    { "Authkey", "A111" },
};

byte[] result = wc.UploadValuesTask("<your_url_here>", "POST", formData);

string json = Encoding.UTF8.GetString(result);

By this was you can send your auth key to your PHP script. The rest is up to you. Sorry if I misunderstood you, feel free to correct me.


text:
Q: Get toDebugString from DecisionTreeClassifier in PySpark ML I trained a DecisionTreeClassifier model using a pipeline like this one:
from pyspark.ml import Pipeline
from pyspark.ml.feature import VectorAssembler, StringIndexer
from pyspark.ml.classification import DecisionTreeClassifier

cl = DecisionTreeClassifier(labelCol='target_idx', featuresCol='features')
pipe = Pipeline(stages=[target_index, assembler, cl])
model = pipe.fit(df_train)

# Prediction and model evaluation
predictions = model.transform(df_test)

where the stages are instances of StringIndexer and VectorAssembler. I can now evaluate the accuracy of the model, for example, with
mc_evaluator = MulticlassClassificationEvaluator(
labelCol="target_idx", predictionCol="prediction", metricName="precision"    )

accuracy = mc_evaluator.evaluate(predictions)
print("Test Error = {}".format(1.0 - accuracy))

Great. Now I need to check the tree model structure. The docs point me to an attribute called toDebugString, but the ML DecisionTreeClassifier does not have this one - it seems to be an attribute only for the MLLib DecisionTree classifier. How can I get the tree structure from the model inside the pipeline from the ML version and plot it?

A: This worked for me in pyspark:
model.stages[2]._call_java('toDebugString')


text:
Q: Как можно правильно разделить представленный метод на две отдельные кнопки? В общем-то, еще один вопрос по Формам от меня (предыдущий вопрос). Есть две LinkLabel кнопки и один TreeView. Первая кнопка добавляет основной узел, вторая подузел для выбранного узла. У самого же TreeView данные и отображение разделены, соответственно есть своя отдельная модель данных, а с ней метод FillVisualTree который вносит узлы с данными в сам список TreeView:
    public void FillVisualTree(TreeNodeCollection tree)
    {
        foreach (var i in Items)
        {
            var node = new TreeNode { Text = i.Name, Tag = i };
            foreach (var si in i.SubItems)
            {
                var subnode = new TreeNode { Text = si.Name, Tag = si };
                node.Nodes.Add(subnode);
            }
            tree.Add(node);
        }
    }

Проблема в том, что этот метод заносит все узлы/подузлы разом, а у меня две отдельные кнопки, как выше уже писал, первая для добавления главного узла и вторая для добавления подузла к выбранному узлу.
Я попробовал разделить этот метод, чтобы он добавлял узлы по кускам.
Cначала занес в поля класса экземпляр класса "дерева", дабы иметь доступ вне метода:
private TreeNode node;

Далее создал метод FillVisualTreeRoot для добавления основного узла:
        public void FillVisualTreeRoot(TreeNodeCollection tree)
        {
         node = new TreeNode();
         foreach (var i in Items)
         {
            node.Text = i.Name;
            node.Tag = i;
         }
        tree.Add(node);
        }

И FillVisualTreeAnswer для его подузла:
        public void FillVisualTreeAnswer(TreeNodeCollection tree)
        {
        var subnode = new TreeNode();
        foreach (var i in Items)
        {
            foreach (var si in i.SubItems)
            {
                subnode.Text = si.Name;
                subnode.Tag = si;
            }
        }
        node.Nodes.Add(subnode);
       }

Также внес в поля уже класса Формы экземпляр модели данных:
ItemModel item;

Потом в обработчике события кнопки для создания узла внес все данные и вызвал ранее созданный метод FillVisualTreeRoot, который должен добавлять узлы с данными в список:
      private void NewRoot_Label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
      {
            item = new ItemModel { Name = "Item1", Text = "Item1 Text" };
            Model.Items.Add(item);
            Model.FillVisualTreeRoot(Roots_TreeView.Nodes);
      }

Все работает на отлично

Но у меня еще не задействована кнопка добавления подузлов.
В обработчике события второй кнопки для подузлов я также внес данные и вызвал второй метод FillVisualTreeAnswer и казалось бы все отлично, но он работает совсем иначе. Место того чтобы добавлять подузлы к ВЫБРАННЫМ узлам, он делает это только с последними созданными:

Немного подумав, я все таки догадываюсь в чем проблема, в общем экземпляре TreeNode nodе, который используется в двух методах в качестве добавления узлов в список.
Так вот, как можно ПРАВИЛЬНО разделить метод FillVisualTree на две кнопки чтобы он ПРАВИЛЬНО создавал и разделял узлы/подузлы?

A: В данном случае вы зря привязали добавление визуального элемента дерева к модели, хотя в этом, отчасти, моя вина, поправил предыдущий ответ.
Так как за отображение отвечает форма, то интерактивное добавление визуальных элементов следует оставить именно ей. Модифицируйте обработчики кликов по ссылке следующим образом:
private void NewRoot_Label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    var item = new ItemModel { Name = "Item1", Text = "Item1 Text" };
    Model.Items.Add(item);
    treeView1.Nodes.Add(new TreeNode { Text = item.Name, Tag = item });
}

private void AddChild_Label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
    //эта проверка нужна, чтобы дочерние узлы добавлялись только в выбранный корень
    //и не добавлялись в дочерние
    if (treeView1.SelectedNode?.Tag is ItemModel item)
    {
        var subItem = new SubItemModel { Name = "Item1", Text = "Item1 Text", Parent = item };
        item.SubItems.Add(subItem);
        treeView1.SelectedNode?.Nodes.Add(new TreeNode { Text = subItem.Name, Tag = subItem });
        //ну и сразу развернем узел в который добавили элемент
        treeView1.SelectedNode?.Expand();
    }
}

К большому сожалению, реализация штатного TreeView в WinForms довольно "топорная" и не поддерживает автоматическую привязку данных через свойство DataSource, которое у него просто отсутствует в отличие от, например, ListBox или ComboBox. Поэтому добавление, удаление и начальную генерацию узлов данного контрола приходится делать руками.
Также стоит посмотреть в сторону классов BindingList<T> и BindingSource.
Есть неплохая статья по основам привязки данных, только читать надо очень внимательно, при беглом просмотре можно упустить важные детали.


text:
Q: VS2013 Net 4_5_2 IIS7 signinManager.PasswordSignIn I am on hols for a week. Wont be able to answer during this time.
Expected Result
When using IIS with website user accounts then a user should be able to login with no issues.
Actual Result
After publishing to local IIS, DefaultConnection security string to MSSQLMS shows 'DOMAIN/USER$' as sql user not found when in fact  var signinManager = Context.GetOwinContext().GetUserManager(); from Login.aspx.cs shows the user and password hash for all website users.
Recreating this bug:
I created a VS2013 aspx project (with MVC and webservices) and Individual Security Accounts, build and run project in debug. Add a user to create the localDB database and connection string. Change connection string to use local MSSQL server. Build and run project no probs. Create a user (localhost). Publish to IIS. Data is returned fine from the same MSSQL server (ApplicationData database). When logging in then receive error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in mscorlib.dll but was not handled in user code. Additional information: Login failed for user 'DOMAIN\workstation$'.
MSSQLMS logs show the sql user not found. MSSQL profiler does not show the transaction.
The strange thing is that in Login.aspx.cs 'var signinManager = Context.GetOwinContext().GetUserManager();' shows all the users' details. The fail is on execution of 'var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);'.
I have added the user to MSSQL server Security, database and at the Table level.

A: IIS uses the AppPool identity to communicate with other (network) resources. I'm not completly sure what you're trying to accomplish here but if you just want to host your identity db in SQL Server instead of using LocalDb, just give the AppPool identity of your IIS website the correct security clearances on the SQL server.
If you would like to do some kind of impersonation of the logged in user, you at first should not use 'Invidual Accounts' and secondly you have to setup impersonation in IIS. This can be done in the properties of the AppPool.


text:
Q: Gaussian Processes for Regression (GPR) and Logistic Regression (LR) I want to implement a model for risk prediction (generate a percentage). I know LR would be adequate to this work but I would like to try GPR.
My question is: is GPR a suitable choice in this case? I know GPR is to generate probability distribution over function and it can give robust estimation for missing data but is it possible to make probabilistic prediction? (or Gaussian Processes for Classification can do this?)
Thank you for your help.  :-)

A: GPR is for Regression problem. LR is for "Classification".
You should use Gaussian Process followed with a nonlinearity (like a softmax) for classification which needs some approximations for learning and prediction. It is included in the following link. You can run the demo to see how it works:
http://www.gaussianprocess.org/gpml/code/matlab/doc/

A: Logistic regression is a regression method for binary response variables (almost what @Daniel says, but not quite). If your risk can be interpreted as a probability of default/collapse/whatever, then Logistic Regression might be appropriate if you can arrange your data to have either "defaulted" or "not defaulted" instead of the risk percentage as the dependent variable.
If not, you're somewhat stuck with regressing against the percentage. You could use Gaussian processes, or indeed any other regressor. The reason I say 'stuck' is that there are some problems with regressing against numbers bound to the interval [0, 1] using standard methods, as a standard linear regressor (or GP, or SVR, or whatever) is usually defined over the entire real line. To get around this, you can specifically use Beta Regression (y ~  Beta) which confines the dependent variable to the appropriate range, or regress against a transformed percentage (for example, the logit or probit transformed proportion will be on the entire real line).


text:
Q: Canonical representation of a class object containing a list element in XML I see that most implementations of JAX-RS represent a class object containing a list of elements as follows (assume a class House containing a list of People)
<houses>
  <house>
    <person>
      <name>Adam</name>
    </person>
    <person>
      <name>Blake</name>
    </person>
  </house>
  <house>
  </house>
</houses>

The result above is obtained for instance from Jersey 2 JAX-RS implementation,
notice Jersey creates a wrapper class "houses" around each house, however strangely it doesn't create a wrapper class around each person!
I don't feel this is a correct mapping of a list, in other words I'd feel more confortable with something like this:
<houses>
  <house>
    <persons>
    <person>
      <name>Adam</name>
    </person>
    <person>
      <name>Blake</name>
    </person>
    </persons>
  </house>
  <house>
  </house>
</houses>

Is there any document explaining how an object should be correctly mapped apart from any opninion?

A: XML documents can only have a single root node, so the <houses> is necessary if you would want to serialize more than one <house>.
A <persons> element is not necessary as a node may contain any number of children with the same tag name – they can be disambiguated by position. It adds complication without adding value or structure. But such a grouping may be adequate e.g. when we have different kinds of inhabitants in our house:
<house>
  <inhabitants>
    <human>
      <name>Larry</name>
    </human>
    <human>
      <name>Guido</name>
    </human>
    <dog>
      <name>Rasmus</name>
    </dog>
  </inhabitants>
</house>

Here, <inhabitants> encodes a relation, whereas <human> and <dog> encode a type.


text:
Q: Determining the round players will meet in a knock-out tournament Given a knock-out tournament with $2^n$ players, I am looking for a formula or algorithm to calculate the round player A will meet player B.
For the case $2^n=16$. Player 7 will meet player 8 in round 1, player 8 can meet player 9 in round 4 (the final).
How do I calculate the round in terms of n, A & B?
Thanks

A: Let $(A-1)_2 = a_k a_{k-1} \ldots a_2 a_1$ and $(B-1)_2 = b_k b_{k-1} \ldots b_2 b_1$ be the binary representations of $A-1$ and $B-1$. Then the round in which $A$ and $B$ will meet is
$$\max_i \ (a_i \neq b_i)$$
Example: $A = 8$, $B = 9$. Then $(A-1)_2 = 7_2 = (0111)_2$ and $(B-1)_2 = (1000)_2$ so they will meet in the finals. If $B = 7$ then $(B-1)_2 = (0110)_2$ so they will meet in round $1$.


text:
Q: Tufte page numbering on first page of new chapter I am using the Tufte-Book style but have very short chapters. The page number is not added to the first page of a new chapter so I end up with very few numbered pages at all.
Question: How can I add page numbering to every page of the chapter including the first page of each chapter?
Thanks in advance,
David.

A: Customize the page style so that every page style is plain
\fancypagestyle{plain}{}


text:
Q: Get a Rect from 3 points I am making a pie chart with a text on each pie slice. To center the text on each pie slice, I need a Rect object explained below:
This is a sample pie chart:

You can see 4 points: center and the three points intersecting the circumference of piechart by three lines:

Now to center the text at each pie slice, I want to make 3 Rect objects for each text:

I don't want to draw any rectangles, but need a Rect objects corresponding to these points.Each Rect must contain the intersections made by the corresponding pie slice on the circle , the center of circle.  Any idea how to do this? I hope I am clear by my question.
My piechart code:
public class PieView extends View {

String[] names;
int values[];

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

public PieView(Context context, int nums[], String nam[]) {
    super(context);
    names = nam;
    values = nums;
}

@Override
protected void onDraw(Canvas canvas) {
    DecimalFormat df = new DecimalFormat("#.00");
    super.onDraw(canvas);
    int radius = getHeight() / 2;
    int total = sum(values);
    String percentage[] = { df.format((values[0] * 100) / total),
            df.format((values[1] * 100) / total),
            df.format((values[2] * 100) / total) };
    Paint green = new Paint();
    Paint red = new Paint();
    Paint blue = new Paint();
    blue.setAntiAlias(true);
    green.setAntiAlias(true);
    red.setAntiAlias(true);
    blue.setColor(Color.parseColor("#30abd9"));
    green.setColor(Color.parseColor("#30d976"));
    red.setColor(Color.parseColor("#db7a26"));
    blue.setStyle(Paint.Style.FILL);
    green.setStyle(Paint.Style.FILL);
    red.setStyle(Paint.Style.FILL);
    RectF rectf = new RectF(
            new Rect(getWidth() / 2 - radius, getHeight() / 2 - radius,
                    getWidth() / 2 + radius, getHeight() / 2 + radius));
    canvas.drawArc(rectf, 0, (values[0] * 360) / total, true, blue);
    canvas.drawArc(rectf, (values[0] * 360) / total, (values[1] * 360)
            / total, true, green);
    canvas.drawArc(rectf, ((values[0] * 360) / total)
            + ((values[1] * 360) / total),
            360 - (((values[0] * 360) / total) + ((values[1] * 360))
                    / total), true, red);
    Paint eraserPaint = new Paint();
    eraserPaint.setColor(Color.parseColor("#f2f2f2"));
    eraserPaint.setStrokeWidth(3);
    canvas.drawLine(getWidth() / 2, getHeight() / 2, getWidth() / 2
            + radius, getHeight() / 2, eraserPaint);
    canvas.drawLine(
            (float) getWidth() / 2,
            (float) getHeight() / 2,
            (float) (getWidth() / 2 + radius
                    * (Math.cos(Math.toRadians((values[0] * 360) / total)))),
            (float) (getHeight() / 2 + radius
                    * Math.sin(Math.toRadians((values[0] * 360) / total))),
            eraserPaint);
    canvas.drawLine(
            (float) getWidth() / 2,
            (float) getHeight() / 2,
            (float) (getWidth() / 2 + radius
                    * (Math.cos(Math.toRadians(((values[0] * 360) / total)
                            + ((values[1] * 360) / total))))),
            (float) (getHeight() / 2 + radius
                    * Math.sin(Math.toRadians(((values[0] * 360) / total)
                            + ((values[1] * 360) / total)))), eraserPaint);
    // if (values[0] != 0) {
    // Rect areaRect1 = new Rect(getWidth()/2, 90,
    // columnsAreaWidth + widthLeft + 15, 130);
    // canvas.drawRect(areaRect1, eraserPaint);
    // RectF bounds1 = new RectF(areaRect1);
    // bounds1.right = eraserPaint.measureText("Easy\n"+values[0], 0, new
    // String(
    // "Easy\n"+values[0]).length());
    // // measure text height
    // bounds1.bottom = eraserPaint.descent() - eraserPaint.ascent();
    // bounds1.left += (areaRect1.width() - bounds1.right) / 2.0f;
    // bounds1.top += (areaRect1.height() - bounds1.bottom) / 2.0f;
    // canvas.drawText("Easy\n"+values[0], bounds1.left,
    // bounds1.top - eraserPaint.ascent(), eraserPaint);
    //
    // }
}

@Override
public void setLayoutParams(LayoutParams params) {
    super.setLayoutParams(params);
}

private int sum(int[] num) {
    int x = 0;
    for (int i = 0; i < num.length; i++) {
        x += num[i];
    }
    return x;
}
}

The commented code is for the text. I need the Rect objects for it.

A: Thanks to @pskink , I got my answer. Here is the full code of my pie chart. I made it for 3 values only, but it can be made general with little changes. Hope it may be use to someone :)
package com.utils;

import org.json.JSONArray;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

public class ColumnsView extends View {

JSONArray array;

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

public ColumnsView(Context context, JSONArray jar) {
    super(context);
    array = jar;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint green = new Paint();
    Paint red = new Paint();
    Paint grey = new Paint();
    Paint textColor = new Paint();
    textColor.setColor(Color.parseColor("#b8b8b8"));
    textColor.setStrokeWidth(5);
    textColor.setTextSize(25);
    grey.setColor(Color.parseColor("#e1e1e1"));
    green.setColor(Color.parseColor("#91cc33"));
    red.setColor(Color.parseColor("#d93030"));
    grey.setStyle(Paint.Style.FILL);
    red.setStyle(Paint.Style.FILL);
    green.setStyle(Paint.Style.FILL);
    int width = getWidth();
    int columnsAreaWidth = width - 200;
    int columnHeight = 240;
    int columnWidth = columnsAreaWidth / (array.length() + 1);
    int gapWidth = columnWidth / array.length();
    try {
        int freeWidth = gapWidth;
        for (int i = 0; i < array.length(); i++) {
            int total = Integer.parseInt(array.getJSONObject(i).getString(
                    "Total"));
            int correct = Integer.parseInt(array.getJSONObject(i)
                    .getString("Correct"));
            int incorrect = Integer.parseInt(array.getJSONObject(i)
                    .getString("Incorrect"));
            int unattempted = Integer.parseInt(array.getJSONObject(i)
                    .getString("Unattempted"));
            String name = array.getJSONObject(i).getString("Level");
            int correctHeight = (columnHeight * correct) / total;
            int unattemptedHeight = (columnHeight * unattempted) / total;
            int incorrectHeight = columnHeight - correctHeight
                    - unattemptedHeight;
            canvas.drawRect(freeWidth, 0, freeWidth + columnWidth,
                    correctHeight, green);
            canvas.drawRect(freeWidth, correctHeight, freeWidth
                    + columnWidth, correctHeight + unattemptedHeight, grey);
            canvas.drawRect(freeWidth, correctHeight + unattemptedHeight,
                    freeWidth + columnWidth, columnHeight, red);
            int xPos = (canvas.getWidth() / 2);
            Rect areaRect = new Rect(freeWidth - gapWidth,
                    columnHeight + 10, freeWidth + columnWidth + gapWidth,
                    columnHeight + 40);
            RectF bounds = new RectF(areaRect);
            bounds.right = textColor.measureText(name, 0, name.length());
            bounds.bottom = textColor.descent() - textColor.ascent();
            bounds.left += (areaRect.width() - bounds.right) / 2.0f;
            bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;
            canvas.drawText(name, bounds.left,
                    bounds.top - textColor.ascent(), textColor);
            // canvas.drawText(name, freeWidth + 10, 300 + 40, textColor);
            freeWidth += columnWidth + gapWidth;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    int widthLeft = 180;
    canvas.drawRect(new RectF(new Rect(columnsAreaWidth + 15, 30,
            columnsAreaWidth + 15 + 40, 70)), green);
    canvas.drawRect(new RectF(new Rect(columnsAreaWidth + 15, 90,
            columnsAreaWidth + 15 + 40, 130)), grey);
    canvas.drawRect(new RectF(new Rect(columnsAreaWidth + 15, 150,
            columnsAreaWidth + 15 + 40, 190)), red);
    grey.setStyle(Paint.Style.STROKE);
    red.setStyle(Paint.Style.STROKE);
    green.setStyle(Paint.Style.STROKE);
    canvas.drawRect(new RectF(new Rect(columnsAreaWidth + 15, 30,
            columnsAreaWidth + 15 + 40, 70)), green);
    canvas.drawRect(new RectF(new Rect(columnsAreaWidth + 15, 90,
            columnsAreaWidth + 15 + 40, 130)), grey);
    canvas.drawRect(new RectF(new Rect(columnsAreaWidth + 15, 150,
            columnsAreaWidth + 15 + 40, 190)), red);
    green.setTextSize(20);
    red.setTextSize(20);
    grey.setTextSize(20);
    Rect areaRect = new Rect(columnsAreaWidth + 15 + 40, 30,
            columnsAreaWidth + widthLeft + 15, 70);
    canvas.drawRect(areaRect, green);
    RectF bounds = new RectF(areaRect);
    bounds.right = green.measureText("Correct", 0,
            new String("Correct").length());
    // measure text height
    bounds.bottom = green.descent() - green.ascent();
    bounds.left += (areaRect.width() - bounds.right) / 2.0f;
    bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;
    canvas.drawText("Correct", bounds.left, bounds.top - green.ascent(),
            green);
    Rect areaRect2 = new Rect(columnsAreaWidth + 15 + 40, 90,
            columnsAreaWidth + widthLeft + 15, 130);
    canvas.drawRect(areaRect2, grey);
    RectF bounds2 = new RectF(areaRect2);
    bounds2.right = grey.measureText("Unattempted", 0, new String(
            "Unattempted").length());
    // measure text height
    bounds2.bottom = grey.descent() - grey.ascent();
    bounds2.left += (areaRect2.width() - bounds2.right) / 2.0f;
    bounds2.top += (areaRect2.height() - bounds2.bottom) / 2.0f;
    canvas.drawText("Unattempted", bounds2.left,
            bounds2.top - grey.ascent(), grey);
    Rect areaRect3 = new Rect(columnsAreaWidth + 15 + 40, 150,
            columnsAreaWidth + widthLeft + 15, 190);
    canvas.drawRect(areaRect3, red);
    RectF bounds3 = new RectF(areaRect3);
    bounds3.right = red.measureText("Incorrect", 0,
            new String("Incorrect").length());
    // measure text height
    bounds3.bottom = red.descent() - red.ascent();
    bounds3.left += (areaRect3.width() - bounds3.right) / 2.0f;
    bounds3.top += (areaRect3.height() - bounds3.bottom) / 2.0f;
    canvas.drawText("Incorrect", bounds3.left, bounds3.top - red.ascent(),
            red);
}

@Override
public void setLayoutParams(LayoutParams params) {
    super.setLayoutParams(params);
}
}

Screenshot:


text:
Q: Django print sqlite db data in template I'm new to django and I'm having a little difficulty getting my database data to print onto my page. I'd appreciate help - and I know I'm doing something silly but I've kinda hit the wall.
I have the DB set up and I can access the data in it without any issues:
python manage.py shell
>>> from homepage.models import User, Oncall
>>> user_data = User.objects.all()
>>> names = []
>>> for x in user_data:
...  names.append(x.first_name + ' ' + x.last_name)
>>> names
[u'Arthur Mencke', u'John Doe']

So then in my views.py I have:
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404, render_to_response
from django.utils import timezone
import datetime
from homepage.models import User, Oncall
from django.template import RequestContext, loader
from django.template import Template, Context
from django.template.defaulttags import register

def index(request):
        now = timezone.now()
        users = User.objects.all()
        return render(request, 'homepage/index.html')

def getUsers(request):
        users = User.objects.all()
        name_list = []
        for x in users:
                name_list.append(x.first_name + ' ' + x.last_name)
        return name_list

And in my index.html file:
{% if name_list %}
        {% for x in name_list %}
                {{ name_list.x }}
        {% endfor %}
{% else %}
        no users
{% endif %}

{{name_list|length}}

This will always show up in the browser with:
no users 0

I've also tried name_list[x] and mucked around with it quite a bit with no luck
Any ideas?
Cheers, Arthur

A: You are doing it wrong, you are not passing the context in index view, take this example:
def index(request):
    users = User.objects.all()
    return render(request, 'homepage/index.html', {'users': users}) # notice here we are adding our context to be used in template, you need pass it explicitly

Then in index.html:
{% for user in users %}
    {{ user.first_name }} {{ user.last_name }}
{% endfor %}


text:
Q: datauris: are PNG and JPEG MIME types interchangable in modern browsers? I have noticed that if you take a base64 string representing the raw bytes of either a JPG or a PNG, call this <B>, and you send a datauri to the browser using either:
data:image/png;base64,<B>

or
data:image/jpeg;base64,<B>

all four combinations work (by work I mean Chrome renders them), the four combinations being

*

*<B> is raw png image, and the data uri uses the png type

*<B> is raw png image, and the data uri uses the jpeg type (was expecting a failure!)

*<B> is raw jpeg image and the data uri uses the png type (was expecting a failure!)

*<B> is raw jpeg image, and the data uri uses the jpeg type

Why is this? The binary encoding of jpeg and png are not the same. I was expecting that if <B> was the raw bytes of a png, the jpeg datauri would fail to render, and visa versa.

A: Data URLs are described in the RFC 2397 proposed standard (The "data" URL scheme) from August 1998:
data:[<mediatype>][;base64],<data>

This document doesn't really go into implementation details such as error handling.
It's worth noting that the media type part is optional and defaults to plain text in 7-bit US-ASCII:

If <mediatype> is omitted, it defaults to text/plain;charset=US-ASCII.

Now, from the context of your question I assume you're really talking about HTML documents and <img> tags. Whether the information inside the src attribute comes from an inline data URL string or an HTTP network request is possibly secondary and I suspect that raw binary data is handled by the same routines inside the browser no matter its source.
You can emulate the same behaviour by sending arbitrary Content-Type headers with regular image files. This can be accomplished by (mis)configuring your web server, writing a download script in a server-side language or just renaming the files. And in fact you don't even need HTML:

In short, it all relates to the ability of browsers to recover from error conditions that arises from the fundamental design philosophy of the World Wide Web, which kind of evolved organically.


text:
Q: Does GreenPlum with PXF support avro data with schema evolution We have user data (avro files) validated and ingested into HDFS using Schema Registry(data keep on evolving) and using GreenPlum with PXF to access HDFS data. Created one external table and trying to query the HDFS data but getting error as,
warehouse=# select * from user;
ERROR:  Record has 151 fields but the schema size is 152  (seg1 slice1 192.168.1.17:6001 pid=6582)
CONTEXT:  External table user
warehouse=#

user HDFS files are ingested using different schema versions, and GreenPlum external table has been created with fields from all the schema versions.


text:
Q: Consecutive One's and Identities, resulting on Totally Unimodular Matrix... I'm trying to prove that a linear problem has integer extreme points. Looking at the matrix structures, I guess the easiest way to prove this is by showing that this matrix is totally unimodular. My matrix (and its structutes) can be described as follows.
\begin{equation}B=
\begin{pmatrix}
 I & A &0\\
 I & 0 & A
\end{pmatrix}
\end{equation}
Such that matrix $A\in R^{m\times n}$ has the consecutive ones property and, thus, is totally unimodular. Can I show that matrix $B$ is also totally unimodular?

A: The matrix
\begin{equation}
\begin{pmatrix}
 A &0\\
 0 & A
\end{pmatrix}
\end{equation}
also has the consecutive ones property and is TUM. It remains TUM if you append one large identity matrix, but you add two smaller identity matrices, which can ruin TUM. Just generating random matrices $A$ quickly results in counterexamples, for example
$$A=\begin{pmatrix}0 & 0 & 1 & 1 & 1\\
1 & 1 & 0 & 0 & 0\\
0 & 1 & 1 & 1 & 1\\
1 & 0 & 0 & 0 & 0\\
1 & 1 & 1 & 1 & 0\end{pmatrix}$$
The submatrix of rows 1,3,5,6,10 and columns 1,5,7,10,13 has determinant 2.


text:
Q: Elasticsearch: Accessing multiple indices created by filebeat I'm using Elasticsearch 6.8 and i'm not able to access multiple indices in a single query. I've read the documentation and also previous questions, but for some reason i can't figure this out.
The setup is fairly standard, i think. I have a filebeat pushing logs into elasticsearch. Didn't really adapt the standard config, so filebeat is creating a new index everyday. I can nicely query every single index to get all results from a day:
# works, returns data from filebeat-6.1.2-2019.12.20
curl -X GET "https://whatever:9200/filebeat-6.1.2-2019.12.20/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "wildcard" : {
            "nginx.access.url" : "/something/*"
        }
    }
}
'

# works, returns data from filebeat-6.1.2-2019.12.19
curl -X GET "https://whatever:9200/filebeat-6.1.2-2019.12.19/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "wildcard" : {
            "nginx.access.url" : "/something/*"
        }
    }
}
'

I'm now trying to query more than one index in a query, to get data from more than one day at once, but i always only get data from the the index filebeat-6.1.2.-2019.12.19, no matter what i do.
# comma-separated list of indeces, nope.
curl -X GET "https://whatever:9200/filebeat-6.1.2-2019.12.20,filebeat-6.1.2-2019.12.19/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "wildcard" : {
            "nginx.access.url" : "/something/*"
        }
    }
}
'

# _all, nope.
curl -X GET "https://whatever:9200/_all/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "wildcard" : {
            "nginx.access.url" : "/something/*"
        }
    }
}
'

# just not specifying an index, nope nope nope.
curl -X GET "https://whatever:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "wildcard" : {
            "nginx.access.url" : "/something/*"
        }
    }
}
'

since this should just work according to all the resources i find, i have the feeling i'm missing something super-obvious.
FWIW, i'm coming from the python library elasticsearch-dsl where i had the exact same problems, but i've used curl in this examples, because it's most generic thing to do. so if anybody has an answer in this direction, this would be very welcome as well.

A: Maybe this is just the size that you need to specify. by default, the search query 10 result. Have you tried to increase this value ?
you can try to add "size":"10000" before "query" in your request.
curl -X GET "https://whatever:9200/filebeat-6.1.2-2019.12.20,filebeat-6.1.2-2019.12.19/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "size":"10000",
    "query": {
        "wildcard" : {
            "nginx.access.url" : "/something/*"
        }
    }
}


text:
Q: Generating Java Sources with sbt JFlex plugin I am pulling my hair using the sbt-jflex plugin to generate Java sources via JFlex, before the main javac phase of sbt (0.12).
The plugin is a clone of the ANTLR plugin, and I found this question which shows how to use the latter.
So I have the following in project/plugins.sbt:
addSbtPlugin("org.scalanlp" % "sbt-jflex" % "0.1-SNAPSHOT")

And this in ./build.sbt:
jflexSettings

sourceGenerators in Compile <+= generate in jflex

But I must be either doing something wrong, or the javac phase comes before the source generators, because when I run sbt compile, I never see the message "JFlex: Using JFlex version X to generate source files". Instead sbt goes straight to compile the Java sources
[info] Compiling 91 Java sources to ...

And then fails because the JFlex output is missing at that stage. Running source-directories shows that src/main/jflex is indeed included, as is target/src_managed/main.

A: After playing around with injecting debug prints, I found that the sbt-jflex plugin assumes sources are in src/main/flex whereas my project has them in src/main/jflex. Adding the following fixes it:
sourceDirectory in jflex <<= (sourceDirectory in Compile) { _ / "jflex" }


text:
Q: migrate users for a site collection (not web app level) I did a 2010 to 2013 migration for a site collection. Is there a way to migrate users for a given site collection instead of web application? the following code is for web app. I dont want to touch the web app as its already running bunch of site collections. The 2013 farm is a fresh farm and not migrated from 2010.
$wa = Get-SPWebApplication -identity http://webapp
$wa.MigrateUsers($true)

A: Short answer, no. But if you use Convert-SPWebApplication, it will only migrate the identities that have not been migrated yet.

A: I did my upgrade some site collection/s at the time, moving them in separate databases. I answered a similar question a year ago so i'm going to quote myself from that thread.
While the official way to do it provided by Microsoft is to Migrate from classic-mode to claims-based authentication by converting a web application.

"However, i was planning to move site collections in a temporerary
  database, one at the time for several reasons. I searched and found this script
  that simply converts a database from Classic to Claims. I've used it
  for multiple databases and has not had one single error related to
  authentication in 2013.
The script is intended to be run AFTER the database has been mounted
  to the web application. ( mount-spcontentdatabse ). This script must
  be executed by your Farm account to. Check the source for the script
  for more information, and be sure to test it before using it in
  production if you decide to use it."

$wa = Get-SPWebApplication http://yourWebAppUrl
$acc = 'domain\user'
$arguments = New-Object Microsoft.SharePoint.Administration.SPWebApplication+SPMigrateUserParameters
$arguments.AddDatabaseToMigrate($wa.ContentDatabases[1])
$wa.MigrateUsersToClaims($acc, $true, $arguments)

So, move a site collection from 2010 to its own temporary content database, move it a 2013 environment, mount it to a web application and then run the script. The important thing is that you have to target the script to the right database so if you have a new web application with one database and then attach a temporary content database, the database added order will be $wa.ContentDatabases[1]. If you have a web application with 3 databases and you mount a fourth database, the number should be $wa.ContentDatabases[3] as you start to count from 0.
I did this for all of our site collections in the spring -14 and we have not had any problems related to authentication after our migration.
Migrate from classic-mode to claims-based authentication in SharePoint 2013 the easy way
Old thread: web application is configured with claims authentication mode however the content database you are trying to attach is intended


text:
Q: Microsoft VSTS doesn't build Android project - JavaMaximumHeapSize - works on local machine I am using private build agent for my builds. (This works on VS Appcenter, if you use their machine but it costs and build is slow, or if you use Hosted VS2017 from VSTS, anyway I am using my own private agent for all VSTS builds, speed and cost).
Error is complaining about JavaMaximumHeapSize.

C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(2188,3):
  Error XA5213: java.lang.OutOfMemoryError. Consider increasing the
  value of $(JavaMaximumHeapSize). Java ran out of memory while
  executing 'java.exe -jar "C:\Program Files
  (x86)\Android\android-sdk\build-tools\27.0.3\lib\dx.jar" --dex
  --no-strict --multi-dex --main-dex-list=obj\Release\multidex.keep --output obj\Release\android\bin D:\agent_work\9\s\src\Yo.MobileApp.Android\obj\Release\android\bin\classes.zip
  "C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\v8.1\mono.android.jar"
  "C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Xamarin\Android\android-support-multidex.jar"
  obj\Release\lp\1\jl\formsviewgroup.jar
  obj\Release\lp\31\jl\arch-core-common.jar
  obj\Release\lp\32\jl\arch-lifecycle-common.jar
  obj\Release\lp\33\jl\bin\classes.jar
  obj\Release\lp\34\jl\bin\classes.jar ob... C:\Program Files
  (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Xamarin\Android\Xamarin.Android.Common.targets(2188,3):
  error XA5213: java.lang.OutOfMemoryError. Consider increasing the
  value of $(JavaMaximumHeapSize). Java ran out of memory while
  executing 'java.exe -jar "C:\Program Files
  (x86)\Android\android-sdk\build-tools\27.0.3\lib\dx.jar" --dex
  --no-strict --multi-dex --main-dex-list=obj\Release\multidex.keep --output obj\Release\android\bin D:\agent_work\9\s\src\Yo.MobileApp.Android\obj\Release\android\bin\classes.zip
  "C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\Common7\IDE\ReferenceAssemblies\Microsoft\Framework\MonoAndroid\v8.1\mono.android.jar"
  "C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Xamarin\Android\android-support-multidex.jar"
  obj\Release\lp\1\jl\formsviewgroup.jar
  obj\Release\lp\31\jl\arch-core-common.jar
  obj\Release\lp\32\jl\arch-lifecycle-common.jar
  obj\Release\lp\33\jl\bin\classes.jar
  obj\Release\lp\34\jl\bin\classes.jar obj\Release...

*

*I already increased JavaMaximumHeapSize to 1G inside of Application
Manifest.

*I already set JDK to 8 and selected x86 architecture:

If I put x64 arch and JDK 8 or same for JDK9 I get error:

2018-04-14T10:32:54.9545073Z ##[error]Cannot bind argument to
  parameter 'KeyName' because it is an empty string.

A: JDK8 and x64 solves teh problem.


text:
Q: Remove Duplicate adjacent Sub-String from String in Microsoft SQL Server I am using SQL Server 2008 and I have a column in a table, which has values like below. It basically shows departure and arrival information.
-->Heathrow/Dublin*Dublin/Heathrow
-->Gatwick/Liverpool*Liverpool/Carlisle *Carlisle/Gatwick
-->Heathrow/Dublin*Liverpool/Heathrow
(The 3rd example shown above is slightly different where the person did not depart from Dublin, instead departed from a Liverpool).
This makes the column too lengthy, and I want to remove only the adjacent duplicates, so the information can be shown like below:
-->Heathrow/Dublin/Heathrow
-->Gatwick/Liverpool/Carlisle/Gatwick
-->Heathrow/Dublin***Liverpool/Heathrow
So, this would still show the correct travel route, but omits only the contiguous duplicates. Also, in the 3rd case, since the departure and arrival information location is not the same, Iwould like to show it as ***.
I found a post here that removes all duplicates (Find and Remove Repeated Substrings) but this is slightly different from the solution that I need.
Could someone share any thoughts please?

A: The first step is to adapt the process defined in the following link so that it splits based on /:
T-SQL split string
This returns a table which you would then loop through checking if the value contains an *.  In that case you would get the text values before and after the * and compare them.  Use CHARINDEX to get the position of the *, and SUBSTRING to get the values before and after.  Once you have those check both values and append to your output string accordingly.

A: So you have a database column that contains this text string?  Is your concern to display the data to the user in a new format, or to update the data in your database table with a new value?
Do you have access to the original data from which this text string was built?  It would probably be easier to re-create the string in the format you desire than it would be to edit the existing string programmatically.
If you don't have access to this data, it would probably be a lot simpler to update your data (or reformat it for display) if you do the string manipulation in a high-level language such as c# or java.
If you're reformatting it for display, write the string manipulation code in whatever language is appropriate, right before displaying it.  If you're updating your table, you could write a program to process the table, reading each record, building the replacement string, and updating the record before moving on to the next one.
The bottom line is that T-SQL is just not a good language for doing this sort of string examination and manipulation.  If you can build a fresh string from the original data, or do your manipulation in a high-level language, you'll have an easier job of it and end up with more maintainable code.

A:
I wrote a code for the first example you gave. You still need to
  improve it for the rest ...

DECLARE @STR VARCHAR(50)='Heathrow/Dublin*Dublin/Heathrow'

IF  (SELECT SUBSTRING(@STR,CHARINDEX('/',@STR)+1,CHARINDEX('*',@STR)-CHARINDEX('/',@STR)-1)) =

   (SELECT SUBSTRING(@STR,CHARINDEX('*',@STR)+1,LEN(SUBSTRING(@STR,CHARINDEX('/',@STR)+1,CHARINDEX('*',@STR)-CHARINDEX('/',@STR)-1))))

   BEGIN
    SELECT STUFF(@STR,CHARINDEX('*',@STR),LEN(SUBSTRING(@STR,CHARINDEX('/',@STR)+1,CHARINDEX('*',@STR)-CHARINDEX('/',@STR)-1))+1,'')
END
ELSE
BEGIN
SELECT STUFF(@STR,CHARINDEX('*',@STR),LEN(SUBSTRING(@STR,CHARINDEX('*',@STR)+1,LEN(SUBSTRING(@STR,CHARINDEX('/',@STR)+1,CHARINDEX('*',@STR)-CHARINDEX('/',@STR)-1)))),'***')
END


text:
Q: debug performance diff of Same code on nearly same cpu/ram I wrote a machine learning model which involves quite amount of numerical optimization computation, it's in Python with Numpy + Scipy.optimize.
The training process is very slow on a Lenovo Thinkpad X220 (with i5-2520M CPU and 4GB RAM, Ubuntu 14.04 OS), but much faster on a Lenovo Thinkpad X240 (with i5-4200U CPU and 4GB RAM).
I compared the 2 CPU's online, X220 CPU (i5-2520M) has higher operating frequency, but X240 CPU (i5-4200U) has Haswell arch. So the performance should pretty much the same, right?
I wonder that why the Python code is so slow on X220 is because the numerical optimization or matrix calculation library is poor on Ubuntu, how should I debug this performance prolem?


text:
Q: Header and Footer repeating for each element in ListView? Hi I am trying to have a listView in one of my Fragments . I tried addHeaderView and addFooterView but that scrolled the header and footer along with list so I tried a different approach but the header and footer is being repeated for each element
My Fragment Layout
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.solutionnest.fragment.RemoteListFragment">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Device List"
        android:id="@+id/listHeader"
        android:singleLine="true"
        android:background="#f4438fd3"
        android:textColor="#ffffffff"
        android:layout_marginBottom="10dp" />
<RelativeLayout android:layout_width="match_parent" android:id="@+id/listContainer"
    android:layout_height="0dp"
    android:layout_weight="1">
    <ListView android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <TextView android:id="@+id/deviceName" android:layout_width="match_parent"
        android:textSize="@dimen/listElementSize"
        android:layout_height="@dimen/ListBoxSize" android:gravity="center" />
</RelativeLayout>
    <LinearLayout
        android:id="@+id/footer"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_weight="0.50"
            android:text="Add"
            android:onClick="addDevice"
            android:id="@+id/addDevice"
            android:layout_height="match_parent"
            android:background="#f4438fd3"
            android:textSize="15dp"
            android:textColor="#ffffffff"
            android:layout_marginLeft="5dp"
            />

        <Button
            android:layout_width="0dp"
            android:layout_weight="0.50"
            android:text="Delete"
            android:onClick="deleteDevice"
            android:id="@+id/deleteDevice"
            android:layout_height="match_parent"
            android:background="#f4438fd3"
            android:textSize="15dp"
            android:textColor="#ffffffff"
            android:layout_marginLeft="5dp"/>
    </LinearLayout>
</LinearLayout>

My getView method in adapter looks like
 public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        Device device = (Device)getItem(position);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.fragment_remote_list,parent ,false);
            holder = new ViewHolder();
            holder.name = (TextView) convertView.findViewById(R.id.deviceName);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        } holder.name.setText(device.getDeviceName());

        return convertView;

    }

A: A simple way to create a header and footer.
In the main activity:
public class MainActivity extends Activity {
    ListView listView;
    TextView tv;

    static final String[] numbers = new String[]{"one", "two", "three",
        "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
        "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
        "seventeen", "eighteen", "nineteen", "twenty", "twenty one",
        "twenty two"};
    View header;
    ViewGroup footer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_id);

        //code to add header and footer to listview
        LayoutInflater inflater = getLayoutInflater();
        ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header,        listView,
            false);
        ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
            false);
        listView.addHeaderView(header, null, false);
        listView.addFooterView(footer, null, false);
        ArrayAdapter adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, numbers);
        listView.setAdapter(adapter);
    }

In the activity xml.
<ListView
    android:id="@+id/list_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="80dp"
    android:gravity="center"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth" >
</ListView>

Create two xml files in the resources/ layout
header.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="HEADER"
        android:background="#cf9f99" />

</LinearLayout>

footer.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="FOOTER"
        android:background="#cf9f99" />

</LinearLayout>

A: Hi after a bit struggle got this fixed .Posting what worked for me..It seems that The list content must be a part of seperate layout file to achieve above requirement my new layout and view configuration are `
 public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        Device device = (Device)getItem(position);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.fragment_remote_list_content,parent ,false);
            holder = new ViewHolder();
            holder.name = (TextView) convertView.findViewById(R.id.deviceName);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if(deviceList.isEmpty())
        {
            holder.name.setText("No Devices");
        }
        else {
            holder.name.setText(device.getDeviceName());
            convertView.setOnClickListener(new OnItemClickListener(position));
        }

        return convertView;

    }

`The fragment_remote_list.xml layout was divided into 2 files
fragment_remote_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context="com.solutionnest.fragment.RemoteListFragment">

    <ListView android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/footer"
        android:layout_below="@+id/listHeader"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Device List"
        android:id="@+id/listHeader"
        android:singleLine="true"
        android:background="#f4438fd3"
        android:textColor="#ffffffff"
        android:layout_marginBottom="10dp" />
    <LinearLayout
        android:id="@+id/footer"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:gravity="center"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_weight="0.50"
            android:text="Add"
            android:onClick="addDevice"
            android:id="@+id/addDevice"
            android:layout_height="match_parent"
            android:background="#f4438fd3"
            android:textSize="15dp"
            android:textColor="#ffffffff"
            android:layout_marginLeft="5dp"
            />

        <Button
            android:layout_width="0dp"
            android:layout_weight="0.50"
            android:text="Delete"
            android:onClick="deleteDevice"
            android:id="@+id/deleteDevice"
            android:layout_height="match_parent"
            android:background="#f4438fd3"
            android:textSize="15dp"
            android:textColor="#ffffffff"
            android:layout_marginLeft="5dp"/>
    </LinearLayout>

</RelativeLayout>

fragment_remote_list_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView android:id="@+id/deviceName" android:layout_width="match_parent"
        android:textSize="@dimen/listElementSize"
        android:layout_height="@dimen/ListBoxSize" android:gravity="center" />
</LinearLayout>


text:
Q: Is there an open source tool to planarize graphs? I read about the planarize function in ArcGIS, which seem to do exactly what I want. Is there a similar feature in QGIS or another free tool?
I have a shapefile with various shapes intersecting each other and I want each intersection to become a node and between every two nodes to have a simple line.
The goal is to easily convert my .shp in .osm and use it with Graphserver. As it is, Graphserver says I don't have edges, and I deduced the above is my problem.
Thanks a lot

A: In GRASS GIS which is topological you can use v.net for this operation. You can access it through the QGIS-GRASS Toolbox.

A: In GRASS GIS the v.clean tool can be set to break intersections.  The rmsa and rmdupl options to v.clean are useful as well.
Returning to this question  for a third time: the snap option to v.clean will snap together features by altering their shape to fix apparent intersections, etc.  snap followed by break should thus do a job similar to ArcGIS Planarize.


text:
Q: Infinite Loop on useEffect I need some help with the following.
The user has access to a Material UI and he can choose to hide/show each column of the table. I have an event listener which gives me info on what column the user shows/hides with a true/false.
So each time the user hides a column I set it on the localStorage and also set the state to update it. (following code)
              onColumnVisibilityChange={(param) => {
                setHideColumns((prev) => ({ ...prev, [param.field]: !prev[param.field] }))
                window.localStorage.setItem(`${param.field}`, param.isVisible === true ? "false" : "true");
              }}

Then I have a useState set to check for the column settings on localStorage and update the state when the component mounts:

const [hideColumns, setHideColumns] = useState<IndexedInt2<boolean>>(initialStateHideColumns);

  const checkStorageNsetHideColumns = () => {
    const hideId = Boolean(localStorage.getItem("id") !== null ? localStorage.getItem("id") : false);
    const hidePatientName = Boolean(localStorage.getItem("patientname") !== null ? localStorage.getItem("patientname") : false)
    const hideOrganizationName = Boolean(localStorage.getItem("organizationname") !== null ? localStorage.getItem("organizationname") : false)
    const hideCreatedOn = Boolean(localStorage.getItem("createdOn") !== null ? localStorage.getItem("createdOn") : false)
    const hideStatus = Boolean(localStorage.getItem("status") !== null ? localStorage.getItem("status") : false)
    setHideColumns((prev) => ({ ...prev, id: hideId, patientname: hidePatientName, organizationname: hideOrganizationName, createdOn: hideCreatedOn, status: hideStatus }))
  }

But I run into a problem: the code above works decently but only the first time you hide/show columns once.. after that, even if you show/hide more columns it will show them as the first time you set it.
I'm almost sure it has to do with the useState not updating each time the hideColumns changes, so I tried adding it as a dependency.. the problem is that now it runs into an infinite loop.
Any idea on how could I fix it?
Thanks a lot in advance!


text:
Q: How to use Task type object in order to store data in Swift I'm studying Swift by making ToDo app.
I tried to store the data by using Task type object,
but I got an error Use of unresolved identifier 'Task'
Could you give some advice please?
import UIKit

class AddTaskViewController: UIViewController {

    @IBOutlet weak var taskTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    //// When Done Button Tapped
    @IBAction func doneButtonTapped(_ sender: Any) {
        let taskName = taskTextField.text

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        **let task = Task(context: context)**

        task.name = taskName
        task.category = taskCategory

        (UIApplication.shared.delegate as! AppDelegate).saveContext()

        dismiss(animated: true, completion: nil)
    }

A: You have to set entity(name & category) in xcdatamodel.


text:
Q: Getting 403 error on store method in Laravel I am learning laravel. Right now working on a project with inertia. Have created a model, controller and view in default settings.
I am able to create user with the built-in user manager.
But getting 403 error while creating records for my custom models.
Can anyone help me as to what could be causing this?
store method on user-creation works. But store method on my custom model throws 403.

A: just need to add @csrf inside your form in the view, you can read more about it here

A: Answering my own question.
Issue was with authorize method of requests. That check was returning false.
As I am using middleware for validation.
More info for future readers.
What is the purpose of the authorize method in a Request class in Laravel?


text:
Q: How to jointly learn two tasks at prediction level? I have trained a network on two different modals of the same image. I pass the data together in one layer but after that, it is pretty much two networks in parallel, they don't share a layer and the two tasks have different set of labels, therefore I have two different loss and accuracy layers (I use caffe btw). I would like to learn these tasks jointly. For example, the prediction of a class of task 1 should be higher in presence of the task 2 predicting a certain class label. I don't want to join them at feature level but at prediction level. How do I get to do this?

A: Why don't you want to join the prediction at feature level?
If you really want to stick to your idea of not joining any layers of the network, you can apply a CRF or SVM on top of the overall prediction pipeline to learn cross-correlations between the predictions. For any other method you will need to combine features inside the network, one way or another. However I would strongly recommend, that you consider doing this. It is a general theme in deep learning, that doing stuff inside the network works better then doing it outside.
From what I have learned by experimenting with joint prediction, you will get the most performance gain, if you share weights between all convolutional layers of the network. You can then apply independent fc-layers, followed by a softmax regression and separate loss functions on top of the jointly predicted features. This will allow the network to learn cross-correlation between features while it is still able to make separate predictions.
Have a look at my MultiNet paper as a good starting point. All our training code is on github.


text:
Q: What is a seed in relation to a random number generation algorithm and why is computer time used to create this seed more often than not? I read that seeds are used to initialize random number generators. But seems like the randomness of the seed doesn't matter much for getting good randomness from the generator. So I want to understand what is a seed actually? Why is it called so? And lastly why time in a computer system is used to generate such seeds?

A: A pseudo-random number generator produces a sequence of numbers. It isn't truly random, but generally a mathematical calculation which produces an output that matches some desirable distribution, and without obvious patterns. In order to produce such a sequence, there must be state stored for the generator to be able to generate the next number in that sequence. The state is updated each time using some part of the output from the previous step.
Seeding explicitly initialises this state. A 'seed' is a starting point, from which something grows. In this case, a sequence of numbers.
This can be used either to always generate the same sequence (by using a known constant seed), which is useful for having deterministic behaviour. This is good for debugging, for some network applications, cryptography, etc.
Or, in situations where you want the behaviour to be unpredictable (always different each time you run a program, a card game perhaps), you can seed with a number likely to be continually changing, such as time.
The 'randomness' of the sequence does not depend on the seed chosen, though it does depend on not reseeding the sequence.


text:
Q: Multithreading with swing I have a question about the use of threads in a gui application. Say (as a simplistic example) i have a swing application with a series of images. I have two threads i want to run that fetch an image of a parent respectively. (So for a given number of students, get a mother image and a father image from each server endpoint). The returned image of the father and the mother is then appended on to the image on screen so i have a series of images with a mother, father, mother, father for multiple students.
How can i schedule this in a multithreaded environment? Each call to get a mother or father image has to be in parallel and not block the displaying of the images on screen. Does the image displayed on the screen refresh after each thread returns an image? How will this be structured?

A: Start with Concurrency in Swing.
The absolute simplest approach might be to use a SwingWorker that has a list of items it needs to look up and allow it to process the list.
The problem with this is it will only run each request one at the other, making it a little slower then other options.  The benefit of this is that it provides easy functionality to re-sync with the Event Dispatching Thread so that you can notify the UI or make changes to it safely.
Another option might be to use Executors, in particular a Thread Pool implementation.
This allows you to submit a number of tasks that should be executed at some time in the future, but allows you to control the number of threads that the process can use at any one time.
The drawback is that you become responsible for syncing the changes back to the UI yourself when you want to update the UI, using SwingUtilities.invokeLater
Now.  You "could" use both.
Basically you would need to setup some kind of "request" class that would allow you to pass the relevant information to, for example, the "mother" and "father" servers, the original image and possibly some kind of callback interface that would tell you when the final image had being rendered.
The requester would build some kind of Runnable or Callable which would wrap a SwingWorker.
When executed, this "request task" would start the SwingWorker, allowing it to fetch the images, merge them and publish the results, which would notify the callback interface.  The "request task" would then simply wait until SwingWorker#get returns before exiting.
As an idea...