text:
Q: Rank result set based on generated random number I have a T-Sql query that generates a random number for each record. What I would also like to do is to either add Rank or Row_Number column
I have tried both Rank and Row_Number, but I get the following error when I put an int in the order by clause:

Windowed functions, aggregates and NEXT VALUE FOR functions do not
  support integer indices as ORDER BY clause expressions

SELECT      TOP(4) PERCENT  CONVERT(VARCHAR(10),Getdate(),103) RunDate
        , EM.EmpCode 'Emp Code'
        , D.DepotDepotDescription 'Depot'
        , cast(rand(checksum(newid())) * 10 as decimal(8, 6)) [Random Number]
        , rank() OVER (order by 100) Row
FROM        ttimport.EmployeeMaster EM
        LEFT OUTER JOIN ttimport.PayrollFrequency PF ON EM.FrequencyDesc = PF.DescCode
        LEFT OUTER JOIN ttimport.Departments DPT ON EM.DepartmentName = DPT.DescCode
        LEFT OUTER JOIN ttimport.Depot D ON EM.DepotDepotDescription = D.DescCode

ORDER BY 4

A: Oh I think I see what your problem is here.  I am assuming you want to rank based on the [Random Number] value?  If that is the case, carry on reading!

You can't use a constant in an order by and expect it to sort in any way, which is why your current script throws an error, as rank requires a sort order.
To reference your Random Number column you just need to wrap it in another select or use a cte to the same end:
WITH data AS
(

    SELECT      TOP(4) PERCENT  CONVERT(VARCHAR(10),Getdate(),103) RunDate
            , EM.EmpCode 'Emp Code'
            , D.DepotDepotDescription 'Depot'
            , cast(rand(checksum(newid())) * 10 as decimal(8, 6)) [Random Number]
    FROM        ttimport.EmployeeMaster EM
            LEFT OUTER JOIN ttimport.PayrollFrequency PF ON EM.FrequencyDesc = PF.DescCode
            LEFT OUTER JOIN ttimport.Departments DPT ON EM.DepartmentName = DPT.DescCode
            LEFT OUTER JOIN ttimport.Depot D ON EM.DepotDepotDescription = D.DescCode
)
SELECT *
      , RANK() OVER (ORDER BY [Random Number]) AS Ranking
FROM data
ORDER BY 4


text:
Q: pandas - update value in dataframe from split element of another df element Python newb learning Pandas, so this is likely not the correct way to approach this.
In dataframe df, have columns testID and proj.
testID is an int (eg '23'), and proj is an underscore_separated_name with 3 parts (e.g. bob_xp_sam). I wish to modify all testID values to become, for eg., xp-23 (by capturing the "xp" from proj and concatinating it to each existing testID value.)
This is where I am at, but it doesn't fly:
df['testID'] = df['proj'].str.split('_')[1] +'-'+ df['testID']

I have tried variations, such as:
df['proj'].split('_')[1]
 > AttributeError: 'Series' object has no attribute 'split'

df['proj'].str.split('_')[1]
> TypeError: can only concatenate list (not "str") to list

Pretty sure my approach is wrong - a little direction would be appreciated.

A: You need another str accessor before [1] to access individual element in the list type column (returned by split):
df['proj'].str.split('_').str[1]
#                         ^^^

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set x-axis ticks at the left of each bar with echarts library? I want to show each x-axis tick at the left of the bar, not at the center, but I'm not sure which setting can help me with this, I tried setting the boundaryGap to false, but no luck. Please notice the x-axis type is time.

http://jsfiddle.net/ztcyhwr9/

A: let xAxis = historyTheft.map(item => moment(item[0]).format('HH:mm'));
let series = historyTheft.map(item => item[1]);

....
option = {
   color: ["#009C95","#21ba45"],
   title : {
       text: 'Fuel History',
       textStyle: {
           fontFamily: 'lato'
       }
   },
   tooltip : {
       trigger: 'axis'
   },
   xAxis: {
       type: 'category',
       data: xAxis
   },
   yAxis : {
       type: 'value'
   },
   series : [
       {
           name:'Fuel Theft',
           type:'bar',
           itemStyle: {normal: {areaStyle: {type: 'default'}}},
           data: series
       }
   ]
}

I hope, it will be helpful for you.


text:
Q: Uploaded dynamic file cannot be found I uploaded a dynamic picture named "IMG_4606.png" through admin page and when loading it through another app, it is not being found.
setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'project_headshots')
MEDIA_URL = '/project_headshots/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")`

models.py
 from django.db import models
        class Project(models.Model):
            title = models.CharField(max_length=100)
            description = models.TextField()
            technology = models.CharField(max_length=20)
            image = models.ImageField(null=True, blank=True, upload_to="iad")

`
html code
 img class="card-img-top" src="{{project.image.url}}" alt=""

ERROR:
 `Not Found: /projects/project_headshots/iad/IMG_4606.png
 [25/Sep/2019 16:28:34]
 "GET /projects/project_headshots/iad/IMG_4606.png HTTP/1.1" 404'


text:
Q: How to create multiple screens in Java? I have been playing around with trying to get a menu screen for my game. I have only been able to figure out how to paint a new Screen on top of an existing one; meaning that the actual game is still running behind the title screen. I don't need actual code but just a description of how I would go about this.

A: One way to display a menu would by by using a JDialog outside of your main application window.  Take a look at the How to Make Dialogs tutorial for more information.
Another possibility would be to use JInternalFrame for your game and menu so they can be wrapped in a larger application frame. These are explained nicely in  How to Use Internal Frames


text:
Q: Instant UPS tracking Number I have a client that has a shopping cart. She wants to implement a module that allows the end user to receive a tracking number immediately after purchase.
I am not too sure if this is possible. My concept is that after the store owner ships the purchase, that's when the store owner receives a tracking number that he/she can give to the purchaser. And the purchaser then can start tracking their package.
I guess my question is... "Is it possible to generate a tracking number to give to the purchaser before the store owner even bothers to wrap up the order and send it out.This is so the purchaser can automatically start tracking their purchase and the store owner doesn't have to manually give them a tracking number." ?
I know this would have to require the api. I just need to know if this is possible before I start investing alot of time in trying to build it.
She is using Magento for her shopping cart service.

A: You can use what's called a tracking reference.
From UPS:

When you create a shipment, you can
  assign a shipment reference that helps
  you track quickly and with ease. This
  reference can contain up to 35
  characters in any combination of
  letters and numbers

http://www.ups.com/content/us/en/resources/track/check/#Track+by+Reference
UPS will store this reference number in its system so that you can have customers track with that instead. They will need to click Track By Reference in the Track Packages & Freight tab.

A: It's "possible" in that way that everything in software is possible. There's nothing built-in or third party that I know of that would build this functionality into a system though.  My experience with the UPS shipping API says that even if you created a UPS shipment at the time of ordering, there's a non-deterministic delay before the actual shipping code is created. See mention of tracking reference in this thread.
If you want to move forward with this, it means creating your own tracking system.  Immediately after generating an order you also generate a unique tracking number, and a tracking URL.  This URL points at your system, and returns a page that lists ou;t any UPS, FedEX, etc tracking numbers that are in the system for that order.  If the order hasn't received its number yet, you list a message like "at source warehouse" instead.
Good luck, ERP and fulfillment integration is always a bear.

A: As far as i think Magento has built-in support for such tracking services.
Dont remember if it supports UPS but i guess it does.
Otherwise use the UPS Developer API and play around with their web services.
And for the advance tracking number as you require that feature is also implemented in Magento for shipping packages as well as order tracking etc...

*

*PS: I observed these in Magento 1.4+

A: You can get bundles of shipping forms with fields such as your business name, address, account etc that are prefilled. These bundles also have sequenced tracking numbers.
You would have to get these bundles and upon receiving them enter the starting number and ending number of the stack into a database. From there the person packing the order must be careful to use the correct form with the order.

A: If you interface with ShipWorks and set it up with your UPS account, it both creates your UPS shipping label, gets the shipping charge and posts the UPS tracking number back to Magento. Very smooth integration.


text:
Q: Comparing a number in a UITextField programmatically I'm trying out some basic Objective-C iPhone coding and I'm trying to compare a number in a UITextField in an if statement.
if (UITextField.text == @"1") {
doSomething
}
I think I have to convert the number in the UITextField to something that can be compared with the 1, but I'm not sure what or how.
Could someone point me in the right direction?

A: You can do it in one of two ways:
The better way would be to convert the UITextField text to an integer value, using the NSString function -(int)intValue;
As in:
if ([UITextField.text intValue] == 1) { doSomething}

Alternatively, you can compare two strings, but you have to use a string comparison function, not equals, becuase you're trying to compare the text of the string, not the pointer.
if ([UITextField.text isEqualToString:@"1"]) { doSomething}


text:
Q: Combined hypergeometric distribution of exclusive sets Given the following:

*

*a set of numbers, 1 to 20

*four sets of five numbers from the set above (each number used once)

*a draw of five different numbers from the first set

How would I determine the probability that (at least) 1/2/3/4/5 number(s) will match in any one of the four sets?
To put it another way, each number drawn will be in one of the four sets. How would I determine the probability that (at least) 1/2/3/4/5 number(s) from those drawn will be in the same set?
I am not well-versed in the language of statistics and was not able to find a similar question answered here or elsewhere. If this question proves to be a duplicate, I will happily remove it. In any case, the community's input would be greatly appreciated.


text:
Q: it seems we'll get the paper over the line My supervisor wrote an email:
''We've got feedback on how our journal paper went. It seems quite helpful feedback, in that it seems we'll get the paper over the line.''
Could anyone tell me what he meant by '' in that it seems we'll get the paper over the line?''
Thanks


text:
Q: Should I be using lambdas in TDD? In TDD, wouldn't lambda's be detrimental? How do we test the functionality of a lambda that is encapsulated within another function? It would seem to me that you wouldn't be able to test that lambda to ensure that it was working as expected. The point of unit tests is to test small units of code. Lambdas are small units of code that seem to me, untestable.
Any help, opinions, clarification, or links would be appreciated.

A:
The point of unit tests is to test small units of code.

That doesn't mean that you should feel compelled to write a unit test for all small units of code. Private methods can be small units of code, but you don't test them directly. You test them by testing the code that calls them. Same goes for lambdas.

A: I, personally, would be testing the code that calls the lambda, not the lambda itself. Should you wish to test the lambda itself, you can expose the lambda public-ally and test it.

A: Yes, you should use lambdas even if you desire to test your code.
A lambda misbehaving will lead to the parent function misbehaving as long as the tests for it cover it well.
Finally, some lambdas are indeed better off extracted. Think before spawning lambdas around, and only use them where they make sense and improve the comprehension of the code. If the parent of a lambda misbehaves, it should be easy to pinpoint the issue inside the lambda, if it's there.


text:
Q: Convert list type dictionary to pandas dataframe - python I want to convert dictionary which has two rows. The values are in the first row and keys are in the second row.
Here is my dictionary:
{'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']],
 'columns': ['id', 'gender', 'array_userid' ,'location']}

I want to convert it into a pandas data framelike below:
     id     gender   array_userid   location
0    1      Male     ['a,b,c']      USA
1    2      Male     ['r,g,e']      JAPAN
3    3      Female   ['f,r,b']      UK

A: Use DataFrame constructor with select values of dictionary:
d = {'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']],
 'columns': ['id', 'gender', 'array_userid' ,'location']}

df = pd.DataFrame(data=d['data'], columns=d['columns'])
print (df)
  id  gender array_userid location
0  1    Male      [a,b,c]      USA
1  2    Male      [r,g,e]    JAPAN
2  3  Female      [f,r,b]       UK


text:
Q: A non-convex optimization problem Given matrices ${\bf A} \in \mathbb R^{m \times n}$ and ${\bf B} \in \mathbb R^{p \times n}$ and scalar $c \in \mathbb R$,
$$\begin{aligned}
  &\underset{{\bf x}, {\bf y} \in \mathbb R^n}{\text{minimize}}  & &  {\bf x}^\top {\bf y} \\
  &\text{subject to}& & {\bf A} {\bf y} \preceq {\bf 0}_m, \quad \| {\bf B} {\bf x} \|_2 \leq c \\
  \end{aligned}$$
What makes this problem non-convex is that fact that both variables $\bf x$ and $\bf y$ are multiplied together in the objective. I am looking for suggestions and resources to tackle the non-convex optimization problem above, which I came across at work. Any help is appreciated.

Motivation
This is a problem in transportation flow optimization, where $\bf x$ are the returns and $\bf y$ are the desired weights. The objective is to maximize the total return subject to linear constraints on weights and a norm constraint on the returns vector.


text:
Q: Connect to SQL Server (on Linux) failed I have installed the new SQL Server on Ubuntu in Virtual Machine.
I can connect from SSMS on Windows computer to this SQL Server, but cannot connect from another computer.

Failed to connect to server 192.168.0.10.
  (Microsoft.SqlServer.ConnectionInfo)
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: Named
  Pipes Provider, error: 40 - Could not open a connection to SQL Server)
  (Microsoft SQL Server, Error: 53)

Both computers are in the same domain.
What to correct? what is wrong?
ping from both windows computers to Ubuntu works OK.

A: I'd go through the following troubleshooting list:

*

*Verify that SQL is up and running: systemctl status mssql-server

*Verify it is responding: sqlcmd -S localhost -U SA -Q "SELECT @@Version"

*Verify that VM is connected to the host: ping 192.168.0.10 // that is from host

*Verify that port is opened (from host): PortQry.exe -n 192.168.0.10 -e 1433

Assuming you do not have any other firewall rules and all verification passes you can do from your host:
sqlcmd -S 192.168.0.10  -U SA -Q "SELECT @@Version"

BTW, I'm not networking guru, but Zero in your VM's IP address looks strange:
192.168._ 0 _.10

A: This issue appears to be related to the way you have configured your virtualized operating system network.
It would help me know which virtualization software you are using.
Check the virtual network interface and make sure it is in bridge mode with the physical network interface.
All machines has to be in the same subnet.


text:
Q: How old is the word "upskirting"? In the comments section of this question the subject derailed slightly: is the word upskirting dependent on today's technology or is it older?

A: The first example of upskirting quoted by the OED is from 1998. And it would appear that it does not predate digital photography.

The habit or practice of taking upskirt photographs or videos. See
  upskirt adj. and n.
1998   Re: Lets start Interesting Post in alt.native (Usenet
  newsgroup) 12 Sept.   Thus begins the fine distinctions of 'privacy'
  rights in public places, of which the issue of 'upskirting' is just
  one.
2000   Atlanta Jrnl. & Constit. (Nexis) 10 Oct. a12   Beginning today,
  Ohio law increases the penalties for secretly taking pictures up a
  woman's skirt.., called 'upskirting'.
2005   West Australian (Perth) (Nexis) 17 Feb. 38   He would hide the
  camera inside a backpack..and..film up his victims' skirts (known as
  upskirting).
2012   C. Quigley & D. Pollock What on Earth are you Wearing? (new
  ed.) 97/1   When my mum was at school, they wouldn't let the boys wear
  patent-leather shoes because they thought they would use them to look
  up girls' skirts. I guess this was the beta version of upskirting.
2017   Times (Nexis) 15 Aug. (Times 2 section) 7   The offence of
  voyeurism doesn't cover upskirting.

A: The term upskirt appears to have been used as early as in June 1998:

"A video, usually taken in a crowded location such as a shopping mall, that is shot up a woman's skirt" without the woman's permission or even knowledge. (Source: Word Spy)
Urban Dictionary's earliest entry for upskirting is from 2006, but Word Spy found a 1998 mention in the Washington Post:

*

*What began as a small photo gallery on the Internet a couple of years ago has rapidly expanded to more than 40 such "Upskirt" sites, including one devoted entirely to shots taken up skirts in Maryland, said [Alexandria detective Harold] Duquette, who has been tracking the trend.
—Patricia Davis, "Video Peeping Toms Seeing More Trouble," The Washington Post, June 7, 1998

(nancyfriedman.typepad.com)

A: upskirt (adj.)  Etymonine.com
by 1997, from up (adv.) + skirt (n.). As a verb by 2008.

"Upskirt" videos, usually taken using low-hanging bags, feature
  up-close-and-personal crotch shots of leggy, panty-clad young women.
  ["Weekly World News," Sept. 29, 1998]

The word is ~ 20 years old. The practice? Since Adam and Eve were evicted from the garden! Small cameras etc (digital) have facilitated such.  I suspect though the practice of 'photographing' occurred back in the 8mm and flash photography days.

A: The earliest use I can find of upskirt in a related sense is in Jack van Niftrik's 1980 novel Where Rumour Never Reaches:

He experienced the contrasting sensations of sorrow at the plight of the Nongamas, the Bikos and the Molefes of the world and a flash of sexual desire by a breathtaking upskirt glimpse of honeyed thighs and white triangle of underwear.

This use is of course an adjective rather than a verb, and it seems that adjective and noun uses are by far the most common. The OED only lists adjective and noun senses, though it does list the noun upskirting as a separate noun (earliest attested use being in 1998) which it says is derived from the adjective rather than from upskirt as a verb. (This does not mean it is denying a verb use that it doesn't record).
Of course, English speakers verb adjectives and nouns all the time, whether directly or to form a gerund form like upskirting, so as long as we can find the adjective upskirt as something deliberately sought (rather than the accidental glimpse van Niftrik's novel describes) we can expect it. The OED has both adjective and noun forms of upskirt attested in 1994.
To conjecture about how far back it may go we can ask how far back we could reasonably expect to find upskirting. Pornographic pictures showing a view up a skirt exist from the early days of photography, (and in painting Fragonad's Les Hasards heureux de l'escarpolette shows a man enjoying such a view, without sharing it with the painting's audience, as far back as ca 1767 while Marilyn Monroe's famous revealing moment in The Seven Year Itch in 1955 was not the earliest in moving pictures by a large measure) but since the gerund form generally refers to deliberately surreptitious pictures taken without consent, the phenomenon of upskirting really depended reasonably fast film and either on the telephoto lens, or small "spy" cameras, so really not much earlier than the 1980s as something that wouldn't need remarkably exotic equipment. (Ubiquitous mobile phone cameras of course make it much easier today).
One only needs terms when discussing something though, which means not just someone actively taking such photographs, but a community of people sharing them and discussing the taking of them. That doesn't really seem to have predated Usenet in any large-scale and continuous manner, so we could take 1980, being the time that it first became possible to share binary files such as photographs on Usenet, as the earliest it could possibly go back to. Realistically we're probably talking about the late 80s or early 90s, but almost certainly no earlier than 1980, and clearly by the time of the first OED attested use in 1998.

A: The word upskirt to refer to photographs taken up women's skirts was coined no later than 1995.
The Internet domain upskirts.com was registered on 1995-10-13, and upskirt.com followed shortly after on 1996-06-10.
The term upskirt predates smart phones or other cell phones with cameras. A Washington Post article reprinted in the June 8, 1998, Amarillo (TX) Daily News warns:

In what they describe as a growing trend, police are beginning to catch video voyeurs trying to shoot private parts in public places. These men are aiming the latest compact camcorders up women's skirts in crowded stores and shopping malls, parks and fairs - and often posting the pictures on the Internet.
. . . [P]olice arrested a 21-year-old man who was holding a palm-size video camera under a woman's dress. . . [P]olice nabbed a 19-year-old man toting a bulky VHS video camera. He was angling for similar shots in the china department. . .
What began as a small photo gallery on the Internet a couple of years ago has rapidly expanded to more than 40 such "Upskirt" sites. . .


text:
Q: Isclosed on Task Object not working correctly I am trying to have my tasks be marked as completed with isclosed mapping to true because I need them to appear in an activity history SOQL query.
I am creating a task with the following field mappings and am very confused as to why isclosed is mapping to false. Doesnt "Completed" move isclosed to true.
            'Subject' => '[Outreach][Out][Outbound][Gmail] Re: Invoice Purchasing',
            'Description' => 'Running a test',
            'ActivityDate' => Date.today()- 1,
            'Status' => 'Completed',
            'WhatId' => Opportunities[0].Id

After I insert the tasks, I am checking the following fields and finding the following results
System.debug(tasks[0].Status); --> Completed
System.debug(tasks[0].IsClosed); ---> False

A: IsClosed is not true until the record is loaded from the database and the Status is a Closed value. This typically means that you need to use after triggers in order to reliably detect when a task has closed. I verified this behavior with the following code:
trigger taskTriggerX on Task (before insert, after insert) {
    for(Task record: Trigger.new) {
        if(Trigger.isBefore && record.Subject=='Before' && !record.IsClosed) {
           record.addError('Is Closed is false in before insert');
        }
        if(Trigger.isAfter && record.Subject=='After' && !record.IsClosed) {
           record.addError('Is Closed is false in after insert');
        }
    }
}

And the following execute anonymous script:
Task[] tasks = new Task[] {
    new Task(Subject='Before',Status='Completed'),
    new Task(Subject='After',Status='Completed')
};
Database.insert(tasks, false);
System.assert(tasks[0].Id == null);
System.assert(tasks[1].Id != null);

Alternatively, if you're checking the data in memory, you need to remember to query the records back from the database:
Task[] tasks = new Task[] {
    new Task(Subject='Before',Status='Completed')
};
Database.insert(tasks, false);
tasks = [SELECT IsClosed FROM Task WHERE Id = :tasks];
System.assert(tasks[0].IsClosed);


text:
Q: Spring Sending Message RAbbitMQ Rollback Hi I use spring rabbit to send message to rabbitmq.
I want to rollback sending message how can I do that ,my goal is to achive that in writing process.
Can anyone share code sample


text:
Q: How to set the environment for Grunt? I defined a task section of my Gruntfile.js for two environments -- development and production. But I don't understand, how Grunt decides, wheter to use which environment section.
Gruntfile.js
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    less: {
      development: {
        options: {
          paths: ["public/css"]
        },
        files: {
          "public/css/style.css": "public/css/style.less"
        }
      },
      production: {
        options: {
          paths: ["public/css"],
          plugins: [
          ],
          modifyVars: {
          }
        },
        files: {
          "public/css/style.css": "public/css/style.less"
        }
      }
    },
    watch: {
      css: {
        files: 'public/css/*.less',
        tasks: ['less'],
        options: {
          livereload: true,
        },
      },
    }
  });

  // Load the plugin that provides the "less" task.
  grunt.loadNpmTasks('grunt-contrib-less');
  // Load the plugin that provides the "watch" task.
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Default task(s).
  grunt.registerTask('default', ['less', 'watch']);

};

How to let Grunt know, which environment is currently active?

A: To alternate I suggest you to create a development task and run it with grunt development
// Default task(s).
grunt.registerTask('default', ['less:production', 'watch']);

// Development task
grunt.registerTask('development', ['less:development', 'watch']);

A: You can have two different grunt files one for development environment and one for production (for instance gruntfile.dev.js and gruntfile.prod.js) and specify which file should be considered as corresponding grunfile by specifying file name in your npm grunt command like this
grunt --gruntfile gruntfile.prod.js

Remember you can define two aliases for your dev and prod grunt commands
see below
"scripts":
 {
    "build:prod": "grunt --gruntfile gruntfile.prod.js",
    "build:dev": "grunt --gruntfile gruntfile.dev.js",
 }

so, by typing npm run build:prod the prod gruntfile will be run and by typing npm run build:dev dev gruntfile will be run.
By doing so you have more flexibility and it becomes easier to maintain changes associated to your grunt configuration


text:
Q: What might I do with the familiar conjured by Conjure Familiar? What is the Conjure Familiar spell for?
Sure the familiar looks neato, but may I treat it as I would a familiar in another game?  So far, it doesn't speak to me, it doesn't supply me with wishes, and it doesn't lead me on a quest.
Have I exhausted what I can do with a familiar after I've successfully conjured it, or is there more to it than meets the eye?

A: A familiar is just a minion. It's only purpose is to attack enemies, and will vanish after 60 seconds. It is possible to use a familiar to level up your combat skills by attacking it, but other than that, it just attacks enemies.


text:
Q: Are VMware Fusion images compatible with ESXi? If I create a VMware virtual image on my Mac (with VMware Fusion 2) it creates a file line Ubuntu.vmwarevm.  Will this file be compatible with a ESXi 4.0 server? In general, are virtual machines for VMware all the same format?

A: In theory, yes, they do.  That being said, not everything is as simple as the marketing would have you believe.  A more obvious example is that on OS X you can create an OS X vm, but you will have a hard time getting that to run on another platform because there are certain requirements that are specific to the Fusion product.
There are aslo different vmWare "hardware" versions to consider and the documentation of the chosen source/destination will outline differences and compatibility issues.
So there is not a strait forward answer for this question.  Anyone who tells you simply yes or no has not tried to do this himself, or is a marketing guy for vmWare...  :-D

A: Virtual machines created with Fusion 2 should be compatible with the latest version of ESX/ESXi server.
From the new virtual machine wizard:

All you will need to do is copy the root folder that contains the .vmx (configuration file) and the .vmdk (virtual hard drive) folders to another machine and import and it should be able to run just fine.
(In addition, you may however lose snapshot/paused state going from one product to another... I have not tested this and cannot be certain.)


text:
Q: CSS Aligning Dynamic Div Having a little issue with floating and a responsive layout.  I have a div container that has a left and right div container inside.  The two have to be on the same "row" but when div container "RIGHT" is set to 100%, it moves it down to the next row.  I have made a quick fiddle here.
http://jsfiddle.net/v5tnshjw/1/

LEFT

RIGHT

.row {
    float: left;
    width: 600px;
    height: auto;
    margin: 0px auto;
}
.leftBox {
    float: left;
    height: 50px;
    background-color: red;
    width: 80px;
}
.rightBox {
    float: left;
    height: 50px;
    width: 100%;
    background-color: blue;
}

The box on the right needs to flow with the browser width but stay on the same line.
Any help or pointers would be great!  Thanks in advance.

A: You could set the inner divs to display:table-cell with the parent as display:table and table-layout:fixed:

.row {
    float: left;
    width: 600px;
    height: auto;
    margin: 0px auto;
    display:table;
    table-layout:fixed;
}
.leftBox {
    display:table-cell;
    height: 50px;
    background-color: red;
    width: 80px;
}
.rightBox {
    width:100%;
    height: 50px;
    display:table-cell;
    background-color: blue;
}

LEFT

RIGHT

A: You can also use the CSS3 calc() function :

.row {
    float: left;
    width: 600px;
    height: auto;
    margin: 0px auto;
}
.leftBox {
    float: left;
    height: 50px;
    background-color: red;
    width: 80px;
}
.rightBox {
    float: left;
    height: 50px;
    width: calc(100% - 80px);
    background-color: blue;
}

LEFT

RIGHT

A: If the left box also needs to scale:
.row {
    float: left;
    width: 600px;
    height: auto;
    margin: 0px auto;
    }
.leftBox {
    float: left;
    height: 50px;
    background-color: red;
    width: 20%;
}
.rightBox {
    float: left;
    height: 50px;
    width: 80%;
    background-color: blue;
}


text:
Q: Merge requests never complete after gitlab omnibus 14.3.6 I'm running the omnibus gitlab package 14.0.12. After updating >= 14.3.6, merge requests no longer work correctly.
The 'assignee', 'reviewer', and 'time tracking' panels in the right sidebar just spin indefinitely. enter image description here
It works again when I revert back to 14.0.12.
I've been unable to find anything useful in the release notes, logs, or a packet capture.
Could anyone point me in some direction please?

A: Gitlab was fine, my own browser was just too old.
I was using Firefox 70 and apparently it breaks some of the JS on gitlab. I had the same 'invalid regexp group' error in the console as in this issue:
https://gitlab.com/gitlab-org/gitlab/-/issues/339482


text:
Q: Workarounds for Hibernate's lack of delete-orphan support for one-to-one and many-to-one relationships? Hibernate has no support for "delete-orphan" cascading of one-to-one or many-to-one relationships.  I recently discovered this, and it's giving me a serious headache.  I have a couple classes in my model that were designed such that the child has no real world meaning outside of the parent.  I only have one DAO for the parent, and not a separate DAO for the child class.
This works:
parent.getChild().setProperty("something");
parentDao.save(parent);

This doesn't do anything:
parent.setChild(null);
parentDao.save(parent);

This is highly unfortunate because now I have to rethink my DAO layer and a few of the operations of my service layer.
Has anyone worked around this limitation in an elegant way?  I'd really like to only concern myself with persisting parent objects.  In this particular case, there is no reason to deal with child persistence except to make Hibernate happy, and only in the case of deleting children.

A: It appears to be a draw back in the framework they MAY address, hopefully soon
http://opensource.atlassian.com/projects/hibernate/browse/HHH-2608
That ticket was opened in 2007 and the latest post complaining about the problem was as recent as a month ago.
What I am doing is putting a property on my object called isMarkedForDeletion.  And if that returns true, i have my dao or my service do an explicit delete.  It is definintely NOT as good as delete-orphan would be, but it works well enough in the spring+hibernate framework.
I will keep an eye on this post as this is a VERY important question.

A: The workaround described here https://forum.hibernate.org/viewtopic.php?p=2379216 worked for me. It uses @OneToMany association with a single element on the "many" side to implement a @OneToOne association and solve the remove-orphans problem.

A: Heureka, fixed in Hibernate 4.27
https://hibernate.atlassian.net/browse/HHH-6484
(not tested)

A: Write database on update trigger on child table.  If parent key is null delete the record from child


text:
Q: Use \n in Python as a normal string I am making a string calculator using numbers. For example:
154 + 246 = 154246
So the user will enter an input of a group of numbers, to separate the numbers using \n. As you know, \n is used to make a new line, but I need to use at as any normal string. I need to separate the numbers using \n into a list.
Code:
num_list = []
# this function will add a number to the list
def ask_num():
    # ask for a number (we will make it a string so we can add comma and /n)
    num = input("Enter numbers: ")

# run the function for asking numbers
ask_num()

A: You can escape the \n using an other \.
>>> print("\\n")
\n
>>> print("\n")

>>> print("/n")
/n

In your case, you asked for /n, which is not used for a newline, so you can normally use it in a string.

A: You can use
r"\n"

or
"\\n"

A: Successful solution:
def ask_num():
    num_list = []
    # ask for a number (we will make it a string so we can add comma and /n)
    num = input("Enter numbers: ")
    # put the num in the list
    num_list.append(num)
    # seperate the numbers
    num_list = num.split(r"\n")
    # print the list
    print(num_list)


text:
Q: How to start MySQL server automatically with application start? How can I start MySQL server automatically with C# WPF application start? I am using xampp. I want to start xampp and then MySQL automatically when the app starts, how to achieve it? I tried this:
ServiceController controller = new ServiceController();

controller.MachineName = ".";
controller.ServiceName = "mysql";

// Start the service
controller.Start();

but it is not working as it says that MySQL service does not exist.
Is this a good way how to do it or is there another way how to start xampp and MySQL automatically with app start so the user does not need to start it each time on his own?


text:
Q: Delete CRLF in Row ending in CRLF I have been looking for some python code that will count delimiters in a record but can't seme to find any examples.
I have a pipe delimited text file with double quotes for text qualifier with CRLF defining the end of the row. As always some columns have CRLF in the text which confuses the output format.

"Start of Record"|""|"SomeText"|"More stuff with CRLF then more text"|"Could even have "CRLF included "|""CRLF

Currently I have the file open in notepad++ and was manually going through using regex
 (?<!")\r\n
to find CRLFs without the preceeding double quote. As I have a few large files to fix I would like to get python to go to the start of the record, count the 5 pipes and delete any CRLF that are in that count but have only a very basic knowledge of python.
I have some basic python code to find and replace some characters but don't think it's good enough to do what is required.
replacement = {'","':'"|"'}
lines = [] with open('C:\OriginalRplPipe.txt') as infile:
for line in infile:
    for src, target in replacement.items():
        line = line.replace(src,target)
    lines.append(line)with open('C:\PipeDel.txt', 'w') as outfile:
for line in lines:
    outfile.write(line)
    print ("Finished")

A: Maybe the following code is what you are looking for. Unfortunately there is a flaw which, so far, I cannot overcome: if a CRLF appears between 2 double quotes, but immediately after the first one, it is not removed. Apart from that, the code works for me.
from pathlib import Path
import re

regex = rb'(".*?[^"])\r\n(.*?")'
reo = re.compile(regex)

in_file = Path('input.txt')
out_file = Path('output.txt')

old_content = in_file.read_bytes()    # read as binary file although it is a text file!

new_content = reo.sub(rb'\1\2', old_content)

out_file.write_bytes(new_content)    # write as binary file although it is a text file!

But now see my second answer.

A: Meanwhile I managed to remove the flaw in my first answer. Below is the new code which should do what you want. It should work independently of the number and position of CRLFs in the fields of your record.
from pathlib import Path
import re

regex_lin = rb'(".*?"\|".*?"\|".*?"\|".*?"\|".*?"\|".*?"\r\n)' # split file into lines
reo_lin = re.compile(regex_lin, re.DOTALL)
regex_rec = rb'".*?"'                                          # split line into records
reo_rec = re.compile(regex_rec, re.DOTALL)

in_file = Path('input.txt')
out_file = Path('output.txt')

old_content = in_file.read_bytes()                             # read as binary file although it is a text file!

lines = reo_lin.findall(old_content)
new_content = b''
for line in lines:
    old_records = reo_rec.findall(line)
    new_line= b''
    for record in old_records:
        record = record.replace(b'\r', b'')
        record = record.replace(b'\n', b'')
        new_line = new_line + record + b'|'
    new_content = new_content + new_line + b'\r\n'

out_file.write_bytes(new_content)                              # write as binary file although it is a text file!


text:
Q: List all forecast CSV files exported to AWS S3 bucket when using AWS Forecast Export Job I have trained a Predictor on AWS Forecast, and used it to make some forecasts.
I want to get these forecasts as CSV files. To do so, I created a "ForecastExportJob".
After the exportation is done, I can successfully see the CSV files in my S3 bucket.
I would like to download them programmatically, so is there a way to have a list of S3 keys that correspond to the CSV files created with the "ForecastExportJob" command?
I could list all objects in the destination buckets and filter them, but I am wondering if there is a "more elegant" solution to my problem.

Put it simply, I would like to know if there is an AWS command that can list the files created by the "ForecastExportJob" command:

*

*electricityforecast_export_job_2021-01-04T06-40-23Z_part0.csv

*...

*electricityforecast_export_job_2021-01-04T06-40-23Z_part7.csv

Note: I am using boto3
Thank you in advance and happy new year!


text:
Q: Save text in memory as attachment I want to save text from a variable in memory as a couchdb attachment. Is it possible to do so without writing it as a file?
Also, I don't have all the text at the same time. I gather the text making HTTP requests one by one. Is it possible to upload the text to couchdb as attachment in realtime?
I am using nodejs.


text:
Q: Get redirected URL without making a request to that URL Say I have a URL, http://www.myurl.com/ and when plugged into my browser, it redirects to http://www.anewurl.newcomain.com/. How can I get just the redirected URL without actually making a request to it?
I've tried things like
r = requests.get('http://www.myurl.com/', allow_redirects=False)

to no avail. That is, the request object gives me no useful information:
{'Content-Type': 'text/html', 'X-Request-ID': 'c6b1ce55-d89c-4d56-82ba-6b9fab1432e2', 'Accept-Ranges': 'none', 'Proxy-Connection': 'keep-alive', 'Location': 'http://www.myurl.com/', 'Server': 'nginx', 'Content-Length': '178', 'X-Dc': 'chi2', 'X-Permitted-Cross-Domain-Policies': 'none', 'X-Download-Options': 'noopen', 'X-Content-Type-Options': 'nosniff, nosniff', 'Date': 'Thu, 15 Dec 2016 20:12:42 GMT', 'X-XSS-Protection': '1; mode=block'}

To emphasize: if I remove allow_redirects=False and look in the headers, I can find what I'm looking for, but this, I think, includes a request at http://www.anewurl.newcomain.com which I want to avoid. Note the same can be said of things like urllib.request.urlopen(http://www.myurl.com/).url, which returns the redirected URL, but I fear also must be making a request to it.
Any help is appreciated, including the pointing out of incorrect assumptions, e.g., perhaps I am not actually making a request to the redirected URL.
Thanks.


text:
Q: Passing field name as parameter to script in ModelBuilder? I am new to ModelBuilder.
I am running a python script from ModelBuilder that requires as it's parameters a table view and specific field names from that tableview. Essentially the script is looking for information from specific fields without knowing what the user may call the fields.
For example, the script needs
an 'address' field and the user may have identified their address field as 'street' in their table.
I am wanting a dropdown field populated by the tableview that the user can select the correct field from and pass that field name to the script as a parameter. I have tried using
the Get Field Values tool and arcpy.GetParameterAsText(1) returns the value of the field but what I need is the field name itself.
I was thinking there should be a way to create a list and populate it with something like:
fieldList = []
fields = arcpy.ListFields(tablePath)

but I have no idea how I would do this in ModelBuilder and be able to use that list to populate and parameter list the user could then use to select the correct field.

A: For a script tool, you could do something like this:

To create a fieldList from the fields that the user has selected, try this in your script:

*

*fieldList = Attributes.split(";")


text:
Q: How to detect if using Key or KeyPath I just ran into the problem where I was trying
[object valueForKey:key]

when I should have used
[object valueForKeyPath:key]

As a quick fix I did this.
if ([[sortDescriptor key] rangeOfString:@"."].location != NSNotFound ) {
     sectionHeader = [object valueForKeyPath:[sortDescriptor key]];
} else {
     sectionHeader = [object valueForKey:[sortDescriptor key]];
}

Is this the best way to handle this scenario?


text:
Q: Conditional Tags Based on Previously Viewed Posts I was looking at the Conditional Tags Archive and was wondering if it's possible to show a widget depending on different posts / pages a visitor has previously viewed.
For example, if I had a car blog and the blog layout contains a sidebar widget that will display a promotion.
This promotion will vary depending on the types of posts a visitor has viewed.
So if a visitor was looking at posts that have to do with the Mazda brand, I'll be able to write a condition for the widget in the sidebar that reads, if he visited blog post X, Y or Z, then this widget will display a promotion for a Mazda Car Dealership near him.
Same for other car types and promotions.
I'm guessing some would it'd be impossible, but I was thinking if tracking a visitor with cookies, it would seem like a viable idea.
Thoughts or suggestions on where to go from here?


text:
Q: unable to redirect page using window.location in js i want to redirect to home page using js function by its not redirecting to different page. getting error like this

file:///D:/dotnetapp/@Url.Content( net::ERR_FILE_NOT_FOUND

 <button class="btn btn-lg btn-primary btn-block btn-signin" type="submit" onclick="login()">Sign in</button>

<script>
    function login() {
        var userid = document.getElementById("Username").value;
        var password = document.getElementById("password").value;
         if (userid == "administrator" & password =="password")
         {
            window.location = "home.html";
        }
        else
        {
            alert("username / password is incorrect");
        }
    }
</script>

A: If it is on the same directory level/relative, you can use this instead.
window.location.href = '/home.html';
// or window.location.href = 'home.html';

Just some additional information for your reference,
window.location is an object with various properties such as href and hash, whereas window.location.href is a string itself. Either ways, setting both window.location and window.location.href to a string value should lead to a redirection to another page.

A: Try using
window.location.href = "home.html"

This link could be useful


text:
Q: Can I run a customized Circle CI build script using the 'nightly build' feature? I'm trying to set up a scheduled job that runs 10 Circle CI builds overnight for feature-test-failure purposes.
I found the Circle CI nightly build documentation and I was able to implement it, but each build is a full build (running all pre and post test processes).  I just want to run one suite of tests (we are running multiple in our normal builds).
I know I could accomplish this with an if statement inside of the circle.yml file.
I was hoping for a more elegant solution.
Anyone have a better idea?

A: Currently an if condition is the only thing we can offer in this case. Sorry about that :(

A: Okay, so technically not an if statement... We ended up doing this.  It's not the greatest but it cuts it down to one line (plus the comment).  We are on Heroku, so we used Heroku Scheduler to run the bash script (that passes the RUN_NIGHTLY_BUILD parameter that to Circle CI and kick off the build (via POST).
./circle.yml:
override:
   # will run if not nightly build
   - test -n "${RUN_NIGHTLY_BUILD}" || bundle exec rake spec:units


text:
Q: git для проекта с большой иерархией Имеется проект который имеет сложную иерархию версий и подверсий, которые разрабатываются и поддерживаются параллельно. На данный момент в качестве системы управления версиями используется svn. Подходит ли в таком случае git как альтернатива? Насколько я понимаю, в репозитории git все крутится вокруг одной главной ветки, а все параллельные, в итоге, сливаются в одну, что не накладывается на мой случай.

A:
Насколько я понимаю, в репозитории git все крутится вокруг одной главной ветки, а все параллельные, в итоге, сливаются в одну

технически — нет, не «крутится». «сливать в одну» или работать с разными ветками одновременно — это вопрос исключительно организационный.

Подходит ли в таком случае git как альтернатива?

если не заострять внимание на том, что термин «ветка» в программах git и svn описывает довольно разные (во всех отношениях) сущности, то для работы с «ветками» программа git подходит гораздо лучше программы svn.

для иллюстрации стоит привести цитату из статьи Скота Чакона (Scott Chacon), автора книги "Pro Git":

В Git, ветки не ругательное слово - они используются и объединяются очень часто, во многих случаях разработчики будут создавать новую ветку для каждой новой возможности и объединять их между собой по несколько раз в день, и это, как правило, безболезненно. Вот, что в первую очередь поразило меня в Git, и, на самом деле, изменило мой подход к разработке.
Когда вы создаете ветку в Git, это происходит локально и очень быстро.

и ссылку на главу 9 из упомянутой книги: 9.1 Git как клиент, 9.2 Миграция на Git, где в первую очередь внимание уделено как раз программе svn.


text:
Q: Stop access to the iCloud notes app on a lost iPad, but keep my notes on the iCloud website? My iPad is lost.
I was using the notes app.  I've changed my Apple ID password to stop someone logging in.
I want to keep my notes and access them by logging into the iCloud website on my laptop.
I want to stop anyone accessing my notes using the app on my lost iPad.  Is this possible please?

A: Did you enabled the 'Find my iPad' option on your lost device? If so, you can go to iCloud.com and remotely delete all data on the iPad without losing your notes in iCloud.
If not, did you use a passcode? All data on the iPad is encrypted and it is highly unlikely that someone evil finds your (locked) device and tries to hack into your notes.
Another workaround would require you to use the Notes application on an OS X computer. Set up your iCloud device and another email account that supports notes (most IMAP accounts do). Then open the Notes application and move all of your notes to the new account. This will eventually sync with your lost device, but you would have to access your notes in the new account.
I do not think that there is a perfect answer to your problem, everything left to do is some damage control.


text:
Q: How can I have a frozen horizontal header in a scrollable QTableWidget? I am creating a single-column QTableWidget for my application (_tw). I want this QTableWidget to be scrollable, both vertically and horizontally. I hid the vertical header but I need the horizontal header.
The problem is that I can't get a "frozen" (insensible to horizontal scroll) horizontal header, and the text of this header is often hidden in the scroll. Furthermore, after the vertical scroll bar, I can see pixels of my horizontal header, which is unwanted.
I have tried to tackle the issue differently, as I already struggled to make this table scrollable horizontally. Unsucessfully, I tried to repositionate the header each time the scroll bar is moved. Even if I failed, this feels more like a workaround than a solution.
_tw->setHorizontalScroolBarPolicy(Qt::ScrollBarAlwaysOn);
_tw->setHorizontalScroolMode(QAbstractItemView::ScrollPerPixel);
_tw->verticalHeader()->hide();
_tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
_tw->horizontalHeader()->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
_tw->horizontalHeader()->setFixedHeight(_headerHeight);
_tw->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);

_tw->horizontalHeader()->setFixedWitdh(_tableWidth);
_tw->setFixedWidth(_tableWidth);

_tw->setColumnWidth(0, _tableWidth + _offset);

I expect the horizontal header to be at the same width of the table, and insensible to scroll. It is currently not the case: the header has the size of the column (bigger than what is displayed on the screen). Since the headter text is aligned horizontally, it is not shown and moves with the scroll.

A: You can try creating a custom class that will apply header-like area to any QAbstractScrollArea (including QTableWidget) and setting viewport margins on your tablewidget. You won't need to mangle with header not beeing scrolled, but if you need some header-like behaviour, you will need to do it manually.
Untested code:
class Header: public QWidget
{
public:
    Header(QAbstractScrollArea* parent=nullptr): QWidget(parent)
    {
        setFixedSize(parent->width(), 40);
    }

    virtual void paintEvent(QPaintEvent* event)
    {
        QPainter painter(this);
        QFont font("Arial");
        QFontMetrics fm(font);
        QRect txtRect;
        QString txt = "Header_name";
        txtRect = fm.boundingRect(txt).trabslated(dx, dy);//translate it to position you want
        painter.setFont(font);
        painter.painter.drawText(txtRect, txt);
    }
};

Then set viewport margins on your tablewidget, something like this:
_tw->setViewportMargins(0, 40, 0, 0);

Then just create instance of Header:
Header *header = new Header(_tw);

If this code works - Romha Korev gets the credit. I took the idea from his answer to this question.
Hope this helps.

A: All the others solutions I tried gave me some pixel gaps that I found too noticeable. I decided to go big, and create a custom QWidget specifically for answering this problem.
Basically I just created a QWidget simply containing the QTableWidget, with no header. For the sake of keeping everything at the same size, I aded a line, which is going to stay empty and will be hidden by a QPushButton. I give this line the height I want for my header, for the same reason.
After modifying the behaviour of the QTableWidget so it would skip the first line, I created a QPushButton with my custom widget as the parent. Fortunately enough in my application, they have the same look as the other QHeader. To make the button "on top of" the empty line, since this is a custom widget, a simple button->move(0, 2); did the trick.


text:
Q: azure: server-side SVG to PNG in node.js azure function app? nothing works does anyone know how to convert SVG images to PNG (or JPG) on the server side? i've a node.js script that needs to do this and send the PNG to the caller. no rendering can be done on the client, it can only read PNGs or JPGs. i've looked at phantomjs, anychart-nodejs, canvas and others. they simply don't install or in the case of phantomjs, it installs and works in some cases and not in others. phantomjs works perfectly in node.js on a windows 10 computer, btw.
any ideas? thanks!

A: i figured it out. using the sharp js library did the trick. it's a bit difficult to get going, though. send me a message if you have trouble; i'll post my solution here.

A: My idea is to render a SVG image to canvas HTML element and then to convert the canvas one to a png image.
Here is my sample code demo.html as below, which I am using a pure JavaScript package canvg/canvg in browser.
<html>
<head>
<script type="text/javascript" src="https://unpkg.com/canvg@3.0.4/lib/umd.js"></script>
</head>
<body>
<svg id="svg_logo" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     height="300" width="300" viewBox="0 0 300 300">

   <defs>
     <g id="SVG" fill="#ffffff" transform="scale(2) translate(20,79)">
        <path id="S" d="M 5.482,31.319 C2.163,28.001 0.109,23.419 0.109,18.358 C0.109,8.232 8.322,0.024 18.443,0.024 C28.569,0.024 36.782,8.232 36.782,18.358 L26.042,18.358 C26.042,14.164 22.638,10.765 18.443,10.765 C14.249,10.765 10.850,14.164 10.850,18.358 C10.850,20.453 11.701,22.351 13.070,23.721 L13.075,23.721 C14.450,25.101 15.595,25.500 18.443,25.952 L18.443,25.952 C23.509,26.479 28.091,28.006 31.409,31.324 L31.409,31.324 C34.728,34.643 36.782,39.225 36.782,44.286 C36.782,54.412 28.569,62.625 18.443,62.625 C8.322,62.625 0.109,54.412 0.109,44.286 L10.850,44.286 C10.850,48.480 14.249,51.884 18.443,51.884 C22.638,51.884 26.042,48.480 26.042,44.286 C26.042,42.191 25.191,40.298 23.821,38.923 L23.816,38.923 C22.441,37.548 20.468,37.074 18.443,36.697 L18.443,36.692 C13.533,35.939 8.800,34.638 5.482,31.319 L5.482,31.319 L5.482,31.319 Z"/>

        <path id="V" d="M 73.452,0.024 L60.482,62.625 L49.742,62.625 L36.782,0.024 L47.522,0.024 L55.122,36.687 L62.712,0.024 L73.452,0.024 Z"/>

        <path id="G" d="M 91.792,25.952 L110.126,25.952 L110.126,44.286 L110.131,44.286 C110.131,54.413 101.918,62.626 91.792,62.626 C81.665,62.626 73.458,54.413 73.458,44.286 L73.458,44.286 L73.458,18.359 L73.453,18.359 C73.453,8.233 81.665,0.025 91.792,0.025 C101.913,0.025 110.126,8.233 110.126,18.359 L99.385,18.359 C99.385,14.169 95.981,10.765 91.792,10.765 C87.597,10.765 84.198,14.169 84.198,18.359 L84.198,44.286 L84.198,44.286 C84.198,48.481 87.597,51.880 91.792,51.880 C95.981,51.880 99.380,48.481 99.385,44.291 L99.385,44.286 L99.385,36.698 L91.792,36.698 L91.792,25.952 L91.792,25.952 Z"/>
      </g>
   </defs>

   <path id="base" fill="#000" d="M8.5,150 H291.5 V250 C291.5,273.5 273.5,291.5 250,291.5 H50 C26.5,291.5 8.5,273.5 8.5,250 Z"/>
   <g stroke-width="38.0086" stroke="#000">
     <g id="svgstar" transform="translate(150, 150)">
       <path id="svgbar" fill="#ffb13b"
         d="M-84.1487,-15.8513 a22.4171,22.4171 0 1 0 0,31.7026 h168.2974 a22.4171,22.4171 0 1 0 0,-31.7026 Z"/>
       <use xlink:href="#svgbar" transform="rotate(45)"/>
       <use xlink:href="#svgbar" transform="rotate(90)"/>
       <use xlink:href="#svgbar" transform="rotate(135)"/>
     </g>
   </g>
   <use xlink:href="#svgstar"/>
   <use xlink:href="#base" opacity="0.85"/>
   <use xlink:href="#SVG"/>
</svg>
<script type="text/javascript">
var svg_content=document.getElementById('svg_logo').outerHTML;
window.onload = () => {

    const canvas = document.querySelector('canvas');
    const ctx = canvas.getContext('2d');

    v = canvg.Canvg.fromString(ctx, svg_content);//'<svg width="600" height="600"><text x="50" y="50">Hello World!</text></svg>');

    // Start SVG rendering with animations and mouse handling.
    v.start();

    var MIME_TYPE = "image/png";

    var imgURL = canvas.toDataURL(MIME_TYPE);

    var dlLink = document.createElement('a');
    dlLink.download = fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
};
</script>
<canvas />
</body>
</html>

A:     var fs = require('fs');
    var svg2img = require('svg2img');

    var svgString = [
    '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="236" height="120" ',
    'viewBox="0 0 236 120">',
    '<rect x="14" y="23" width="200" height="50" fill="#55FF55" stroke="black" stroke-width="1" />',
    '</svg>'
    ].join('');

    //convert from svg string
    svg2img(svgString, function(error, buffer) {
        //returns a Buffer
        fs.writeFileSync('foo1.png', buffer);
    });

    You will find more info here:-
    https://www.npmjs.com/package/svg2img


text:
Q: php session Cannot send session cookie I am trying to solve this error related to session in php. please do help me. thankyou!

Warning: session_start(): Cannot send session cookie - headers already
  sent by (output started at C:\xampp\htdocs\myfolder\Login.php:117) in
  C:\xampp\htdocs\myfolder\Login.php on line 155
Warning: session_start(): Cannot send session cache limiter - headers
  already sent (output started at
  C:\xampp\htdocs\myfolder\Login.php:117) in
  C:\xampp\htdocs\myfolder\Login.php on line 155

here is the php code:
$adm_user=$_POST['username'];
$adm_pass=$_POST['password'];
if($adm_user=="" || $adm_pass=="")
{
    echo'Fields Cannot Be Empty';
}
else
{
    $adm_login_sql="SELECT admin_login.username, admin_login.password
                    FROM admin_login
                    WHERE username='$adm_user' AND password='$adm_pass'";

    $adm_login_query=mysql_query($adm_login_sql);

    if (!$adm_login_query)
        {
        echo "Error: No records found" . mysql_error();
        }
    else
        {
            echo "query successful<br>";

            $adm_login_row=mysql_fetch_array($adm_login_query);

            $check_uname=$adm_login_row[0];
            $check_pass=$adm_login_row[1];

                if($check_uname==$adm_user && $check_pass==$adm_pass)
                {
                    session_start();
                    $_SESSION['name']=$adm_user;

                    header('location:admin.php');
                }
                else
                {
                    echo 'Password Missmatch!!!';
                }

        }
}

A: add @ob_start(); in first code line and change
session_start(); to @session_start();

A: "Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start(). Better yet, just make session_start() the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).


text:
Q: Can you run VBA excel without having Enable all macros checked My boss wants me to have a formula to black out 5 check boxes if one excel Check box =TRUE. However working with a large company I cannot Enable all macros for security reasons. I do have the Trust access to the VBA checked. My code is all VBA and works but after saving it and reopening it, it no longer works. The file type is macro-enable. IS this a Security issue or am I doing something incorrect?
-Saved file under macro-Enable
-Checked the VBA trust module box
-Code was working
-no pop up errors upon opening and closing
-The formula is to change it from an unchecked character box to a checked and vise versa due to other circumstances
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As
Boolean)
If Target.Column = 15 Then
    If Target.Value = Chr(254) Then
        Target.Value = Chr(168)
        Cancel = True
    ElseIf Target.Value = Chr(168) Then
        Target.Value = Chr(254)
        Cancel = True
    End If
End If
End Sub


text:
Q: Access Azure web app through reverse proxy Can you tell me whether the following scenario could be possible?
I want to access an Azure web app through a reverse proxy running on-premise.
The proxy will be responsible to authenticate the users, add a JWT (or SAML) to the request and forward it to my Azure Web App.
The Azure Web App will authorize (or not) the user to perform the request.
Potentially, there can be multiple reverse proxies on different sites.
Anybody has experience with such a setup?
Of course, this prevent the Web App to be globally available but that is not an issue.
Thanks,

A: An Azure Web App always has a public name and IP, therefor it is possible to bypass your reverse proxy and access directly the app using its public name, or IP.
However, if you need to make the traffic between your reverse proxy and the app private, you got a few options. You can either run your app in a VM or in an App Service Environment. Both offer private network access, i.e. can be added to a virtual network and a VPN tunnel be built to your on-premises network.
Difference between an ASE and a VM is that the VM you manage and maintain, while the ASE is a private PaaS service, i.e. private app service managed and maintained by Microsoft, thus more limited in capabilities than a VM.
Pricewise, a normal Azure Web App is the cheapest option. VM or an ASE are considerably more expensive.


text:
Q: Concatenating Escape Characters to A String - Python I want to concatenate a hexadecimal digit hh with \x, to make a string "\xhh" that I will then put into a list and convert that into a long string. Here is my current code for that, which raises an error:

ValueError: invalid \x escape

This error makes sense to me, since I believe that \x has to be attached to something in order for the computer to recognize it, and I'm not sure how I can do that. I am wondering, would something like "\" + "x" + hh work, and also, is there a more efficient way of doing this?
Here is my code as it stands when it caused the error:
(Note - volt, curr, and checksum values vary. I just put example values in for this)
voltValues = [30, 30, 30]
currValues = [30, 30, 30]
checksumValues = [39, 33]
v1 = "\x" + voltValues[0]
v2 = "\x" + voltValues[1]
v3 = "\x" + voltValues[2]
c1 = "\x" + currValues[0]
c2 = "\x" + currValues[1]
c3 = "\x" + currValues[2]
cs1 = "\x" + checksumValues[0]
cs2 = "\x" + checksumValues[1]

list = [ "\x01", "\x30", "\x53", v1, v2, v3, c1, c2, c3, "\x46", "\x46", "\x46", "\x30", "\x30", "\x30", "\x32", "\x46", "\x46", cs1, cs2, "\x0D" ]
return ''.join(list)

I want it to return "\x01\x30\x53\x30\x30\x30\x30\x30\x30\x46\x46\x46\x30\x30\x30\x32\x46\x46\x39\x33\x0D".

A: You can shortcut the whole process by saying int(s, 16)  to convert each two-character hex code s into an integer, and chr() to convert it further into a character. For example,  chr(int('4A', 16)) returns 'J'.   Your attempted concatenation of '\x' fails because hex codes like \xAA are interpreted as literals in the Python code itself, at the time when the interpreter reads it.
But by the way, the volt values in your program are not expressed in hex to start with. Or as strings.  The following all give the same result:
v = 0x4A   # the proper way to write int literals in hex
print chr(v)

v = 74     # without the 0x, this is interpreted as decimal
print chr(v)

v = '4A'   # in quotes, it can be anything you like, but then you need int(v,16)
print chr(int(v, 16))

A: The way you have it currently, Python is creating a string with value "\x" and then tries to add 30 to it (which will fail, because that would be concatenating a str and an int).
What you want to do would be something like this:
v1 = chr(int(str(voltValues[0]), 16))

This will first make a string from your value, so that int() can parse it. It then parses this string at the base 16 (it parses it as hex data). After that, it creates the string that has an encoding of the integer you just created. This means that e. g.
>>> chr(0x30)
'0'
>>> "\x30"
'0'
>>> chr(0x41)
'A'
>>> "\x41"
'A'

A: You want to look at the chr built-in function.
v1 = chr(voltValues[0])

will set v1 to '\x1e'.
If you wanted that to be hex, then setting voltValues[0] to 0x30 will yield a v1 of '0'.


text:
Q: Force close stating Unable to start activity component info I am calling an activity from another activity via intents and passing values through bundle(String values) but It could not start the activity this is the code and log cat errors please help me solve this
Activity which is calling another activity
if(v==btndate){
    Intent i2=new Intent(accounts.this,calcok.class);
        String frm=edtdate1.getText().toString();
        String to=edtdate2.getText().toString();
        Log.e("acc->calcok","inbetween intents");
        Log.e("from date",frm);
            Log.e("to date",to);
        i2.putExtra("from",(String)frm);
        i2.putExtra("to",(String) to);
        startActivity(i2);
}

Acitivity called by the previous one
package dlp.android.digichronicle;

import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class calcok extends Activity{
DBHandandler  myDbHelper=new DBHandandler(this);
SQLiteDatabase Mydatabase;
float inc,exp;
String s1,s2,s3;
String stattionlist,DBname="widgets";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.myDbHelper = new DBHandandler(this);
     Bundle b=getIntent().getExtras();
System.out.println("Got from acc"+b);
String frm=b.getString("frm");
String to=b.getString("to");
    if(b!=null)
    {

        Log.e("frm",frm);
        Log.e("to",to);
             Log.e("Entered accounts->" +"CALCCCC","");
             try {
                    FetchingData();
                    myDbHelper.openDataBase();

                    Mydatabase = myDbHelper.getWritableDatabase();

                    String s =second.ge;

                    if(s.equalsIgnoreCase("accounts")){
                ArrayList<Float> inclist=new  ArrayList<Float>();
                ArrayList<Float> explist=new ArrayList<Float>();
                        try{
                 explist =myDbHelper.calc(Mydatabase,"exp",frm,to);

                inclist =myDbHelper.calc1(Mydatabase,frm,to);
                         }
                         catch(Exception e){
                        inclist.add(500.0f);
                                explist.add(320.0f);
                         }
                float inc= sum(inclist);
                float exp= sum(explist);
                    float sav=inc-exp;
                    if(sav<0){
                        s3="Deficit Amount";
                        }
                        else
                        {
                            s3=Float.toString(sav);
                        }
                        s1=Float.toString(inc);
                        s2=Float.toString(exp);
                      }
           Toast.makeText(getApplicationContext(), "GOt Details",Toast.LENGTH_LONG).show();

             } catch (SQLException e) {
                 //TODO Auto-generated catch block
                e.printStackTrace();
            }
        myDbHelper.close();
        Mydatabase.close();
        Intent i3=new Intent(calcok.this,accounts.class);
       i3.putExtra("inc",s1);
       i3.putExtra("exp",s2);
       i3.putExtra("sav",s3);
        startActivity(i3);
       }

         }
 public static float sum(ArrayList<Float> list){
      if(list==null || list.size()<1)
        return 0;

      float sum = 0;
      for(Float i: list)
        sum = sum+i;

      return sum;
    }

private void FetchingData() {

     try {  myDbHelper.onCreateDataBase();

    } catch (IOException ioe) {

        throw new Error("Unable to create database");
    }
    try {

        myDbHelper.openDataBase();
        Mydatabase = myDbHelper.getWritableDatabase();

    }catch(SQLException sqle){

        throw sqle;

    }

}
  }

Logcat errors
11-24 20:52:26.318: I/System.out(842): cursortrue
11-24 20:52:29.267: D/Testing(842): Checkpoint 2
11-24 20:52:29.647: D/dalvikvm(842): GC_FOR_ALLOC freed 9093K, 24% free 30100K/39303K, paused 91ms
 11-24 20:52:29.817: I/dalvikvm(842): threadid=3: reacting to signal 3
 11-24 20:52:29.837: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
 11-24 20:52:32.247: D/dalvikvm(842): GC_CONCURRENT freed 655K, 21% free 31399K/39303K, paused 5ms+23ms
 11-24 20:52:32.337: I/dalvikvm(842): threadid=3: reacting to signal 3
 11-24 20:52:32.366: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
 11-24 20:52:32.767: I/dalvikvm(842): threadid=3: reacting to signal 3
 11-24 20:52:32.797: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
 11-24 20:52:35.757: E/acc->calcok(842): inbetween intents
 11-24 20:52:35.847: I/System.out(842): Got from accBundle[mParcelledData.dataSize=64]
 11-24 20:52:35.847: D/AndroidRuntime(842): Shutting down VM
 11-24 20:52:35.858: W/dalvikvm(842): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
 11-24 20:52:35.897: E/AndroidRuntime(842): FATAL EXCEPTION: main
 11-24 20:52:35.897: E/AndroidRuntime(842): java.lang.RuntimeException: Unable to start   activity ComponentInfo{dlp.android.digichronicle/dlp.android.digichronicle.calcok}: java.lang.NullPointerException: println needs a message
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
  11-24 20:52:35.897: E/AndroidRuntime(842):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at and roid.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.os.Handler.dispatchMessage(Handler.java:99)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.os.Looper.loop(Looper.java:137)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.app.ActivityThread.main(ActivityThread.java:4424)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at java.lang.reflect.Method.invokeNative(Native Method)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at java.lang.reflect.Method.invoke(Method.java:511)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at dalvik.system.NativeStart.main(Native Method)
11-24 20:52:35.897: E/AndroidRuntime(842): Caused by: java.lang.NullPointerException: println needs a message
11-24 20:52:35.897: E/AndroidRuntime(842):  at android.util.Log.println_native(Native Method)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.util.Log.e(Log.java:231)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at dlp.android.digichronicle.calcok.onCreate(calcok.java:30)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.app.Activity.performCreate(Activity.java:4465)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at an droid.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
  11-24 20:52:35.897: E/AndroidRuntime(842):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
  11-24 20:52:35.897: E/AndroidRuntime(842):    ... 11 more
   11-24 20:52:36.297: I/dalvikvm(842): threadid=3: reacting to signal 3
  11-24 20:52:36.317: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
  11-24 20:52:36.567: I/dalvikvm(842): threadid=3: reacting to signal 3
  11-24 20:52:36.576: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
  11-24 20:52:37.117: I/dalvikvm(842): threadid=3: reacting to signal 3
  11-24 20:52:37.137: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
  11-24 20:52:37.619: I/dalvikvm(842): threadid=3: reacting to signal 3
   11-24 20:52:37.647: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
   11-24 20:52:38.147: I/dalvikvm(842): threadid=3: reacting to signal 3
   11-24 20:52:38.177: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
   11-24 20:52:38.697: I/dalvikvm(842): threadid=3: reacting to signal 3
  11-24 20:52:38.707: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
  11-24 20:52:39.217: I/dalvikvm(842): threadid=3: reacting to signal 3
   11-24 20:52:39.237: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
   11-24 20:52:39.737: I/dalvikvm(842): threadid=3: reacting to signal 3
  11-24 20:52:39.757: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
  11-24 20:52:39.877: I/Process(842): Sending signal. PID: 842 SIG: 9
  11-24 20:52:41.037: I/dalvikvm(857): threadid=3: reacting to signal 3
  11-24 20:52:41.107: I/dalvikvm(857): Wrote stack traces to '/data/anr/traces.txt'
  11-24 20:52:41.246: D/dalvikvm(857): GC_FOR_ALLOC freed 70K, 3% free 9121K/9347K, paused 68ms

A: Your frm is null in the calcok Activity (As it very clearly states in Logcat).
11-24 20:52:35.897: E/AndroidRuntime(842): Caused by: java.lang.NullPointerException: println needs a message
11-24 20:52:35.897: E/AndroidRuntime(842):  at android.util.Log.println_native(Native Method)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at android.util.Log.e(Log.java:231)
 11-24 20:52:35.897: E/AndroidRuntime(842):     at dlp.android.digichronicle.calcok.onCreate(calcok.java:30)

So, I guess it's the way you're receiving the extras. Try:
String frm = getIntent().getStringExtra("frm");
String to = getIntent().getStringExtra("to");

EDIT: Just realized you're putting the extra as from, and receiving it as frm. That's the error.

A: See this line in your logcat: Caused by: java.lang.NullPointerException: println needs a message. Somewhere you are not passing any print message to your log statement. Plz check all your log statement gain. And make sure you have included the activity in the AndroidManifest file.
And while recieving the intent You are missing out. Try recieving intents as suggested. It will surely get resolved.


text:
Q: Css main file not load to browser I have ubunto server working with nginx,
and after running npm run build in my react project, the build directory created with the path static/css/main.ca4e3296.chunk.css -> and that is the main css file of the project.
After ftp that build directory to the server, I checked this file and it transfered successfully, but on the production it's value is all the index.html content (I have no idea why).
I also copy paste all the static/css/main.ca4e3296.chunk.css file's content from the server to the browser and it's all the css worked again, which means the problem here is that file that it's value changes from the server to the browser.
Also, in the console, I get this message:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://bucard.co.il/static/css/main.ca4e3296.chunk.css".

By the way, this is my index.html page if it's couses the issue:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Bucard | Digital Business Card</title>

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <link rel="canonical" href="https://bucard.co.il/" />

  <link rel="icon" id="favicon" href="%PUBLIC_URL%/favicon.ico" />
  <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
  <link rel="preload" href="https://fonts.googleapis.com/css2?family=Assistant:wght@300&display=swap" as="style"
    onload="this.rel='stylesheet'" />
  <link rel="preload" href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" as="style"
    onload="this.rel='stylesheet'" />
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

  <meta name="title" content="Bucard | Digital Business Card" />
  <meta name="description"
    content="Bucard - Digital Card Website" />

  <meta property="og:locale" content="he_IL" />
  <meta property="og:type" content="website" />
  <meta property="og:title" content="Bucard | Digital Business Card" />
  <meta property="og:image" content="https://bucard.co.il/favicon.ico" />
  <meta property="og:description"
    content="Bucard - Digital Card Website" />
  <meta property="og:url" content="https://bucard.co.il/" />
  <meta property="og:site_name" content="Bucard" />

Any help please ? Or maybe it's Nginx problem?
This problem causes only on production.
edit: Just saw that removing GENERATE_SOURCEMAP=false from .env file solved the problem, but the components are shown again. so that's temporary solution.

A: I just looked at the source code of your website, there's no CSS file named main.ca4e3296.chunk.css there.
It's probably the nginx routing settings that causes the redirect to your 404 page, which is fine.
You need to remember that with each new build the output files' names change, and the main index.html file is updated as well to link to the new files, so main.ca4e3296.chunk.css may have existed sometime in the past but not anymore. Currently, both 2.b42aba3b.chunk.css and main.a6f3b637.chunk.css are responding as expected.
If I were you I'd read more about your bundler (most likely Webpack)


text:
Q: How can I see the LOG.debug output from CopyMapper of DistCp job in Hadoop? I'm using a recent version of Hadoop with YARN, and after running a distcp job successfully, I'm trying to see the output of LOG.debug lines from CopyMapper.java and RetriableFileCopyCommand.java, but even though I've enabled DEBUG logging in log4j.properties (and of course copied this file to all the nodes in my cluster), I cannot see the output of these lines.
The LOG.debug statements I'm interested are:
LOG.debug("DistCpMapper::map(): Received " + sourcePath + ", " + relPath);

(from: CopyMapper.java )
LOG.debug("Copying " + sourceFileStatus.getPath() + " to " + target);
LOG.debug("Target file path: " + targetPath);

(from RetriableFileCopyCommand.java)
The distcp job copies about 20 files from one cluster to another and reports success. Then I check the YARN WEB UI and see that job is listed under FINISHED jobs. When I click on that, application_1454924704123_0001 in my case, I see only 1 entry in the list, such as
appattempt_1454924704123_0001_000001     Mon Feb 8 10:51:27 +0100 2016    http://hadoop10:8042       Logs

And when I click on the "Logs" I see that there's a "syslog : Total file length is 165516 bytes." And when I examine its contents I don't see any DEBUG lines (I see a lot of INFO lines), I also don't see any strings such as DistCpMapper or Target file path that should have been produced by CopyMapper and RetriableFileCopyCommand.
I also SSHed into hadoop10 node, and did a grep but still couldn't find such DEBUG output, e.g.:
grep -r "Target file" /var/log/hadoop/

returns no result.
In my log4j.properties, I have lines such as:
hadoop.root.logger=DEBUG,console,RFA
log4j.logger.org.apache.hadoop.tools.mapred=DEBUG

And in my hadoop-env.sh I have the following line:
export HADOOP_DAEMON_ROOT_LOGGER=DEBUG,RFA

Is this not enough to see the output of all of the expected LOG.debug statements from all of the classes in org.apache.hadoop.tools.mapred package such as CopyMapper and RetriableFileCopyCommand? Or am I looking at the wrong directory?
You can see the contents of my log4j.properties and hadoop-env.sh files at the end of this message, I made sure that they are the same on all of the nodes in the cluster.
log4j.properties:
# Define some default values that can be overridden by system properties
#hadoop.root.logger=INFO,console
#hadoop.root.logger=INFO,console,RFA
hadoop.root.logger=DEBUG,console,RFA
hadoop.log.dir=.
hadoop.log.file=hadoop.log

# Define the root logger to the system property "hadoop.root.logger".
log4j.rootLogger=${hadoop.root.logger}, EventCounter

# Logging Threshold
log4j.threshold=ALL

# Null Appender
log4j.appender.NullAppender=org.apache.log4j.varia.NullAppender

#
# Rolling File Appender - cap space usage at 5gb.
#
hadoop.log.maxfilesize=256MB
hadoop.log.maxbackupindex=20
log4j.appender.RFA=org.apache.log4j.RollingFileAppender
log4j.appender.RFA.File=${hadoop.log.dir}/${hadoop.log.file}

log4j.appender.RFA.MaxFileSize=${hadoop.log.maxfilesize}
log4j.appender.RFA.MaxBackupIndex=${hadoop.log.maxbackupindex}

log4j.appender.RFA.layout=org.apache.log4j.PatternLayout

# Pattern format: Date LogLevel LoggerName LogMessage
log4j.appender.RFA.layout.ConversionPattern=%d{ISO8601} %p %c: %m%n
# Debugging Pattern format
#log4j.appender.RFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n

#
# Daily Rolling File Appender
#

log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRFA.File=${hadoop.log.dir}/${hadoop.log.file}

# Rollover at midnight
log4j.appender.DRFA.DatePattern=.yyyy-MM-dd

log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout

# Pattern format: Date LogLevel LoggerName LogMessage
log4j.appender.DRFA.layout.ConversionPattern=%d{ISO8601} %p %c: %m%n
# Debugging Pattern format
#log4j.appender.DRFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n

#
# console
# Add "console" to rootlogger above if you want to use this
#

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n

#
# TaskLog Appender
#

#Default values
hadoop.tasklog.taskid=null
hadoop.tasklog.iscleanup=false
hadoop.tasklog.noKeepSplits=4
hadoop.tasklog.totalLogFileSize=100
hadoop.tasklog.purgeLogSplits=true
hadoop.tasklog.logsRetainHours=12

log4j.appender.TLA=org.apache.hadoop.mapred.TaskLogAppender
log4j.appender.TLA.taskId=${hadoop.tasklog.taskid}
log4j.appender.TLA.isCleanup=${hadoop.tasklog.iscleanup}
log4j.appender.TLA.totalLogFileSize=${hadoop.tasklog.totalLogFileSize}

log4j.appender.TLA.layout=org.apache.log4j.PatternLayout
log4j.appender.TLA.layout.ConversionPattern=%d{ISO8601} %p %c: %m%n

#
# HDFS block state change log from block manager
#
# Uncomment the following to suppress normal block state change
# messages from BlockManager in NameNode.
#log4j.logger.BlockStateChange=WARN

#
#Security appender
#
hadoop.security.logger=INFO,NullAppender
hadoop.security.log.maxfilesize=256MB
hadoop.security.log.maxbackupindex=20
log4j.category.SecurityLogger=${hadoop.security.logger}
hadoop.security.log.file=SecurityAuth-${user.name}.audit
log4j.appender.RFAS=org.apache.log4j.RollingFileAppender
log4j.appender.RFAS.File=${hadoop.log.dir}/${hadoop.security.log.file}
log4j.appender.RFAS.layout=org.apache.log4j.PatternLayout
log4j.appender.RFAS.layout.ConversionPattern=%d{ISO8601} %p %c: %m%n
log4j.appender.RFAS.MaxFileSize=${hadoop.security.log.maxfilesize}
log4j.appender.RFAS.MaxBackupIndex=${hadoop.security.log.maxbackupindex}

#
# Daily Rolling Security appender
#
log4j.appender.DRFAS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRFAS.File=${hadoop.log.dir}/${hadoop.security.log.file}
log4j.appender.DRFAS.layout=org.apache.log4j.PatternLayout
log4j.appender.DRFAS.layout.ConversionPattern=%d{ISO8601} %p %c: %m%n
log4j.appender.DRFAS.DatePattern=.yyyy-MM-dd

#
# hadoop configuration logging
#

# Uncomment the following line to turn off configuration deprecation warnings.
# log4j.logger.org.apache.hadoop.conf.Configuration.deprecation=WARN

#
# hdfs audit logging
#
hdfs.audit.logger=INFO,NullAppender
hdfs.audit.log.maxfilesize=256MB
hdfs.audit.log.maxbackupindex=20
log4j.logger.org.apache.hadoop.hdfs.server.namenode.FSNamesystem.audit=${hdfs.audit.logger}
log4j.additivity.org.apache.hadoop.hdfs.server.namenode.FSNamesystem.audit=false
log4j.appender.RFAAUDIT=org.apache.log4j.RollingFileAppender
log4j.appender.RFAAUDIT.File=${hadoop.log.dir}/hdfs-audit.log
log4j.appender.RFAAUDIT.layout=org.apache.log4j.PatternLayout
log4j.appender.RFAAUDIT.layout.ConversionPattern=%d{ISO8601} %p %c{2}: %m%n
log4j.appender.RFAAUDIT.MaxFileSize=${hdfs.audit.log.maxfilesize}
log4j.appender.RFAAUDIT.MaxBackupIndex=${hdfs.audit.log.maxbackupindex}

#
# NameNode metrics logging.
# The default is to retain two namenode-metrics.log files up to 64MB each.
#
namenode.metrics.logger=INFO,NullAppender
log4j.logger.NameNodeMetricsLog=${namenode.metrics.logger}
log4j.additivity.NameNodeMetricsLog=false
log4j.appender.NNMETRICSRFA=org.apache.log4j.RollingFileAppender
log4j.appender.NNMETRICSRFA.File=${hadoop.log.dir}/namenode-metrics.log
log4j.appender.NNMETRICSRFA.layout=org.apache.log4j.PatternLayout
log4j.appender.NNMETRICSRFA.layout.ConversionPattern=%d{ISO8601} %m%n
log4j.appender.NNMETRICSRFA.MaxBackupIndex=1
log4j.appender.NNMETRICSRFA.MaxFileSize=64MB

#
# DataNode metrics logging.
# The default is to retain two datanode-metrics.log files up to 64MB each.
#
datanode.metrics.logger=INFO,NullAppender
log4j.logger.DataNodeMetricsLog=${datanode.metrics.logger}
log4j.additivity.DataNodeMetricsLog=false
log4j.appender.DNMETRICSRFA=org.apache.log4j.RollingFileAppender
log4j.appender.DNMETRICSRFA.File=${hadoop.log.dir}/datanode-metrics.log
log4j.appender.DNMETRICSRFA.layout=org.apache.log4j.PatternLayout
log4j.appender.DNMETRICSRFA.layout.ConversionPattern=%d{ISO8601} %m%n
log4j.appender.DNMETRICSRFA.MaxBackupIndex=1
log4j.appender.DNMETRICSRFA.MaxFileSize=64MB

#
# mapred audit logging
#
mapred.audit.logger=INFO,NullAppender
mapred.audit.log.maxfilesize=256MB
mapred.audit.log.maxbackupindex=20
log4j.logger.org.apache.hadoop.mapred.AuditLogger=${mapred.audit.logger}
log4j.additivity.org.apache.hadoop.mapred.AuditLogger=false
log4j.appender.MRAUDIT=org.apache.log4j.RollingFileAppender
log4j.appender.MRAUDIT.File=${hadoop.log.dir}/mapred-audit.log
log4j.appender.MRAUDIT.layout=org.apache.log4j.PatternLayout
log4j.appender.MRAUDIT.layout.ConversionPattern=%d{ISO8601} %p %c{2}: %m%n
log4j.appender.MRAUDIT.MaxFileSize=${mapred.audit.log.maxfilesize}
log4j.appender.MRAUDIT.MaxBackupIndex=${mapred.audit.log.maxbackupindex}

# Custom Logging levels

#log4j.logger.org.apache.hadoop.mapred.JobTracker=DEBUG
#log4j.logger.org.apache.hadoop.mapred.TaskTracker=DEBUG
#log4j.logger.org.apache.hadoop.hdfs.server.namenode.FSNamesystem.audit=DEBUG

# Jets3t library
log4j.logger.org.jets3t.service.impl.rest.httpclient.RestS3Service=ERROR

# AWS SDK & S3A FileSystem
log4j.logger.com.amazonaws=ERROR
log4j.logger.com.amazonaws.http.AmazonHttpClient=ERROR
#log4j.logger.org.apache.hadoop.fs.s3a.S3AFileSystem=WARN

log4j.logger.org.apache.hadoop.fs.s3a.S3AFileSystem=DEBUG
log4j.logger.org.apache.hadoop.tools.mapred=DEBUG
#log4j.logger.org.apache.hadoop=DEBUG

#
# Event Counter Appender
# Sends counts of logging messages at different severity levels to Hadoop Metrics.
#
log4j.appender.EventCounter=org.apache.hadoop.log.metrics.EventCounter

#
# Job Summary Appender
#
# Use following logger to send summary to separate file defined by
# hadoop.mapreduce.jobsummary.log.file :
# hadoop.mapreduce.jobsummary.logger=INFO,JSA
#
hadoop.mapreduce.jobsummary.logger=${hadoop.root.logger}
hadoop.mapreduce.jobsummary.log.file=hadoop-mapreduce.jobsummary.log
hadoop.mapreduce.jobsummary.log.maxfilesize=256MB
hadoop.mapreduce.jobsummary.log.maxbackupindex=20
log4j.appender.JSA=org.apache.log4j.RollingFileAppender
log4j.appender.JSA.File=${hadoop.log.dir}/${hadoop.mapreduce.jobsummary.log.file}
log4j.appender.JSA.MaxFileSize=${hadoop.mapreduce.jobsummary.log.maxfilesize}
log4j.appender.JSA.MaxBackupIndex=${hadoop.mapreduce.jobsummary.log.maxbackupindex}
log4j.appender.JSA.layout=org.apache.log4j.PatternLayout
log4j.appender.JSA.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
log4j.logger.org.apache.hadoop.mapred.JobInProgress$JobSummary=${hadoop.mapreduce.jobsummary.logger}
log4j.additivity.org.apache.hadoop.mapred.JobInProgress$JobSummary=false

#
# shuffle connection log from shuffleHandler
# Uncomment the following line to enable logging of shuffle connections
# log4j.logger.org.apache.hadoop.mapred.ShuffleHandler.audit=DEBUG

#
# Yarn ResourceManager Application Summary Log
#
# Set the ResourceManager summary log filename
yarn.server.resourcemanager.appsummary.log.file=rm-appsummary.log
# Set the ResourceManager summary log level and appender
yarn.server.resourcemanager.appsummary.logger=${hadoop.root.logger}
#yarn.server.resourcemanager.appsummary.logger=INFO,RMSUMMARY

# To enable AppSummaryLogging for the RM,
# set yarn.server.resourcemanager.appsummary.logger to
# <LEVEL>,RMSUMMARY in hadoop-env.sh

# Appender for ResourceManager Application Summary Log
# Requires the following properties to be set
#    - hadoop.log.dir (Hadoop Log directory)
#    - yarn.server.resourcemanager.appsummary.log.file (resource manager app summary log filename)
#    - yarn.server.resourcemanager.appsummary.logger (resource manager app summary log level and appender)

log4j.logger.org.apache.hadoop.yarn.server.resourcemanager.RMAppManager$ApplicationSummary=${yarn.server.resourcemanager.appsummary.logger}
log4j.additivity.org.apache.hadoop.yarn.server.resourcemanager.RMAppManager$ApplicationSummary=false
log4j.appender.RMSUMMARY=org.apache.log4j.RollingFileAppender
log4j.appender.RMSUMMARY.File=${hadoop.log.dir}/${yarn.server.resourcemanager.appsummary.log.file}
log4j.appender.RMSUMMARY.MaxFileSize=256MB
log4j.appender.RMSUMMARY.MaxBackupIndex=20
log4j.appender.RMSUMMARY.layout=org.apache.log4j.PatternLayout
log4j.appender.RMSUMMARY.layout.ConversionPattern=%d{ISO8601} %p %c{2}: %m%n

# HS audit log configs
#mapreduce.hs.audit.logger=INFO,HSAUDIT
#log4j.logger.org.apache.hadoop.mapreduce.v2.hs.HSAuditLogger=${mapreduce.hs.audit.logger}
#log4j.additivity.org.apache.hadoop.mapreduce.v2.hs.HSAuditLogger=false
#log4j.appender.HSAUDIT=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.HSAUDIT.File=${hadoop.log.dir}/hs-audit.log
#log4j.appender.HSAUDIT.layout=org.apache.log4j.PatternLayout
#log4j.appender.HSAUDIT.layout.ConversionPattern=%d{ISO8601} %p %c{2}: %m%n
#log4j.appender.HSAUDIT.DatePattern=.yyyy-MM-dd

# Http Server Request Logs
#log4j.logger.http.requests.namenode=INFO,namenoderequestlog
#log4j.appender.namenoderequestlog=org.apache.hadoop.http.HttpRequestLogAppender
#log4j.appender.namenoderequestlog.Filename=${hadoop.log.dir}/jetty-namenode-yyyy_mm_dd.log
#log4j.appender.namenoderequestlog.RetainDays=3

#log4j.logger.http.requests.datanode=INFO,datanoderequestlog
#log4j.appender.datanoderequestlog=org.apache.hadoop.http.HttpRequestLogAppender
#log4j.appender.datanoderequestlog.Filename=${hadoop.log.dir}/jetty-datanode-yyyy_mm_dd.log
#log4j.appender.datanoderequestlog.RetainDays=3

#log4j.logger.http.requests.resourcemanager=INFO,resourcemanagerrequestlog
#log4j.appender.resourcemanagerrequestlog=org.apache.hadoop.http.HttpRequestLogAppender
#log4j.appender.resourcemanagerrequestlog.Filename=${hadoop.log.dir}/jetty-resourcemanager-yyyy_mm_dd.log
#log4j.appender.resourcemanagerrequestlog.RetainDays=3

#log4j.logger.http.requests.jobhistory=INFO,jobhistoryrequestlog
#log4j.appender.jobhistoryrequestlog=org.apache.hadoop.http.HttpRequestLogAppender
#log4j.appender.jobhistoryrequestlog.Filename=${hadoop.log.dir}/jetty-jobhistory-yyyy_mm_dd.log
#log4j.appender.jobhistoryrequestlog.RetainDays=3

#log4j.logger.http.requests.nodemanager=INFO,nodemanagerrequestlog
#log4j.appender.nodemanagerrequestlog=org.apache.hadoop.http.HttpRequestLogAppender
#log4j.appender.nodemanagerrequestlog.Filename=${hadoop.log.dir}/jetty-nodemanager-yyyy_mm_dd.log
#log4j.appender.nodemanagerrequestlog.RetainDays=3

# Appender for viewing information for errors and warnings
yarn.ewma.cleanupInterval=300
yarn.ewma.messageAgeLimitSeconds=86400
yarn.ewma.maxUniqueMessages=250
log4j.appender.EWMA=org.apache.hadoop.yarn.util.Log4jWarningErrorMetricsAppender
log4j.appender.EWMA.cleanupInterval=${yarn.ewma.cleanupInterval}
log4j.appender.EWMA.messageAgeLimitSeconds=${yarn.ewma.messageAgeLimitSeconds}
log4j.appender.EWMA.maxUniqueMessages=${yarn.ewma.maxUniqueMessages}

hadoop-env.sh:
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export HADOOP_PREFIX=/opt/hadoop-3.0.0-SNAPSHOT
export HADOOP_CONF_DIR=$HADOOP_PREFIX/etc/hadoop
export HADOOP_OS_TYPE=${HADOOP_OS_TYPE:-$(uname -s)}

case ${HADOOP_OS_TYPE} in
  Darwin*)
    export HADOOP_OPTS="${HADOOP_OPTS} -Djava.security.krb5.realm= "
    export HADOOP_OPTS="${HADOOP_OPTS} -Djava.security.krb5.kdc= "
    export HADOOP_OPTS="${HADOOP_OPTS} -Djava.security.krb5.conf= "
  ;;
esac

export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$HADOOP_PREFIX/share/hadoop/tools/lib/*
export HADOOP_LOG_DIR=/var/log/hadoop

export HADOOP_DAEMON_ROOT_LOGGER=DEBUG,RFA


text:
Q: how to separate source code and data while minimizing directory changes during working? This is a general software engineering problem about working on Linux. Suppose I have source code, mainly scripts. They manipulate text data, take text files as input and output. I am thinking about how to appropriately separate src code and data while minimizing directory changes during working.  I see two possibilities:

*

*mix code and data together. In this way, it minimizes directory transitions  and eliminating the need of typing paths to files during working. Most of the time I just call:
script1 data-in data-out # call script
vi data-out # view result

The problem is that as the number of code and data files grows, it looks messy facing a long list   of both code and data files.

*Separate code and data in two folders, say "src" and "data". When I am in "src" folder, doing the above actions would require:
script1 ../data/data-in ../data/data-out # call script
vi ../data/data-out or cd data; vi data-out # view result

The extra typing of parent directories "../data" causes hassle, especially when there are lots of quick testings of scripts.
You might suggest I do it the other way around, in the data folder. But then similarly I need to call ../src/script1, again a hassle of typing prefix "../src". Yeah, we could add "src" to PATH. But what if there are dependencies among scripts across parent-child directories? e.g., suppose under "src" there are "subsrc/script2", and within script1, it calls "./subsrc/script2 ..."? Then calling script1 in "data" folder would throw error, because there is no "subsrc" folder under "data" folder.
Well separation of code & data, and minimizaing directory changes seem to be conflicting requirements. Do you have any suggestions? Thanks.

A: I would use the cd - facility of the shell plus setting the PATH to sort this out — possibly with some scripts to help.
I'd ensure that the source directory, where the programs are built, is on my PATH, at the front.  I'd cd into either the data directory or the source directory, (maybe capture the directory with d=$PWD for the data directory, or s=$PWD for the source directory), then switch to the other (and capture the directory name again).  Now I can switch back and forth between the two directories using cd - to switch.
Depending on whether I'm in 'code work' or 'data work' mode, I'd work primarily in the appropriate directory. I might have a simple script to (cd $source_directory; make "$@") so that if I need to build something, I can do so by running the script.  I can edit files in either directory with a minimum of fuss, either with a swift cd - plus vim, or with vim $other_dir/whichever.ext.  Because the source directory is on PATH, I don't have to specify full paths to the commands in it.
I use an alias alias r="fc -e -" to repeat a command.  For example, to repeat the last vim command, r v; the last make command, r m; and so on.
I do this sort of stuff all the time.  The software I work on has about 50 directories for the full build, but I'm usually just working in a couple at a time.  I have sets of scripts to rebuild the system based on on where I'm working (chk.xyzlib and chk.pqrlib to build in the corresponding sets of directories, for example; two directories for each of the libraries).  I prefer scripts to aliases; you can interpolate arguments more easily with scripts whereas with aliases, you can only append the arguments.  The (cd $somewhere; make "$@") notation doesn't work with aliases.

A: It's a little more coding, but can you set environment variables from the command line to specify the data directory?
export DATA_INPUT_DIR=/path/to/data
export DATA_OUTPUT_DIR=/path/to/outfiles

Then your script can process files relative to these directories:
# Set variables at the top of your scripts:
in_dir="${DATA_INPUT_DIR:-.}"   # Default to current directory
out_dir="${DATA_OUTPUT_DIR:-.}" # Defailt to current directory

# 1st arg is input file.  Prepend $DATA_INPUT_DIR unless path is absolute.
infile = "$1"
[ "${1::1}" == "/" ] || infile="$DATA_INPUT_DIR/$infile"

# 2nd arg is output file.  Prepend $DATA_OUTPUT_DIR unless path is absolute.
outfile = "$2"
[ "${2::1}" == "/" ] || outfile="$DATA_OUTPUT_DIR/$outfile"

# Remainder of the script uses $infile and $outfile.

Of course, you could also open several terminal windows: some for working on the code and others for executing it.  :-)