text:
Q: Add a unit test for each new bug In my job all developers that resolve a bug have to add a new unit test that warns about this type of bugs (in the case it occours again). If a unit test is not possible (for example, a webpage design issue), then QA department has to create a test case to manually check it.
The idea behind this is that if a defect has not been detected before the product release is because there isn't an appropriate unit test to detect it. So the developer has to add it.
The question is: is this common in any software development methodology? This technique has a name? I would like to learn more about it, but I need some information to start with it.

A: This is quite common. We use this in our team. For Every production defect, the developer must add a note on the root cause of the problem , add a failing unit test and add a test impact analysis before the ticket can be pushed to dev state to check in the code.
The failing unit test must pass before we can push  the code to production.
I don't think this has a specific name except that general "regression testing". This is very useful and we have started seeing a rise in the quality of the product after we started following this process.

A: Absolutely!
If you can agree that unit tests are a good thing, then you will realise that if there is a bug then there is a missing unit test covering that code path.
So what should happen is, you write a unit test that shows the bug exists, fix the actual bug, then the unit test will pass.
If you have no unit tests at all, then this can be a good way of starting to introduce unit tests to a project.

A: The technique is test-driven development. It's not really about being able to spot a similar bug next time, although the suite of repeatable tests is always helpful. The point is that you can demonstrate that you've isolated what is wrong with the code, proved that it is wrong, fixed it, proved that the fix is correct.
There's a quote that I can't quite recall or find, but roughly it is: "Every bug is a test not yet written."
Trying to sell it as a regression test is a lost battle, IMHO. Given how infrequently these things catch a repeated bug, most developers will just say, "Why bother, when I can simply fix it?"

A: This technique is pretty common and, in my opinion, the best name for it is "Defect Driven Testing" (I came up with it myself and then found it described under this name long time ago).

You sometimes might see some people call these tests "Regression Tests", but I personally find it somewhat hard to justify this name. A somewhat more widespread definition (and one that, arguably, makes much more sense for this name) of "regression testing" is "running tests after making any change to the code to make sure that you did not introduce any regressions" and your CI that tests each branch on push to the repository satisfies it.


text:
Q: Ionic,cordova Unable to merge dex am trying to add Facebook account kit to my project, my project has also native google map plugin when i tried to add facebook account kit plugin i got the error

*

*What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

A: I was facing same issue. Installing plugin cordova-android-support-gradle-release fixed the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure eclipse tomcat to run multiple web application I am using Eclipse and configured tomcat in eclipse. I want to run Tomcat in debug mode from Eclipse. I have two application under my server.
tomcat-instance
  > site1
  > site2

I want these two application to start when I run tomcat in debug/start mode from Eclipse. But problem  is that we can specify only one working directory from eclipse tomcat configuration.
 ${workspace_loc:site1/target}

So, the other application (site2) is not deployed. So, if I want to check site2 I have to change configuration. How to run multiple webapplication here.  Does anybody know how to do this ?
Another example is shown below

A: Define Tomcat server configuration on 'Servers' view, then you can add multiple modules/applications to that instance.


text:
Q: How do I send a file stream using Quart in Python? Following the example set in Izmailoff's blog post, I was able to send remote files from Flask to the user, but when I switched to Quart, I started receiving a TypeError: 'function' object is not iterable error.
The code is almost the exact same as on the blog, and I've tried using await to no avail, as it errored out with object Response can't be used in 'await' expression.
My code is as follows, with raw_url being the direct-access URL:
req = requests.get(raw_url, stream=True)
return Response(stream_with_context(req.iter_content()), content_type=req.headers['content-type'])

A: The error

for data in iterable:  # type: ignore

TypeError: 'function' object is not iterable

is telling you that the stream_with_context() is not returning an object of type iterable. You can indeed inspect that by printing the output of that function and see what it returns.
My only guess would be that the values returned by the iter_content() of the req module may be different from the one on the blog
req.iter_content()

and hence the error. I am also inclined to think that this could also be caused by difference in flask/python versions.


text:
Q: Entity Framework modelbuilder mapping problems I'm having trouble defining my modelbuilder for my entities and throwing an error when trying to set the current values for that entity. The line causing problems down below is:
       context.Entry(tEntity.TaskSchedule.ScheduleDaysAndTimes).CurrentValues.SetValues(selectedTask.TaskSchedule.ScheduleDaysAndTimes);

I'm throwing an 'The entity type EntityCollection`1 is not part of the model for the current context.'
Heres my setup:
public class TaskEntity
{
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public virtual int TaskId { get; set; }

       public virtual TaskScheduleEntity TaskSchedule { get; set; }
}
public class TaskScheduleEntity
{
    /*Foreign Key*/
    public virtual int TaskId { get; set; }
    public virtual TaskEntity TaskEntity { get; set; }

    public virtual ICollection<ScheduleDayTimeEntity> ScheduleDaysAndTimes { get; set; }

public class ScheduleDayTimeEntity
{
    public int TaskScheduleID { get; set; }
    public virtual TaskScheduleEntity TaskScheduleEntity { get; set; }

    public virtual ICollection<DateTime?> Times { get; set; }
}

 modelBuilder.Entity<TaskEntity>()
            .HasKey(k => k.TaskId)
            .HasRequired(s => s.TaskSchedule)
            .WithRequiredPrincipal(p => p.TaskEntity)
            .WillCascadeOnDelete(true);

        modelBuilder.Entity<TaskScheduleEntity>()
            .HasKey(k => k.TaskId)
            .HasMany(t => t.ScheduleDaysAndTimes)
            .WithRequired(a => a.TaskScheduleEntity)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<ScheduleDayTimeEntity>()
            .HasKey(k => k.TaskScheduleID);

public void SaveTasks()
    {
        using (var context = new AppContext())
        {
            var tEntity = context.Tasks.First(x => x.TaskId == selectedTask.TaskId);

            context.Entry(tEntity).CurrentValues.SetValues(selectedTask);
            context.Entry(tEntity.TaskSchedule).CurrentValues.SetValues(selectedTask.TaskSchedule);

            context.Entry(tEntity.TaskSchedule.ScheduleDaysAndTimes).CurrentValues.SetValues(selectedTask.TaskSchedule.ScheduleDaysAndTimes); /* Error thrown here*/

            context.SaveChanges();

        }

    }

A: DbContext.Entry() is expecting a single entity, and you're giving it an ICollection<ScheduleDayTimeEntity>
You need to update your code so you loop through the collection:
foreach (var scheduleDayTimeEntity in tEntity.TaskSchedule.ScheduleDaysAndTimes)
{
  context.Entry(scheduleDayTimeEntity).CurrentValues.SetValues(/* Correct Value goes here */ );

}


text:
Q: How to check if len is valid I have a function
def foo(bar):
    #do some things
    len(bar)

If I call
foo(42)

it throws an exception of

TypeError: object of type 'int' has no len()

How do I check if the entered value can be used with len()?

A: Since len() calls __len__() magic method under the hood, you can check if an object has __len__ method defined with the help of hasattr():
>>> def has_len(obj):
...     return hasattr(obj, '__len__')
...
>>> has_len([1,2,3])
True
>>> has_len('test')
True
>>> has_len(1)
False

A: You can do it using try and except for best results:
def foo(bar):
    #do some things
    try:
        print(len(bar))
    except TypeError:
        print('Input not compatible with len()')

A: You can do:
if hasattr(bar, '__len__'):
    pass

Alternatively, you can catch the TypeError.

A: You can test if the object is Sized:
import collections.abc

if isinstance(bar, collections.abc.Sized):

The isinstance() test is true if all abstract methods of Sized are implemented; in this case that's just __len__.
Personally, I'd just catch the exception instead:
try:
    foo(42)
except TypeError:
    pass  # oops, no length


text:
Q: What is "Descriptive Discriminant Analysis"? I have found some references to "Descriptive Discriminant Analysis" or DDA. In particular, this paper recommends it as a follow-up to a significant MANOVA result. Briefly, it is described as "a statistical procedure which creates a set of perfectly uncorrelated  linear  equations  that  together  model  the differences  among  groups  in  the  MANOVA".
However, I have found surprisingly little mention of DDA elsewhere, which made me wonder if it has a more common name, or if it has been superceded by other methods, or if it is in fact the same as Linear Discriminant Analysis (LDA). I have tried following up references within the above source, but other articles do not seem to make a distinction, and simply refer to discriminant analysis, or LDA. Here it is mentioned briefly in contrast to "predictive" discriminant analysis. I can see that there is a difference in motivation between simply wanting to describe differences among groups and wanting to predict group membership, but it is not clear to me why these different aims cannot both be met by an LDA.
DDA is implemented separately to Linear Discriminant Analysis (LDA) in the R package DiscriMiner. There the main reference is in French, which made me wonder if this is simply an issue of mis-translating the name of another test.
Does "Descriptive Discriminant Analysis" exist in its own right, and if so, how does it differ from Linear DA?

A: There exists a real difference between Descriptive Discriminant Analysis(DDA) and Predictive Discriminant Analysis (PDA). which is depicted in the diagram given below. I found it here: http://as.wiley.com/WileyCDA/WileyTitle/productCd-0471468150.html


text:
Q: Writing numbers on the top of the matrix as shown in figure I'm trying to write numbers on a matrix as shown in the figure. Please help in this issue. Thank you so much for your time.

A: You can do that with blockarray:
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{blkarray, bigstrut}

\begin{document}

\begin{frame}
\[ \bigstrutjot=5pt
X = \begin{blockarray}{*{7}{c}}
& 1 & 2 & \dots & j & \dots &n \\
  \begin{block}{r[*{6}{c}]}%
    1 & & & & & & \bigstrut[t]\\
    2 & & & & & & \\
    \vdots & & & & & & \\
    i & & & & & & \\
    \vdots & & & & & & \\
    m & & & & & & \bigstrutjot = 3pt\bigstrut[b]\\
  \end{block}\
  \end{blockarray} \]
\end{frame}

\end{document}


text:
Q: lost custom data when tableView refresh -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  ItemsCustomCell *cell;
  static NSString *CellIdentifier = @"Cell";
  cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil)   {
     cell = [[ItemsCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

  NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ItemsCustomCell" owner:self options:nil];
  cell = [nib objectAtIndex:0];
  cell.itemName.text=titles[indexPath.row];

  [ cell.addButton setBackgroundImage:[UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
  [cell.addButton addTarget:self action:@selector(Checktag:event:)forControlEvents:UIControlEventTouchUpInside];
  cell.cellBackgroudImage.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"list_bg.png"] ];

  NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.itemsTableView indexPathsForVisibleRows]];

  NSIndexPath *indexPathVisibleRowsLast= [anArrayOfIndexPath lastObject];

  [ cell.addButton setBackgroundImage:[UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
  int firstVisible=(indexPathVisibleRowsLast.row)-8;
  CGPoint offset = itemsTableView.contentOffset;
  CGRect bounds = itemsTableView.bounds;
  CGSize size = itemsTableView.contentSize;
  UIEdgeInsets inset = itemsTableView.contentInset;
  float y = offset.y + bounds.size.height - inset.bottom;
  float h = size.height;
  float reload_distance = 10;

  }
}
return cell;

}
This code is used to change image of cell .button when it is clicked
- (void)Checktag:(id)sender event:(id)event
{
        UIButton *btnClicked=(UIButton *)sender;
        NSLog(@"%i",btnClicked.tag);
        [ btnClicked setBackgroundImage:[UIImage imageNamed:@"tick_btn.png"]
                                   forState:UIControlStateNormal];
        NSSet *touches = [event allTouches];
        UITouch *touch = [touches anyObject];
        CGPoint currentTouchPosition = [touch locationInView:itemsTableView];
        NSIndexPath *indexPath = [itemsTableView indexPathForRowAtPoint: currentTouchPosition];

        NSString *title=titles[indexPath.row];
        NSString *id1=idAll[indexPath.row];
        [mySelectedItems addObject:title];
        [idSelectedItems addObject:id1];
        NSLog(@"value of indePath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);
}

when table refresh all the change imaged is set to default

A: Look the last lines of the code
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ItemsCustomCell *cell;
    static NSString *CellIdentifier = @"Cell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)   {
        cell = [[ItemsCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ItemsCustomCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];

        [ cell.addButton setBackgroundImage:[UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
        [cell.addButton addTarget:self action:@selector(Checktag:event:)forControlEvents:UIControlEventTouchUpInside];
        cell.cellBackgroudImage.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"list_bg.png"] ];

        NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.itemsTableView indexPathsForVisibleRows]];

        NSIndexPath *indexPathVisibleRowsLast= [anArrayOfIndexPath lastObject];

        [ cell.addButton setBackgroundImage:[UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
        int firstVisible=(indexPathVisibleRowsLast.row)-8;
        CGPoint offset = itemsTableView.contentOffset;
        CGRect bounds = itemsTableView.bounds;
        CGSize size = itemsTableView.contentSize;
        UIEdgeInsets inset = itemsTableView.contentInset;
        float y = offset.y + bounds.size.height - inset.bottom;
        float h = size.height;
        float reload_distance = 10;

    }
    cell.itemName.text=titles[indexPath.row];

    if ([idSelectedItems containsObject:indexPath])
    {
        [ cell.addButton setBackgroundImage:[UIImage imageNamed:@"tick_btn.png"]
                               forState:UIControlStateNormal];
    }

}

A: On the top of your class
@implementation YourViewController : UIViewController
{
  NSMutableDictionary *selectedRows;
}

Then change this method to look like this
- (void)Checktag:(id)sender event:(id)event
{
        UIButton *btnClicked=(UIButton *)sender;
        NSLog(@"%i",btnClicked.tag);
        [ btnClicked setBackgroundImage:[UIImage imageNamed:@"tick_btn.png"]
                                   forState:UIControlStateNormal];
        NSSet *touches = [event allTouches];
        UITouch *touch = [touches anyObject];
        CGPoint currentTouchPosition = [touch locationInView:itemsTableView];
        NSIndexPath *indexPath = [itemsTableView indexPathForRowAtPoint: currentTouchPosition];

        NSString *title=titles[indexPath.row];
        NSString *id1=idAll[indexPath.row];
        [mySelectedItems addObject:title];
        [idSelectedItems addObject:id1];
        NSLog(@"value of indePath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);

// Add this lline of code

    [selectedRows setBool:YES forKey:title];
}

Finally in your cellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  ItemsCustomCell *cell;
  static NSString *CellIdentifier = @"Cell";
  cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil)   {
     cell = [[ItemsCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

  NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ItemsCustomCell" owner:self options:nil];
  cell = [nib objectAtIndex:0];
  cell.itemName.text=titles[indexPath.row];

  [ cell.addButton setBackgroundImage:[selectedRows boolForKey:titles[indexPath.row]] == YES ? [UIImage imageNamed:@"add_btn.png"] : [UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
  [cell.addButton addTarget:self action:@selector(Checktag:event:)forControlEvents:UIControlEventTouchUpInside];
  cell.cellBackgroudImage.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"list_bg.png"] ];

  NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[self.itemsTableView indexPathsForVisibleRows]];

  NSIndexPath *indexPathVisibleRowsLast= [anArrayOfIndexPath lastObject];

  [ cell.addButton setBackgroundImage:[UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
  int firstVisible=(indexPathVisibleRowsLast.row)-8;
  CGPoint offset = itemsTableView.contentOffset;
  CGRect bounds = itemsTableView.bounds;
  CGSize size = itemsTableView.contentSize;
  UIEdgeInsets inset = itemsTableView.contentInset;
  float y = offset.y + bounds.size.height - inset.bottom;
  float h = size.height;
  float reload_distance = 10;

  }
}
return cell;
}


text:
Q: How to replace Javascript of production website with local Javascript? On my production website, I have compiled Javascript.
<script src="/js/mycode.min.js"></script>

It would be very convient for debugging if I could make my browser replace that with
<script src="http://localhost/js/mycode1.js"></script>
<script src="http://localhost/js/mycode2.js"></script>
...

I know I could manipulate the DOM using something like Greasemonkey userscripts, but I couldn't come up with a solution which would prevent the execution of "mycode.min.js".
Any ideas?

A: The way I do it:

*

*Download and install Fiddler if you are on windows.

*Enable it to catch http traffic [IE/Chrome does it by default, Firefox - enable it through the add on it installs]

*Load up the page in question.

*Find the file you want to replace in the http traffic list on the left and click on it.

*On the right there is an AutoResponder tab. click on it.

*Click on the checkbox to "enable automatic responses"

*Click Add.. button

*The 2nd dropdown on right, choose the option that says "find a file"

*Locate the file in the dialog and click save

*Repeat steps 4-9 until you replace all the files you want to replace

*Refresh the browser window and your new js files are running

Instead of replacing the js file, you can replace the html file and change the js links on the page.
You can install Charles if you are on a mac/linux. (not free, has trial) Steps are similar, but not the same.
If you are using Google Closure to compress files, you can install their plug-in to do the source mapping.

A: What about using a subdomain like http://static.example.comfor static files (e.g. .js files), and changing the hostfile?
<script type="text/javascript" src="http://static.example.com/js/mycode.min.js"></script>

Add the following line to the hostfile (/etc/hosts for Linux, C:\WINDOWS\System32\drivers\etc\host):
static.example.com 127.0.0.1

Of course you've to run a server with the files from http://static.example.com/ on 127.0.0.1.
Another solution is using a (local) proxy server like Privoxy for redirecting http://example.com/js/ to http://localhost/js/.

A: To add a NEW file you can use something like one of the other post:
document.body.appendChild(document.createElement("script").src = "http://example.com/addThisJSFile.js");

This tampermonkey script can replace any JS file on a webpage with your custom one from a domain:
// ==UserScript==
// @name         ReplaceJS
// @namespace    http://example.com/
// @version      1.0.0
// @description  Replace javascript files on any webpage!
// @author       Mr.Sonic Master
// @match        *
// @run-at       document-start
// ==/UserScript==

var newJSFile = "http://example.com/newJSFile.js"; //The JS file to load in replacment od old JS file

var oldJSFile = "oldJSFile.replaceThis.js"; //The old JS file as it is named in inspect element (make sure its spelled EXACTLY the same)

var pattern = new RegExp(oldJSFile, "i"); //Create the RegExp pattern with the /i switch to make it case-insensitive

function injectScript(originalPage) { //Function injectScript replaces the file
    console.log('Replace stage 2: Replace text matching', oldJSFile, 'with', newJSFile);
    var moddedPage = originalPage.replace(pattern, newJSFile); //Modify the HTML code that we got, replacing the old JS file with the new one
    document.open();
    console.log('Replace stage 3: Write new HTML to page...');
    document.write(moddedPage); //Write to the page the new HTML code
    document.close();
}

setTimeout(function() { //Wait a bit for the page's HTML to load...
    console.log('Replace stage 1: target HTML');
    injectScript(document.documentElement.outerHTML); //Run function injectScript with the page's HTML as oldPage in the function
}, 1111);

A: Without using any web proxy below chrome feature can be used to apply local overrides for js and css files
https://developer.chrome.com/blog/new-in-devtools-65/#overrides

A: Assuming your scripts are simply the raw version of the production file, you can just crack open your favorite debugger or JS console and import your scripts:
document.body.appendChild(document.createElement("script")).src =
    "http://localhost/js/mycode1.js";

Doing so will overwrite the originally defined functions and variables.  You'll have to manually re-run window.onload.  If you have script that runs immediately or on load that changes much on the page, you may have some work to do to get it back to the original state.
Good luck!

A: Though the epascarello's solution works, there is a quicker solution for the minified files debugging. Consider using JavaScript source maps. Modern Firefox and Chrome supports them.
The idea of source map is to say browser where to find the unminified version. When you start the debugging in your browser developer tools - browser loads unminified version of the script and shows you the easy-to-read JavaScript (or whatever code you compiled to JavaScript) code in the debugger.

A: Add something to your URL to distinguish between your dev and prod context ;
example :
http://url_of_prod.com
http://url_of_dev.com?debug=true
and then, use some javascript to check if the GET variable debug is ON or NOT or  check the URL with
 if (window.location.host.indexOf('url_of_dev') > -1) ...
THEN USE a load function to load or not your file, as in this example :
http://www.softpeople.fr/replaceswitch-dev-local-production-website-javascript-during-debug/


text:
Q: More elegant way to return index of a list I am writing a circle-list in C++. Here is my code
class CList
{
private:
    class ListNode
    {
    public:
        int v;
        ListNode *prev;
        ListNode *next;
        /*constructor*/
    };
    ListNode *_tail;
public:
    typedef const void* const Index;//need a way to represent something like 'index' or 'position'
    CList():_tail(0)
    {

    }
    void print()const;
    void insert(Index pos, const int &value);
    Index find(/*some condition*/);
};

The nested-class ListNode is just used to implementation, so I don't want user of CList can access ListNode. But as it is a list, user can insert new node in some position, so I add the member Index(the Index should not be modified!). But it is stupid and I have to cast it to ListNode* manually. Is there an elegant way to do this? or using a nested-class is just a mistake at the begging.

A: The canonical C++ way for dealing with positions in containers is, of course, to use iterators. An iterator could hold, internally, a pointer to your ListNode and use the dereference operator*() and operator->() to provide access to the element at the given position. Two iterators would be comparable to determine if they point to the same location (i.e., to the same internal ListNode). Aside from the find() operation, the insert() operation could also provide an iterator. ... and, of course, an erase() member could use an iterator to remove the element.
To fully support find() you'll also need some sort of indicator, e.g., a singular iterator pointing to null rather than to a ListNode, to indicate that the element wasn't found.


text:
Q: Distance metric for moving points I am looking for a distance metric for cluster moving wagons to trains. I get data from different trains. On each of the wagons a GPS receiver is installed, which gives me the following values:
longitude / latitude / speed v / direction dir in degrees.
So far I have calculated the distance of two points from lat/lon and create the following formula from it:
distance = sqrt (am^2 + b(delta v)^2 + c*(delta dir)^2)
a,b,c are weight factors for tuning the results. The results are quite good. My question now is, is there a better approach than using the weighted Euclidean distance? I tried cosine distance but the results are not as good as for the euclidian distance. Any ideas?


text:
Q: Gulp Minify-CSS deletes CSS Gulp minify-css is deleting css that I have recently added to my main css file. I have included the block of code that is being deleted by the gulp minify-css command. I have reorganized the css in my directory and also altered the order that cleanCSS is called.
new-age.css:
input[type=email]{
    width: 50%;
    margin-right: 50px;
    color: #000000;
    padding: 1px;
}

gulpfile.js:
// Minify compiled CSS
gulp.task('minify-css', ['less'], function() {
    return gulp.src('css/new-age.css')
        .pipe(cleanCSS())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css/'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

A: If your Just just looking to minify CSS try this below, Its old code but it should work still, let me know if it doesn't and i'll write you something up
var minfyCSS = require('gulp-minify-css');

gulp.task('minfy-css', function() {
    return gulp.src('css/new-age.css')
        .pipe(minfyCSS)
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('css/'));
});


text:
Q: Find the value of $\sqrt3\csc 20^o -\sec 20^o$
Find the value of $$\sqrt3\csc 20^o -\sec 20^o.$$

How do you solve this? Please help. Don't even know how to start this.

A: \begin{eqnarray}\sqrt3 \csc 20^o -\sec 20^o&=&  {\sqrt3\over \sin 20^o} -{1\over \cos 20^o}\\
&&\\
 &=&{\sqrt3 \cos 20^o - \sin 20^o\over \cos 20^o\sin 20^o}\\
&&\\
 &=&4{\cos 30^o \cos 20^o - \sin 20^o\sin 30^o \over 2\cos 20^o\sin 20^o}\\
&& \\
&=&4{ \cos 50^o \over \sin 40^o}= 4\end{eqnarray}

A: Hint:
$$
\sqrt3 \csc x - \sec x = \frac{\sqrt3}{\sin x} - \frac{1}{\cos x},
$$
and $\displaystyle 20^o = \frac{\pi}{9}$ radians.


text:
Q: Visual studio compiler errors I am making c++ dll in visual studio community 2019 but as I created project its shows me errors.
default code for c++ dll
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

But visual studio gives these errors:
E1696   cannot open source file "windows.h"
E0020   identifier "BOOL" is undefined
E0065   expected a ';'  4

I have try messing with some settings which I seen on internet but that haven't helped.

A: >>E1696   cannot open source file "windows.h"
First of all you should check the physical existence of the file, it should be in "C:\Program Files (x86)\Windows Kits\10\Include" folder in your Visual Studio install directory.

If the file exists, you should Go to Tools->Options and expand Projects and solutions. Select VC++ Directories from the tree and choose Include Files from the combo on the right.You should see:
$(WindowsSDK_IncludePath);

If the file does not exist,you should download and install the Windows 10 SDK in the VS2019 installer.

The selected version needs to be the same as the version set in the project.

>>E0020   identifier "BOOL" is undefined
E0065   expected a ';'  4
When you solve the first error, these error will also be solved.


text:
Q: Debugging runtime stack error occurring once end of main function is reached I've converted some legacy Fortran code to C using the f2c converter (f2c), and I've created a Visual Studio 10 solution on Windows 7 (64-bit). I've also had to link my C++ program (test.cpp, containing my main function) with the f2c library (built on my system using nmake).
The program runs, but once the end of the main function is reached, I receive the following Debug error:
Stack around the variable 'qq' was corrupted
Stack around the variable 'pf' was corrupted
Stack around the variable 'ampls' was corrupted

I am wondering if this might be due to a "correction" made by the f2c converter in the converted C (from Fortran) file:
/* Parameter adjustments */
--x1;
--xabs;
--ximag;
--xreal;
--work4;
--work3;
--work2;
--work1;
--ampls;
--pf;
--qq;
--tri;

This seems a bit odd, since all of these variables are C arrays, and I think that the f2c program is simply doing some pointer arithmetic so that index 0 in the array becomes index 1, in a similar fashion to Fortran.
I don't know if this could also be due to something going wrong with the converted code accessing an element of the array that has not been allocated.
What is the best way to debug this error and fix it?

A: Potential reasons:

*

*This error is usually related to writing outside the bounds of an array (dynamic or static array). This error can occur by writing\getting a value in a -ve index or index >= size_of_array.

*This error also accurs if your pointer is not set to its correct location. (e.g. ptr = 0, ptr = 55, points to deleted (released; or has been free) memory, or any invalid address)

Best way to debug your error in my mind is to debug your prorgam step-by-step and watch those pointer values. There must be some wrong with them.

A: What you say could be true. I would suggest to create a very small program that uses an array and decrements the pointer exactly as f2c does. Something like
int aa[10];
int *pa = aa;
--pa;
pa[1] = ...

That is, test the suspected code in the small scale. You might isolate the cause to the problem this way. (Finding a workaround is a different story)

A: Are you compiling with the debug versions of the crt?  That might give you some more information.
Also, is it possible that your library is built as C and your application is written as C++?
Those errors you mention are sometimes because of different calling conventions.  You do state it's a 64bit application, so it shouldn't be an issue (all 64bit apps use the same calling convention), but it's worth looking into.
Is it possible to add all the fortran converted code to visual studio and not do a seperate make?


text:
Q: How to evaluate $\displaystyle{\int{\frac{1}{\sqrt{e^{2x}-4}}}\,dx}$ Please, could someone correct my exercise? I got it by myself, but the result that I found is differend by the WolframAlpha result... Could you tell me, please, if I'm wrong an where?

Thanks in advance!

A: There is an error in the beginning. Setting $u^2 - 4 = s^2 \implies u^2 = s^2 +4$ and not $s^2-4$ as you have written. Because of this the entire integration is incorrect.

A: To solve the problem, it may be useful to let $e^x=2\sec t$. Then $e^x\,dx=2\sec t\tan t\,dt$, so $dx=\tan t\,dt$. The bottom turns out to be $2\tan t$, so we end up needing
$$\int\frac{1}{2}\,dt.$$


text:
Q: Criar servidor xmpp Gostaria de saber se ainda existe a possibilidade de escrever um SERVIDOR XMPP em C#. Já tentei procurar pela internet, em muitos sites, e eles só disponibilizam o CLIENTE. Não sei se o cliente pode ser usado para essa função, sei que XMPP é bem antigo, porém preciso disso pra trabalhar com um sistema de um game.
OBS: Já tentei OpenFire e Jabber, porém eu quero trabalhar com queries customizadas, e conexão com banco de dados, conectar-se a um servidor dedicado, etc.


text:
Q: how to transform csv files of various encoding into utf-8 I have 95 small CSV files downloaded from web. Their schemas are supposed to be very similar. I am trying to concatenate them with Python pandas, but when calling pd.read_csv, the various encoding of those files are causing problems, and I am not sure what's the best way to transform them into consistent encoding, e.g. utf-8. The encodings include
ASCII text, with CRLF line terminators
Little-endian UTF-16 Unicode English text, with CRLF line terminators
Little-endian UTF-16 Unicode text, with CRLF line terminators
Little-endian UTF-16 Unicode text, with CRLF, CR line terminators
UTF-8 Unicode (with BOM) English text, with CRLF line terminators
UTF-8 Unicode (with BOM) text, with CRLF line terminators

The above list is generated with
file -b *.csv | sort | uniq

A: Have you tried writing:
import pandas as pd
df=pd.read_csv(file,encoding='utf-8')


text:
Q: how to get the point2(destinationPoint) with point1(startPoint) in latlng and distance in meters I have a point1 in latlng format and a distance in meter format. Now my question is
How can I get Point2 by using the point1 and distance?
I found many related questions and just cannot understand their extended discussion.
I just want simple javascript formula or code to demonstrate me how to do the calculation.
Thank you very much.

Update:
The distance contains 2 directions: x and y
The X meters offset from the centre.
The Y meters offset from the centre.
And in here, centre is point1.
So
point1 looks like : -34.127895, 140.56842
distance looks like: 3532 meter, 9211 meter

Update 2

I almost there, I found the formula to calculate the 3rd(unknown)side of the triangle.
Now I have sin(wantedAngel) = sine(90)/(X*Y).
Now I just want to know how to do the un-sin() math operation in Javascript. wantedAngel is bearing.

A: You won't be able to calculate this the easy way. Latitude and longitude are not easily convetable to meters because of the earth not being a flat surface.
Have a look at this table (it would help reading the whole article). You can see that one degree latitude equals 111.32 km. Going 23 degree to the north it equals only 102.47 km until it gets to zero reaching the north pole.
Have a look at the circles getting smaller to the top and the bottom:

I think it won't get much easier than the approach provided here:
How to calculate the latlng of a point a certain distance away from another?

A: All credits go to @geocodezip :)
JavaScript:
function initialize() {
 var map = new google.maps.Map(document.getElementById('map-canvas'), {
  center: new google.maps.LatLng(-34.127895, 140.56842),
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var bounds = new google.maps.LatLngBounds();

  var infowindow = new google.maps.InfoWindow();
  var marker = new google.maps.Marker({
  position: map.getCenter(),
  map: map
   });
    bounds.extend(map.getCenter());
   var south = google.maps.geometry.spherical.computeOffset(marker.getPosition(),3532,180);
    var line1 = new google.maps.Polyline({
        map:map,
        path: [marker.getPosition(),south],
        strokeWeight: 2,
        strokeColor: "#ff0000"
    });
    bounds.extend(south);
  var destination = google.maps.geometry.spherical.computeOffset(south,9211,90);
    bounds.extend(destination);
    var line2 = new google.maps.Polyline({
        map:map,
        path: [south, destination],
        strokeWeight: 2,
        strokeColor: "#ff0000"
    });

    var destMarker = new google.maps.Marker({
      position: destination,
      map:map
  });
    map.fitBounds(bounds);
    document.getElementById('info').innerHTML = "distance is "+(google.maps.geometry.spherical.computeDistanceBetween(marker.getPosition(), destination)/1000.0).toFixed(2)+"  km";
    var line3 = new google.maps.Polyline({
        map:map,
        path: [marker.getPosition(), destMarker.getPosition()],
        strokeWeight: 2,
        strokeColor: "#0000FF"
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

Html

CSS
#map-canvas, html, body {
    height: 95%;
    width: 100%;
}

Or you can take a look at :
http://jsfiddle.net/A8yZL/1/


text:
Q: Why must all co-efficents $c_j$ be positive in the integration of step functions? I am working through a proof of the following theorem:
'If $f$ and $g$ are step functions having $f(x) \geq g(x)$ for all real values $x$, then $\int f \geq \int g$.
So far I understand and thus have stated that $(f-g)(x) = f(x) - g(x)$ is a step function. We can rewrite $f-g$ as $\sum_{j=1}^{m}c_j \cdot \chi_{I_j}$. It then states that since $f(x) \geq g(x)$ for all $x$, the co-efficents $c_j$ forming the function values must be positive. But why is that so?
Any help would be greatly appreciated.

A: While we can write it with a mix of coefficients in which some are negative, there's at least one representation with positive coefficients.
We subdivide the domain based on the values of $f-g$. Write $\mathbb{R}$ as a disjoint union of intervals $I_j$, such that $f-g$ is constant on each $I_j$. These intervals will be intersections of the intervals for $f$ and those for $g$.
Then, since its a disjoint union, $0\le f(x)=c_j$ for any $x\in I_j$.


text:
Q: How to output all categories and sub-categories in a hierarchical form from categories table? I've a categories table with columns id, name, level, parent_id. I have a product category like .. Jewellery and watches > Jewellery > Ear-rings.
My categories look like
id, name, level, parent_id
1, Jewellery and watches, L1, null
2, Jewellery, L2, 1,
3, Ear-rings, L3, 2

How do I write a query that will give me the following output
id, name, displayName
1, Jewellery and watches, Jewellery and watches
2, Jewellery, Jewellery and watches > Jewellery
3, Ear-rings, Jewellery and watches > Jewellery > Ear-rings

A: Use a recursive query.
with recursive top_down as (
    select id, parent_id, name, name as display_name
    from categories
    where parent_id is null
union all
    select t.id, t.parent_id, t.name, concat(display_name, ' > ', t.name)
    from categories t
    join top_down r on t.parent_id = r.id
)
select id, name, display_name
from top_down;

 id |         name          |                 display_name
----+-----------------------+-----------------------------------------------
  1 | Jewellery and watches | Jewellery and watches
  2 | Jewellery             | Jewellery and watches > Jewellery
  3 | Ear-rings             | Jewellery and watches > Jewellery > Ear-rings
(3 rows)

Note, that the column level is basically redundant.


text:
Q: Python: "Unused variable" warning in PyDev Here is my code, and there is a "compiler" warning (is that the correct term for it?) under the instantiation of normDataSet below:
def autoNorm(dataSet):
    minVals = dataSet.min(0)
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = np.zeros(np.shape(dataSet)) # Warning under "normDataSet" here.
    m = dataSet.shape[0]
    normDataSet = dataSet - np.tile(minVals, (m, 1))
    normDataSet = normDataSet / np.tile(ranges, (m, 1))
    return normDataSet, ranges, minVals

The full warning in PyDev reads: Unused variable: normDataSet
Is there a way to eliminate this warning without having to suppress it with @UnusedVariable? Or am I missing something?

A: The variable isn't unused, but the assignment you're making is pointless, since you reassign to normDataSet without ever using the value you first assigned. The line flagged can be removed entirely.
Don't suppress the warning; it's there to tell you there's a problem.


text:
Q: Passing List as a parameter from Lightning Component to Apex Class My Component code :
<aura:attribute type="List" name="filterCriteriaList"/>

My Componenet Helper.js code :
getOperator : function(component, event, helper){
        var fieldName = component.find("fieldSelect").get("v.value");
        var index = component.find("hiddenIndex").get("v.value");
        console.log(' >>>>> ' + JSON.stringify(component.get('v.filterCriteriaList')));
        var action = component.get("c.fetchOperators");
        action.setParams({ "index" : index, "fieldName" : fieldName, "filterCriteriaItemJson" : JSON.stringify(component.get('v.filterCriteriaList'))});

        action.setCallback(this, function(response) {

My Apex controller code:
@auraEnabled
    public static void fetchOperators(Integer currentIndex, String fieldName, String filterCriteriaItemJson){
        //System.debug('***filterCriteriaItemJson='+filterCriteriaItemJson);
        List<FilterCriteria> filterCriteriaItems = (List<FilterCriteria>)JSON.deserializeStrict(filterCriteriaItemJson,List<FilterCriteria>.class);
        for(FilterCriteria f : filterCriteriaItems){
            if (f.index == currentIndex && f.fieldName.equalsIgnoreCase(fieldName)){
                f.operatorsList  = Utility.getOperator(f.mapFieldTypes.get(fieldName));
            }
        }
    }

For your referrence I have FilterCriteria as wrapper class and I am creating List<FilterCriteria> and sending it from component to apex controller to manipulate further values in wrapper.
When i call fetchOperators from helper file then it throws error saying
    FATAL_ERROR System.UnexpectedException: Salesforce System Error: 1803375914-142009 (577092351) (577092351)
FATAL_ERROR Class.System.JSON.deserializeStrict: line 19, column 1
 FATAL_ERROR Class.PaginationFilterController.fetchOperators: line 61, column 1

I tried using $A.util.json.encode in helper fiel to encode wrapper list but no luck. Need help on this.
Thanks in advance
Below is the WrapperClass
@auraEnabled
public string objectname { get; set; }
@auraEnabled
public string fieldname { get; set; }
@auraEnabled
public string fieldvalue { get; set; }
@auraEnabled
public string fieldtype { get; set; }
@auraEnabled
public string operator { get; set; }
@auraEnabled
public String condition {get;set;}
@auraEnabled
public boolean lookupicon { get; set; }
@auraEnabled
public integer index { get; set; }
@auraEnabled
public sObject sObjectToBind {get;set;}
@auraEnabled
public List<SelectOption> fieldList { get; set; }
@auraEnabled
public List<SelectOption> operatorsList { get; set; }
@auraEnabled
public map<String,String> mapFieldTypes { get; set; }
public String Query ='';

public FilterCriteria(integer i){
    objectname  = '';
    fieldname  = '';
    fieldvalue  = '';
    fieldtype  = '';
    operator  = '';
    condition = 'and';
    index = i;
    fieldList = new List<SelectOption>{new SelectOption('','--None--')};
    operatorsList  = new List<SelectOption>{new SelectOption('','--None--')};
    mapFieldTypes  = new  map<String,String>();
}

public List<SelectOption> getConditionList(){
    List<SelectOption> conditionList = new List<SelectOption>();
    conditionList.add(new SelectOption('or','OR'));
    conditionList.add(new SelectOption('and','AND'));
    return conditionList;
}

private string getSelectedValue(){
    if (sObjectToBind == null || fieldname == null)
        return null;
    else if (sObjectToBind != null && fieldname != null && (sObjectToBind.get(fieldname) == null
                            || sObjectToBind.get(fieldname) == ''))
        return null;
    else
        return String.valueOf(sObjectToBind.get(fieldname));
}

public boolean getisProcessAble(){
    if (fieldname != '' && operator != '' && getSelectedValue() != null)
        return true;
    else
        return false;
}

Below is the JSON
[{"condition":"and","fieldList":[{"disabled":false,"escapeItem":false,"label":"--None--","value":""},{"disabled":false,"escapeItem":false,"label":"--None--","value":""},{"disabled":false,"escapeItem":false,"label":"Account ID","value":"accountid"},{"disabled":false,"escapeItem":false,"label":"Assistant's Name","value":"assistantname"},{"disabled":false,"escapeItem":false,"label":"Asst. Phone","value":"assistantphone"},{"disabled":false,"escapeItem":false,"label":"Birthdate","value":"birthdate"},{"disabled":false,"escapeItem":false,"label":"Business Fax","value":"fax"},{"disabled":false,"escapeItem":false,"label":"Business Phone","value":"phone"},{"disabled":false,"escapeItem":false,"label":"Clean Status","value":"cleanstatus"},{"disabled":false,"escapeItem":false,"label":"Contact ID","value":"id"},{"disabled":false,"escapeItem":false,"label":"Created By ID","value":"createdbyid"},{"disabled":false,"escapeItem":false,"label":"Created Date","value":"createddate"},{"disabled":false,"escapeItem":false,"label":"Data.com Key","value":"jigsaw"},{"disabled":false,"escapeItem":false,"label":"Deleted","value":"isdeleted"},{"disabled":false,"escapeItem":false,"label":"Department","value":"department"},{"disabled":false,"escapeItem":false,"label":"Do Not Call","value":"donotcall"},{"disabled":false,"escapeItem":false,"label":"Email","value":"email"},{"disabled":false,"escapeItem":false,"label":"Email Bounced Date","value":"emailbounceddate"},{"disabled":false,"escapeItem":false,"label":"Email Bounced Reason","value":"emailbouncedreason"},{"disabled":false,"escapeItem":false,"label":"Email Opt Out","value":"hasoptedoutofemail"},{"disabled":false,"escapeItem":false,"label":"Fax Opt Out","value":"hasoptedoutoffax"},{"disabled":false,"escapeItem":false,"label":"First Name","value":"firstname"},{"disabled":false,"escapeItem":false,"label":"Full Name","value":"name"},{"disabled":false,"escapeItem":false,"label":"Home Phone","value":"homephone"},{"disabled":false,"escapeItem":false,"label":"Is Email Bounced","value":"isemailbounced"},{"disabled":false,"escapeItem":false,"label":"Jigsaw Contact ID","value":"jigsawcontactid"},{"disabled":false,"escapeItem":false,"label":"Languages","value":"languages__c"},{"disabled":false,"escapeItem":false,"label":"Last Activity","value":"lastactivitydate"},{"disabled":false,"escapeItem":false,"label":"Last Modified By ID","value":"lastmodifiedbyid"},{"disabled":false,"escapeItem":false,"label":"Last Modified Date","value":"lastmodifieddate"},{"disabled":false,"escapeItem":false,"label":"Last Name","value":"lastname"},{"disabled":false,"escapeItem":false,"label":"Last Referenced Date","value":"lastreferenceddate"},{"disabled":false,"escapeItem":false,"label":"Last Stay-in-Touch Request Date","value":"lastcurequestdate"},{"disabled":false,"escapeItem":false,"label":"Last Stay-in-Touch Save Date","value":"lastcuupdatedate"},{"disabled":false,"escapeItem":false,"label":"Last Viewed Date","value":"lastvieweddate"},{"disabled":false,"escapeItem":false,"label":"Lead Source","value":"leadsource"},{"disabled":false,"escapeItem":false,"label":"Level","value":"level__c"},{"disabled":false,"escapeItem":false,"label":"Mailing Address","value":"mailingaddress"},{"disabled":false,"escapeItem":false,"label":"Mailing City","value":"mailingcity"},{"disabled":false,"escapeItem":false,"label":"Mailing Country","value":"mailingcountry"},{"disabled":false,"escapeItem":false,"label":"Mailing Geocode Accuracy","value":"mailinggeocodeaccuracy"},{"disabled":false,"escapeItem":false,"label":"Mailing Latitude","value":"mailinglatitude"},{"disabled":false,"escapeItem":false,"label":"Mailing Longitude","value":"mailinglongitude"},{"disabled":false,"escapeItem":false,"label":"Mailing State/Province","value":"mailingstate"},{"disabled":false,"escapeItem":false,"label":"Mailing Street","value":"mailingstreet"},{"disabled":false,"escapeItem":false,"label":"Mailing Zip/Postal Code","value":"mailingpostalcode"},{"disabled":false,"escapeItem":false,"label":"Master Record ID","value":"masterrecordid"},{"disabled":false,"escapeItem":false,"label":"Mobile Phone","value":"mobilephone"},{"disabled":false,"escapeItem":false,"label":"Other Address","value":"otheraddress"},{"disabled":false,"escapeItem":false,"label":"Other City","value":"othercity"},{"disabled":false,"escapeItem":false,"label":"Other Country","value":"othercountry"},{"disabled":false,"escapeItem":false,"label":"Other Geocode Accuracy","value":"othergeocodeaccuracy"},{"disabled":false,"escapeItem":false,"label":"Other Latitude","value":"otherlatitude"},{"disabled":false,"escapeItem":false,"label":"Other Longitude","value":"otherlongitude"},{"disabled":false,"escapeItem":false,"label":"Other Phone","value":"otherphone"},{"disabled":false,"escapeItem":false,"label":"Other State/Province","value":"otherstate"},{"disabled":false,"escapeItem":false,"label":"Other Street","value":"otherstreet"},{"disabled":false,"escapeItem":false,"label":"Other Zip/Postal Code","value":"otherpostalcode"},{"disabled":false,"escapeItem":false,"label":"Owner ID","value":"ownerid"},{"disabled":false,"escapeItem":false,"label":"Photo URL","value":"photourl"},{"disabled":false,"escapeItem":false,"label":"Reports To ID","value":"reportstoid"},{"disabled":false,"escapeItem":false,"label":"Salutation","value":"salutation"},{"disabled":false,"escapeItem":false,"label":"System Modstamp","value":"systemmodstamp"},{"disabled":false,"escapeItem":false,"label":"Title","value":"title"}],"fieldname":"birthdate","fieldtype":"","fieldvalue":"","index":1,"mapFieldTypes":{"id":"ID","isdeleted":"BOOLEAN","masterrecordid":"REFERENCE","accountid":"REFERENCE","lastname":"STRING","firstname":"STRING","salutation":"PICKLIST","name":"STRING","otherstreet":"TEXTAREA","othercity":"STRING","otherstate":"STRING","otherpostalcode":"STRING","othercountry":"STRING","otherlatitude":"DOUBLE","otherlongitude":"DOUBLE","othergeocodeaccuracy":"PICKLIST","otheraddress":"ADDRESS","mailingstreet":"TEXTAREA","mailingcity":"STRING","mailingstate":"STRING","mailingpostalcode":"STRING","mailingcountry":"STRING","mailinglatitude":"DOUBLE","mailinglongitude":"DOUBLE","mailinggeocodeaccuracy":"PICKLIST","mailingaddress":"ADDRESS","phone":"PHONE","fax":"PHONE","mobilephone":"PHONE","homephone":"PHONE","otherphone":"PHONE","assistantphone":"PHONE","reportstoid":"REFERENCE","email":"EMAIL","title":"STRING","department":"STRING","assistantname":"STRING","leadsource":"PICKLIST","birthdate":"DATE","ownerid":"REFERENCE","hasoptedoutofemail":"BOOLEAN","hasoptedoutoffax":"BOOLEAN","donotcall":"BOOLEAN","createddate":"DATETIME","createdbyid":"REFERENCE","lastmodifieddate":"DATETIME","lastmodifiedbyid":"REFERENCE","systemmodstamp":"DATETIME","lastactivitydate":"DATE","lastcurequestdate":"DATETIME","lastcuupdatedate":"DATETIME","lastvieweddate":"DATETIME","lastreferenceddate":"DATETIME","emailbouncedreason":"STRING","emailbounceddate":"DATETIME","isemailbounced":"BOOLEAN","photourl":"URL","jigsaw":"STRING","jigsawcontactid":"STRING","cleanstatus":"PICKLIST","level__c":"PICKLIST","languages__c":"STRING"},"objectname":"","operator":"","operatorsList":[{"disabled":false,"escapeItem":false,"label":"--None--","value":""}],"sObjectToBind":{}}]


text:
Q: how to get hour from timestamp and attonate it and count its number of occurances in django I have a "startTime" field in my model which contains timestamp.I want to get a list with count of only hour from that stamp.I mean my code should be able convert and get only hour from the timestamp and count the number of occurance of each hour.I tried doing
datetime.datetime.fromtimestamp(int(<timestamp>)).strftime(\'%H\'))

this thing returns only hour from a timestamp but when i tried incorporating it in the queryset..it failed..this is what i tried in my views.py
 timehour = InteractionWith.objects \
    .values('startTime')\
    .annotate(times=Count('datetime.datetime.fromtimestamp(int("startTime")).strftime(\'%H\'))'))

A: You can annotate the queryset with ExtractHour [Django-doc]:
from django.db.models import Count
from django.db.models.functions import ExtractHour

timehour = InteractionWith.objects.values(
    hour=ExtractHour('startTime')
).annotate(
    times=Count('pk')
).order_by('hour')


text:
Q: How to change state radio button, when switching slides by next/prev button? I made a simple slider, but it doesn't work properly: https://jsfiddle.net/iamolivia/r1d96eyx/1/
When I click the "Next/Prev" button,  radio doesn't change state. How can I supplement this code?
 $('.controls').click(function(){
    $( ".slide" ).animate({opacity: .4});
    id = $(this).data('b');
    $('.slide').removeClass('active');
    $('#'+id).addClass('active');
    $( ".slide" ).animate({opacity: .9});
});

var i=1;
var cur = 0;
$('.next').click(function(){
    $( ".slide" ).animate({opacity: .4});
    cur = i+1;

    if(i<3)
    {
        $('.slide').removeClass('active');
        $('#b' + cur).addClass('active');
        i++;
        $( ".slide" ).animate({opacity: .9});
    }
   else if(i==3)
    {
        i=1; cur=1;
        $('.slide').removeClass('active');
        $('#b' + cur).addClass('active');
        $( ".slide" ).animate({opacity: .9});
    }
});

$('.prev').click(function(){
    $( ".slide" ).animate({opacity: .4});
    cur = i-1;
    i--;

    $('.slide').removeClass('active');
    $('#b' + cur).addClass('active');
    $( ".slide" ).animate({opacity: .9});

    if(i<1)
    {
        i=3; cur=3;
        $('.slide').removeClass('active');
        $('#b' + cur).addClass('active');
        $( ".slide" ).animate({opacity: .9});
    }
});

A: To do this you need to set the checked property on the .control radio which matches the index of the active slide. To do that you can use eq(), index() and prop().
However it's worth noting that your logic is a lot more complicated than it needs to be. You can simplify it by removing the incremental variables which count the index of the current slide and simply working with the .active class in the DOM
to determine what the next shown slide should be using prev() and next(). Also note the use of the data-dir attribute to DRY up the logic between the button handlers.

var $controls = $('.controls').on('change', function() {
  var $slides = $(".slide").stop().animate({ opacity: .4 });
  $slides.removeClass('active');
  id = $(this).data('b');
  $('#' + id).addClass('active');
  $slides.animate({ opacity: .9 });
});

$('.next, .prev').click(function() {
  var direction = $(this).data('dir');
  var $slides = $(".slide").stop().animate({ opacity: .4 });
  var $activeSlide = $slides.filter('.active').removeClass('active');
  var $targetSlide = $activeSlide[direction]();
  if ($targetSlide.length === 0)
    $targetSlide = $slides[direction == 'next' ? 'first' : 'last']()
  $targetSlide.addClass('active');
  $controls.eq($targetSlide.index()).prop('checked', true);
  $slides.animate({ opacity: .9 });
});
.wrapper {
  height: 250px;
  overflow: hidden;
}

.slider {
  height: 250px;
}

.slide {
  height: 100%;
  width: 100%;
  display: none;
  padding: 20px;
  color: #fff;
  font-weight: 900;
  opacity: 1;
}

.control {
  transform: translateY(-50px);
}

.slide:nth-of-type(1) {
  background: #dd2525;
}

.slide:nth-of-type(2) {
  background: #3791ee;
}

.slide:nth-of-type(3) {
  background: #df6af0;
}

.active {
  display: block;
}

.prev,
.next {
  background: white;
  width: 40px;
  height: 40px;
  border-radius: 20px;
  border: none;
  cursor: pointer;
  opacity: 0.4;
}

.prev:hover {
  opacity: 0.6;
  transform: scale(1.1);
  transition: .5s;
}

.next:hover {
  opacity: 0.6;
  transform: scale(1.1);
  transition: .5s;
}

.control input {
  margin-left: 5px !important;
  margin-right: 5px !important;
}

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

Slide 1

Slide 2

Slide 3

    <button id="c4" class="prev" data-dir="prev" value=""></button>
    <input id="c1" class="controls" name="radio" type="radio" checked="checked" data-b="b1" />
    <input id="c2" class="controls" name="radio" type="radio" data-b="b2" />
    <input id="c3" class="controls" name="radio" type="radio" data-b="b3" />
    <button id="c5" class="next" data-dir="next" value=""></button>


text:
Q: Android: how to know how many percent of media player loaded from url?  mediaPlayer = new MediaPlayer();
 try {
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
     } catch (IOException e) {
       e.printStackTrace();
     }
     mediaPlayer.start();

this is my mediaplayer for play voice from url

A: You can have in a Thread or Coroutine Job the following code:
while(player.isRunning) {

  val percentage = (player.currentPosition / player.duration.toFloat())
  ...
}


text:
Q: How to write such a MySQL statement? create table test(
  id ...
  weight ..
);

How to write such a statement so that the weight of each record is at least the weight of previous record plus 1?
recordN.weight >=(recordN-1).weight+1

A: you need to check it before inserting in to table, e.g. you can get the last row from the table with query
select weight from test where id = (select MAX(id) from test);

then compare this weight value from the values you are inserting and
if (newWeight >= weight)
{
   //insert here
}

A: One of the ways is to store the weight in a variable and then use it in an update statement
SELECT weight FROM test ORDER BY id DESC LIMIT 1 INTO @weight;
INSERT INTO test (weight) VALUES (@weight+1);

That will get the weight of the previous record and use it in the next insert statement (assuming you have auto increment ids).
You can also concatenate the query:
INSERT INTO test (weight) SELECT (weight+1) FROM test ORDER BY id DESC LIMIT 1;

A: Sounds strange. Are you updating existing data, adding a new row to the table or selecting the data sorted by weight?
Sorting is easiest, use SELECT ... ORDER BY weight;
Adding a row, you could use the previous answer:
INSERT INTO test (weight) (SELECT (max(weight)+1) FROM test);
Although note that
(1) There is an autoincrement function in MySQL if that's what you're looking for;
(2) in good DB tables, row order is immaterial; rows can be sorted without information being lost. If you are relying on row order for anything, consider your database design again.
Finally, if you're trying to update the data, adding to the weight, it's a common problem. I always have to look it up online, so I'll leave you to do that :)


text:
Q: Set React base background color while display mostly uses components I am currently trying to style a React project in which App.js mainly serves the function of Routing and navigating to its components:
App.js

import {useState, useEffect} from 'react';
import Models from './pages/Models';
import Loadingpage from './pages/Loadingpage';
import Output from './pages/Output';
import './App.css';
import {BrowserRouter, Route, Switch} from "react-router-dom";

function App() {
 // state variables and function declarations.....

 return (
 <Browserouter>
  <Switch>
   <Route path="/" exact>
   {isLoading===true?
    <Loadingpage/>
    :
    <Models/>
   </Route>
   <Route path="/models/output" exact>
    <Output/>
   </Route>
  </Switch>
 </Browserouter>
 );
}

The flow works as follows:

*

*If app.js is in a loading state, we render the loading page component. Here is the loading page's entire body:

        <div  className="Loading page"
            style={{
                display: 'flex',
                alignItems: 'center',
                background: "#A0C5E8",
                justifyContent: 'center',
            }}
        >
            <FlowerSpinner size={props.size} color={props.color}/>
        </div>

*

*When the loading time has elapsed, we render the model page (which consists simply of buttons)

*When a button is clicked, the output page is rendered.

The components work completely fine, and they all work the same way the loading page does. They simply render as a component overtop (or so it appears). However, the component pages only render the section of space they take up, which makes it seem like the underlying background needs to be changed somewhere. Here is what happens:

As shown, the pages have their own divs in which their respective background is displayed. I have already tried wrapping each component in a div with the corresponding background color, and the entire app.js in a div as well:
eg.
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    background: "#A0C5E8",
                    justifyContent: 'center',
                  }}
                >
                  <Loadingpage size={300} color="black"/>
                </div>

How do I successfully change the base background color? Help would be greatly appreciated, thanks for reading!

A: To change the background color of the whole page , you need to apply the style to the body tag of the html and import styles in the index.js or App.js file :
styles.css
body {
  background : #A0C5E8
}

index.js or App.js
import './styles.css'

A: If the background color is different on other pages, consider using a react hook to add and remove classes from the body after the page has changed route.
styles.css
.loading-page {
    background : #A0C5E8
}

import React, { useEffect } from "react";
import './styles.css';
function App() {
 // state variables and function declarations.....
  useEffect(() => {
    document.body.classList.add('loading-page');
    return function cleanup() {
      document.body.classList.remove('landing');
    };
  });
   ...
}


text:
Q: ERROR cursor does not exist after first loop in PL/pgSQL I need to load a large number of csv files in to a PostgreSQL database. I have a table source_files which contains the file paths and a flag which indicates whether a file has already been loaded for all the csv files I need to load.
I have written the following code which loads the first file correctly but then throws the error:

ERROR:  cursor "curs" does not exist

Why am I getting this error and how can I fix it?
DO $$
DECLARE
    file_record record;
    curs CURSOR
        FOR SELECT id, file_path
            FROM source_files
            WHERE added_to_db=FALSE
            ORDER BY id;
BEGIN
    OPEN curs;
    LOOP
        -- Get next entry in source file which contains name of csv to load
        FETCH curs INTO file_record;
        exit WHEN NOT found;
        BEGIN
            -- As we need to add a column to the data after loading csv but before inserting
            -- into final table we use a temporary table mytemp
            DROP TABLE mytemp;

            CREATE TABLE mytemp
            (
                dataA numeric,
                dataB numeric
            );

            -- Load csv file
            EXECUTE FORMAT('COPY mytemp
                            FROM ''%s''
                            DELIMITER '',''
                            CSV HEADER;', file_record.file_path);

            -- Add Column specifying what source file the data is from
            ALTER TABLE mytemp
                ADD COLUMN source_id int;

            UPDATE mytemp
                SET source_id=file_record.id;

            -- Add the data to the destination table
            INSERT INTO data_table(
                dataA,
                dataB,
                source_id
            )
            SELECT
                mytemp.dataA,
                mytemp.dataB
                mytemp.source_id
            FROM
                mytemp

            -- Set a flag to indicate that the current file in source_files has been loaded
            UPDATE source_files
                SET added_to_db=TRUE WHERE CURRENT OF curs;

            COMMIT;
        END;

    END LOOP;
    CLOSE curs;

END $$;

A: There big problem with your code is the COMMIT. You can use COMMIT in a DO statement, but the cursor is closed as soon as the transaction ends.
In SQL you can create a cursor WITH HOLD that remains valid after the transaction has ended, but that is not available in PL/pgSQL.
I suggest removing the COMMIT.
Another error in your code is your use of the format function, which exposes you to SQL injection. Instead of
FORMAT('COPY mytemp
        FROM ''%s''
        DELIMITER '',''
        CSV HEADER;', file_record.file_path);

use
FORMAT('COPY mytemp
        FROM %L
        DELIMITER '',''
        CSV HEADER;', file_record.file_path);

You can make the code much simpler by using an implicit cursor in the loop:
FOR file_record IN
   SELECT id, file_path
   FROM source_files
   WHERE added_to_db=FALSE
   ORDER BY id
LOOP
   ...
END LOOP;

That saves you declaring the cursor and the EXIT WHEN. The OPEN and CLOSE statements are unnecessary anyway.


text:
Q: Creating local database for Windows Phone 8 application I am trying to create a simple database for my WP8 application, to store some data.
[Table(Name="LocationDatas")]
    public class LocationData
    {

        public int _locationDataId;
        private Nullable<int> _workoutID;
        private EntityRef<Workout> _workoutRef = new EntityRef<Workout>();
        private int _timestamp;
        private double _longitude;
        private double _latitude;
        private double _altitude;
        private double _speed;

        [Column(IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
        public int LocationDataIds
        {
            get { return _locationDataId; }
            set { _locationDataId = value; }
        }

        [Column(Storage = "_workoutID", DbType = "Int")]
        public int? WorkOutId
        {
            get { return _workoutID; }
            set { _workoutID = value; }
        }

        [Association( Storage = "_workoutRef", ThisKey = "WorkOutId", OtherKey = "LocationDataIds", IsForeignKey = true)]
        public Workout Workout
        {
            get
            {
                return this._workoutRef.Entity;
            }
            set
            {
                this._workoutRef.Entity = value;
                if ((value != null))
                {
                    this.WorkOutId = value.WorkOutId;
                }
            }
        }
//...

And the other side of the association:
[Table(Name="Workouts")]
    public class Workout
    {
        private int _workOutId;
        private EntitySet<LocationData> _locationDataIds = new EntitySet<LocationData>();
        private DateTime _date;
        private long _duration;
        private double _distance;
        private double _averageSpeed;
        private int _calories;

        [Column(IsPrimaryKey = true, IsDbGenerated = true, CanBeNull = false)]
        public int WorkOutId
        {
            get { return _workOutId; }
            set { _workOutId = value; }
        }

        [Association( Storage = "_locationDataIds", ThisKey = "LocationDataIds", OtherKey = "WorkOutId", IsForeignKey = true)]
        public EntitySet<LocationData> LocationDataIds
        {
            get { return this._locationDataIds; }
            set { this._locationDataIds.Assign(value); }
        }
//...

Here is my DataContext:
public class SportsTrackerDataContext : DataContext
    {
        public static string DBConnectionString ="Data Source=isostore:/SportsTracker.sdf";

        public SportsTrackerDataContext(string connectionString)
            : base(connectionString) { }

        public Table<Workout> workouts;
        public Table<LocationData> locationdatas;
    }

When I'm trying to create the database, I've getting an exception:
using (SportsTrackerDataContext db = new SportsTrackerDataContext(SportsTrackerDataContext.DBConnectionString))
            {
                if (db.DatabaseExists() == false)
                {
                    //Create the database
                    db.CreateDatabase(); //exception thrown here
                    MessageBox.Show("ok");
                }
            }

The Exception:
Invalid column ID. [ LocationDataId ]

I used this as a reference, and I can't see whats wrong in my code.
Other thing: is this a proper way to store such data, or should I try something else?

A: I'm guessing Workout is the parent table and the LocationData the child table.
The idea is that you declare an EntityRef to the child table (a reference to the parent table) and an EntitySet to the parent table (the set of LocationData items with a WorkoutID).
Bcareful with the names of your private fields and your public properties, you have misspelled some of them in your associations.
That's the way your Workout EntityRef association should be declared in your LocationData class:
private EntityRef<WorkOut> _workOutRef;

[Association(
    Storage = "_workOutRef", ThisKey = "WorkOutID", IsForeignKey = true)]
public WorkOut WorkOut
{
    ...
}

Storage points to your private EntityRef field.
ThisKey points to the name of your foreign key public property.
IsForeignKey sets WorkOutID as the foreign key.
On the WorkOut class, you declare an EntitySet like this:
private EntitySet<LocationData> _locationsData;

[Association(
    Storage = "_locationsData", OtherKey = "WorkOutID")]
public EntitySet<LocationData> LocationsData
{
    ...
}

Storage points to your EntitySet private field.
OtherKey points to the referenced Key of the parent table.


text:
Q: Left Join Linq query gives Null reference exception   This is inside a wcf ria service class for my light switch application.i just cannot figure why this exception occurs at run time when running the lightswitch application.how can i get rid of this for this query to run.pls help
Both loan and release table were created using lightswitch inside lightswitch.relationship between loan and release is one to zero or one i.e one loan can have one release.this query itself is from a previous SO question i came accross
    [Query(IsDefault = true)]
    public IQueryable<PendingLoans> GetPendingLoans()
    {
        var query = from c in this.context.Loans
                  join p in this.context.Releases
                  on c.Id equals p.Loan.Id into cp
                  from p in cp.DefaultIfEmpty()
                  select new PendingLoans
                  {
                      Billno=c.BillNo,

                      releaseid = p == null ? 0 : p.Id
                  };
        return query.AsQueryable();

    }


text:
Q: How to fill the empty spaces in the grid in HTML? As I am displaying the notes on my note taking app, which is a grid, if I have a short note then there is empty space left. How can fill it up by pushing the cards below to go up and stick to card on the top. I am using bootstrap's grid layout for displaying the cards:- See here
I also have the screenshot of how the cards are looking currently.

You can see that there is a gap between the cards and I want to fill it up
Also here is the template of a single card
    let cardTemplate = `

${title.value}

                            ${content.value}

                        Show More
                        Delete
                        Edit

`;

and i am putting this card in a div whenever a button is clicked

I have not done any css on the div since I like the looks as it is.
Thanks for reading my query!

A: I think what you're looking for is masonry. It's a grid property that allows that exact behavior that you are looking for. It can be done with grid-template-rows:masonry;. Here is a link that would tell you exactly how you can do it.

A: Try adding class h-100 inside
** or h-50 or h-25,which makes an element or div as tall with height utilities. it is readily available in bootstrap.
refer this link for getting more information about pre-defined sizes classes in bootstrap


text:
Q: How many programming languages do you work with on a daily basis and how do you effectively manage language specific tasks Edit:
How do you manage individual tasks when working on multiple languages
In day to day task handling, how many different programming languages do you work with?

*

*Do you make a mental shift when working on each language?

*Do you Prioritize them and keep each task per language separately.

*Do you code in stages based on progress of each task switching seamlessly between languages/IDE/Environment

*Do you apply the same coding style/conventions on all the languages (not syntax)?

Related:
Is it normal for programmer to work on multiple projects simultaneously

A: As indicated by SK-logic the mental shift should not be a problem if you use well-choosen domain specific languages. But often you cannot choose the language, so it sometimes takes a moment to switch. In my experience the difficulty is more in switching syntax than in switching programming style. The only annoying shift that I always experience is the comment style shift: If I just open a file to quickly change a line of code, it often goes:
#  what
// the
;  f***
%  is
-- the one-line comment character or sequence?

A: In my last job: Java, C++, C#, JavaScript and VBScript.
But thankfully, all of the above were in very different contexts (and across a few products) - so once you knew each codebase well enough, the mental switch to different contexts was actually quite easy and logical.
In truth, what bothered me more was interruption by client support issues. Internally switching to a task in another language was never a problem in itself.

A: Today I've written Java, Python, C++, and SQL (if it counts). And I've been at work for less than 2 hours.
If you do this regularly, then the mental shift becomes negligible. It has nothing to do with multitasking. It's just like walking for a while, then driving a car, then driving a bike, then swimming. No problem, because they're sequential things.
Regardless, the point is to complete one task before moving to the next. I tend to define tasks in terms of a concrete functionality, fix, or such. Often that task is accomplished with only one language, but it may require several of them. For example, when working with JNI, you'll typically make changes to both the Java and native sides in parallel.
Some answers:

Do you code in stages based on progress on each task switching seamlessly between languages/IDE/Environment

It's important to be able to switch seamlessly between IDEs, editors, environments. Usually I keep them all open all the time.

Do you apply the same coding style /conventions on all the languages(Not syntax)?

If it's an interface over which two languages are talking, then yes - variable names and such must be similar. Otherwise, I try to apply the typical coding style of that language.

A: I work with 2 languages: c# and python.
I use them both in the same project, but obviously for different tasks.
When I'm working on a task, I work on that task until it is in a complete state, or until I can't concentrate on it any more. This means, if I have to switch between languages, there is little to no cognitive dissonance as I'll have already come out of thinking in either language when I'm done with the last task.
Admittedly I will take a short break when I come out of a task, which probably helps a lot.

A: As few as possible. It generally involves 1. Python, plus 2. HTML templating, 3. HTML+CSS and sometimes 4. Javascript. Switching from Python to JS definitely requires a mental shift, also because I need to use different tools.
I add HTML+CSS as separate from HTML templating even though the might not be languages per se (or they might, depends on your religion), because it also requires a mental shift and usage of other tools, although not so bad as switching to Javascript. Fiddling with HTML+CSS from a design perspective, to make the page look like the requires mockup, is a different mindset from making HTML templates. But it's more orthogonal to Python than Javascript, which means I need to switch out my programming mindset for another one. :)

A: Daily I use:

*

*HTML/CSS

*Javascript / JQuery

*VBScript / JScript

*PHP

*SQL

*C# / Asp.Net

I also use Python, Java and XML (does that count?) occasionally. My job involves editing various websites, which could be built in any web language (even had a Perl one once) and use wildly different paradigms/templates (procedural, MVC, OOP etc).
To answer the question - I mostly use Notepad++ as my IDE for the first 5 listed, then Visual Studio for Asp.Net.
It can be a pain switching quickly between each language - remembering whether or not you need semicolons at the end of lines, or whether if loops have braces or not. Switching from VBScript to JScript is the absolute worst for this - the files both end in .asp and look fairly similar at first glance, so it takes a while to work out why I'm getting errors.

A: I write applications for ISP side of things, there is also a culture of "do what you are comfortable with", often written by a lot of network engineers who dabble in programming.  I have to deal with on a weekly basis, programs that are quite well written, to the truly horrific.  What I will often encounter, and work on...

*

*Perl, Often quickie one-off scripts, or often used by people who only know (or like) Perl.  More of the legacy stuff is written in Perl I find.  Some of the worst stuff is written in Perl, not because the language is bad, but because it's easily misused by beginning programmers.  I still use this myself for certain types of one-off programs.  I rarely use it for anything larger.

*PHP, Lots of this around, often a starter language for the dabblers.  Some very well written programs, some schlock.  For certain types of web applications, I'll chose PHP because I can get it to ground quicker.

*Shell Scripting, Mostly use it for running other programs or tasks like reading logs.

*Expect, still encounter this (and zealots who insist it is nirvana for executing commands on network devices).  I work on it when I have to, but a baby kitten is killed somewhere in the world when I encounter one of those many thousands of lines long programs without a single function in sight, just one long iterative pasta farm.

*C, Rarely used because of portability issues, but I will use it to perform specific tasks.

*Java, I use this often because of extensive library support, and easy deployment.  We have a very heterogeneous network, and a IT staff that has an agenda different than mine.  With Java I can include libraries and not be concerned that IT has to "upgrade" something on the system I need to deploy the program.  Most often this is my programming language of choice.

There are also other languages (.net, VB, Phyton, Rails, etc) out there in the company, but I haven't had to work on them...yet.
Edit, for the edit...
You do have to mentally shift when you work between languages.  Most often what I'll lose track of is the syntax.  I keep a collection of reference books at the ready.  I'll find it takes about a half-hour to get back into the mindset of the other other language.  The more obtuse the syntax for the language, the longer the shift.  I find that shifting from doing Java to doing Perl probably takes the longest if I haven't touched Perl for a time.  The more you do this, the easier it gets.

A: At the moment I'm writing Ruby, PHP, Java, C and JavaScript and will write for a minimum of 1 hour in each of these each day. The main problem is really a matter of finding the time as they are all for unrelated projects.
Mental Shift
My work style is such that I like to work for large periods of time. Unfortunately, this means if I only have a single thing on, when I encounter a mental block with a piece of code, it will take a me a long time to get over it. I don't find taking a break helps either. By having other projects, and in particular other languages, to switch to whenever I get stuck means by the time I get back to the original language, I immediately have a solution.
Therefore, yes there is a mental shift and I think it makes me much more productive.
Prioritizing Tasks
I use a task manager (gTasks for Android) and have a separate todo list for each project. If a project requires multiple languages then I don't separate them. This is usually because they will be strongly related in some way. For example, JavaScript and Ruby for doing some AJAX stuff. If the languages are technically for the same project but the project is so large that they are essentially unrelated then I will likely count them as separate projects.
Generally, my priority is "whichever list has the most tasks" but I will always switch if I get stuck on a problem.
Coding Conventions
Its a bit of a mix:

*

*If the project is developed with others then obviously I will conform to whatever conventions have been decided on for that project.

*If the project is personal then I like my code to look consistent with the dominant style in the community/standard library for a given language. I find it hard to read Java code if all of the users functions are in snake_case, for example. Equally, camelCase methods in Ruby look weird and out of place.

*For conventions which aren't made obvious from simply using a language, such as indentation, I will tend to adopt my own standards and use them in all languages I use. In the case of indentation, I always use 2 spaces. For brace style, I always use what Wikipedia is currently deciding to call the Compact Control Readability Style.

Aside: The biggest challenge for me is actually switching between style languages. It is very difficult to be racing along when coding SASS alongside Ruby and then having to switch back to CSS for everything else. To a lesser extent, I have the same problem with HAML/HTML and JSON/XML.

A: There's a pattern forming here:

*

*Front end: whatever runs on a browser (javascript, html and css)

*Business Logic: any of the whole plethora of general-purpose languages

*Backend: SQL

*Build Script: Some scripting language

So for me its: javascript, HTML, and CSS, C#, Transact-SQL, and Windows Powershell.

Do you apply same coding style /conventions on all the languages(Not syntax)?
No, I make a point of programming according to the convention of the language. A simple example:
   // C#
   int MyFunction()
   {
       return 0;
   }

   // Javascript
   function myFunction() {
      return 0;
   }

Employing visually different coding conventions helps me make the mental shift between languages. Conversely, if my code looked the same in each language, I'm going to make syntactical errors from forgetting which language I'm coding in.

A: I am often using six or more languages within one project. Most of them are usually specific to that project only.
Mental shift is only required if you're using a language that is not appropriate for a task. Otherwise it is natural to use the best fit. Different sets of languages are used for different stages of a project.

A: I use C (embedded), C++ (desktop), Python, Matlab and VHDL (a sort of hardware programming language) on a frequent basis, often all in the same day.  In my environment, this sort of language dexterity is essential in my view.
I often can't get everything I need to on a particular project done in one language efficiently. For example, both embedded C and VHDL are pretty low-level, so I often use Python to parse their results (or even generate code).
Switching between them rapidly is not an issue after a while, it's like switching from a hammer to a screwdriver - right tool for the job.

A: It really depends on how working is defined... I use C# for developing Microsoft Surface applications every day. Java I also use every day for my Android applications. But I try to educate myself and started using R, Ruby and Objective-C. Sometimes I also need some SQL and if you include script languages and other languages into your question then also JavaScipt, SPARQL and BeanShell.
Do you apply the same coding style /conventions on all the languages(Not syntax)?
I try to follow the coding conventions of each language but especially between Java and C# I have some difficulties because of the curly braces and the upper case method naming in C#:
public void test() {
   ...
}

vs.
public void Test()
{
   ...
}

A: I build web apps. So currently its:

*

*XHTML

*JavaScript

*C# as part of the

*ASP.Net Framework (this sort of is a language too)

*T-SQL for database communication

*English for communicating with humans.

Editors: Sublime Text (out of choice), Visual Studio 2010 (no other feasible choice when it comes to ASP.Net)

A: At my job I use Java, C, Python, Django, and small bits of PHP.  I also worked on a really small project in Microsoft's C++.
I don't use all of them everyday, but some days I do use them all with no problem.  On a typical day I only use one or two.  The programming I do at home usually involves working with different technologies than I use at work like Qt or Ruby on Rails.


text:
Q: Rails: Multi-tenancy with Devise and Apartment gem I'm creating a multi-tenant app using devise and apartment gems. I'm using postgresql database. I've created a few models. 'User' model is in global namespace and it is used for authentication by devise gem. There are some other models (e.g. Project, Setting etc) which are in tenant namespace.
I've followed this tutorial for creating this multi-tenance app: https://gorails.com/episodes/multitenancy-with-apartment?autoplay=1
The multi-tenancy feature is working fine in a sense that if I login to two separate subdomains (e.g. user1.example.com and user2.example.com) from their relevant accounts (e.g. user1@gmail.com and user2@gmail.com) it works fine and I can create unique records for each tenant.
Now, the issue is, I can login to any subdomain using any email and the tenant records would be shown based on the subdomain present in address bar. e.g. I can login with user1@gmail.com at user2.example.com and it will succesfully autheticate and will display records of user2 tenant.
My question is, while logging in how can I check if current user's subdomain matches with the requested subdomain (on address bar), if it matches proceed with authentication and display admin dashboard and if not (logging in from wrong subdomain or from TLD) authenticate the user but redirect him to his relevant subdomain's dashboard. How can I do that?
UPDATE # 1:
I was able to restrict the user login to their specific sub-domain by using minor devise configuration. In devise.rb file I've added :subdomain attribute in the list of authentication keys, so it will also check for correct subdomain value together with email, however I'm not sure how to provide the subdomain value to the login form correctly. I can use a hidden field like this in login form <%= f.hidden_field :subdomain, value: request.subdomain %> but it is hackable as user can change it's value from browser inspector.
UPDATE # 2:
I was able apply a fool proof method to restrict user login to their specific sub-domain. I've followed this method: https://github.com/plataformatec/devise/wiki/How-to:-Scope-login-to-subdomain
Now, my only issue is that user is unable to login from TLD (e.g. example.com), I want it to be possible but after login user must be redirected to their relevant sub-domain with alive session.

A: Supposing you're saving the subdomain on the User model, you can create a validation in your controller you can use something like:
if user.subdomain == request.subdomain
  redirect_to root_url(subdomain: user.subdomain)
else
  everything_is_ok
end

A: If you store your subdomain in your User table and if you check it via request.subdomain then how can someone join the another tenant(company) ? They can be included in more than one company.
That's why, I created 2 middle tables to handle it.

*

*I've user table for all of my users.

*I've account table to store subdomains with its creator.

*And I've account_permissions to find out who are authorized to where.

So, when user1 comes to user2.example.com, I'm querying to my Account_permissions and if it has permission for user2.example.com, I let it go.
This way seems like sense.

A: If someone still have a similar problem and is not very expert in ROR, I suggest  building the base app first and then making it multi_tenant using that video.
After building your app, you only need to install the apartment gem, then make a model which stores tenants information and then exclude it from being multi_tenanted.


text:
Q: How do I associate a single record with a multiple factory girl models? I have a User model and Country model. There are a limited set of countries (only 1 right now) and in my factory, I'm not sure how to associate each User record with a single Country. I tried creating a country factory and associating each user with a country but since my country data is static, it tried to create a new country for each user, which failed because i have uniqueness validations on country. Here's what I tried:
  factory :country do
    country_iso 'GB'
    country_code 44
    country 'United Kingdom'
    active true
  end

  factory :user do
    email { Faker::Internet.email }
    password { Faker::Internet.password(10) }
    country

    after(:create) do |usr, evaluator|
      create_list(:canned_response, 3, user: usr)
    end

    trait :admin do
      admin true
    end
  end

How do I create a single Country that each user factory created will be associated with?

A: You can use the existing country or create one if none exists:
factory :user do
  email { Faker::Internet.email }
  password { Faker::Internet.password(10) }
  country { Country.first || create(:country) }

  # ...
end


text:
Q: How to convert HTML to RTF in UWP I want to convert HTML to RichTextBlock in UWP. I found some answers in stackoverflow tried the code in following link
link
But when I try to bind html property in richtextblock controls it gives error saying The name "Properties" does not exist in the namespace "using XAMLHtml"
I included following code to convert HTML to RTF in XAMLHtml.cs file
class XAMLHtml
{
    public class HtmlProperties : DependencyObject
    {
        public static readonly DependencyProperty HtmlProperty =
            DependencyProperty.RegisterAttached(
                "Html",
                typeof(string),
                typeof(HtmlProperties),
                new PropertyMetadata(null, HtmlChanged));

        private static RichTextBlock _currentObject;

        private static void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var richText = d as RichTextBlock;
            if (richText == null) return;

            _currentObject = richText;

            //Generate blocks
            var xhtml = e.NewValue as string;
            var blocks = GenerateBlocksForHtml(xhtml);

            _currentObject = null;

            //Add the blocks to the RichTextBlock
            richText.Blocks.Clear();
            foreach (var b in blocks)
                richText.Blocks.Add(b);
        }

        private static List<Block> GenerateBlocksForHtml(string xhtml)
        {
            var blocks = new List<Block>();

            try
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(xhtml);

                var block = GenerateParagraph(doc.DocumentNode);
                blocks.Add(block);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return blocks;
        }

        // TODO this method seams to be removing necessary spaces in #text nodes
        private static string CleanText(string input)
        {
            var clean = Windows.Data.Html.HtmlUtilities.ConvertToText(input);
            //clean = System.Net.WebUtility.HtmlEncode(clean);
            if (clean == "\0")
                clean = "\n";
            return clean;
        }

        private static Block GenerateBlockForTopNode(HtmlNode node)
            => GenerateParagraph(node);

        private static void AddChildren(Paragraph p, HtmlNode node)
        {
            var added = false;
            foreach (var child in node.ChildNodes)
            {
                var i = GenerateBlockForNode(child);
                if (i != null)
                {
                    p.Inlines.Add(i);
                    added = true;
                }
            }
            if (!added)
            {
                p.Inlines.Add(new Run { Text = CleanText(node.InnerText) });
            }
        }

        private static void AddChildren(Span s, HtmlNode node)
        {
            var added = false;

            foreach (var child in node.ChildNodes)
            {
                var i = GenerateBlockForNode(child);
                if (i != null)
                {
                    s.Inlines.Add(i);
                    added = true;
                }
            }
            if (!added)
            {
                s.Inlines.Add(new Run { Text = CleanText(node.InnerText) });
            }
        }

        private static Inline GenerateBlockForNode(HtmlNode node)
        {
            switch (node.Name)
            {

                case "b":
                case "B":
                case "strong":
                case "STRONG":
                    return GenerateBold(node);
                case "i":
                case "I":
                case "em":
                case "EM":
                    return GenerateItalic(node);
                case "u":
                case "U":
                    return GenerateUnderline(node);
                case "br":
                case "BR":
                    return new LineBreak();
                default:
                    return GenerateSpanWNewLine(node);
            }

        }

        private static Inline GenerateBold(HtmlNode node)
        {
            var bold = new Bold();
            AddChildren(bold, node);
            return bold;
        }

        private static Inline GenerateUnderline(HtmlNode node)
        {
            var underline = new Underline();
            AddChildren(underline, node);
            return underline;
        }

        private static Inline GenerateItalic(HtmlNode node)
        {
            var italic = new Italic();
            AddChildren(italic, node);
            return italic;
        }

        private static Block GenerateParagraph(HtmlNode node)
        {
            var paragraph = new Paragraph();
            AddChildren(paragraph, node);
            return paragraph;
        }

        private static Inline GenerateSpanWNewLine(HtmlNode node)
        {
            var span = new Span();
            AddChildren(span, node);
            if (span.Inlines.Count > 0)
                span.Inlines.Add(new LineBreak());
            return span;
        }

    }
}

here what I write in xaml file
<Page
x:Class="SampleHtml.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converter="using XAMLHtml"
xmlns:html="using HTMLPage1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <RichTextBlock converter:Properties.Html="{Binding HTMLPage1}" Grid.Row="0"/>
</Grid>

here is the code in html file

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

This text is bold

This text is italic

This is subscript and superscript

If anyone can help me with this I would appreciate.Thank you

A: This project is class lib for UWP platform. please download the full project and refer it.
I check the code the class name is HtmlProperties but not Properties, so you need edit your xaml code like the following
<RichTextBlock converter:HtmlProperties.Html="{x:Bind HtmlString}" />

In general we could use WebViewBrush to get the webview content then set it the  Rectangle control. for more please refer this document.


text:
Q: Поиск элементов с одинаковой длиной в кортеже Получаю данные бд в кортеж, после этого мне нужно отделить номер телефона и изменить его. Была идея превратить кортеж в строку, но как дальше вырезать номер из строки не понял. Пытался реализовать поиск по длине, но со вложенным кортежем это кажется невозможным. Подскажите пожалуйста в какую сторону думать.
def execute_read_query(connection, query):
cursor = connection.cursor()
result = None
try:
    cursor.execute(query)
    result = cursor.fetchall()
    return result
except Error as e:
    print(f"The error '{e}' occurred")

select_persdata = "SELECT * from personal"
numbers = execute_read_query(connection, select_persdata)

for user in numbers:
    print(user)