text:
Q: Check CONSTRAINT Not work in SQL Server I have to restrict to insert duplicate data in my table with condition
Here is SQL Server Table
CREATE TABLE [dbo].[temptbl](
    [id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [DSGN] [varchar](500) NULL,
    [RecordType] [varchar](1000) NULL
)

I want to put condition on RecordType, if RecordType is 'SA' Than check CONSTRAINT (means if DSGN = 0 and RecordType = 'SA' Exist than i don't want to insert that data.
if DSGN = 1 and RecordType = 'SA' Not Exist than i want to insert that data.
If RecordType is other than 'SA' than insert any data
For that i create constraint but it is not work
ALTER TABLE temptbl  WITH CHECK  ADD CONSTRAINT chk_Stuff CHECK (([dbo].[chk_Ints]([DSGN],[RecordType])=(0)))
GO

ALTER FUNCTION [dbo].[chk_Ints](@Int_1 int,@Int_2 varchar(20))
RETURNS int
AS
BEGIN

DECLARE @Result INT

    BEGIN
        IF @Int_2 = 'SA'
        BEGIN
            IF NOT EXISTS (SELECT * FROM [temptbl] WHERE DSGN = @Int_1 AND RecordType = @Int_2)
            BEGIN
                SET @Result = 0
            END
            ELSE
            BEGIN
                SET @Result = 1
            END
        END
        ELSE
        BEGIN
            SET @Result = 0
        END
    END
    RETURN @Result
END

But it is not working. please suggest me

A: Ditch the function and the check constraint:
CREATE UNIQUE INDEX IX_temptbl_SA ON temptbl (DSGN) WHERE RecordType='SA'

This is known as a filtered index.
Your check constraint wasn't working as you thought it would because when a check constraint is evaluated for any particular row, that row is already visible within the table (within the context of that transaction) and so each row was effectively blocking its own insertion.

A: Use With NOCheck for only new data. Here is the link provided.
https://technet.microsoft.com/en-us/library/ms179491(v=sql.105).aspx


text:
Q: How to add and remove HTML elements depending on number in input field I have a number input field in which a user can enter a number. Depending on this number, some new input fields are generated.
Currently I have no problems adding fields, as long as the new number put in by the user is higher than the previous. I can't remove the generated fields if the user puts in a lower number though.
So i.e. a user types in '5', which generates 5 new fields. If the user adjusts this number to '3', there are still 5 generated fields.
Input HTML
<input type="number" class="form-control" name="amount_of_vote_groups" id="amount_of_vote_groups">
Javascript (jQuery)
var i = 1;
$('#amount_of_vote_groups').change(function () {
    while (i <= this.value) {
        $('#right-column').prepend(
                '
' +
                    // Some other stuff here
                '
'
        );
        i++;
    }
    if (this.value > i) {
        $('#right-column').remove('#generated-field-' + i);
    }
});

I know I'm doing something stupid with the remove statement, but I just can't it get figured out. I'm a real sucker at javascript ;)

A: I'd do it like this:
$('#amount_of_vote_groups').change(function() {
  $('#right-column div.form-group').remove();
  for (var i = 1; i <= this.value; i++) {
    $('#right-column').prepend(
      '
div
'
    );
  }
});

jsFiddle example
Whenever you change the number input, clear out any divs that may exist, then spin through a loop to add  the new ones.

A: The if loop should also be a while loop like this:
while (this.value > i) {
  $('#right-column').remove('#generated-field-' + i);
  i--;
}

A: In case someone stumbles along this question that wants to keep the generated forms already on the screen and only remove those that are greater than the requested number, here is an approach that uses jQuery's filter to get the excess form groups, then removes them. It also moves index information to a data- attribute on the div to demonstrate how you might be able to expand on this to filter on other attributes without putting information into a div id.
var currForms = 0;
$('#amount_of_vote_groups').change(function() {
  var numForms = this.value;
  if (currForms > numForms) {
    $('#right-column .form-group').filter(function(index, ele) {
        return $(ele).data('index') >= numForms;
    }).remove();
    currForms = numForms;
  } else {
    while (currForms < numForms) {
      $('#right-column').append(
        '
' +
        'Field ' + currForms + ':<input type="text">' +
        '
'
      );
      currForms++;
    }
  }
});

Here's a fiddle. You can enter text in the generated inputs, and notice they remain for forms that are still on the page after entering in a lower number.

A: There is a solution depends on the difference of count between the i generated and the count of available elements, the class selector, this solution is assured from deleting the first element:
 var i = 1;
$('#amount_of_vote_groups').change(function () {
    while (i <= this.value) {
        $('#right-column').prepend(
                '
' +
                    '<input type="text" value="'+i+'" />'+
                '
'
        );
        i++
    }
  //alert($(this).val())
    if ((i-1) > $(this).val()) {

       // alert($('.form-group').size()+"***"+i)
      beDel = i - $('.form-group').size();
      for (j =0; j < beDel; j++){
        $('.form-group:first').remove();
      }
      --i;
    }

});

This is a DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: In PowerPoint, how do you replace a decimal separator with a comma A few slides in my PowerPoint are in a different language and I having difficulties changing percentage numbers to the format required by the language.
In the category Percentage how do I change the  format Code form 0.0% (3.8% 10.6% 13.0%) to something like 0,0% (3,8% 10,6% 13,0%)?

A: Unfortunately, you cannot change the decimal separator just for PowerPoint.
PowerPoint uses the separators defined in the operating system for the language region.
Changing them requires changes that are permanent and system-wide.
Please note that usually you need to restart PowerPoint in order to let the
changes take effect.

A: A workaround I have found is multiplying my data set by 1000 and using 0\,0 \% as the format code. Not the prettiest and requires a bit more logic when using openXML to create slides in both Enlgish and French.
The French Graphs are identical to the English ones except that the selected data is a column that multiplies the column containing the original values by 1000.


text:
Q: Preventing media folder in Django from being overwritten with new update I have a Django model which includes an Image Field, and an app which consumes the model instance including all images. The problem I'm having now is while my data and the img local link resides on my AWS RDS database, the media folder which contains the images for the model is not. Thus every time I deploy a new version of the app (I'm using Beanstalk for deployment), my media folder is wiped clean and all my image link dies as a result.
Below is my model:
class Item(models.Model):
    # Fields
    name = models.CharField(max_length=30, help_text="Enter item name")
    description = models.TextField(help_text='Enter a short description')
    image = models.ImageField(help_text='Upload item image', upload_to='image/item/',
                              default='image/demo.jpg')

    # Methods
    def __str__(self):
        return str(self.name)
    def get_absolute_url(self):
        return reverse('model-detail-view', args=[str(self.id)])

And I use serve to retrieve the image from Django.
url(r'^resource/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),

Now what would be the best way to resolve this problem? I would not want to upload the image to another server then link back to Django, it's best if I can save it to my database the moment I upload the file from my model form.
All feedback is appreciated.

A: See the EB documentation on design considerations:

Elastic Beanstalk applications run on Amazon EC2 instances that have no persistent local storage. When the Amazon EC2 instances terminate, the local file system is not saved, and new Amazon EC2 instances start with a default file system.

So, you cannot do what you are asking. You must upload the files to a persistent storage system; S3 is the obvious choice.


text:
Q: Callback from CBCentralManagerDelegate to retrieve CBPeripheral on IOS8 I have a BluetoothManager class managing BTLE communication. I can scan and connect to a CBPeripheral and discover services or characteristics. I have the good callbacks from CBCentralManagerDelegate and CBPeripheralDelegate
When I'm connected to a CBPeripheral, I save the UUIDString in CoreData to retrieve this peripheral when I relaunched the app.
This is my Swift code to retrieve peripherals when I restart the app:
func retrievePeripheralsWithIdentifiers(identifiers: [AnyObject]!){
    let data = self.centralManager.retrievePeripheralsWithIdentifiers(identifiers)

    println("Data retrieved: \(data)")

    for peripheral in data as [CBPeripheral] {

        println("Peripheral : \(peripheral)")
        peripheral.delegate = self
        centralManager.connectPeripheral(peripheral, options: nil)
    }
}

This is what I've got:
Data retrieved: [<CBPeripheral: 0x1669fcd0, identifier = XXXXX, name = Peripheral1, state = disconnected>]
Peripheral : <CBPeripheral: 0x1669fcd0, identifier = XXXXX, name = Peripheral1, state = disconnected>

I can find one of my peripheral without any problem. But when I call the line "centralManager.connectPeripheral(peripheral, options:nil)", I don't have any response.
These methods
func centralManager(central: CBCentralManager!, didRetrievePeripherals peripherals: [AnyObject]!)
func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!)
func centralManager(central: CBCentralManager!, didFailToConnectPeripheral peripheral: CBPeripheral!, error: NSError!)

are not called back to let me know what's wrong. So I can find the good peripheral but I can't connect to it.
However, I have the same code to connect to some peripherals when I'm scanning and it works; my own CBCentralManager has a the good delegate and my peripheral too.
What am I doing wrong?
I'm on Xcode-Beta5 with a iPod-Touch iOS8-Beta5.
Thanks,
Ben
EDIT
Ok, that's more weird
I try this following code from my older app on iOS7 & Objective-C, I saved the UUIDString when I'm connected, and try to retrieve peripherals. It works well:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"UUIDString"]) {
    NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:[defaults objectForKey:@"UUIDString"]];
    NSArray * data = [self.centralManager retrievePeripheralsWithIdentifiers:@[uuid]];

    if ( [data count] > 0 ){
        self.currentPeripheral = [data objectAtIndex:0];
        [self.currentPeripheral setDelegate:self];

        [self.centralManager connectPeripheral:self.currentPeripheral options:nil];
    }
} else {

    NSLog(@"Scanning started");
    /*...*/
}

That's the same code from my new app on iOS8 & Swift:
    let userDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.objectForKey("UUIDString") != nil {

        let uuid = NSUUID(UUIDString: userDefaults.objectForKey("UUIDString") as String)
        let data = self.centralManager.retrievePeripheralsWithIdentifiers([uuid]) as [CBPeripheral]

        if data.count > 0 {

            self.currentPeripheral = data[0]

            println("Current peripheral \(self.currentPeripheral)")
            self.currentPeripheral!.delegate = self
            self.centralManager.connectPeripheral(self.currentPeripheral!, options: nil)
        }
    } else {

        println("Start Scanning")
        /*...*/
    }

I try my old app on iPod Touch iOS7 and it works well.
I try my old app on iPod Touch iOS8 and it works also fine.
I try my new app on iPod Touch iOS8 and it doesn't work.
I didn't find any differences between the both codes. I can scan, discover and connect peripherals, but connect to retrieved peripherals seems not working on iOS8 & Swift.

A: It looks like in your original example, you aren't saving a local copy of the CBPeripheral.
From the CBCentralManager Class Reference - connectPeripheral:

Pending connection attempts are also canceled automatically when peripheral is deallocated.

A: Please check whether you save local copy of CBPeripheral object or not.
You must save local copy of peripheral to avoid dealloc after finishing call back function.
If peripheral object dealloc before calling didConnect peripheral callback, core bluetooth automatically cancels pending connection request.

A: Even having reference of peripheral last time connected, i was facing issue. What trick worked is first get previously connected peripheral using identifier by calling

retrievePeripheralsWithIdentifiers

.

*

*Now Connect it and try to discover services. Then put one NSTimer and
wait for 3-4 seconds.

*On didDiscoverServices delegate callback. Invalidate Timer.

*Now even after 4 seconds also service not discovered then just disconnect it and connect back.

*This time it will sure discover services. I have used this trick and its working for me since long time.

A: In my case (iphone4s/ios8.2), my problem was because I tried doing the reconnection in viewDidLoad() of a controller, but moving it to viewDidAppear() fixed it.


text:
Q: AWS VPC client endpoint I need a kind of 'point2site' vpn solution in AWS VPC. I choose VPC Client VPN Endpoint. But I found the Client VPN Endpoint is not yet available in Tokyo region.
I want to setup a VPC in us-east-1(North Virginia) region, where Client VPN Endpoint is available. I want to setup my workload VPC in Tokyo region, so I want to setup a VPC peering to connect us-east-1(North Virginia) region and Tokyo region. Is it possible to setup Client VPN Endpoint in us-east-1(North Virginia) region, and then connect to Tokyo region by means of VPC peering?

A: You can create a VPC Peering connection between the two regions:

*

*In Tokyo, create a peering connection to the VPC in N. Virginia

*In N. Virginia, accept the peering connection

*Update route tables in both VPCs to route traffic via the peering connection

I tested this between Tokyo and N. Virginia and is worked fine.


text:
Q: Import Gitlab projects in Github I've recently made a Gitlab account which I want to use as a portfolio. I've created a Github Page with some content in it. Now the problem is, I'm trying to import all my projects I've made in Gitlab to my Github account. I've searched off Google and forums, some suggested I need to make tokens, which I tried but it didn't work.
I've tried to literally import a single Gitlab repository into my Github repository with the "+" button near my profile. It didn't work with the message "No source repositories were detected at https://git.osl.frl/JVeenswijk/pfSense. Please check the URL and try again" (Yes the project is set to public) from which I believe importing from Gitlab just doesn't work properly.
So I tried it with tokens, importing and even through the Github Desktop but neither of these work for me. I find it quite strange that Github and Gitlab have such trouble of connecting to each other, from my perspective they're almost the same with the functionalities but different features.
Now the question is:

*

*Is there a way to import my projects from my Gitlab to Github account?

*Can I just create a link from a Gitlab repository and put it on my Github Page without having to login if someone clicks on that link (read-only)?

A: You can do it. It's a feature of gitlab, mirror another repository.
The option for doing it are on project page -> settings -> repository -> mirror a repository. This option allows you both options: pulling from a remote repository, and pushing to it.
For doing what are you asking, there's the gitlab help:
To set up a mirror from GitLab to GitHub, you need to follow these steps:
Create a GitHub personal access token with the public_repo box checked.
Fill in the Git repository URL field, with the personal access token instead of a password.
For example: https://<GitHubUsername>:<GitHubPersonalAccessToken>@github.com/group/project.git.
Click the Mirror repository button.
Wait, or click the update button.

Please, check help on gitlab (https://gitlab.com/help/workflow/repository_mirroring) for more information.

A: I just successfully transferred the repository from GitLab to GitHub.
The repository in GitLab is private, which indicates that the GitHub Importer does not work, therefore, I follow below link and it works.
the instruction from GitHub official web page
Steps

*

*Create a new repository on GitHub. You'll import your external Git repository to this new repository.

*On the command line, make a "bare" clone of the repository using the external clone URL. This creates a full copy of the data, but without a working directory for editing files, and ensures a clean, fresh export of all the old data.

$ git clone --bare https://external-host.com/extuser/repo.git
# Makes a bare clone of the external repository in a local directory

*Push the locally cloned repository to GitHub using the "mirror" option, which ensures that all references, such as branches and tags, are copied to the imported repository.

$ cd repo.git
$ git push --mirror https://github.com/ghuser/repo.git
# Pushes the mirror to the new GitHub repository

4.Remove the temporary local repository.

$ cd ..
$ rm -rf repo.git


text:
Q: Upload multiple files with associated names I have a form which has a upload button. I have another button which adds another file upload field. What I want to do is let the user choose the file he wants to upload and also let him associate the file with a name. For example, I have a model which looks like:
public class ViewModel
{
    public string FileName { get; set; }
    public string FileLink { get; set; }
}

When a user uploads a file, it gets sent to a folder on my machine and then the associated filename will be put into the FileLink field. My problem is associated the file upload with a filename field and allowing the user to add multiple upload forms to the form where they can also associate those forms with fields. Currently If I do something like IEnumerable, it will get all the uploaded files but without the associated names. What should I do? Is there a good plugin for stuff like this?


text:
Q: Add product short description to WooCommerce email notifications Based on Add the product description to WooCommerce email notifications answer, how to add product short description instead of product description (which tend to be longer) to both email notifications?

A: To display short description on email notifications sent to admin, use the following:
// Displaying short product description in email notifications sent to admin
add_action( 'woocommerce_order_item_meta_end', 'product_description_in_new_email_notification', 10, 4 );
function product_description_in_new_email_notification( $item_id, $item, $order = null, $plain_text = false ){
    // Only on email notifications
    if( is_wc_endpoint_url() ) return;

    $product_obj = wc_get_product( $item->get_product_id() );
    $short_descr = $product_obj->get_short_description();

    if( ! empty($short_descr) ) {
        // Display the product description
        echo '

' . $short_descr . '

';
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should work.


text:
Q: Complete mice function results don't match with $imp I'm running an imputation in mice and something strange is happening with the complete function.
If I display the results using $imp from my object for a specific variable these are my results:
head(mice.train$imp$ViolentCrimesPerPop)

Now I run:
complete.train<-mice::complete(mice.train,1)

which should fill in the missing values in my data using the results from the first imputation
but when I check the first index listed in imp for example,
> complete.train$ViolentCrimesPerPop[1349]
[1] 366.34

Its not 113.81 like in my imp table.

A: I figured out my problem- because I sampled for the training data from my original dataset the rownames were all out of order . So those row numbers in that table aren't actually the row numbers.. Thanks!


text:
Q: Columns into Rows - PIVOTING I am trying to convert columns into rows. I have input data like below in the Oracle Table EMP -

At runtime, user can pass their own start time and end time, for ex suppose - 15-Dec-2020 to 31-Dec-2021. In this case, he should get the result like below for each MONTH END which falls between these dates -

Here "1" is nothing but the value of HEADCOUNT column value.
so MONTH END columns names are generating dynamically.
I tried below query but it is not fullfilling my requirement. DATE_PERIOD is a normal date time table having all the dates details(like month end, day name, quarter etc) for next 20 years). I tried PIVOT function as well in oracle but not able to generate the desired output. Can someone please help!!

I am able to write another query to produce the MONTH_END_DATE in the rows.


text:
Q: Help calculating variance of a random variable This is related to this question Average end point of 1-dimensional random walk?
Given several discrete random variables such that $p(Z_i=1-2k)=p$, where $k$ is a small real number, and $p(Z_i=-1)=1-p$, a random walk is the sum $X_t = \sum\limits_{i=1}^t Z_i$.
The expectation is given by:
$$\mathbb{E}[X_t] = \sum\limits_{i=1}^t\mathbb{E}[Z_i] = \sum\limits_{i=1}^tp(1-2k) -(1-p) = (p(1-2k)+p-1)t$$
1- I would like to calculate the standard deviation of the random walk and also the standard deviation of the mean.
For the first one I need to calculate the variance of $X_t$ and for the second one I need the variance of $E[X_t]$.
2- Also I would like to do these calculations using Mathematica but I don't know how to define the distribution.
Trying to do the first calculation by hand and using the definition of variance:
$$Var[X_t]=E[X_t^2]-(E[X_t])^2$$
How do I calculate $E[X_t^2]$?
Thanks.

A: By definition, $E[z(X)]=\sum z(x)*f(x)$, where $f(x)$ is the density. So,
$$ E[X_t^2] = p*(1-2k)^2 + (1-p)*(-1)^2 = p-4kp+4pk^2+1-p=4pk^2+1-4pk$$


text:
Q: Some apps don't accommodate small screen of iPhone SE I rarely install apps because I don't want to navigate the uncertain security implications.  On the few occasions that I do, however, a significant portion of those apps seem to be designed only for phone with larger screens.  Essential parts of the display reside below the bottom edge of the iPhone SE screen.  Some pages of some apps allow scrolling/panning, but not always.  Sometimes, it seems that they assumed that no one would have a phone so small as to be unable to access the bottom portions of the content, so the content doesn't scroll, and I can't access the bottom parts.
For example, some parts of the Tim Hortons app for reward points allows you to redeem points for food/beverages, but some parts of the menu becomes inaccessible.  Another example is an app to access a certain vendor's security camera; it requires that you create an account with the company, but I can only access the login fields -- not the links to create an account, which are below the bottom edge of the display.  I don't know if I can use a friend's bigger phone to create an account, but even if I could, the controls for accessing the video are also way down, and would be inaccessible using my iPhone SE.
I tried using a pinch gesture to shrink the size of the content so that the content lower down on the page would fit on the screen.  Resizing of the content doesn't seem to be possible.
The iPhone SE is not a rare phone.  I can't be the only one butting against this problem.  How do others deal with this?

A: Unfortunately this is all too common with unsuitable app development and quality assurance practices. I would consider this issue to be a bug with the app that should be reported to the developer. Apps should be able to be used with any text size, but this may help in the short term:

Adjust the text size when you're using an app

*

*Open Control Center, then tap the Text Size button.
(If you don't see the Text Size button, add it to Control Center—go to Settings  > Control Center, then choose Text Size).

*Drag the slider up or down to increase or decrease the text size.
To change the text size for all apps, tap All Apps at the bottom of the screen.

https://support.apple.com/guide/iphone/iph3e2e1fb0/ios


text:
Q: Create filter queries by hand using elasticsearch_dsl I am trying to build arbitrary nested queries stored in a some data structures (possibly a tree).
From the manual I gather that filter type of queries are special types of Bool queries, so that
s = Search()
s = s.filter('terms', tags=['search', 'python'])

and
s = Search()
s = s.query('bool', filter=[Q('terms', tags=['search', 'python'])])

are the same.
I tried this on my query, but something is not working properly.
This first query works and returns the expected results:
s = Search(using=client, index='index')
s = s.filter('term', some_field=some_value)
print(s.to_dict())

>>> {'query': {'filtered': {'filter': {'term': {'some_field': 'some_value'}}, \
     'query': {'match_all': {}}}}}

Mimicking the example in the query does not seem to work:
s = Search(using=client, index='index')
s = s.query(Q('bool', filter=[Q('term', some_field=some_value])]))
print(s.to_dict())
>>> {'query': {'bool': {'filter': [{'term': {some_field': some_value}}]}}

Note that I am using version 1 of ElasticSearch because for some reason AWS has not upgraded yet.

A: If you're using ES 1.x, then you cannot use the second way, i.e. the one that yields a bool/filter query.
If you get that query, that means you're using elasticsearch-dsl 2.x or later, which is not correct.
You need to modify your requirements.txt file to include this
# Elasticsearch 1.x
elasticsearch-dsl<2.0.0


text:
Q: How to run web server (Warp) in async/concurrent mode? I'm using https://hackage.haskell.org/package/warp-3.3.24/docs/Network-Wai-Handler-Warp.html
I don't know much about haskell concurrency. Say I would like to run two servers on different ports:
So I do:
 do
   Warp.run 3000 waiApp
   Warp.run 3002 waiApp

Then server is run on 3000 is working, but it never gets to the next line.
I tried:
 do
   forkIO $ Warp.run 3000 waiApp
   forkIO $ Warp.run 3002 waiApp

But it doesn't seem to work, each of them just stop after forking.
How to make it work properly? Also I want to allow the code below to be executed aslo.
UPD:
So the current solution is just to add
forever (threadDelay 1000)

in the end of the main, I wonder if it is the correct way to do this.

A: So, we should not allow the main thread to terminate. Something like this should work:
 do
   a1 <- Async.async $ Warp.run 3000 waiApp
   a2 - Async.async $ Warp.run 3002 waiApp
   ...
   Async.waitAny [a1, a2]


text:
Q: Modify connect() timeout period I have done a bit of searching and can't seem to find the answer I'm looking for, the only answers I could find were to use select to see if the socket had timed out which is what I am already doing.
What I want to know is there anyway to change the length of time before connect() would timeout? I am currently using select() which returns with errno set to EINPROGRESS until eventually returning with ETIMEDOUT. Is there anyway I can change the amount of time it takes before this ETIMEDOUT would occur? Currently it happens after about 60 seconds. I have tried adjusting the timeout value I pass into the select() call however, this only affects how long it takes before select() will time out.

A: *

*Create the socket.

*Put it into non-blocking mode.

*Issue connect().

*Call select() or poll() or epoll(), specifying your desired timeout, and specifying the socket as a writefd, i.e. blocking until the timeout expires or the socket becomes writable.

*If the timeout expires, close the socket etc.

*Otherwise get the last error on the socket via getsockopt() and see if it's zero. If so, the connection has succeeded, otherwise it has failed.

Note that you cannot increase the connect timeout beyond the platform default (about a minute) by this means, but you can decrease it.

A: setsockopt(3) allows you to set this: http://linux.die.net/man/3/setsockopt
Slightly confusing, the timeout values are actually properties of the socket.
The options you are looking for are: SO_SNDTIMEO and SO_RCVTIMEO
EDIT
As stated in the comments, this doesn't work for connect. Here is why:
http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout
As a solution it is suggested to set limits on the amount of retry SYN packets the kernel sends to establish the connection after the initial handshake failed. The time is doubled since the last retry, which means a) you can only set the amount of retries, which indirectly adds up to a connect timeout value and b) this is OS specific and system wide. Not a solution for you probably....


text:
Q: NodeSelector for Job - use it only if NodeSelector exists I have a Job Object which shall use a Node Selector to only use Nodes, which have a GPU under the hood. I know to to set it (it gets converted from a string in a python program).
    job = f"""
    apiVersion: batch/v1
    kind: Job
    ....
          nodeSelector:
            sma-gpu-size: {gpu_size}
    """

Our ops team sets this selectors in the next few weeks, but currently when setting the node selector, the service is not able to start.
2022-09-20T07:20:24Z [Warning] 0/35 nodes are available: 2 node(s) had taint {node-role.kubernetes.io/infra: }, that the pod didn't tolerate, 3 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 30 node(s) didn't match Pod's node affinity/selector.

Is it somehow possible to use these node_selectors only if they are available, something like this (pseudo yaml)?
    job = f"""
    apiVersion: batch/v1
    kind: Job
    ....
          nodeSelector:
            if_available:
                sma-gpu-size: {gpu_size}
            else:
                Any
    """

A: It's not, but you can replace the nodeSelector with a nodeAffinity to achieve that.
spec:
  [...]
  affinity:
    nodeAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: sma-gpu-size
            operator: In
            values:
            - {gpu_size}

From docs:

preferredDuringSchedulingIgnoredDuringExecution: The scheduler tries to find a node that meets the rule. If a matching node is not available, the scheduler still schedules the Pod.

After the label has been added, you can switch to requiredDuringSchedulingIgnoredDuringExecution:

requiredDuringSchedulingIgnoredDuringExecution: The scheduler can't schedule the Pod unless the rule is met. This functions like nodeSelector, but with a more expressive syntax.

or back to nodeSelector.


text:
Q: Inequality in $3$ variables with constraint How can I prove that if
$$
(x+y+z-3)^2=xy+yz+zx-3, \ x,y,z\in\mathbb{R}
$$
Then
$$
3+ xyz(x+y+z)\geq 6xyz
$$
without using Lagrange multipliers?

A: Let $x+y+z=3u$, $xy+xz+yz=3v^2$, where $v^2$ can be negative and $xyz=w^3$.
Hence, the condition does not depend on $w^3$ and we need to prove that $f(w^3)\geq0$, where $f$ is a linear function.
But a linear function gets a minimal value for an extremal value of $w^3$,
which happens for equality case of two variables.
Id est, it remains to prove our inequality for $y=x$ and $(2x+z-3)^2=x^2+2xz-3$.
We need to prove that $3+x^2z(2x+z)\geq6x^2z$ and the rest is easy.


text:
Q: How to make Spring Boot see my images from resources Hi I Have such images in resources/static and put them into my index.html
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Test</title>

    <form method="POST" enctype="multipart/form-data" action="/">

                <input type="submit" value="Test"/>

    </form>

Then, in ResourceConfig
@Configuration
@EnableWebMvc
@ComponentScan
public class ResourceConfig extends WebMvcConfigurerAdapter {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/images/",
            "classpath:/static/", "classpath:/public/" };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }
    }
}

The problem is, that application doesn't see my images. I've added resource handler, but it hasn't worked. The output is
Output

A: This @Override method addResourceHandlers shows Spring Framework where are all you static resources. So... your folder which contains images which are also a static resource must be under your root static resource handler. Set it like this and create this folder under WebContent folder in your project.
@Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    }

A: This line in your html template

makes me think you are using Thymeleaf as your template engine. If that is that case, you should use this to refer to static content:

if your png file is indeed in the root of your static folder.


text:
Q: Let $\dim(V)=n$. Given $v \in V$, $v \neq 0$, show that there is a basis ${v_1, \dots, v_n}$ for $V$ such that $v=v_1+\cdots+v_n$
Let $\dim(V)=n$. Given $v \in V$, $v \neq 0$, show that there is a basis ${v_1, \dots, v_n}$ for $V$ such that $v=v_1+\cdots+v_n$.

I'm trying to do it using induction. I tried with $n=0$, but that is awkward, so I also do it for $n=1$
Suppose $n=0$, then $V=\emptyset$, so the basis is also $\emptyset$, and so $\emptyset=\emptyset$.
Suppose $n=1$.  Then $V=span({v_1})$ for some vector $v_1$. Then if we choose $v \in V$, then we have $v=c*v_1$ for some $c \in \mathbb R$. and $c*v_1$ is a new basis for $V$, so it holds for $n=1$
Suppose it hold for all values less than $k$. Let us prove it for $k$.
Choose a vector $v \in V$.
Now, this is where I get stuck. I'm not sure how to prove that it is the sum of the vectors of a basis.

A: Extend $\{v\}$ to a basis $\{v,v_1,\cdots ,v_{n-1}\}$ let $v_n=v-v_1-v_2-\cdots -v_{n-1}$.

A: Suppose $v \neq 0$. Take any basis $B = \{b_1,...,b_n\}$ of $V$, there will exist some $b_k\in B$, such that $v = \lambda_1 b_k + ... + \lambda_k b_k + ... + \lambda_n b_n$ and $\lambda_k\neq 0$ (there will exist some coordinate in this basis that is nonzero).
Now take $v' = v - \lambda_k b_k$. Then by induction, there exists a basis $B'$ of $V' = Span(B \backslash\{b_k\})$ ($n-1$-dimensional vector space), such that $v' = \sum\limits_{b'\in B'} b'$.
Then $B'\cup\{\lambda_k b_k\} = B''$ is a basis of $V$ and $v = v' + \lambda_k b_k = \sum\limits_{b'\in B'}b' + \lambda_k b_k = \sum\limits_{b''\in B''}b''$.
Another case you have to take care of is when $v' = 0$, this can happen when only one coordinate is non-zero. Then by induction you get a basis such that n-1 coordinates are 1, and the last one is zero, and then you proceed as above.


text:
Q: Creating click events for looped rectangles in canvas I have a basic canvas square with a grid of rectangles inside, how can I create click events that change the fill color of a specific rectangle within the grid when clicked. Is there a method to fit inside of the loop coordinate detection or is there a better library that will create clickable rectangles?
Here is a demo of my work: https://codesandbox.io/s/brave-worker-ywe3z5

const App = () => {
  const canvasRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");

    context.imageSmoothingEnabled = false;
    context.fillStyle = "#000000";
    context.fillRect(0, 0, context.canvas.width, context.canvas.height);

    for (var y = 1; y <= 1000; y += 11) {
      for (var x = 1; x <= 1000; x += 11) {
        context.fillStyle = "rgba(255,255,255,0.1)";
        context.lineWidth = 1;
        context.fillRect(x, y, 10, 10);
      }
    }
  }, []);

  return <canvas ref={canvasRef} width={1002} height={1002}></canvas>;
};

ReactDOM.render(<App/>, document.getElementById('root'));
.App {
  font-family: sans-serif;
  text-align: center;
}

Here is a sample of something I'm trying to achieve: https://www.sandbox.game/en/map/


text:
Q: Websockets:  and @ServerEndpoint I'm currently digging into JSF 2.3 and websockets.
The use of <f:websocket> within xhtml pages and the definition of web socket endpoints using @ServerEndpoint is clear to me.
But is there any way to combine those two to get <f:websocket> to connect to an existing annotated ServerEndpoint?
Haven't found any useful info about that.

A:
But is there any way to combine those two to get <f:websocket> to connect to an existing annotated ServerEndpoint?

No.
The <f:websocket> only listens to its own autoregistered ServerEndpoint.
Whatever problem you thought to solve this way has to be solved differently.


text:
Q: How to add dates to pm2 error logs? Is there a way to add timestamps to error logs in .pm2/logs?
I noticed that pm2 logs command shows aggregated logs with timestamps, but looking into log files - there are only messages and stacktraces without dates.

A: To use standard formated timestamp:
pm2 start app.js --time

Or if you want to prefix logs with custom formated timestamp:
pm2 start app.js --log-date-format <format>

Where <format> is a moment display format (eg YYYY-MM-DD HH:mm Z).
And if your app is already running you can use reload for a 0-second-downtime reload:
pm2 reload app.js --time

Or
pm2 reload app.js --log-date-format <format>

A: I use PM2, but I don't care for the logs that much. Instead I use bunyan, which gives a ton of flexibility for logging. If you npm install it with --global you can also use it as a live log viewer:
This won't timestamp your console.log output, though. But If you convert to log.info() or any other Bunyan log function you will get nice logging.
To view live pm2 logs with bunyan, just pipe it:
pm2 logs | bunyan

A: *

*first update the format (make sure server timezone is what you want)
pm2 restart 0 --log-date-format "DD-MM-YYYY HH:MM Z"

*save all processes
pm2 save

*run these
npm i -G pm2 //if not latest
pm2 update

this works and show log in servers time zone other wise time zone will be different

A: As per the command line help (pm2 logs -h) running pm2 logs --timestamp command should add the timestamp to the logs. However it does seem to not affect old logs! Apparently only new logs show up with timestamp.
To fix this issue pass --log-date-format="YYYY-MM-DD HH:mm Z" to pm2 as a param. For example:
pm2 start bin/www --log-date-format="YYYY-MM-DD HH:mm Z"

Using process.json
I like process.json for starting my app for convenience so my process.json contains the following:
{
  "apps" : [
    {
      "name"        : "app",
      "script"      : "bin/www",
      "log_date_format" : "YYYY-MM-DD HH:mm Z"
    }
  ]
}

then I start my app by just running:
pm2 start process.json

Once done I see the timestamp showing up just by running:pm2 logs Notice that I didn't have to specify --timestamp to see the timestamp.
app (out): 2016-08-04 13:46 +01:00: My log here

A good read: http://pm2.keymetrics.io/docs/usage/log-management/

A: For process.yml , follow these example format. It Worked for me
 apps:
  - script   : ./SampleApi/app.js
    name     : 'api-proxy-app'
    instances: 2
    exec_mode: cluster
    watch  : true
    log_date_format : "YYYY-MM-DD HH:mm Z"

Sample Log format with DateTime:
2019-07-28 13:46 +06:00: channel created for cancel mandate--####################################
2019-07-28 13:46 +06:00: channel created for cancel mandate--####################################
2019-07-28 13:46 +06:00: channel created for exception scenario--####################################
2019-07-28 13:46 +06:00: channel created for create mandate--####################################
2019-07-28 13:46 +06:00: create channel initiated for cancel mandate--------------------->
2019-07-28 13:46 +06:00: create channel initiated for create mandate--------------------->
2019-07-28 13:46 +06:00: create channel initiated for update mandate--------------------->

Using --log-date-format didn't worked for me.

A: As per the pm2 logs official documentation, you can use --time, which prefixes logs with a standard formatted timestamp.
pm2 start app.js --time

If you have already created the app, you can update it while restarting the application with:
pm2 restart 0 --time

Make sure to pm2 save afterwards.
Note that you can also use a custom formatter as per this issue & this commit:
pm2 start app.js --log-date-format 'DD-MM HH:mm:ss.SSS'

where 'DD-MM HH:mm:ss.SSS' is any momentjs valid format.

A: pm2 start app.js --log-date-format "YYYY-MM-DD HH:mm"

A: Wasted 30 mins on this.

*

*Din't work

*

*Other answers din't work

*Official CLI din't work too:  pm2 start app.js [OPTIONS], ex:  pm2 start app.js --time

*Worked

*

*Official Ecosystem file worked great  (procedure is below)

*

*Create an Ecosystem file pm2-config.js in your application root (ex: beside package.json)

Paste the below contents & save:
module.exports = {
  apps: [
    {
      name: "my-app1",
      script: "./index.js",
      time: true,  // <----------------------- This is the key to make it work
      watch: false,
      env: {
        PORT: 4001,
        NODE_ENV: "production",
      },
    },
  ],
};

*

*Now create a shell script start.sh (OR, batch file, OR, directly run below commands)

Paste the below contents & save:
pm2 stop pm2-config.js
pm2 delete pm2-config.js
pm2 start pm2-config.js


text:
Q: Extract the version from filename I want to extract the version number from the name of my build zip file.
build name: build102p12.zip
I want to extract 102p12 from this.
I am using linux enviornment: rhel 6.

A: You want to remove the substrings build and .zip from the string build102p12.zip.
Assuming that you have the original string in a shell variable name:
name='build102p12.zip'

name="${name#build}"  # remove prefix "build"
name="${name%.zip}"   # remove suffix ".zip"

$name will now be the string 102p12.
See the manual of your shell for further information about the ${parameter#word} and ${parameter%word} variable substitutions.

If you have the line (and nothing else)
build name : build102p12.zip

in the file buildinfo:
$ buildversion="$( grep -oE '[0-9]+p[0-9]+' buildinfo )"

The extended regular expression [0-9]+p[0-9]+ will match anything that looks like NNNpNNN where each NNN is some sequence of digits.  This assumes that this only occurs once in the buildinfo file.


text:
Q: HTTP request from Adobe InDesign script? I add a button in Adobe InDesign with an action to perform request xml from restful webservice, but I couldn't find any objects like XMLHttpRequest or ActiveXObject. I don't know there is any object in sdk that lets me do that job?

A: This is an old question, but since it has not been marked as answered yet I'll add one more option for future searchers.
Check out the Extendables library for InDesign - it has that plus many other things you should be using.


text:
Q: Fedora and Samba on VirtualBox I have Linux Fedora 18 installed as a VM Guest.
Trying to share directories from the Linux VM Guest box to the Windows 7 Host. (NOTE: VirtualBox is installed on Windows 7, and the Linux virtual machine is created on it).
I made my Samba share using text on this link:

*

*http://www.howtoforge.com/fedora-19-samba-standalone-server-with-tdbsam-backend
I made all proper changes in /etc/samba/smb.conf, added proper user, etc. I even disabled SeLinux, and flushed the Iptables configuration. Samba is up and running of course. Also, I can ping Linux from Windows.
This is the error I'm getting:

Error code 0x800704cf  The network location cannot be reached. For
  information about network troubleshooting, see Windows Help

There are lots of other resources, like:

*

*http://www.sevenforums.com/network-sharing/113729-password-protected-network-share.html#post978798
I did what is described there, and still having same problem. In all of the cases, I have same error.
Can you give me some tips on what I'm doing wrong in this case?

A: When I've setup Samba in the past, I've needed to create a network bridge device on the VM host, and then added the IP address for the VM guest to this bridge device.
To that end you can take a look at this tutorial which shows how to make use of a bridge device using VirtualBox, titled: Network & sharing in VirtualBox - Full tutorial.


text:
Q: Will I ever be offered a Governor position by a non-English Governor? I have played the game as a Dutch merchant. My victory was "Become a Governor". But as I have reached the end of the game, I was offered the governor position by every English governor, although I am Dutch.
Is that normal? Will I always be offered that position by the English no matter what my nation is?


text:
Q: Convert java listeners to kotlin flow I'm developing on Android and in my source code there are a lot of listeners based on callback .
I want to convert some part of those to a kotlin flow.
I read many articles, where talks about callbackFlow, but I don't think it right choice to me.
In my case there is something like this:
interface ActionListener{
   public void actionStarted(actionId:Int)
   public void actionProgress(actionId:Int, elementCreated:ExampleElement)
   public void actionEnd(actionId:Int)
}

class MainProductor{
   ActionListener actionListener;

   MainProductor(ActionListener actionListener){
    this.actionListener = actionListener
   }

   void start(){
        //start some heavy works that start to call actionListener
   }
}

UseCase:
when I call start  some action with certain id starts and begin to create some ExampleElement
In the UI I have to show a list of ExampleElement produced by the actions with id A and with id B.
In the UI I have to show a progress when one of both action starts and until all elements produced by the two actionIds are been created,
(this part is soo tricky)
how can continue to use this ActionListener and adapt it to new kotlin flow ? Is possible way ?

A: The main point of using callbackFlow would be that it automatically registers and unregisters a listener upon being started/cancelled. A possible solution to deal with multiple callback methods would be to create corresponding event classes and emit those.
sealed interface ActionListenerEvent {
    class Started(val actionId: Int) : ActionListenerEvent
    class ProgressChanged(val actionId: Int, val progress: Float, val elementCreated: ExampleElement) : ActionListenerEvent
    class Finished(val actionId: Int) : ActionListenerEvent
}

fun actionEvents() = callbackFlow {
    val listener = object : ActionListener {
        override fun actionStarted(actionId: Int) {
            trySend(ActionListenerEvent.Started(actionId))
        }

        override fun actionProgress(actionId: Int, progress: Float, elementCreated: ExampleElement) {
            trySend(ActionListenerEvent.ProgressChanged(actionId, progress, elementCreated))
        }

        override fun actionEnd(actionId: Int) {
            trySend(ActionListenerEvent.Finished(actionId))
        }
    }

    registerListener(listener)

    awaitClose {
        unregisterListener(listener)
    }
}

If you want a solution that has more control over when your listener is registered/unregistered, you can also use MutableSharedFlow to expose the events.
class MainProductor{
    val events = MutableSharedFlow<ActionListenerEvent>() // may need to configure replay and buffer depending on your specific use case
    private val listener  = object : ActionListener {
        override fun actionStarted(actionId: Int) {
            events.tryEmit(ActionListenerEvent.Started(actionId))
        }

        override fun actionProgress(actionId: Int, progress: Float, elementCreated: ExampleElement) {
            events.tryEmit(ActionListenerEvent.ProgressChanged(actionId, progress, elementCreated))
        }

        override fun actionEnd(actionId: Int) {
            events.tryEmit(ActionListenerEvent.Finished(actionId))
        }
    }

    fun start(){
        registerListener(this.listener)
    }

    fun stop(){
        unregisterListener(this.listener)
    }
}

Edit: example usage
Although I am not entirely sure about the expected behavior, especially what to do with the elementCreated: ExampleElement part, I would assume you want to display a list of currently running actions with their respective progress. Aggregating events into such a list might look something like this:
data class RunningAction(val id: Int, val progress: Float)// TODO integrate "elementCreated"

fun collectEvents() = flow {
    val runningActions = mutableMapOf<Int, RunningAction>()
    actionEvents().collect { event ->
        when (event) {
            is ActionListenerEvent.Started -> {
                runningActions[event.actionId] = RunningAction(id = event.actionId, progress = 0f)
            }
            is ActionListenerEvent.ProgressChanged -> {
                val action = runningActions[event.actionId]
                if(action != null){
                    runningActions[event.actionId] = action.copy(progress = event.progress) // TODO integrate "elementCreated"
                }
            }
            is ActionListenerEvent.Finished -> {
                runningActions.remove(event.actionId)
            }
        }
        emit(runningActions.values)
    }
}

A:  interface ActionListener {
        fun actionStarted(actionId: Int)
        fun actionProgress(actionId: Int, progress: Float, elementCreated: ExampleElement)
        fun actionEnd(actionId: Int)
 }

 class MainProductor(val actionListener: ActionListener) {
        fun start() {
            //start some heavy works that start to call actionListener
        }
 }


text:
Q: How to create shadow effect in uitableviewcell? i am developing one application in which i want to create shadow effect similar to shown in below image at bottom uitableviewcell.

How can i do that?any tutorial or sample code? I have checked http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html,
http://www.touchthatfruit.com/?tag=uitableview
and some other ones.but they have shadow at bottom of uitableview with same height.and how to
add shadow at side borders of each section containing the date(not the entire tableview).I can create the dropdown shadow at bottom.but what about side borders of last uitableview cell of each section.and one way is creating the image and setting it as background of tableviewcell.But how to resize the image and will it look proper because each section has dynamic number of entries.one section only have 1 entry and other may contain 15 or more entries.(here image is for entire section which contains date).i can have seperate image for only last tableviewcell of each section.This is i know.but is there any better approach or do it programatically?

A: You can refer the following link for shadow effect in uitableview that will help you
try this
A fundamental piece of a view is it's layer which is a CALayer. You can access it through the layer property of a view:
myView.layer
In the documentation CALayers have several properties that control the shadow. You should be able to tell the navigation bar's layer to cast a shadow. Along with the layers of any other content that you want to cast a shadow.
myView.layer.shadowOffset

myView.layer.shadowRadius

You will need to be sure to add the QuartzCore framework to your project to access this property

A: Will each section always be the same size?  If so why don't you subclass the UITableViewCell to draw the notebook like item with the drop shadow included?
You can also add a transparent UIImageView over the UITableView to get the darkened corners.
EDIT:
This effect is a bit tricky, you're going to want to look into how to use UIBezierPaths (http://developer.apple.com/library/IOS/#documentation/UIKit/Reference/UIBezierPath_class/Reference/Reference.html).
The top portion can be an image (the rings and tab effect).  You can then draw the rest of the cell in the drawRect function. (This more efficient than using the shadow properties in layer which is important in a UITableViewCell).
You'll want to override your UITableViewCell class and implement a custom drawRect: function.
Here's some code to get you started:
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect
    {

        /* Draw top image here */

        //now draw the background of the cell.
        UIBezierPath *path1 = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 320, 50)];
        [[UIColor grayColor] set];
        [path1 fill];

        UIBezierPath *path2 = [UIBezierPath bezierPathWithRect:CGRectMake(0, 52, 320, 50)];
        [[UIColor whiteColor] set];
        [path2 fill];

        UIBezierPath *path3 = [UIBezierPath bezierPathWithRect:CGRectMake(0, 104, 320, 50)];
        [[UIColor grayColor] set];
        [path3 fill];

        UIBezierPath *path4 = [UIBezierPath bezierPathWithRect:CGRectMake(0, 156, 320, 50)];
        [[UIColor whiteColor] set];
        [path4 fill];

        //and so on...

        //Let's draw the shadow behind the last portion of the cell.
        UIBezierPath *shadow = [UIBezierPath bezierPathWithRect:CGRectMake(0, 208, 320, 52)];
        [[UIColor darkGrayColor] set];
        [shadow fill];

        //Finally, here's the last cell with a curved bottom
        UIBezierPath *path5 = [UIBezierPath bezierPath];
        [path5 moveToPoint:CGPointMake(0, 208)];
        [path5 addLineToPoint:CGPointMake(320, 208)];
        [path5 addLineToPoint:CGPointMake(320, 258)];
        [path5 addCurveToPoint:CGPointMake(0, 258) controlPoint1:CGPointMake(160, 254) controlPoint2:CGPointMake(160, 254)];
        [[UIColor grayColor] set];
        [path5 fill];
    }

The code isn't quite drag and drop, You still need to add the white lines, fix some sizes, and tweak the last cell and shadow to be just right. But it should be enough to get you started.
Cheers!

A: Take a look at my answer to a similar question, this one may be a possible solution to your problem! By altering the shadow path you should be able to achieve the desired shadow effect!

A: This can be achieved using the bezierpath:Check the URL for getting various shadow effects:http://nachbaur.com/blog/fun-shadow-effects-using-custom-calayer-shadowpaths


text:
Q: Error while loading image from file-loader I am facing error while getting same bundled image from different route
While my app is in route http://localhost:8080
My image load perfectly from url http://localhost:8080/3e8b0bc82f581817994bbe9e9396170b.jpg
But as my app route changed to http://localhost:8080/dashboard
My image also loads from url http://localhost:8080/dashboard/3e8b0bc82f581817994bbe9e9396170b.jpg
Since the image is at url location http://localhost:8080/3e8b0bc82f581817994bbe9e9396170b.jpg
 So it shows 404 resource not found error while getting the resources from the given location.
I am using  require('../image.jpg') to add image in my app.
This is my webpack.config.js file.

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'react',  "env"]
      }
     },
      { test: /\.(png|jpg|svg)$/i, loader: "file-loader",
        options:{outputPath:'images/'}},
      {test:/\.json?$/,loader:'json-loader'}

    ],

  },
devServer: {
    historyApiFallback: true,
    contentBase: './public',
    hot:true
  },
devtool:"cheap-module-eval-source-map"

}

I am using webpack version: "^3.1.0".


text:
Q: Pandas - All I want is a single series value output with not other metadata I have 2 dataframes that I have successfully merged together which results in a single desired row of data.
Then I successfully determined the whole value difference between two integer columns.
Now all I want to do is output the integer value result, with no other metadata.
IN:
def answer_four():
Top15 = answer_one()
Top15_6th = answer_three()
Top15_6th = Top15_6th.iloc[[5]]

# https://stackoverflow.com/questions/36538780/merging-dataframes-on-index-with-pandas

Top15_6th_ab = pd.merge(
                           Top15_6th[['avgGDP']],
                           Top15[['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']],
                           left_index = True,
                           right_index = True
                       )

Top15_6th_ab['Value_10yr_Change'] = Top15_6th_ab['2015'] - Top15_6th_ab['2006']

return Top15_6th_ab['Value_10yr_Change']

answer_four()
OUT:
Country
United Kingdom     246702696075
Name: Value_10yr_Change, dtype: float64
All I want in OUT is:
246702696075
I assume I need to add some method/parameters after my return clause, but through much research I have found the answer.
Thanks for your time and assistance in advance!
Matt

A: Top15_6th_ab['Value_10yr_Change'][0]


text:
Q: PHP / Javascript minification I am curious if there is a full minifier that can do javascript AND the php / html minification? As a for instance, if you look at this pen:
http://codepen.io/ajhalls/pen/qmEKVY
You can see in the HTML area you have the code
 <div class="col-sm-1 svgPatternItem " data-id="svgPattern-42 " style="font-size:14px;text-shadow: 0px 0px 4px rgb(0, 0, 0);color:#fff;position:relative;width:100px;height:100px; ">

Then in the javascript, you have:
$(".svgPatternItem").each(function( index ) {

while the class svgPatternItem makes it descriptive and readable, it is unnecessarily long. In sublime I could do a global search and replace to make that class aa, and the next one class ab and so on, but that is exactly the type of work you would expect a macro to excel at, yet I haven't found one that will modify both.
To further complicate matters, I have mixed in some new ECMAScript 2017 that breaks most minifiers, but which made development so much more pleasant like using the backtick when defining multiline variables. I could revert things to previous JS if needed, but it makes it harder to develop on unless it is required.
I was looking at http://esprima.org and it seems that if you look at the online parser with the js code from the codepen earlier you would just need to look for the callee => arguments => value and if it was an alphanumeric value, do a global search and replace using a short variable name through the entire code base  of php and javascript which "should" work.
All that being said, as evidenced from my last two questions, I haven't found a way to do that parsing myself using javascript or PHP. Maybe python could do it, but I wonder if I need a full windows application such as Sublime to do the work for me so am wondering if anyone else has solved this particular issue.

A: As far as JavaScript minification is concerned the best is Google Closure Compiler.
It has an online version as well as a downloadable runnable java jar file.
Know more about Google Closure compiler for JS here:
https://closure-compiler.appspot.com/home
https://developers.google.com/closure/compiler/
HTML Minification:
There is a Repository at github that lets you CSS and JS and HTML into a single line of code, you can find it at https://github.com/searchturbine/phpwee-php-minifier
It runs on the PHP engine.
If you want to obfuscate your JS code there is a concept called uglification It basically minifies as well as obfuscates your code against reverse engineering upto a certain level find more about it at :https://github.com/mishoo/UglifyJS2


text:
Q: building dynamic linQ queries I have seen a few old post but cannot figure out how to achieve this, Please help with an example.
I need to create a filter method to get data based on user inputs in a form, which may be random in nature. My current code is given below, which i felt weired and incomplete. How can i replace this with dynamic LINQ queries as the i may need to add more parameters in future. I couldn't figure out the Expression Trees thing. Please somebody enlighten me.
 public Status GetAssets(String AssetNumber, int AssetCategoryId)
    {
        var status = Status.ReportInfo("Data Retrieval initiated");

        var assetsRepo = new EFRepository<DAL.Entities.Assets, long>(new ProductionControlDataContextFactory(DataBase));
        try
        {
            if (AssetNumber == "" && AssetCategoryId == 0)
            {
                status = Status.ReportWarning("Invalid Entry.");
            }
            else if (AssetNumber == "")
            {
                var assetsData = assetsRepo.FindAll(x => x.AssetCategoryId == AssetCategoryId, x => x.AssetCategory).ToList();
                status = Status.ReportSuccess("Data Retrieved Successfully.");
                status.Data = assetsData;
            }
            else if (AssetCategoryId == 0)
            {
                var assetsData = assetsRepo.FindAll(x => x.AssetNumber == AssetNumber, x => x.AssetCategory).ToList();
                status = Status.ReportSuccess("Data Retrieved Successfully.");
                status.Data = assetsData;
            }
            else
            {
                var assetsData = assetsRepo.FindAll(x => x.AssetNumber == AssetNumber && x.AssetCategoryId == AssetCategoryId, x => x.AssetCategory).ToList();
                status = Status.ReportSuccess("Data Retrieved Successfully.");
                status.Data = assetsData;
            }

        }
        catch (Exception ex)
        {
            return Status.ReportError("Couldn't Retrieve Data.");
        }

        return status;

this is my entity class
public class Assets : ProductionControlEntity<long>
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public override long Id { get; set; }

    [ForeignKey("AssetCategory")]
    public int? AssetCategoryId { get; set; }
    public virtual AssetCategory AssetCategory { get; set; }

    [Index("IX_AssetNumber", 1, IsUnique = true)]
    [StringLength(150)]
    public string AssetNumber { get; set; }

    public string AssetDescription { get; set; }

    public string ManufacturerModelNumber { get; set; }

    public Boolean CalibrationRequired { get; set; }

    public DateTime? LastCalibrationDate { get; set; }

    public DateTime? NextCalibrationDueDate { get; set; }

    public Boolean AssetStatus { get; set; }

    public Boolean IsDeleted { get; set; }

    public DateTime LastModified { get; set; }

    public string uuid { get; set; }

    //public ICollection<EquipmentEntries> EquipmentEntries { get; set; }

}

Any help appreciated. Thanx in advance..

A: Try this:
 if (string.isNullOrEmpty(AssetNumber) && AssetCategoryId == 0) {
            status = Status.ReportWarning("Invalid Entry.");
        }
        else {
            var assetsData = assetsRepo.FindAll(x => ((!string.isNullOrEmpty(AssetNumber) && AssetCategoryId != 0 && x.AssetCategoryId == AssetCategoryId && x.AssetNumber == AssetNumber)
                || (string.isNullOrEmpty(AssetNumber) && AssetCategoryId != 0 && x.AssetCategoryId == AssetCategoryId)
                || (!string.isNullOrEmpty(AssetNumber) && AssetCategoryId == 0 && x.AssetNumber == AssetNumber)), x => x.AssetCategory).ToList();
            status = Status.ReportSuccess("Data Retrieved Successfully.");
            status.Data = assetsData;
        }

Let me know if have queries, HAPPY CODING !!!


text:
Q: Node Crypto Encryption and decryption alogorithem I am looking for standard utility for supporting the encryption & decryption based on the below algorithm in node server side.
algorithm: aes-256-gcm
using the createCipheriv, createDecipheriv from nodejs crypto module.
Please suggest some working references

A: The utility need to build it from your side, and based on your needs below are the small code may help you to build the utility:
const crypto = require('crypto');

// This two value (ivValueEn , ivValueDe) should be same, to decode the text properly!
// you can generate any strong value and past it at the same place of you can have it from the config value.

  const ivValueEn = "c5949f09a7e67318888c5949f09a7e6c09ca51e602867318888c5949f09a7e6c09ca51e602867318888";
  const ivValueDe = "c5949f09a7e6c09ca51e602867318888c5949f09a7e6c09ca51e602867319ca51e602867318888";

// insert your key here, better to chose a strong key
const keyValue = "c5949f09a7e6c09a7e6c09ca51e602867318888c5949f09a7e6c09ca51e602867318888";

// slicing are not required you can remove the slice(0,64) part & the console.log as well
  const alog = 'aes-256-gcm'
  const ivEn = ivValueEn.toString('hex').slice(0,64); console.log(ivEn);
  const ivDe = ivValueDe.toString('hex').slice(0,64); console.log(ivDe);

// The one that working with me correctly is to slicing the key to (32) characters.
  const key = keyValue.slice(0,32);
  const cipher = crypto.createCipheriv(alog,key,ivEn);
  const decipher = crypto.createDecipheriv (alog,key,ivDe);


text:
Q: KeyPress Enter for Selenium We are doing automation testing and came around with a situation where i need to download the file from the browser .
In Download when the download button is hit we are coming to the system pop for the download where we need to perform the enter operation .
Can some one help us how to perform the enter or keyboard operation currently we are using robot API but it is not working on grid system ,
Here is my code for robot can it be enhanced and used or do we have any alternate way to do it
******** Code *************
public void downloadReportFromMyExport(WebDriver driver, String downloadSufixId) throws AWTException,
            InterruptedException
    {
        String downloadPrefixId =     ConfigProperty.getConfig("downloadPrefixId").trim();
        String[] suffix;
        suffix = StringUtil.split(downloadSufixId, "TR_EXP_");
        String suffixPart = suffix[0];
        String completeId = downloadPrefixId.concat(suffixPart);
        By id = By.id(completeId);
        WebElement element = driver.findElement(id);
        element.click();
        Robot pressKey = new Robot();
        pressKey.keyPress(KeyEvent.VK_ENTER);
        pressKey.keyRelease(KeyEvent.VK_ENTER);
        threadSleep("5");
        pressKey.keyPress(KeyEvent.VK_ALT);
        pressKey.keyPress(KeyEvent.VK_F4);
        pressKey.keyRelease(KeyEvent.VK_F4);
        pressKey.keyRelease(KeyEvent.VK_ALT);
        logger.info("Downlaod Complete");
    }

A: In firefox browser,
Solution-1
You can change the browser settings so that it saves all downloads to that location without asking.
Refer below link to know to change that setting in firefox.
https://support.mozilla.org/en-US/kb/startup-home-page-download-settings
Solution-2
By using firefox profile setting you can achieve this.
FirefoxProfile profile=new FirefoxProfile();
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.dir","C:\\Users\\Downloads\\");         profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver=new FirefoxDriver(dc);

A: yeah i've encountered the same issue
better change the browser settings to save in a particular path
for handling different browsers like,
in FF,
i've used
in firefox by default the control will be on "OPEN" option so..
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

for IE (to save alt+s,to open alt+O) here im saving the file
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);

for chrome
by default,when ever you click dowload button it will save without showing any popups
and i've succeeded hope it helps you
-Ajay


text:
Q: gource export video error "could not find codec parameters"  I want to output a video of gource, I follow this guide Creating videos with gource
but I get error on video codec. I also use this guide  enable libx264 support on
This is my error :

gource -o - | ffmpeg -y -b 3000K -r 60
-f image2pipe -vcodec ppm -i - -vcodec libx264 -vpre slow -threads 0
gource.mp4
pipe:: could not find codec parameters

A: I think I finally fixed this problem for me by installing the following packages
(you probably don't need all of them):
libnetpbm10-dev (2:10.0-12.2)
libavfilter1 (4:0.6.2-1ubuntu1.1)
libavformat52 (4:0.6.2-1ubuntu1.1)
libpostproc51 (4:0.6.2-1ubuntu1.1)
libswscale0 (4:0.6.2-1ubuntu1.1)
libavcodec-extra-52 (4:0.6.2-1ubuntu2)
libavutil-extra-50 (4:0.6.2-1ubuntu2)
The complete error I got to start with:
[image2pipe @ 0x23036e0]Could not find codec parameters (Video: ppm)
[image2pipe @ 0x23036e0]Estimating duration from bitrate, this may be inaccurate
pipe:: could not find codec parameters


text:
Q: How to defer the execution of a python task in tornado? I've got an internet site running on tornado, with video features (convert, cut, merge).
The video traitement is quite long, so i want to move it to another python process, and keep the tornado process as light as possible.
I use the mongo db for commun db functionalities, synchronously as the db will stay light.

A: Use Celery to defer tasks
video.py:
@task
def convert(video):
  ...

tornadoserver.py
import video
...
def get(self):
    paramvideo=...
    convert.delay(paramvideo)
    ...

A: Use mongo to defer task
video.py:
def convert():
    ...
db = Connection().my_db
cursor = db.tasks.find(tailable=True)
while cursor.alive:
    try:
        next = cursor.next()
        if next.t=='convert':
           convert(next.d)
    except StopIteration:
        time.sleep(1)

tornadoserver.py
...
def get(self):
    ...
    paramvideo=...
    conn.tasks.insert({t:'convert',d:paramvideo})


text:
Q: using quartz with out the quartz plugin in grails i'm trying to use quartz to schedule jobs in grails with out using the plugin.
this is the code:
1 - RunMeTask.java
package tt;
public class RunMeTask {
    public void printMe() {
        System.out.println("Run Me ~");
    }
}

2 - resources.groovy (under conf/spring)
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerBean;
import tt.RunMeTask

beans = {
    runMeTask(RunMeTask){}

    runMeJob(JobDetailFactoryBean) {
        targetObject = ref('runMeTask')
        targetMethod = "printMe"
    }

    simpleTrigger(SimpleTriggerBean){
        jobDetail = ref('runMeJob')
        repeatInterval = "5000"
        startpDelay = "1000"
    }

    schedulerFactoryBean(SchedulerFactoryBean){
        jobDetails = [ref('runMeJob')]
        triggers   = [ref('simpleTrigger')]
    }

}

i get the following exception:
Error Fatal error during compilation org.apache.tools.ant.BuildException: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.SimpleTriggerBean has interface org.quartz.SimpleTrigger as super class (Use --stacktrace to see the full trace)
can anyone help?

A: ok i figure it out. wasn't that hard when i think about it.the good thing about it its just as simple as you would do it in java and no plugin that may or may not work on grails certain version or any trouble that can caused by using a plugin.
there is 1 change in the code from the question:

*

*RunMeTask.java (this can also be RunMeTask.groovy) must implement runnable and so
it look like this:
package tt;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class RunMeTask implements Runnable {
static Random r = new Random();
public void printMe() throws IOException {
File f = new File("c:\ofer.txt"+r.nextInt());
f.createNewFile();
System.out.println("fff");
}
public void run(){
try {
printMe();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

one funny thing is the println of "fff" occures only 2 times but a new file is created as expected every 5 seconds.
ok so thats it now a new file is created every 5 seconds in your c directory.
no plugin and no hassle. if anyone know why the  System.out.println("fff");  occures only 2 times i will be happy to know.
thanks


text:
Q: 4D - is it any good? Recently I found out that the company a friend of mine co-owns uses 4D, which I've never heard of before. They swear by it, but they're non-technical and what they say about it sounds like memorized marketing blurb. Unfortunately the 4D website also seems devoid of any actual information and is filled with words like "comprehensive", "solution", "platform" and "integrated" instead.
Since that thing is rather expensive and uses a custom language that I don't have much inclination to learn just for one project, I'm cautious about it and I'm wondering if anyone had any experience with it? Would you recommend it? What is it good for? What competitive advantage would I gain by learning it as a programmer, or using it as a company?

A: In my opinion, there is no reason to begin learning 4D unless you want a simple database app and are unable or unwilling to learn how to create GUIs in a bigger language. The main advantage that 4D has is that the built in functionality between the UI and the database can handle most of what is needed. If you want something quick, small, and inhouse, you can get by with 4D but if you need to develop a powerful commercial application you will run into a few walls. If you need something that 4D doesn't provide automatically it will be very difficult to get it working.
I consider the language completely archaic. It works for what it does but our product has become limited by the language and database itself. We keep running into weird quirks and have to code our way around them.
I have experience in 4D 2003 and 2004 but we haven't upgraded to the latest version because of the costs. It is extremely expensive. Each customer needs to buy licenses for each computer that needs to run the software. Our product costs over $1000 for a new office because of the licenses. When a new version of 4D is released every single customer has to pay to upgrade their licenses.

A: After looking at https://www.4duk.com/products/ataglance.html, I'd recommend you stay clear - it looks like one of those products that's going nowhere.
It reminds me of the time I was made use a development platform called Witango - absolute nightmare to use, and all apps had to be rewritten in .NET very shortly afterwards.
Invest your time learning something more mainstream/employable.

A: Avoid at all cost. 4D used to be a good Mac database twenty years ago but is obsolete today. Extremely expensive to deploy and poorly supported. I have used it for many years and have since moved to Real Studio for cross-platform database development, which has a more modern language and a far more active developer community.

A: I'll be wary of investing too much into something like this. On the good side, if that's what your company uses learning it will pay dividends. But the skills you learn will be hard to use in other places.

A: 4D has been around for a long time (~25 years), so it's much older than e.g. MySQL. Think of it as a professional version of Microsoft Access: It has its own Pascal-inspired host language, its own relational database engine, a very mature IDE for rapid GUI development and a custom runtime which allows for true "write once, run anywhere" (anywhere being Mac OS (X) and Windows, that is). Nowadays, it also understands SQL, there's a server version and even an integrated web server. It's fairly powerful, so the comparison to Access probably does not do it justice.
Today, I believe it's mostly used for legacy apps which are as old as 4D is. I don't think I would learn it again today, much less start new projects with it, since you can get the same functionality and then some by stacking up open source components.

A: I think more than half the replies over here are inaccurate. I know of more than 20 companies with over 1000 users. And I believe there are a lot more.
With 4D v12.1 (www.4d.com) you can easily deploy at the click of a button for single-user, client server, Mac, Win. And there are easy to setup plugins for integration with Flex, iPhone and Android OS. Their KB and documentation is very neat and comprehensive.
They have a great engineering team and the support from 4D and the online community is just fabulous. I have been using 4D for several years and I have no complaints.
4D as someone else pointed out gives you a fully integrated backend database and frontend. The client server connections are stateful so you dont need to worry about record handling and client server session handling.
At less than $1000 per year it is not expensive and you can deploy unlimited single user apps. Which other propreitory development platform gives you that?
I am sure Real Software has its Pros and Cons too. There are many choices nowadays and there are many ways to skin a cat.

A: I used to do some very serious 4D work, one of the systems I wrote is still in use as an enterprise system about 16 years later. I got frustrated because they were taking years to come out with the new object-oriented version of the language and I was writing thousands of lines of code to use a third-party table control.
4D delivers cross-platform, very high-performance client-server systems using a proprietary server. The database model is much more set-oriented than SQL and pulls the sets all the way into the core language. It does a nice job of delivering code to the clients because it compiles all procedures to native code which is cached locally and updated on-demand when it is out of date.
The language and GUI environment have their quirks but the flip-side is that there will probably be a good living to be made from supporting it as a legacy platform. if you can get someone else to pick up the tab for the tools, it may be a useful addition to your consulting toolbox. You have to consider how much business-specific code is gonna be out there for a unique product with that long a history!
An engineer for whom I have huge respect was recently hired by 4D which says a lot about their commitment to the future, hiring this kind of guy.
I've been working a lot with legacy systems recently, doing a port from old Mac stuff to WPF and the contrast between the mostly-unused complexity of Visual Studio and old Mac tools reminded me of 4D. I'm also porting my OOFILE C++ database and reporting frameworks to REALbasic - the OOFILE set-oriented operations came directly from what I loved about 4D and this too made me think I was too harsh in this answer originally.
The thing to remember about 4D is that it was set-oriented from the beginning (written by a mathematician) and much easier to use for many things than SQL. The deployment model of 4D Server is a superb combination of desktop app and network provision - compiled components are cached on the server and automatically sent to a client when needed. There's no need to shutdown or actively push or deploy updates. The GUI model of 4D was frustrating but looking at the site today, they have solved most of the issues that I had to use third party solutions for years ago.

A: Avoid it like the plague.  My company uses it and it's just a constant exercise in frustration.  It performs no where near as well as the sales pitch would have you believe, and documentation is either non-existent or not helpful.


text:
Q: Excel file is saved in Eclipse jee folder, not in project folder Goodmorning,
I am trying to download a Excel file that in my main method saves the excel file in my root folder of my project, but when I try it via the webapp with a HTTPServlet it gets saved in C:\User\MyUser\eclipse\jee-2020-03\eclipse\
I am trying to save my excel files not in a root folder but in a subfolder from my root folder (excel_files) so that I can clean the entire folder at once without removing too much important.
What am I doing wrong? And how can i save my files in the subfolder of my root?
ExcelController.java
package houseoftyping.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.time.LocalDate;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import houseoftyping.domain.Course;
import houseoftyping.domain.User;
import houseoftyping.sql.SQLConnection;

/**
 * Servlet implementation class FormController
 */
@MultipartConfig
public class ExcelController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExcelController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (request.getParameter("type").equals("upload")) {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            handleUpload(request, response);
        } else if (request.getParameter("type").equals("downloadLatestExcel")) {
            handleDownload(request, response, false);
        } else if (request.getParameter("type").equals("downloadFullExcel")) {
            handleDownload(request, response, true);
        }
    }

    @SuppressWarnings("resource")
    private void handleDownload(HttpServletRequest request, HttpServletResponse response, boolean fullDownload) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("Username")) {
                SQLConnection conn = new SQLConnection();
                User user = conn.findUserByName(cookie.getValue());
                XSSFWorkbook workbook = new XSSFWorkbook();
                LocalDate ld = LocalDate.now();
                String fileName = "";
                try {
                    if (request.getParameter("isAccountant").equals("true")) {
                        if (fullDownload) {
                            workbook = conn.fillWorkbookWithAllRegistrationsAccountant(workbook, user);
                            fileName = "export-inschrijvingen-" + ld.getDayOfMonth() + "-"
                                    + findFullMonthByInt(ld.getMonthValue()) + "-" + ld.getYear() + "-administratie";
                        } else {
                            workbook = conn.fillWorkbookWithLastRegistrationsAccountant(workbook, user);
                            fileName = "export-laatste-inschrijvingen-" + ld.getDayOfMonth() + "-"
                                    + findFullMonthByInt(ld.getMonthValue()) + "-" + ld.getYear() + "-administratie";
                        }
                    } else {
                        if (fullDownload) {
                            workbook = conn.fillWorkbookWithAllRegistrations(workbook, user);
                            fileName = "export-inschrijvingen-" + ld.getDayOfMonth() + "-"
                                    + findFullMonthByInt(ld.getMonthValue()) + "-" + ld.getYear();
                        } else {
                            workbook = conn.fillWorkbookWithLastRegistrations(workbook, user);
                            fileName = "export-laatste-inschrijvingen-" + ld.getDayOfMonth() + "-"
                                    + findFullMonthByInt(ld.getMonthValue()) + "-" + ld.getYear();
                        }
                    }
                    ServletOutputStream os = response.getOutputStream();
                    File file = new File(fileName + ".xlsx");
                    FileOutputStream fileOut = new FileOutputStream(file);
                    workbook.write(fileOut);
                    System.out.println(file.getAbsolutePath());
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
                    fileOut.close();
                    workbook.close();
                    os.flush();
                    response.flushBuffer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String findFullMonthByInt(int monthValue) {
        switch (monthValue) {
        case 1:
            return "januari";
        case 2:
            return "februari";
        case 3:
            return "maart";
        case 4:
            return "april";
        case 5:
            return "mei";
        case 6:
            return "juni";
        case 7:
            return "juli";
        case 8:
            return "augustus";
        case 9:
            return "september";
        case 10:
            return "oktober";
        case 11:
            return "november";
        case 12:
            return "december";
        }
        return null;
    }

    private void handleUpload(HttpServletRequest request, HttpServletResponse response) {
        Part filePart = null;
        try {
            filePart = request.getPart("file");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ServletException e1) {
            e1.printStackTrace();
        }
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        try {
            InputStream fileContent = filePart.getInputStream();
            Workbook workbook = WorkbookFactory.create(fileContent);
            createCoursesByWorkbook(workbook);
        } catch (Exception E) {
            E.printStackTrace();
        }
    }

    public void createCoursesByWorkbook(Workbook workbook) {
        Sheet sheet = null;
        for (Sheet s : workbook) {
            if (s.getSheetName().equals("import scholen")) {
                sheet = s;
            }
        }
        for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
            if (j != 0) {
                Row row = sheet.getRow(j);
                int i = 0;
                Course c = new Course(row.getCell(i++).getStringCellValue().replaceAll("\\s", ""),
                        row.getCell(i++).getStringCellValue(), row.getCell(i++).getStringCellValue(),
                        String.valueOf(row.getCell(i++).getNumericCellValue()) + "0",
                        String.valueOf(row.getCell(i++).getNumericCellValue()) + "0");
                c.saveCourse();
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

This is one of the methods that fills my workbook (which works perfectly fine)
XSSFSheet sheet = workbook.createSheet("Inschrijven-site");
       int rowCount = 0;
       Row headerRow = sheet.createRow(rowCount++);
       int columnCount = 0;
       String allCellHeaderNames = "Cursuscode,Geslacht,Geboortedatum,Voornaam,Tussenvoegsel,Achternaam,Naam Ouders,Adres,Stad,Adres nummer,Postcode,E-mailadres,Telefoonnummer,IBAN,Ter name van,Betalingsoptie,Mandaatdatum,Mollie Afgerond(0=nee 1=ja),Factuursturen Afgerond(0=nee 1=ja)";
       String[] cellHeaderNames = allCellHeaderNames.split(",");
       for (int i = 0; i < 19; i++) {
           Cell cell = headerRow.createCell(columnCount++);
           cell.setCellValue(cellHeaderNames[i]);
       }
       SQLConnection sqlConnection = new SQLConnection();
       Connection conn = sqlConnection.getConnection();
       String query = "SELECT * FROM registration";
       try {
           Statement stmn = conn.createStatement();
           // execute the query, and get a java resultset
           ResultSet rs = stmn.executeQuery(query);
           while (rs.next()) {
               columnCount = 0;
               Row row = sheet.createRow(rowCount++);
               for (int i = 2; i < 21; i++) {
                   Cell cell = row.createCell(columnCount++);
                   cell.setCellValue(rs.getString(i));
               }
               if(rs.isLast()) {
                   user.updateLastExport(Integer.parseInt(rs.getString(1)));
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return workbook;


text:
Q: How to clear txt file having different Delimiter using SSIS package? I have text file which is having ^(CAP) and ,(Comma) as a delimiter and after clearing i need to load to sql . I have tried my best to clear a source file
But still file is not cleaned as expectation .

Please find the below picture i have tried to correct the source file

But still file is not cleared as expected . Please find below uncleared file .

A: You have a variety of issues here.

*

*You have identified the header row delimiter as a comma. A row delimiter is the, usually invisible, delimiter than indicates a row's worth of data has happened. Traditionally, this is an Operating System specific value but it's a Carriage Return (CR), Line Feed (LF) or Carriage Return/Line Feed.

*Your source data is not a comma delimited file with caret/circumflex/cap text delimiters. You have a comma-space delimited file which SSIS doesn't support in the editor. However, if you hand edit the dtsx file as I outlined in How to read a flatfile with lowercase thorn as the delimiter to specify that it should use comma space ColumnDelimiter="_x002C__x0020_"
Given a truncated version of your source data
ListCode, CAS, Name
^216^, ^^, ^Coal Dust^
^216^, ^7782-24-5^, ^Graphite (Natural)^
^216^, ^^, ^Inert or Nuisance Dust^

and the comma (0x2C) space (0x20) edited into the raw dtsx connection manager, I was able to pull data as I believe you are expecting

You might also run into additional issues given your selection of code pages and not checking the Unicode button but that's beyond my ability to generate matching source data from an image.

A: Just replace the ^, ^ with ^,^
It looks like your source
 CAS, SubName, ListCode, Type, CountryCode, ListName
 ^1000413-72-8^,^fasiglifam^,^447^,^Chemical Inventory^,^EU^,^ECICS Custom Tariff Codes^
 ^1000413-72-8^,^fasiglifam^,^0^,^^,^NN^,^SPHERA Global Substance List^

Then edit your connection manager with below details

[![enter image description here][2]][2]
It will work .
[2]: https://i.stack.imgur.com/0x89k.png


text:
Q: Solve $2A{\frac{1-\sqrt{w}}{\log{w}}}=1$ in terms of Lambert W function. I have tried it in this way: $$2A(1-\sqrt{w})=\log{w}$$ $$w\exp(2A\sqrt{w})=\exp{2A}$$ $$A^2w\exp(2A\sqrt{w})=(A\exp{A})^2$$ $$A^2w=W^2(A\cdot \exp{A})$$ $$w=A^-2W^2(A\cdot \exp{A})$$
Is this solution right?

A: To get the full extent of the solutions, follow Claude Leibovici's advice.
Note that if you set $y=w^{1/2}$, then $y^2=w$, but because of the squaring you are going to miss solutions, so you need to set up two equations, one for the positive and one for the negative root of the substitution:
$$\begin{align}
\frac{2A(1-y)}{\ln(y^2)}&=1\,\,\,\,(1)\\
\frac{2A(1+y)}{\ln(y^2)}&=1\,\,\,\,(2)
\end{align}$$
After simplifying you get:
$$\begin{align}
y&=\exp(A(1-y))\,\,\,(3)\\
y&=\exp(A(1+y))\,\,\,(4)
\end{align}$$
which now have the visible solutions via the standard Lambert algebraic proccess:
$$
\begin{align}
(3)\implies y&=\frac{W(A\cdot\exp(A))}{A}=1\,\,\,\,\text{(for $A>0$, W is a partial inverse of }z\cdot\exp(z))\,\,\,(5)\\
(4)\implies y&=\frac{W(-A\cdot\exp(A))}{-A}\,\,\,(6)
\end{align}$$
from which upon reversing the substitution $y=w^{1/2}$ you get:
$$\begin{align}
(5)\implies w_1&=1\\
(6)\implies w_2&=\left(\frac{W(-A\cdot\exp(A))}{-A}\right)^2
\end{align}$$

$\mathbf{Addendum}$-1
If you are wondering about whether $w_2$ simplifies further, yes, it does and it equals 1, because the numerator of the fraction in the parenthesis equals $-A$ again. For details please refer to this answer of mine from an older question by Gottfried Helms.

$\mathbf{Addendum}$-2 (second root clarification)
I was wrong on my first Addendum concerning the second root. It is true that:
$$W(|A|\exp(|A|)=|A|$$
but this does not apply in this case because the signs are alternating, so:
$$\frac{W(-A\cdot\exp(A))}{-A}$$
$\mathbf{cannot}$ be simplified further.
To conclude, the solutions are $w_1=1$ (for $A>0$), and $w_2=\left(\frac{W(-A\cdot\exp(A))}{-A}\right)^2$ (for $A<0$), as above in (6).

$\mathbf{Addendum}$-3 (addressing additional solutions)
It is possible that $w_2$ may be complex for all the branches of $W$. Here's an example with Maple code:
W := proc (k, w) options operator, arrow; LambertW(k, w) end proc
sol2 := proc (k, A) options operator, arrow; W(k, -A*exp(A))^2/A^2 end proc
for k from -3 to 3 do evalf(sol2(k, 2)) end do #for A=2

outputs:
-49.98644048 - 0.3118949792 I
-15.63286398 - 2.455783917 I
-0.5299074982 - 1.853237059 I
-0.5299074982 + 1.853237059 I
-15.63286398 + 2.455783917 I
-49.98644048 + 0.3118949792 I
-104.0602403 - 3.292630660 I
So, in the case of $A=2$ all solutions $w_2$ are complex. You can check that these are indeed solutions, by substituting back to the original equation.
If you have more questions, comment and I will add more.

$\mathbf{Addendum}$-4 (addressing your last comment and correcting a typo)
The curves for the ranges of $W(k,z)$ are exactly:
$$
C_k(y) =
\begin{cases}
-y\cot(y)+yi,  &y\in(2k\pi,(2k+1)\pi) \text{, if $k\ge 0$} \\
-y\cot(y)+yi, &y\in((2k+1)\pi,(2k+2)\pi)\text{, if $k<0$}
\end{cases}
$$
In Maple they can be plotted as:
restart;
with(plots):
f:=y->-y*cot(y)+y*I;
p0 := complexplot(f(y), y = 0 .. Pi-.2, scaling = constrained);
p01 := complexplot(f(y), y = -Pi+.2 .. 0, scaling = constrained);
p1 := complexplot(f(y), y = 2*Pi+.5 .. 3*Pi-.5, scaling = constrained);
p12 := complexplot(f(y), y = -3*Pi+.5 .. -2*Pi-.5, scaling = constrained);
p2 := complexplot(f(y), y = 4*Pi+.8 .. 5*Pi-.8, scaling = constrained);
p23 := complexplot(f(y), y = -5*Pi+.8 .. -4*Pi-.8, scaling = constrained);
display(p0, p01, p1, p12, p2, p23);

I am just breaking the whole thing into segments and subtracting a bit from the ranges to adjust it for full screen.
Sorry, I don't know MatLab, so I have no idea how you could port this. In Maple they are just plots on the Complex plane.
(Corrected a typo, also. Note that the function is $f(y)=-y\cot(y)+yi$, $\mathbf{not}$ $f(y)=\cot(y)+yi$ as I had on my code).