text:
Q: Need help understanding this inheritence hierarchy I am looking at a complex and generic legacy framework which I will eventually need to extend, first up however is to simply understand it, and I'm struggling to do so due to the inheritence hierarchy and structure.
This all forms part of the inner workings of a WCF services stack, handling the requests, responses, etc.
I've included only the class signatures and their constructors as a sample as the inner functionality is of no concern.
public sealed class ProcessDerived : ProcessBase<Filter, RequestExternal, RequestItemExternal, ResponseCallBack, ResponseInternal>
{
    public ProcessDerived(ProcessManager Manager) : base(Manager) { }
}

public abstract class ProcessBase<TFilter, TRequestExternal, TRequestItemExternal, TResponseCallBack, TResponseInternal>
    : ProcessBaseSync<TFilter, TRequestExternal, TRequestItemExternal, TResponseCallBack, TResponseInternal>
    where TFilter : FilterBase
    where TRequestExternal : class
    where TRequestItemExternal : class
    where TResponseCallBack : class
    where TResponseInternal : ProcessResponseBase
{
    protected ProcessBase(ProcessManager Manager) : base(Manager) { }
}

public abstract class ProcessBaseSync<TFilter, TRequestExternal, TRequestItemExternal, TResponseCallBack, TResponseInternal>
    : ProcessBaseCache<TFilter, TRequestExternal, TRequestItemExternal, object, TResponseCallBack, TResponseInternal, CacheKeyBase>
    where TFilter : FilterBase
    where TRequestExternal : class
    where TRequestItemExternal : class
    where TResponseCallBack : class
    where TResponseInternal : ProcessResponseBase
{
    protected ProcessBaseSync(ProcessManager Manager) : base(Manager) { }
}

public abstract class ProcessBaseCache<TFilter, TRequestExternal, TRequestItemExternal, TResponseImmediate, TResponseCallBack, TResponseInternal, TCacheKey>
    : IProcess, IProcess<TFilter, TResponseInternal>, IProcess<TResponseCallBack>
    where TFilter : FilterBase
    where TRequestExternal : class
    where TRequestItemExternal : class
    where TResponseImmediate : class
    where TResponseCallBack : class
    where TResponseInternal : ProcessResponseBase
    where TCacheKey : CacheKeyBase
{
    private ProcessManager _manager;

    protected ProcessBaseCache(ProcessManager Manager)
    {
        _manager = Manager;
    }
}

The main questions I have:
1) What is the technical term used to describe this multiple inheritence structure, like seen on the first line: "ProcessDerived : ProcessBase".
It reminds me of tuples, but I don't understand whats happening here on a technical level. Is this just a way to get around the multiple inheritence limitation?
2) Does it inherit from "ProcessBase" as well as all the type parameters next to it?
3) What is the purpose of adding ": base(XYZ)" to the constructor? Is this simply a requirement to match the class inheritence (constructor mimicking the class signature)? I don't understand why this is required.
This complex 4-tier hierarchy seems very unecessary and feels impossible to follow.
I'm clearly missing some fundamental C# knowledge here.

A: To answer your first (and second) question, you can extend a single base class and then implement several interfaces, but the code you posted only extends a single base class. It just happens that ProcessBase accepts 5 different types, but it's still one class.

As for your third question, they added base because the class extends a base class that doesn't have a parameterless constructor.
Here's a simpler example demonstrating the same concept. The Person class has a single ctor expecting a name, so any class that extends it must provide that parameter via a call to base().
public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

public class Employee : Person
{
    public DateTime HireDate { get; set; }

    public Employee(string name, DateTime hireDate) : base(name)
    {
        HireDate = hireDate;
    }
}

A:
1) What is the technical term used to describe this multiple inheritence structure, like seen on the first line: "ProcessDerived : ProcessBase.

That's single inheritance. ProcessDerived inherits from ProcessBase<Filter, RequestExternal, RequestItemExternal, ResponseCallBack, ResponseInternal>.

2) Does it inherit from "ProcessBase" as well as all the type parameters next to it?

ProcessBase<Filter, RequestExternal, RequestItemExternal, ResponseCallBack, ResponseInternal> is a (closed generic) type. ProcessDerived inherits from it.
ProcessBase<TFilter, TRequestExternal, TRequestItemExternal, TResponseCallBack, TResponseInternal> is the corresponding open generic type -- the type parameters TFilter etc haven't yet been specified.

3) What is the purpose of adding ": base(XYZ)" to the constructor? Is this simply a requirement to match the class inheritence (constructor mimicking the class signature)? I don't understand why this is required.

When you subclass is instantiated, it needs to call one of the base class's constructors. If the base class has a parameterless constructor, this is called implicitly. If it doesn't, you need to explicitly call one of its constructors, passing all necessary parameters, using : base(...).

I'm clearly missing some fundamental C# knowledge here.

I suspect the knowledge you're missing is around generics - you seem to think that generic types, and generic type parameters, are involved in inheritance.


text:
Q: Add same member many time together with add card trello but don't work Add same member many times to gather with add card trello but don't work
PROBLEM
When I input an same username, for example
{ "adwin", "adwin", "robert", "dave"}

If first adwin finishes loop add member is ok, then second adwin time to add.
The code exit loop and stop working.
and
When I input usernames aren't in the board or username is fake.
{ "hghg$*#hgh", "us7s5209hf9", "8shjd76dhj3" }

When add card finish and come to add Member It's stop working and exit program.
It's not working loop to finish to add another username.
Plan
I think add Member to a board before add into a card will work but it not work again.
#r"Manatee.Trello.dll"
#r"Manatee.Json.dll"
using System.Net;
using System.ComponentModel;
using System.Drawing;
using System.Windows;
using Manatee.Trello;
using Manatee.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    string Appkey = "df45ee60b0ff10c19377354490f7054b";
    string Token = "6af303020a7a4d24d9cf5a1dd8adf2e5ff95c46888b0371c0b2dba45b2a32d7d";
    string BoardID = "5b40363293193091c1ba5013";
    string ListID = "5b40363293193091c1ba5015";
    string name ="CardAddMember";
    string description ="desccccc";
    string duedate ="2019-08-04";
    string iscomplete =true;
    string[] user = {"userinboard","notusername","userinboard"};
        try
        {
            DateTime duedatetime = DateTime.Parse(duedate);//time
            bool torf = Boolean.Parse(iscomplete);//finish work check
            TrelloAuthorization.Default.AppKey = Appkey;
            TrelloAuthorization.Default.UserToken = Token;
            ITrelloFactory factory = new TrelloFactory();
                var List = factory.List(ListID);
                var Board = factory.Board(BoardID);
                //var MemberType = factory.Board();
                char[] commaSeparator = new char[] { ',' };
                string[] authors = username.Split(commaSeparator, StringSplitOptions.None);
                var card = await List.Cards.Add(name, description, null, duedatetime, torf, null, null);//add card to trello

                foreach (string author in authors){
                    var Member = factory.Member(author);
                    await Board.Memberships.Add(Member); // Add member in a board but cant add <<<<<<<<<????????
                    await card.Members.Add(Member); //add member in card
                }
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            return response;
        }
        catch //find some err [example not find user]
        {
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
}

What should I do ?
Cr.marc_s edit world

A: You're going to need to check the members before you add them.  Trello returns an error when you attempt to add a member to a board/card but that member already exists.  This, in turn, will cause Manatee.Trello to throw an exception.
Additionally, a member must belong to a board before they can be assigned to a card.
Checking for these members first should resolve your problem.
await Board.Memberships.Refresh(); // this will fetch all of the members of the board

foreach (string author in authors){
    var Member = factory.Member(author);
    if (!Board.Memberships.Any(m => m.Member == Member))
        await Board.Memberships.Add(Member);
    if (!Card.Members.Contains(Member))
        await card.Members.Add(Member);
}

This should resolve the problems you're seeing.
Lastly, when you catch an exception, it's helpful to specify the exception and possible print out or log the result.  Trello's pretty good at returning error messages with their failure responses, and Manatee.Trello will include them in its TrelloInteractionExceptions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi string replace im trying to replace normal text with ascii text in this program:
so a will be replaced by â & ETC.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TextConverter
{
    public partial class TextCoverter : Form
    {
        public TextCoverter()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] normal = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
            string[] ascii = { "â", "ß", "ç", "ð", "è", "ƒ", "ģ", "н", "ι", "j", "ќ", "ļ", "м", "и", "ю", "ρ", "Ω", "ѓ", "$", "τ", "ט", "Λ", "ш", "χ", "У", "ź" };

            for (int i = 0;  i < 26; i++)
            {
                textBox2.Text = textBox1.Text.Replace(normal[i], ascii[i]);
            }

        }

    }
}

But it doesn't replace with Ascii. Please help.

A: Since you are writing the result into a variable that is different from the original, only the last letter gets replaced. You should either write to the same box, or write to a temp string, and write it to the second box at the end.
var tmp = textBox1.Text;
for (int i = 0;  i < 26; i++)
{
    tmp = tmp.Replace(normal[i], ascii[i]);
}
textBox2.Text = tmp;

Generally speaking, this is not the most efficient algorithm to do replacements, because it operates on an immutable string. You would be better off creating a mutable string builder, and writing it one character at a time.
const string repl = "âßçðèƒģнιjќļмиюρΩѓ$τטΛшχУź";
var res = new StringBuilder();
foreach (char c in textBox1.Text) {
    if (c >= 'a' && c <= 'z') {
        res.Append(repl[c-'a']);
    } else {
        res.Append(c);
    }
}
textBox2.Text = res.ToString();

A: textBox2.Text = textBox1.Text.Replace(normal[i], ascii[i]);
you replace textBox1 again and again, but not save previos state, so work only last loop iteration


text:
Q: HTML - Line break gets interpreted as whitespace character When coding in HTML & PHP, line breaks get interpreted as a space character. This can be problematically when using a list in order to achieve a horizontal menu because the space changes the padding unpredictably. I use this workaround for this:
Note: The
 elements will have a display: inline(-block); property.

...
<?php
    ?>
...
<?php
    ?>
...
<?php
    ?>
...
<?php
    ?>
...

This is really sad. I don't think it is supposed to be that way. I also don't want to mess up the code in a different way by say... add both
 and the next
 on one line (which is essentially the same as above).
Question: Is there a best practice solution for this?

A: After giving this some more research, I came up with the solution. Like here, people try to advertise my problem to others as a solution, which I won't accept.
But it's so simple. Don't use inline-block
.horizontal-menu ul li
{
    display: inline-block;
}

But use table-cell!
.horizontal-menu ul li
{
    display: table-cell;
}

Next time I have a similar issue, I will just try out more display options :)


text:
Q: Logarithms Question Find the logarithms of the following numbers to the base 2:
32
I know 32 is 2^5. What is the format of the answer? Thanks

A:
Find the logarithms of the following numbers to the base 2:
(...)
What is the format of the answer?

This is usually written as:
$$\log_{2} 32$$

I know 32 is 2^5.

This is indeed equal to $5$ for exactly that reason:
$$\log_{2} 32 = 5 \iff 2^5 = 32$$
Or in general (for $a>0$ and $a \ne 1$, $x>0$):
$$\log_{a} x = y \iff a^y = x$$


text:
Q: c# wrapper for c++ library,char array to stype* i have a c++ library and i wanted to write a wrapper in c# for a function in the library.Function returns string  from library and i convert it char array in wrapper and function in the wrapper returns a char * to UI Form ,data that comes from wrapper converted to a sbyte* in the UI Form.I try to convert it to string in UI like this:
//i am giving values from a textbox
//and i am calling Function from wrapper
sbyte * data=c++library.class.function(double parameter1,double parameter2);
string result = new string.Empty;
while(*data!='\0'){
      result +=(char)(*data);
      ++data;
}
// and i try to show string in a textbox when i click a button,
textbox.Text=result;

but when i click the button,if i wait to see "12345" in textbox,i am seeing "&%**>" likee this unicode charecters,and if i continue to click button,string is changing,most times i can see right data but,continue to click it changes and showing unicode characters.
Can u help me abot How can i resolve this problem?

A: You need to use Platform Invoke, and let it marshal the string.

A: No, you will have to write the p/invoke code yourself. Though I have some code that does exactly what you need, since it is untested, I would rather refer you to a published article that has received good marks from peers.
Check out "Advanced Topics in PInvoke String Marshaling," at  http://www.codeproject.com/Articles/138614/Advanced-Topics-in-PInvoke-String-Marshaling,


text:
Q: spring boot serve angular Im having trouble serving my angular application with Spring boot.
@RequestMapping("/home")
public String home() {
    return "index";
}

Folder structure
resources > public > index.html

If I go to localhost:8080/home I get this error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback.

Mon Dec 17 13:30:33 CET 2018
There was an unexpected error (type=Internal Server Error, status=500).
Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'

But if I go directly to http://localhost:8080/index.html it does work
If I go straight to http://localhost:8080 I get:
No mapping for GET /

A: Files you place under resources/public are for static hosted files - this is where you would place html landing pages, css, images and JS resources - no request mapping is needed in code.
Your code example should only return the string defined but without seeing the rest of the code its hard to say why its failing.


text: Q: SQL Reporting Service URL: 404 Not Found. No funciona la url de reporting service al iniciar el report server configuration manager y le doy iniciar, cuando accedo al LINK del servicio web url me da un error que es el de la siguiente imagen


text:
Q: Javascript obejct merge+add algorithm I was trying to merge & add these two objects like this :
obj1 = {
  jpg: 1,
  gif: 3,
}

obj2 = {
  jpg: 1,
  avi: 5,
}

obj3 = mergeAdd(obj1, obj2);
// obj3 = {
//   jpg: 2,
//   gif: 3,
//   avi: 5,
// }

First, I create this which takes O(n^2) likes :
for (let foo in obj1) {
  for (let bar in obj2) {
    if (foo === bar) {
      // Exists : Add count
      obj1[bar] += obj2[bar];
    } else {
      // Don`t Exists : Copy from obj2
      obj1[bar] = obj2[bar];
    }
  }
}

And then, one 'new idea' came into my mind - using hash function :

*

*Get hash value for 'key' of obj1 & obj2.

*Insert or add 'value' of obj1 & obj2 to new array using their hash value as an index of the array.

*Make the array into new object.

What I want to know :

*

*Is there any library which have function like mergeAdd(obj1, obj2)?

*Is my 'new idea' faster than mergeAdd(obj1, obj2)?

*What is the fastest algorithm to do mergeAdd?

Thanks!

A: A solution with linear complexity.

var obj1 = { jpg: 1, gif: 3, },
    obj2 = { jpg: 1, avi: 5, },
    merged = function (array) {
        var r = {};
        array.forEach(function (a) {
            Object.keys(a).forEach(function (k) {
                r[k] = (r[k] || 0) + a[k];
            });
        });
        return r;
    }([obj1, obj2]);

document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');

A: Are you able to use ES6? you can do this easily with the new Object.assign() method:
let newObj = Object.assign({}, obj1, obj2);

without ES6:
var newObj  = {};
obj1 = {
  jpg: 1,
  gif: 3,
};

obj2 = {
  jpg: 1,
  avi: 5,
};
Object.keys(obj1).forEach(function(k) {
    newObj[k] = obj1[k];
});
Object.keys(obj2).forEach(function(e) {
    newObj[e] = obj2[e];
});

working fiddle: https://jsbin.com/rogada/edit?js,console
taken from: http://es6-features.org/#ObjectPropertyAssignment

A: A generic recursive/functional solution. Takes an array of objects and merges each one into an output object. No idea how performant it is compared to the other answers though - it's probably pretty bad.
function addValues(obj) {
  return function (p, c) {
    p[c] = (p[c] || 0) + obj[c];
    return p;
  }
}

function mergeObject(obj, out) {
  return Object.keys(obj).reduce(addValues(obj), out);
}

function processArray(arr, fn, out) {
  out = out || {};
  if (!arr.length) return out;
  out = fn(arr.shift(), out);
  return processArray(arr, fn, out);
}

var arr = [{ jpg: 1, gif: 3 }, { jpg: 1, avi: 5, }];
processArray(arr, mergeObject); // { jpg: 2, gif: 3, avi: 5 }

DEMO


text:
Q: Firebird select statement gives SQLSTATE = 42S02 I've made a very simple database and am trying
select * from klant;

I've verified the table exists, and last week was able to see data in it. Today however I keep getting
Statement failed, SQLSTATE = 42S02
Dynamic SQL Error
-SQL error code = -204
-Table unknown
-KLANT
-At line 1, column 15

The same select query in flameRobin gives the following error:
Error: *** IBPP::SQLException ***
Context: Database::Statistics
Message: isc_database_info failed

SQL Message : -902
can't format message 13:98 -- message file C:\WINDOWS\SYSTEM32\firebird.msg not found

Engine Code    : 335544727
Engine Message :
Error writing data to the connection.

I have copied the firebird.msg to the system32 folder so it should be able to find it there.
Any pointers toward the solution would be greatly appreciated. Similar question  all seem to point toward issues with transactions, I can't see that being the problem here.
Edit:
I'm using the included ISQL tool from firebird and start the session by connecting to the database that includes my table. Same for flamerobin, first connect to database, I can see the table that i want to select from but it gives this error.
Edit2:
Finally reinstalled Firebird making sure I gave it admin right, which I think it had before, but wasn't sure about. This seems to have fixed it.


text:
Q: UIScrollView overlapping popping UIViewController I've got a UIScrollView with multiple pages, each containing a UITableViewController (similar to the Reminders-App).
Clicking a cell in each of these UITableViewControllers cause a DetailViewController to be pushed.
However, when the DetailViewController gets popped, it immediately disappears behind the UIScrollView, instead of sliding away smoothly. I can see the next page of the UIScrollView sliding away, but when the DetailViewController is pushed from the last page, the transition looks fine because there is no content on the UIScrollView that could overlap the dismissed DetailViewController.
Edit
This is how I create the view controller hierarchy (simplified):
ScheduleViewController.m:
- (void) viewDidLoad {
    // ...
    for (int i = 0; i < 3; ++i) {
        MyTableViewController *myTableViewController = [[MyTableViewController alloc] initWithNibName:@"MyTableView" bundle:nil];

        [self.scrollView addSubview:myTableViewController];
        [self addChildViewController:myTableViewController];
        [myTableViewController didMoveToParentViewController:self];
    }

And here is
tableView:didSelectCellAtIndexPath: in MyTableViewController:
(void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // ...
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

        DetailViewController* detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
        [self.navigationController pushViewController:detailViewController animated:YES];

    }
}

What could I be doing wrong here? Are there any workarounds to this behavior?

A: The superview for your UIScrollView needs to have clipsToBounds set to TRUE (the option is called Clip Subviews in the interface builder, if you creating your view that way.) As you noticed, it appears that the UIScrollView is probably running off its superview, since it is so much larger, and that is causing your animation to look bad. Clipping it will keep that from happening.


text:
Q: Poor performance with QSyntaxHighlighter of QTextEdit In  Syntax Highlighting in QTextEdit example, I want highlight xml text in a QTextEdit, so change only some part of text, like the one in the angle brackets, and not all text.
All work properly, but with big file, the software not responding.
is there any way to slow down the refresh Or as an alternative refresh only the visible part of the QTextEdit?
Thank you

A: I use this way For Highlighting in QTextEdit:
I add one QTextEdit in my UI file :

and In mainwindow.cpp Just add this:
MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->textEdit->setTextBackgroundColor(Qt::yellow);
}

means setTextBackgroundColor(Qt::yellow);
This is its result:


text:
Q: javascript split('\n') and not ('\n\n') I am trying to make a filter that splits all \n and rejoins them as \n\n. Is there a way to bypass all \n\n combinations and only target the single \n? The issue now is that everytime i unfocus the input the filter fires and adds additional spaces to existing double spaces.
working fiddle: https://jsfiddle.net/oe7axeab/701/
        filters: {
        lyrics: {
            write(input) {
                var line = input,
                        bomb = line.split("\n"),
                        group = bomb.join("\n\n");

                return group;
            },
        },
        marked: marked
    }

A: I am trying to create a regex where in it will select only single instance of \n and convert that to \n\n
var str   = 'test \n test1 \n\n test2 \n test3 \n\n';
    **var regex = /([^\n]+)\n([^\n]+)/g;**

    if (str.match(regex)) {
        str = str.replace(regex, "$1" + "\n\n" + "$2");
    }

Output : 'test \n\n test1 \n\n test2 \n\n test3 \n\n'


text:
Q: How to split row data into multiple columns I have data like this:
ColumA
A1:Data1 A2:Data2 A3:Data3
A1:Data4 A2:Data5 A3:Data6

I want to produce output like this:
A1        A2        A3
Data1     Data2     Data3
Data4     Data5     Data6

A: You can use pivot To use rows as a column Here is one interesting Link Refer This.

A: declare @T table
(
  ColumnA varchar(50)
)

insert into @T values
('A1:Data1 A2:Data2 A3:Data3'),
('A1:Data4 A2:Data5 A3:Data6')

select substring(ColumnA, Pos.A1+3, Pos.A2-Pos.A1-3) as A1,
       substring(ColumnA, Pos.A2+3, Pos.A3-Pos.A2-3) as A2,
       substring(ColumnA, Pos.A3+3, Pos.AX-Pos.A3-3) as A3
from @T as T
  cross apply (select charindex('A1:', ColumnA) as A1,
                      charindex('A2:', ColumnA) as A2,
                      charindex('A3:', ColumnA) as A3,
                      len(ColumnA)+1            as AX) as Pos


text:
Q: Access denied to a file on FAT file system I just got a new phone which is supplied with a 2 GB SD card. I bought a bigger card to replace it and I want to copy the preloaded data to the new card.
The default card's filesystem is FAT and I've formatted the new card with FAT32.
So far so good.
When I'm trying to copy the data from the default card, I receive an access denied error on some of the files, the system won't allow me to read them.
How can I unlock these files? As this is a FAT file system, taking ownership in Windows 7 doesn't have any effect. I tried creating an image and writing the image but that makes the partition only 2 GB big - and doesn't really fix the problem of me being unable to copy (e.g. backup) the files.

A: Since you've tried the .iso (creating an image) approach, why not mount the .iso in Windows and copy it out of the image to the new card? Directions for this process: howtogeek.com/howto/windows-vista/…

A: Can you run chkdsk on the card, or a similar tool, to see if the operating system is rejecting reads from them because of corruption?

A: If you just tried to mass copy everything on it, your phone has likely placed some files on it that are locked for it's use only, and you wouldn't want them anyway.
Unless you skip those that are denied and then you can pinpoint an actual file as having be one of yours...


text:
Q: Wagtail Page Reverse Error when trying to edit a page I'm getting the following error:
Reverse for 'wagtail_serve' not found. 'wagtail_serve' is not a valid view function or pattern name.

This is a new install and I'm trying to edit the default landing page. I've never had this error before.
Django==2.2.1
wagtail==2.5
wagtail-condensedinlinepanel==0.5.2
wagtailmenus==2.13

Any ideas on what could be causing this? Did I miss a setting somewhere? Any suggestions?


text:
Q: Making GET request to a tiktok url in order to get a canonical link I want to make a GET request to a tiktok url via python but it does not work.
Let's say we have a tiktok link from a mobile app – https://vt.tiktok.com/ZS81uRSRR/ and I want to get its video_id which is available in a canonical link. This is the canonical link for the provided tiktok: https://www.tiktok.com/@notorious_foodie/video/7169643841316834566?_r=1&_t=8XdwIuoJjkX&is_from_webapp=v1&item_id=7169643841316834566
video_id comes after /video/, for example in the link above video_id would be 7169643841316834566
When I open a mobile link on my laptop in a browser it redirects me to the canonical link, I wanted to achieve the same behavior via code and managed to do it like so:
import requests
def get_canonical_url(url):
    return requests.get(url, timeout=5).url

It was working for a while but then it started raising timeout errors every time, I managed to fix it by providing cookie. I made a request to Postman(it works when I make GET request through postman though), copied cookies, modified my function to accept cookies and it started working again. It had been working with cookies for ~6  months although last week it stopped working again, I thought that the reason might be in the expired cookies but when I updated them it didn't help.
This is the error I keep getting:
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='www.tiktok.com', port=443): Read timed out. (read timeout=5)

The weirdest thing is that I can make my desired request just fine via curl:

Or via Postman:

Recap
So the problem is that my python GET request never succeeded and I can't understand why. I tried using VPN in case tiktok has banned my ip, also I tried to run this request on some of my servers to try different server locations but none of my attempts worked.
Could you give me a piece of advice how to debug this issue further or maybe any other ideas how I can get video_id out of mobile tiktok link?

A: Method 1 - Using subprocess
Execute curl command and catch the output and it will take ~0.5 seconds.
import subprocess
import re
process_detail = subprocess.Popen(["curl", "https://vt.tiktok.com/ZS81uRSRR/"], stdout=subprocess.PIPE)
output = process_detail.communicate()[0].decode()
process_detail.kill()
canonical_link = re.search("(?P<url>https?://[^\s]+)+\?", output).group("url")
print("Canonical link: ", canonical_link)

Method 2 - Using proxies
We need to use proxies. here is the solution for free proxies which we can scrap and apply dynamically using BeautifulSoup..
First install BeautifulSoup using pip install BeautifulSoup
Solution:
from bs4 import BeautifulSoup
import requests

def scrap_now(url):
    print(f"<======================> Scrapping Started <======================>")
    print(f"<======================> Getting proxy <======================>")
    source = requests.get('https://free-proxy-list.net/').text
    soup = BeautifulSoup(source, "html.parser")
    ips_container = soup.findAll("table", {"class": "table table-striped table-bordered"})
    ip_trs = ips_container[0].findAll('tr')
    for i in ip_trs[1:]:
        proxy_ip = i.findAll('td')[0].text + ":" + i.findAll('td')[1].text
        try:
            proxy = {"https": proxy_ip}
            print(f"<======================> Trying with: {proxy_ip}<======================>")
            headers = {'User-Agent': 'Mozilla/5.0'}
            resp = requests.get(url, headers=headers, proxies=proxy, timeout=5)
            if resp.status_code == requests.codes.ok:
                print(f"<======================> Got Success with: {proxy_ip}<======================>")
                return resp.url
        except Exception as e:
            print(e)
            continue
    return ""

canonical_link = scrap_now("https://vt.tiktok.com/ZS81uRSRR/")
print("Canonical link: ", canonical_link)

Output:

Method - 3: Using Selenium
We can do this with selenium as well. It will take almost 5 seconds
First, install selenium using pip install selenium==3.141.0
then execute below lines:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.media_stream_mic": 1,
    "profile.default_content_setting_values.media_stream_camera": 1,
    "profile.default_content_setting_values.geolocation": 1,
    "profile.default_content_setting_values.notifications": 1,
    "credentials_enable_service": False,
    "profile.password_manager_enabled": False
})
options.add_argument('--headless')
options.add_experimental_option("excludeSwitches", ['enable-automation'])
browser = webdriver.Chrome(ChromeDriverManager(cache_valid_range=365).install(), options=options)
browser.get("https://vt.tiktok.com/ZS81uRSRR/")
print("Canonical link: ", browser.current_url)

Note: On first run it will take a bit more time as it will download web drivers automatically, but after that it will use cache only.


text:
Q: Find the max price in JSON import requests
import json

url = "https://graphs2.coinmarketcap.com/currencies/bitcoin/"
r = requests.get(url)
cont = r.json()
print(cont)

maxPrice = 0
for item in cont["price_btc"]:
    if(item[1] > maxPrice):
        maxPrice = (item[1])

print (maxPrice)

In my code, I am trying to find the max price in "price_btc" from a JSON file (in the file, each item in "price_btc" is [amount, price]). When I run my code, it prints out 1.0, which isn't the right value.

A: Looks at https://graphs2.coinmarketcap.com/currencies/bitcoin/ and doing a quick look at specifically the "price_btc" property, then all the [amount, price] values, all price values appear to be 1.

A: I think than you are taking always item[1] and you have to look item[0].
Look the array: "price_btc": [[1367174841000, 1.0], [1367261101000, 1.0]...]
Always 1.0 it will be more bigger than maxPrice = 0
Greetings!


text:
Q: Customize ActionBar TabBar (ActionBarSherlock) I have been stuck on this issue for some days now. Can anyone help me customize the Tabs displayed below the ActionBar (NavigationMode is NAVIGATION_MODE_TABS) ?
I basically want to change the background color of the tabs and the underline color of the currently selected Tab. So far this is what I have done, yet it doesn't work. I am using ActionBarSherlock.
<style name="Theme.Styled" parent="@style/Theme.Sherlock.Light">
    <item name="actionBarStyle">@style/Widget.Theme.Styled.ActionBar</item>
    <item name="android:actionBarStyle">@style/Widget.Theme.Styled.ActionBar</item>

    <item name="actionBarTabBarStyle">@style/customActionBarTabStyle</item>
    <item name="android:actionBarTabBarStyle">@style/customActionBarTabStyle</item>

    <item name="actionBarTabBarStyle">@style/customActionBarTabBarStyle</item>
    <item name="android:actionBarTabBarStyle">@style/customActionBarTabBarStyle</item>

    <item name="actionBarTabTextStyle">@style/customActionBarTabTextStyle</item>
    <item name="android:actionBarTabTextStyle">@style/customActionBarTabTextStyle</item>
</style>

<style name="customActionBarTabStyle" parent="style/Widget.Sherlock.Light.ActionBar.TabView">
    <item name="android:background">@color/red</item>

    <item name="android:textSize">12dp</item>

</style>

<style name="customActionBarTabBarStyle" parent="style/Widget.Sherlock.Light.ActionBar.TabBar">
    <item name="android:background">@color/red</item>
</style>

<style name="customActionBarTabTextStyle" parent="style/Widget.Sherlock.Light.ActionBar.TabText">
    <item name="android:titleTextStyle">@style/Theme.Styled.ActionBar.TitleTextStyle</item>
    <item name="android:textStyle">bold</item>
</style>

<style name="Widget.Theme.Styled.ActionBar" parent="Widget.Sherlock.ActionBar">
    <item name="android:background">#A9E2F3</item>
    <item name="background">#A9E2F3</item>
    <item name="android:titleTextStyle">@style/Theme.Styled.ActionBar.TitleTextStyle</item>
</style>

<style name="Theme.Styled.ActionBar.TitleTextStyle" parent="android:style/TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">@color/red</item>
    <item name="android:textStyle">bold</item>
</style>

<style name="Animations" />

A: You can use the available style generator, or get some more insight from this or this related question.

A: I'm not sure if you need this anymore but I will post the answer for other people to see. You can set this in the background Drawable of the customActionBarTabStyle as a Drawable resource:
<style name="customActionBarTabStyle" parent="style/Widget.Sherlock.Light.ActionBar.TabView">
    <item name="android:background">@drawable/actionbar_tabs_selector</item>
    <item name="android:textSize">12dp</item>
</style>

The resource should be a Selector, something among these lines:
<!-- This is the "@drawable/actionbar_tabs_selector" layout !-->

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/actionbar_tab_style_nselected"/>
    <item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/actionbar_tab_style_selected"/>

    <!-- Pressed state -->
    <item android:state_pressed="true" android:drawable="@drawable/actionbar_tab_style_selected" />

    <!-- Focused state -->
    <item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/actionbar_tab_style_nselected"/>
    <item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/actionbar_tab_style_nselected"/>

</selector>

So the resources here are 2 Layer Lists. One for when the tab is inactive, and one for when the tab is selected and active. So you set 2 Layer Lists depending on the selected state.
A single Layer List may look like this:
<!-- This is the "@drawable/actionbar_tab_style_nselected" layout !-->

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Bottom Line -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/HCL_orange" />
        </shape>
    </item>

    <!-- Tab color -->
    <item android:bottom="2dip">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
        </shape>
    </item>
</layer-list>

Thus the first item is the bottom line that you could define as your underline color of the currently selected Tab, and the second item is the color of the whole tab.


text:
Q: DD-WRT Block all but one site Im trying to block all websites but one with DD-WRT on a Linksys router. I am currently using this script:
iptables -I FORWARD 1 -p tcp -d dd-wrt.com --dport 80 -j ACCEPT
iptables -I FORWARD 2 -p tcp --dport 80 -j DROP

But this does not seem to work, as it is blocking access via HTTP to dd-wrt.com as well. Any help?

A: Make sure you're allowing the return traffic, at the moment it looks like traffic is probably getting out, but responses are not being allowed:
iptables -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT


text:
Q: truffle - artifacts.require is not a function I am currently learning solidity and creating my first project. I am trying to test the deployment of my contract with truffle and i keep getting the below error
TypeError: artifacts.reqiure is not a function

Syntax looks correct and there are no errors appearing. I have also gone into the truffle console and the migration seems to have deployed ok and Color.json is now in my abis folder as well.
Any help will be appreciated, all files are below.
Color.sol
pragma solidity 0.5.0;

import "./ERC721Full.sol";

contract Color is ERC721Full {

  // Initialise function
  constructor () ERC721Full("Color", "COLOR") public {

  }

}

Color.test.js
const Color = artifacts.reqiure('./Color.sol')

require('chai')
  .use(require('chai-as-promised'))
  .should()

contract('Color', (accounts) => {
  let contract

  before(async () => {
    contract = await Color.deployed()
  })

  describe('deployment,', async() => {
    it('deploys successfully', async() => {
      contract = await Color.deployed()
      const address = contract.address
      console.log(address)
      assert.notEqual(address,"")
      assert.notEqual(address, 0x0)
      assert.notEqual(address, null)
      assert.notEqual(address, undefined)
    })

    it('has a name', async () => {
      const name = await contract.name()
      assert.equal(name, 'Color')
    })

    it('has a symbol', async () => {
      const symbol = await contract.symbol()
      assert.equal(symbol, 'COLOR')
    })
  })
})

2_deploy_contracts.js
const Color = artifacts.require("Color");

module.exports = function(deployer) {
  deployer.deploy(Color);
};

1_init_migration.js
const Migrations = artifacts.require("Migrations");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

A: Make sure you have
require('@nomiclabs/hardhat-truffle5');

Before you're trying to call artifacts.require

A: You have a typo in Color.test.js
const Color = artifacts.reqiure('./Color.sol')

should be require

A: I tried out this particular code and it shows out an error message and after looking into the line it is just a small spelling error in this particular line in the color code: -
const Color = artifacts.reqiure('./Color.sol')

Try replacing it with this: -
const Color = artifacts.require('./Color.sol')


text:
Q: I want to start my node server in the hosting and it gives me this error and the routes within the project do not work, it gives me a 503 error, npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! servidor@1.0.0 start: node app.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the servidor@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/antoxxx/.npm/_logs/2022-03-14T17_53_07_593Z-debug.log


text:
Q: VallidationAttribute check multiple values in a condition I'm still new to ASP.NET MVC and I'm struggling with a validator I need to implement.
I have a UserName property in my Account model, that needs to be checked for uniqueness.
It's declared as followed:
[Required(ErrorMessageResourceName = "UserNameRequiredError", ErrorMessageResourceType = typeof(App_LocalResources.Resources))]
[Display(Name = "UserName", ResourceType = typeof(App_LocalResources.Resources))]
[VallidateAccount(Field = AccountChecks.UserNameUnique, ErrorMessageResourceName = "UserNameUniqueError", ErrorMessageResourceType = typeof(App_LocalResources.Resources))]
public string UserName { get; set; }

The used ValidationAttribute has the following to perform the check
public class VallidateAccountAttribute : ValidationAttribute
{
    public AccountChecks Field { get; set; }
    public int ID { get; set; }

    public override bool IsValid(object value)
    {
        switch (Field){
            case AccountChecks.UserNameUnique:
                return CheckUserName((string)value);
            //Other Fields
            default:
                throw new ParameterException("Invallid Field");
        }
    }

    private bool CheckUserName(string username)
    {
        Account account = Connection.DB.Accounts.FirstOrDefault(x => x.UserName == username);
        return !string.IsNullOrEmpty(username) && (account == null || account.AccountID == this.ID);
    }
    //Other checks
}

And now for the problem:
The entered username is correctly passed into the validation through the value parameter of the IsValid method, but I can't find a way to pass the ID along with it.
I've tried to pass it along the same way I pass the Field parameter, but I can't use the this keyword.
[VallidateAccount(Field = AccountChecks.UserNameUnique, ID = this.AccountID, ErrorMessageResourceName = "UserNameUniqueError", ErrorMessageResourceType = typeof(App_LocalResources.Resources))]

Can anyone please help me in passing through the ID value?
EDIT: Implemented solution proposed by Rahul RJ
Remote validation provided me with the ability to do exactly what I wanted.
The new UserName property:
[Required(ErrorMessageResourceName = "UserNameRequiredError", ErrorMessageResourceType = typeof(App_LocalResources.Resources))]
[Display(Name = "UserName", ResourceType = typeof(App_LocalResources.Resources))]
[System.Web.Mvc.Remote("UserNameUnique", "Validation", AdditionalFields = "AccountID", HttpMethod = "POST", ErrorMessageResourceName = "UserNameUniqueError", ErrorMessageResourceType = typeof(App_LocalResources.Resources))]
public string UserName { get; set; }

The ValidationAttribute is no longer used in this case, instead it is replaced with a new ValidationController.
using System.Web.Mvc;
using MyProject.Models;

namespace MyProject.Controllers
{
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public class ValidationController : Controller
    {
        MyDbContext _repository;
        public ValidationController() : this(Connection.DB) { }

        public ValidationController(MyDbContext repository)
        {
            _repository = repository;
        }
        //NOTE: Make sure the parameters have the same name as your properties!!!
        public JsonResult UserNameUnique(string UserName, int AccountID = 0)
        {
            Account account = Connection.DB.Accounts.FirstOrDefault(x => x.UserName == UserName);
            return Json(!string.IsNullOrEmpty(UserName) && (account == null || account.AccountID == AccountID), JsonRequestBehavior.AllowGet);
        }
    }
}

A: You can do the Remote Side Validation in this Scenario.
with that you can easily check the Exsisting UserName.
Use this http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx  for your Reference

A: You're doing to much! If you want to validate for uniqueness then just do that.
Where you have .FirstOrDefault you should change to .Any and just check to see if there is any rows with that username.
private bool CheckUserName(string username) {
if(string.IsNullOrEmpty(username))
    return false;
return !Connection.DB.Accounts.Any(x => x.UserName == username);
}


text:
Q: Bootstrap Collapsible Form -- Just One Panel Available at a Time I have implemented the following Bootstrap accordion/collapsible form on my website. Please see this fiddle: https://jsfiddle.net/eswv56ha/
Here's my HTML markup too:

 Delivery Address 

            Content First

        <button id="toggle-delivery" type="button" class="btn-checkout" data-toggle="collapse" data-parent="#checkout-accordion" href="#collapse-delivery">Deliver to This Address</button>

 Delivery Options 

        Content Second
        <button id="toggle-payment" type="button" class="btn-checkout" data-toggle="collapse" data-parent="#checkout-accordion" href="#collapse-payment">Select Delivery Option</button>

 Payment 

        Content Third

I used dummy content for the panel body as the content is generated dynamically with PHP. The accordion replaces the checkout form on my WooCommerce website. So far, it is fully functional and behaves as expected, however, I'd like to go one step further and somehow disable the second and third panels (Delivery Options & Payment) when the first one (Delivery Address) is toggled. Then, when the user clicks "Deliver to This Address" button, the second panel would be enabled. At this point, the first panel (Delivery Address) will be collapsed BUT still enabled/toggleable, the second one (Delivery Options) will be toggled, and the third one (Payment) should be disabled/not toggleable. When the user clicks "Select Delivery Option," the last/third panel (Payment) should be enabled. The first (Delivery Address) and second (Delivery Options) panels should be collapsed BUT active, and the third one (Payment) should be enabled and toggled.
Once the third panel is toggled/activated/enabled, the rest would be collapsed, but still accessible - i.e. if the user wants to go back to her billing info and change the address or select a different delivery option.
Ideally, I'd like to apply an overlay to the disabled panels, like this:

As they become enabled/active, the overlay would be gradually removed. How can I do this?

A: You need to use Javascript to accomplish this. To begin, look at Bootstrap's documentation for the events that fire if a collapsible element is toggled. For example:
//Fires when #panel-delivery is triggered to be shown
$('#panel-delivery').on('show.bs.collapse', function() {
       // Enable / Disable other panels here.
    })

And this will work just fine as you can see here. Do note I altered some of your code, since your markup is all over the place. I put the Jquery on the bottom of  so it's easier to see what it does.
My advice would be to first validate whatever the user needs to fill in before he can press the button to access the next panel. Could be as simple as making sure no required input is empty. (Not as a replacement for any back-end validating, but solely for better user experience).
Hope this helped.


text:
Q: Error message: cannot find table 0 First I would like to apologise for the length of this post. But I want you to understand the entire issue.
I have to merge three datasets (dsGetForm, dsmedication_details and dsbroadband_details), and show the result in a table.
Sometimes dsbroadband_details contains rows and sometimes it doesn't.
This is what I am using right now to merge the datasets.
if (dsGetForm != null && dsmedication_details != null && dsbroadband_details != null)
{
   dsGetForm.Tables[0].Merge(dsmedication_details.Tables[0]);
   dsGetForm.Tables[0].Merge(dsbroadband_details.Tables[0]);
}
else if (dsGetForm == null && dsmedication_details != null)
{
   dsGetForm = dsmedication_details;
}
else if (dsGetForm == null && dsbroadband_details != null )
{
   dsGetForm = dsbroadband_details;
}

The problem is that, the stored procedure (SP) which is used to fill the dataset dsbroadband_details is giving me this error message when the result of stored procedure is null

Error message: Cannot find table 0.
  Description: An unhandled exception
  occurred during the execution of the
  current web request. Please review the
  stack trace for more information
  about the error and where it
  originated in the code.
Exception Details:
  System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail,
  System.ServiceModel, Version=3.0.0.0,
  Culture=neutral,
  PublicKeyToken=b77a5c561934e089]]:
  Cannot find table 0

This is my stored procedure
Alter Procedure dbo.OEA_SP_GET_BROADBAND (
                @appid    NUMERIC,
                @clientid NUMERIC,
                @Lang Varchar(10))
AS
   SET nocount  ON
   BEGIN
  declare @PIName as varchar(100)
  declare @username as varchar(20)
  declare @pform_id as varchar(20)
  declare @pform_desc as varchar(100)
  declare @userid varchar(20)
  declare @msn tinyint

  set @PIName=''
  if exists(SELECT app_id from ext_well_new_programs (nolock) where app_id=@appid and new_prog_id='BB' and status='A')
  begin
      select @PIName=dbo.oea_fn_fetch_fullname(@appid,primary_msn,1,@lang,@clientID)
          from app_application with (nolock)
      where app_id = @appid
  end

  if @PIName <> ''
  begin
    select Distinct @username = dbo.oea_fn_fetch_caaname(prog.last_update_id, 30000)
            from app_prog_submission prog (nolock)
            where app_id = @appid

            select @userid = user_id, @msn = primary_msn
            from app_application (nolock)
            where app_id = @appid

            set @pform_id = 'learnmore'
    set @pform_desc = 'Cash Back for Broadband at Home'

    select @PIName as mem_name, @appid as app_id, @username as username, @pform_id as pform_id, @pform_desc as pform_desc, 0 as noncust, @userid as userid, @msn as msn
 END
     End

I think, I need to add a else condition after if @PIName <> '' condition.
My question is what should that else condition be?
Since I only need the values of the select statement (at the end) of the if @PIName <> ''
condition when this condition is true, I am a bit confused what else that should be?
Any help is much appreciated.

A: It looks to me like there are cases when your SP doesn't return any results, therefore no "table 0". I would rather construct a @results memory table, insert data (if any) in this table and do a final select mem_name, app_id, ... from @results before exiting the SP. Or any other SQL construct that actually returns a resultset, even empty.


text:
Q: using fetch with-in require js I'm trying to learn require js, and am working on extending the multi page demo found from here: https://github.com/requirejs/example-multipage with fetch.
From the demo code in the git repo above, I have modified the www/js/app/model/m1.js code to look like this.  Everything else from the demo is basically the same.
define(['./Base','fetch'], function (Base) {

    var m1 = fetch('data/people.json')
    .then(function(response) {
        return response.json();
    });

    return new Base(m1);

});

(I have fetch polyfil loading as a shim, that is why it is included in the define arguments - but dev on latest chrome which has support for fetch)
Ideally this returns a new Base object that uses the resolved json from the fetch to populate its data source. this.data = data, when the new Base object is created.
Currently though, it seems I only get the promise back and can't get the json out.  Though if I console.log the promise I can see the successful response in there.

A: I think the problem is how you assign to m1. You can't use the return value of fetch. The execution order of your code is as follows: start fetching, create and return Base, receive data from fetch. So you don't have the data yet when you're building Base. That's a common pattern (and pittfall) in JS. Can you work with a callback or Promise?
define(['./Base','fetch'], function (Base, callback) {
    fetch('data/people.json')
    .then(function(response) {
        callback(response.json());
        // or maybe you want
        //Base(response.json());
    });
});


text:
Q: How to find column with matching value and assign it to the textbox1 in user form VBA i am having problem loading data from matched cell to current date into the texbox in the user form
I have
Private Sub NSheet_Click()
    MoveSheet (1)
    txtBox2.Text = "1st: " & " 2nd: " & " 3rd: "
End Sub

and when next is selected moveSheet will switch to the next sheet in the workbook
then i have function
Sub FindtheDay()
    Dim rFind As Range
    Dim kolona As Long
    Dim today As Date
    today = Date

    With ActiveSheet.Range("F2:AJ2")
        Set rFind = .Find(What:=today, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
        If Not rFind Is Nothing Then
            kolona = CStr(rFind.Column)
            KolLN = kolona
        End If
    End With
End Sub

that is looking for cell that match to the current date (date only)
then i need that column number as reference to the cell that is 48 row below the one where it was found.
basicli, when Next button is pressed i whant it to switch sheet and then to find column with matching date and then to point to cell Range(ColumNumber & "50") and send that value into textbox

*

*also i have three cels ColumnNumber,50,51 and 52 that i whant to put in textbox on user form

All I have tried is giving me error about wrong type
Also I am using public variables because some of them i need i other Sub procedures
Thanks,
D

A: So you cant create a Range of Columns like that. It has to be like this:
.Range(Columns(1), Columns(50))

If you want to show some value in a userform then you can assign it with addressing it like that.
Sub Test()
UserForm1.TextBox1.Text = Worksheets("Sheet1").Range("A1").Value
UserForm1.Show
End Sub


text:
Q: Isolating test APK build I have a situation where in an Android project with instrumentation tests I have all of the production code precompiled and ready to be installed as an .apk (a React Native environment).
Whenever I run instrumentation tests, I initially build the AndroidTest .apk using Gradle by running:
./gradlew assembleDebugAndroidTest -DtestBuildType=debug

(i.e. in a pretty standard way).
Trouble is that despite explicitly specifying only the xxxAndroidTest task, all of the production code assembly Gradle tasks are run as well. This is an extreme time waster to me since - as I explained, the production apk is already there, and thus code compilation (and packaging, signing, etc.) is scarce.
In essence, I have no dependency in production code from the instrumentation code -- even the ActivityTestRule I use is created dynamically and isn't directly bound to my main activity:
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(launchIntent, 0);
Class<?> activityClass = Class.forName(resolveInfo.activityInfo.name);
ActivityTestRule<?> activityTestRule = new ActivityTestRule(activityClass, false, false);

Question is: How can I isolate / restrict Gradle's work so it would only include test-related tasks? I even tried inspecting the tasks tree using this Gradle plugin, but couldn't find a clear place to "cut the tree" down.

A: Well so far I've come up with this (heuristic) solution, that does 2 things:

*

*I noticed that most of the time that goes to waste is due to sub-projects that are not needed for the job. Therefore, the solution provides an easy way to exclude implementations from test building.

*Out of the tasks remaining in the list, still - the plugin iteratively force-disables tasks that are not related but run nonetheless.
It boils down to this helper Gradle script:
// turbo-test-apk.gradle

def isEnabled = System.getProperty('TURBO_TEST_APK') != null

project.ext.dependenciesExcludeTest = { depsClosure ->
    if (!isEnabled) {
        dependencies(depsClosure)
    }
}

gradle.taskGraph.whenReady { graph ->
    if (isEnabled) {
        def disabledTasks = new ArrayList<Task>(graph.allTasks.size())

        [/.*JsAndAssets.*/, /package.*Release/, /package.*Debug/, /compile.*/, /.*[Pp]roguard.*/, /.*[Nn]ew[Rr]elic.*/, /.*AndroidTest.*/].forEach { regex ->
            graph.allTasks.findAll { it.name ==~ regex }.forEach({ task ->
                disabledTasks.add(task)
                task.enabled = false
            })
        }

        graph.allTasks.findAll { it.name ==~ /.*AndroidTest.*/ }.forEach({ task ->
            task.enabled = true
        })

        println '--- Turbo test build: task scanning ---'
        disabledTasks.forEach { task ->
            if (!task.enabled) {
                println 'Force-skipping ' + task
            }
        }
        println '---------------------------------------'
    }
}

Namely, the dependenciesExcludeTest enabled the exclusion of unwanted subprojects, and the task-graph-ready callback does the disabling. NOTE that the regex list is custom made, and is not generic. It makes sense for my project as react native projects have a heavy-weight JS-bundling tasks called bundleJsAndAssets, and I also have new relic installed. Nevertheless, this can be easily tailored to any project.
Also, the app.gradle looks something like this:
apply plugin: 'com.android.application'

apply from: './turbo-test-apk.gradle'

dependencies {
    implementation "org.jetbrains.kotlin:$kotlin_stdlib:$kotlinVersion"
    implementation "com.android.support:support-v4:$supportLibraryVersion"
    implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
    // etc.
}
// These will be excluded when executing test-only mode
dependenciesExcludeTest {
    implementation project(':@react-native-community_async-storage')
    implementation project(':any-unneeded-sub-project')
}

So when gradle is run like this (i.e. with a custom TURBO_TEST_APK property):
./gradlew assembleDebugAndroidTest -DtestBuildType=debug -DTURBO_TEST_APK

the script will apply its work and reduce the overall build time.
This solution isn't optimal: tricky to maintain, doesn't omit all of the unnecessary work. I'd be very happy to see more effective solutions.


text:
Q: Can reputation across stack exchange sites be pooled? I ask because things like up-voting require reputation, but in areas where I'm knowledgeable, I don't have many questions, and the ones I do have already been asked, and answered well, making reputation hard to acquire.   (I'm assuming the only practical way to gain reputation is to ask and answer questions).
Across the whole network, I've got more than sufficient reputation, but not on those sites where I have knowledge and would most like to up-vote.

A: There is association bonus. When you have an account on the stack exchange network with 200 rep or above, you get 100 association bonus on any other stack exchange site, You will be given 100 rep association bonus.
Apart from that there is no other way you can pool reputation and I don't think it will be a good idea to pool reputation. That you have moderation privileges (10k+ rep) on christianity doesn't mean you are fit to moderate stack overflow


text:
Q: SharePoint 2013 Composed Look - How to add .spcolor and .preview file to SP Server via VS package? We are using VS2012 and SP2013.
Presently we are deploying a masterpage via VS module (without feature event receiver, so we are not activating it on deployment).
Then, creating a composed look with this masterpage via PowerShell. Now the problem is that, the composed look does not appear in the 'change the look and feel' unless you add a corresponding '.preview' file. Reference: Check the pre-requisites section
I need to know that:-

*

*How do I place this .preview file via VS package into the 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\GLOBAL'?

*We have also created a .spcolor file which needs to be uplaoded to 'themes/15 folder' via VS package.
Please guide. I guess we need to use the module project item. But what change to make in the elements.xml file?

A: *

*Create a mapped folder in your project and place .preview file inside it.

*Add a module to the project and provide the url which references /_catalogs/theme/15 in the XML file in order to place .spcolor file in it.


text:
Q: How to run .bat file on Heroku? (trying to set up discord music bot on Heroku) I have been trying to host a discord bot on Heroku.
Bot link:
https://github.com/Just-Some-Bots/MusicBot
I have set it all up and successfully host it on my own computer.
The problem is that I want to host it on an online service like Heroku.
Successfully deploy and it said found a python app.
However I didn't see the bot in discord goes online...
This is what I think the problem is,
when I host it on my computer I have to run "runbot.bat" file
which looks like this:
@ECHO off

CHCP 65001 > NUL
CD /d "%~dp0"

SETLOCAL ENABLEEXTENSIONS
SET KEY_NAME="HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
SET VALUE_NAME=HideFileExt

FOR /F "usebackq tokens=1-3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
    SET ValueName=%%A
    SET ValueType=%%B
    SET ValueValue=%%C
)

IF x%ValueValue:0x0=%==x%ValueValue% (
    ECHO Unhiding file extensions...
    START CMD /c REG ADD HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v HideFileExt /t REG_DWORD /d 0 /f
)
ENDLOCAL

IF EXIST %SYSTEMROOT%\py.exe (
    CMD /k py.exe -3.5 run.py
    EXIT
)

python --version > NUL 2>&1
IF %ERRORLEVEL% NEQ 0 GOTO nopython

CMD /k python run.py
GOTO end

:nopython
ECHO ERROR: Python has either not been installed or not added to your PATH.

:end
PAUSE

And there's a file called "procfile" which I learned from here:
https://www.reddit.com/r/discordapp/comments/5dkqpd/help_how_do_you_host_a_discord_bot_from_heroku/
I have tried
worker: runboot.bat

,
worker: python run.py

and
worker: python bot.py

but no luck. I think the process type is missing or wrong for the .bat file.
How do I run .bat file on Heroku?
Or if anyone has some experience of hosting this bot, any help would be really appreciated. thanks!

A: Heroku runs Linux. So, it's just technically impposible to run batch file (as well as ffmpeg.exe from that github repo).

A dyno is a lightweight Linux container that runs a single user-specified command. said the docs.

So try some Linux-compatible programs instead.
p.s. run heroku logs for detailed info about why your app couldn't work.


text:
Q: Set default meta properties on Vue Router I have searched the documentation here, and whilst there is a meta property on the VueRouter object, it doesn't seem to be doing anything (there is no description on the actual property in the docuementation)...
Consider the following routes:
let routes = [
    {
        path: '/',
        component: require('./views/Home').default
    },
    {
        path: '/about',
        component: require('./views/About').default,
        meta: {
            transitionColor: '#000' // Note this property
        }
    }
];

I would like to do something like this:
export default new VueRouter({
    mode: 'history',
    routes,
    meta: {
        transitionColor: '#fff'
    }
});

The intention of the above code is to set the default $route.meta.transitionColor to #fff for all routes, and then allow the route to override this if it is supplied in the route level meta.
Is there a way to set default meta properties on Vue Router in this way?

A: To my knowledge, it does not exist. However, with navigation guards, you can achieve something very similar.
router.beforeEach((to, from, next) => {
   // manipulate route (e.g. set meta)
});

A: NavGuards are pretty handy - here's an simple example how to achieve something like you requested but using another meta-property - here called in router/index.ts somewhere after createRouter was invoked. The example declares every page without an explicitly auth-declaration as private using the custom meta-property requiresAuth (and sets the page title afterwards, while we're on it):
router.beforeEach((to, from) => {
  if (!Object.prototype.hasOwnProperty.call(to?.meta, "requiresAuth")) {
    to.meta.requiresAuth = true;
  }
  document.title =
    "APP BRAND - " + i18n.global.t(`component.appNav.${String(to.name)}`);
  next();
});


text:
Q: How to exit a while statement inside of a while statement to get back to the first while statement? I put a while statement nested inside of another while statement and I'm wondering how I could exit/break the while to get to the other while.

A: Use break statement inside the inner loop to break it and resume iteration of the outer loop.

A: Here is an example you can run:
for x in range(10):
    for y in range(10):
        if y == 5:
            break
        else:
            print "%s, %s" % (x, y)

Notice that even though y in the inner loop should reach a value of 9, it never gets higher than 4 because the inner loop is broken when y == 5.
Here is the output that I get when I run this:
0, 0
0, 1
0, 2
0, 3
0, 4
1, 0
1, 1
1, 2
1, 3
1, 4
2, 0
2, 1
2, 2
2, 3
2, 4
3, 0
3, 1
3, 2
3, 3
3, 4
4, 0
4, 1
4, 2
4, 3
4, 4
5, 0
5, 1
5, 2
5, 3
5, 4
6, 0
6, 1
6, 2
6, 3
6, 4
7, 0
7, 1
7, 2
7, 3
7, 4
8, 0
8, 1
8, 2
8, 3
8, 4
9, 0
9, 1
9, 2
9, 3
9, 4


text:
Q: ruby on rails project pulling from an api trying to save bids from bids controller and display on the user show page I'm accessing an api to pull the lowest price and event id and then based on the current lowest price you can place a bid I'm currently stuck at just creating a bid and saving it to the user show page I can manually enter the params on the event show page which triggers my create method on bid page which then all bids placed by a user should show up on a user show page because a user has many bids and bid belongs to a user below is a snippet from my event show page showing the ability to manually create a bid and save to the database
    <%= form_tag "/bids", method: :post do %>

     <%= label_tag :bid, "place your bid "   %>
     <%= text_field_tag :bid %>

     <%= label_tag :event %>
     <%= text_field_tag :event_id, params[:id] %>

      <%= label_tag :user_id %>
      <%= text_field_tag :user_id %>

      <%= label_tag :lowest_price %>
      <%= text_field_tag :lowest_price %>

      <%= submit_tag "Submit" %>

   <% end %>

here is my create method in my bids controller for the time being
    def create
    @bidd = Bid.new(event_id: params[:event_id], user_id: params[:user_id], bid: params[:bid], lowest_price: params[:lowest_price])

 if session[:user_id] == current_user.id
   @bidd.save
   flash[:success] = "bid created."
   redirect_to "/users/#{current_user.id}"
else
   flash[:warning] = 'please sign in'
   redirect_to '/login'
 end

end
and then here is my user/show page which is just @bidd in skull tags i know i need something like at @bidd.bid but im creating from my bid controller and showing on the user page so basically I'd like to find a way to display all the users bids on a user show page and also not have to manually enter the event id and current lowest price and user id to save a bid. also the the event id is being pulled from an api i thought first to make a userbid thru model but didnt think that would be necessary
       #<%maybe something like @ <% @bidd.each do |a| %>

event: <%= a.event_id %>

Price: <%= a.bid %>

    <% end %>

A: i had a naming issue in my user show method
    def show
  @bids = Bid.where(user_id: current_user.id)
render 'show.html.erb'

should be
        @bidds
and
    <% @bidds.each do |a| %>

event: <%= a.event_id %>

Price: <%= a.bid %>

    <% end %>

worked to display that users bids now lets see if it can be done without having to fill in those params manually on the event show page.


text:
Q: Connection to database I am trying to create a class that I can use within my application to easily connect to my database and run queries as needed.  I found this post but it is not quite working like I expect.
Here is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
//a class that returns a connection to the database
namespace epaCUBE_Utility_Tool
{
    public class epaCUBE_DB
    {

        public static SqlConnection GetConnection()
        {
            string str = "user id=MyUserName;" +
               "password=MyPassword;server=myServer;" +
               "database=myDatabase; " +
               "connection timeout=30";

            SqlConnection con = new SqlConnection(str);
            con.Open();
            return con;
        }
    }
}

and here is how I am trying to use it:
 private void button1_Click(object sender, EventArgs e)
 {
     var connection = epaCUBE_DB.GetConnection();
     connection.Open();
     SqlDataReader rdr = null;
     string CommandText = "SELECT Field1, Field2 FROM TableName";
     SqlCommand cmd = new SqlCommand(CommandText, connection);
     rdr = cmd.ExecuteReader();
     while (rdr.Read())
     {
         this.comboBox1.Items.Add(rdr["Field1"].ToString() +
  ": " + rdr["Field2"].ToString());
     }
     connection.Close();
 }

when I press the button I get an error
InvalidOperationException: The connection was not closed. The connection's current state is open.
What am I doing wrong?
Thanks,
Leslie

A: GetConnection calls Open for you, but you're calling it again manually after you called GetConnection. Call it inside GetConnection or outside, but not both places.

A: Problem is in GetConnection() you already open the connection. All these problems came with your static method.
This is not good way to do this, better to create a new instance of SqlConnection when you need and dispose after use. The underlying connection pooling will be able to manage the physical connections.
separate your UI with Data access, Here you read the data from database and same time adding items to controls. You need to re-factor the code.
You can have method like below to retrieve data
public List<string> GetFields()
{
    List<string> fields = new List<string>();
    string CommandText = "SELECT Field1, Field2 FROM TableName";
    using (var connection = new SqlConnection(epaCUBE_DB.GetConnectionString()))
    {
        connection.Open();
        using (var cmd = new SqlCommand(CommandText, connection))
        using (var reader = cmd.ExecuteReader())
        {

            while (reader.Read())
            {
                fields.Add(reader["Field1"].ToString() + ": " + reader["Field2"].ToString());
            }
        }
    }
    return fields;
}

A: You're trying to open a connection which is already open, this results in exception.
before opening the connection check the connection status and then open the connection
cmd.Connection.Open();

add the following check/cleanup code:
if (cmd.Connection.State == ConnectionState.Open)
{
    cmd.Connection.Close();
}

A: I program quite defensively; I expect faults to occur and try to handle that gracefully.
As such..
// Define this once in a class and re-use for every connection..
string myConnString = "user id=MyUserName;" +
       "password=MyPassword;server=myServer;" +
       "database=myDatabase; " +
       "connection timeout=30";

    using (SqlConnection mySqlConnection = new SqlConnection(myConnString))
    {
        using (SqlCommand mySQLCommand = new SqlCommand("SELECT Field1, Field2 FROM TableName", mySqlConnection) { CommandType = CommandType.Text})
        {
            try
            {
                mySqlConnection.Open();
                using (SqlDataReader rdr = mySQLCommand.ExecuteReader())
                {
                    this.comboBox1.Items.Add(rdr["Field1"].ToString() + ": " + rdr["Field2"].ToString());
                }
            }
            catch (Excecption e)
            {
              // Deal with it as you wish
            }
            mySqlConnection.Close();
         }
     }


text:
Q: Is that possible for Windows to play format playlist.m3u8 which made fully support on iOS or Mac? There are live TV and radio channels which the file format is playlist.m3u8 and this file can be played on iOS as well as Mac OS X.
I wonder if there is any workaround or way to make it play on Windows OS or any browser plugin so that I can play them?

A: Pretty much any player that supports .m3u playlists should be able to handle the .m3u8 playlists,  there just may be some character display problems (since .m3u8 is a Unicode version of .m3u to support extended character sets).
Available here is a list of players that support the .m3u8 file type specifically.
WinAmp is my personal favorite for media playing on Windows.

A: m3u8 playlists are used to implement HTTP Live Streaming (HLS) which is a way of streaming live video (H.264 and AAC) over HTTP
HTTP Live Streaming is supported by Mac OS X and iOS, and Android Ice Cream Sandwhich, but I don't know of any Windows based players.
There is an SDK you can get to allow the writing of Windows 8 and Windows Phone 8 applications which support HLS
3ivx HLS Client SDK for Windows 8 and Windows Phone 8


text:
Q: Simultaneous Search and Sort in React/Redux I'm working on a simple search and sort mechanism for a test blog application.
Each function in isolation works correctly yet I'm having trouble piecing the two together.
I just want a user to be able to have the ability to search for a blog title, while also having the ability to sort by blog likes.  I likely will add future filtering capabilities at some point, so I want to make sure I set this up the right way.
I've tried multiple ways to piece the two together in my Blogs component (where I'm listing the blogs) but without any luck.
Here is my search function which takes a search term (variable 'search') and the current 'blogs' state, along with my filter function which is just sorting based on blog likes.
const searchBlogs = ({ blogs, search }) => {
  return search
    ? blogs.filter(a => a.title.toLowerCase().includes(search.toLowerCase()))
    : blogs;
};

const filterBlogs = ({ blogs, filter }) => {
  if (filter === "DESC") {
    return blogs.sort((a, b) => b.likes - a.likes);
  } else {
    return blogs.sort((a, b) => a.likes - b.likes);
  }
};

I'm storing the update state of blogs after search in mapstatetoprops like so:
blogsToShow: searchBlogs(state)

And then mapping over blogsToShow in my Blogs component
const Blogs = ({ blogsToShow }) => {
  return (

      {blogsToShow.map(blog => (
        <Blog key={blog.id} blog={blog} user={blog.user} />
      ))}

  );
};

I tried to call the filterBlogs function within the searchBlogs function like this but that got really messy and didn't work, leading to some infinite looping issues.
const searchBlogs = ({ blogs, search, filter }) => {
  filterBlogs(blogs, filter)
  return search
    ? blogs.filter(a => a.title.toLowerCase().includes(search.toLowerCase()))
    : blogs;
};

I know there has to be a simpler and more efficient way to do this.
Note, didn't want to post too much code on this, but here is my Search component where I am dispatching to the redux store:
const Search = props => {
  const handleSearch = event => {
    props.searchChange(event.target.value.toLowerCase());
  };

  const handleFilter = event => {
    props.filterChange(event.target.value);
  };

  const style = {
    marginBottom: 10
  };

  return (

      search
      <input onChange={handleSearch} />
      <select onChange={handleFilter}>
        <option value="DESC">Sort Likes Descending</option>
        <option value="ASC">Sort Likes Ascending</option>
      </select>

  );
};

const mapStateToProps = state => {
  return {
    filter: state.filter,
    search: state.search
  };
};

export default connect(mapStateToProps, { searchChange, filterChange })(Search);

A: well, i came up with something that works, but it's not very elegant.
if anyone any prettier ideas, i'm all ears.  thanks!enter code here
const Blogs = ({ blogsToShow, filter }) => {
  return (

      {filter === "DESC"
        ? blogsToShow
            .sort((a, b) => b.likes - a.likes)
            .map(blog => <Blog key={blog.id} blog={blog} user={blog.user} />)
        : blogsToShow
            .sort((a, b) => a.likes - b.likes)
            .map(blog => <Blog key={blog.id} blog={blog} user={blog.user} />)}

  );
};


text:
Q: Exclude classes from a dependency in Maven I have a project which depends on an artifact which is controlled by a supplier. This artifact contains some classes that I depend on, and some which are older and causing problems. Is there a way to get maven to automatically expand a jar, remove classes, and re-package them as a dependency? I'll try to give an example.
supplier:artifact:1.0.0
com.supplier.useful.ClassA
com.supplier.dto.ClassB (old)

us:dependency:1.1.20
com.supplier.dto.ClassB (new)

us:project-web:1.1.20
- supplier:artifact:1.0.0
- us:dependency:1.1.20

So - I need to use ClassA in project-web, but I need to use the ClassB from the dependency artifact. I can't modify supplier:artifact, or us:dependency.
Any ideas?!

A: Since version 2.0.9 maven preserves the classpath ordering so if you define your patched classes in a jar BEFORE the supplier jar it will hide the supplier implementation.
Alternatively you can look at the maven shade plugin as it does exactly what you are asking according to me.

A: If you are using Maven 2.0.9+, then just put your class in a jar and declare it as dependency before the artifact from your supplier. As mentioned by @Peter, Maven uses the pom order for the classpath since Maven 2.0.9 (see MNG-1412 / MNG-3111).
If for whatever reason you're not satisfied with this solution, then you could use the Maven Dependency Plugin to unpack the dependency in target/classes (which should be on the compile classpath) using dependency:unpack with some excludes (see Unpacking specific artifacts). I wouldn't even try to repackage it, this will introduce useless complexity (replacing the old jar with the new one on the compile classpath won't be trivial, if feasible).


text:
Q: Creating Multiple table in Oracle I am using Oracle Express 10g and I'm enter the following text to create 2 tables in the sql command line, but it is not working.
CREATE TABLE student (
    matric_no     VARCHAR2(8),
    first_name    VARCHAR2(20),
    last_name     VARCHAR2(20),
    date_of_birth DATE
);

CREATE TABLE student1 (
    matric_no     VARCHAR2(8),
    first_name    VARCHAR2(20),
    last_name     VARCHAR2(20),
    date_of_birth DATE
);

Can anyone see what I am doing wrong.
Thanks

A: By "command line" you probably mean the web application that comes with Oracle Express 10g. This application has several browser incompatibilities and is basically unable to execute several statements at once (also see Oracle 10g - invalid character on DB importing).
Either put your statements in a text file and upload them as a SQL script. Or switch to a better tool such as SQL Developer (downloadble from Oracle web site).

A: Are you sure you didn't type this out in WORD?
Sometimes there are problems with "invisible" characters. For example if you hit TAB in WORD, it will store it as a special character which will thereby cause an error when you try running it in SQLPlus.


text:
Q: How to render a form of another class view in Yii? In Yii, I have a view belonging to class A, and in a view corresponding to this class, I want to add a form to create a model of another class.
So, in protected/views/pictures/myview.php, I have:
<?php
/* @var $this PicturesController */
/* @var $model Pictures */

$objectForm = new Objects();
$newForm = ObjectsController::renderPartial('create',array('model'=>$objectForm),true);

?>

And I am trying to add a form to render protected/views/objects/create.php. But the above code doesn't work since the view is still trying to load the create form from the Pictures class. Since I am obtaining errors saying that same properties of Objects are not defined, because the system is loading the Pictures create form.
How can I add the create form of the Objects model?
Note: I added "applications.controllers.*" to the import array in main.php, but I understand this is a bad practice. Is there any possible solutions that doesn't involve me to do this?
Thanks.

A: In this case you just needed to link the correct view in the renderPartial:
$objectForm = new Objects();
$newForm = ObjectsController::renderPartial('/objects/create',array('model'=>$objectForm),true); // "/objects/create", and not "create".

Those errors were giving because Yii understood you were rendering to the create view of pictures, and you gave it the model of Objects (rather than the model of Pictures).
If we were talking about a render call in the controller, and you want to render a view from another action that belongs to another controller, you do not render to this view directly. You have to "redirect" to the action of this other controller (that belongs to the other class).

A: try like this this
$this->renderPartial('application.staff.views.default.create',array());

this is the format
$this->renderPartial('context_text.views.display._display_text');


text:
Q: How do you forecast ARIMA with multiple regressors? The complete R data and code for my question is here: https://pastebin.com/QtG6A7ZX.
I am new to R and still a beginner when it comes to time series analysis, so please forgive my ignorance.
I am attempting to model and forecast some enrollment data with 2 dummy-coded regressors. I have already used auto.arima to fit the model:
model <- auto.arima(enroll, xreg=x)
Before I forecast with this model, I am attempting to test its accuracy by selecting only a part of the time series (1:102 instead of 1:112), and likewise, a partial list of regressors.
Based on auto.arima, I fit the partial model as follows:
model_par <-arima((enroll_partial), c(1, 1, 1),seasonal = list(order = c(1, 0, 0), period = 5), xreg=x_par)
I have tried three different ways to forecast and get essentially the same error:
fcast_par <- forecast(model_par, h=10) #error
fcast_par <- forecast(model_par, h=10, xreg=x_par) #error
fcast_par <- forecast(model_par, h=10, xreg=forecast(x_par,h=10)) #error

'xreg' and 'newxreg' have different numbers of columns

I have tested using auto.arima with the partial data. That works, but gives me a different model and, although I specified 10 predictions, I get over 50:
model_par2 <- auto.arima(enroll_partial, xreg=x_par)
fcast_par <- forecast(model_par2, h=12, xreg=x_par)
fcast_par
So, my main question is, how do I specify an exact model and predict using more than 1 regressor given my data (see Paste Bin link above)?

A: You have two problems. One of them is that the various forecasting functions in R are making it (intentionally?) difficult on you.
The first problem is that you need to define the values of your regressors for the forecasting period. Extract the relevant data from x by using window():
x_fcst <- window(x,start=c(2017,4))

The second problem is that forecast() (which dispatches to forecast.Arima()) is a red herring here. You need to use predict() (which dispatches to predict.Arima() - note the capitalization in both cases!):
predict(model_par,newxreg=x_fcst,h=nrow(x_fcst))

which yields
$pred
Time Series:
Start = c(2017, 3)
End = c(2019, 1)
Frequency = 5
[1] 52.00451 52.00451 52.00451 52.00451 52.00451 52.00451 52.00451 52.00451
[9] 52.00451

$se
Time Series:
Start = c(2017, 3)
End = c(2017, 3)
Frequency = 5
[1] 17.13345

You can also use auto.arima(). Confusingly enough, this time forecast() (which still dispatches to forecast.Arima()) does work:
model_par2 <- auto.arima(enroll_partial, xreg=x_par)
forecast(model_par2,xreg=x_fcst)

which yields
        Point Forecast     Lo 80     Hi 80      Lo 95     Hi 95
2017.40       39.91035 17.612358  62.20834   5.808514  74.01219
2017.60       59.51003 32.783451  86.23661  18.635254 100.38481
2017.80       69.81000 39.290834 100.32917  23.134962 116.48505
2018.00       57.49140 23.601444  91.38136   5.661183 109.32162
2018.20       55.45759 18.503034  92.41214  -1.059524 111.97470
2018.40       34.57866 -7.306747  76.46406 -29.479541  98.63686
2018.60       52.30199  6.702068  97.90192 -17.437074 122.04106
2018.80       61.61591 12.582055 110.64977 -13.374900 136.60672
2019.00       50.47661 -1.765945 102.71917 -29.421485 130.37471

And yes, you do get five times as many predictions. The first column is an expectation forecast, and the others give prediction intervals. These are governed by the level parameter to forecast().

A: The forecast() function is from the forecast package, and works with model functions that are from that package. This is why it is possible to produce forecasts from auto.arima() using forecast(model_par2,xreg=x_fcst).
The arima() function comes from the stats package, and so there are no guarantees that it would work with forecast(). To specify your own ARIMA model, you can use the Arima() function, which behaves very similarly to arima(), but you will be able to produce forecasts from it using forecast(model_par2,xreg=x_fcst).


text:
Q: Prediction with regression equation in R First of all let me tell you I'm very new to R, so my question might sounds weird to you, I want to predict the weight of an individual from the height. For that I need to find the equation of the regression line (in the following form) for this problem:
Weight = intercept + (slope) x Height
I've the following form of data ?
Any idea about how to find regression line equation
dat <- read.table(text = "SampleNo,Height,Weight
                          1,65.78,112.99
                          2,71.52,136.49
                          3,69.40,153.03
                          4,68.22,142.34
                          5,67.79,144.30
                          6,68.70,123.30
                          7,69.80,141.49
                          8,70.01,136.46
                          9,67.90,112.37",
                  sep = ",", header = T)

A: You can accomplish this with the lm function.
lm1 <- lm(Weight ~ Height, data = dat )

I want to predict Weight as a function of Height so I use the syntax Weight ~ Height.
Finally, I run the coefficients function on the lm1 object to get the coefficient for Height and the intercept.
coefficients(lm1)
    (Intercept)      Height
    -177.650244    4.525168

If I want to predict the result for Weight for a certain set of Heights, I can do that with the following:
> predict(lm1, newdata = data.frame((Height = c(65, 68.5, 71.6))))
       1        2        3
116.4857 132.3238 146.3518

You can get additional information about the fit using the summary function on the lm1 object. This will provide R^2 values, more info on the estimates, etc...
summary(lm1)

Call:
lm(formula = Weight ~ Height, data = vals)

Residuals:
    Min      1Q  Median      3Q     Max
-17.239  -9.500  -2.697  11.283  16.634

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -177.650    193.247  -0.919    0.389
Height         4.525      2.808   1.611    0.151

Residual standard error: 13.03 on 7 degrees of freedom
Multiple R-squared:  0.2705,    Adjusted R-squared:  0.1663
F-statistic: 2.596 on 1 and 7 DF,  p-value: 0.1512

A great (free) resource for regression and many other machine learning techniques in R can be found here. It's a great book to learn about stats and how to implement those methods in R.


text:
Q: How to supply command line argument to perl script through Java I am running perl script through Java. The code is as shown below.
try {
    Process p = Runtime.getRuntime().exec("perl 2.pl");
    BufferedReader br = new BufferedReader(
                               new InputStreamReader(p.getInputStream()));
    System.out.println(br.readLine());
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

My perl script is in such way that when I run it directly through command line it ask me to supply input file. My question is how could I supply file name to perl script through Java?

A: If you don't want to add another command line argument to your script (which is much cleaner and more robust) you need to write to the script's stdin.
This snippet should work (Test.java):
import java.io.*;

public class Test
{
    public static void main(String[] args)
    {
        ProcessBuilder pb = new ProcessBuilder("perl", "test.pl");
        try {
            Process p=pb.start();
            BufferedReader stdout = new BufferedReader(
                new InputStreamReader(p.getInputStream())
            );

            BufferedWriter stdin = new BufferedWriter(
                new OutputStreamWriter(p.getOutputStream())
            );

            //write to perl script's stdin
            stdin.write("testdata");
            //assure that that the data is written and does not remain in the buffer
            stdin.flush();
            //send eof by closing the scripts stdin
            stdin.close();

            //read the first output line from the perl script's stdout
            System.out.println(stdout.readLine());

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

To test it you can use this short perl script (test.pl):
$first_input_line=<>;
print "$first_input_line"

I hoped that helped. Please also have a look at the following Stackoverflow article.
*Jost


text:
Q: Save Glide image onClick in ViewPager I'm showing images from the server with RecyclerView. When a user clicks in RecyclerView item it open with ViewPager and FullImage fragment. There is a button that user can save that image.
For now, when user click on a button, I get the image position and save it with another glide request like this -
GlideApp.with(container.getContext())
    .asBitmap()
    .load(image.getUrl())
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
               // I want here the trigger option. When user click btn
              // saveImage(resource, image.getTitle());
                        imageViewPreview.setImageBitmap(resource);
            }
});

It takes time and data cause it sending another req. I want that when a user clicks on a button, It should save from that original Glide resource. Now how can I trigger that option?
GlideApp.with(container.getContext())
    .asBitmap()
    .load(image.getUrl())
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
               // I want here the trigger option. When user click btn
              // saveImage(resource, image.getTitle());
                        imageViewPreview.setImageBitmap(resource);
            }
});

A: You can use a global Bitmap variable, and after first load (when user switch to the current picture) set that bitmap. So, onResourceReady you will do something like currentBitmap = resource.
Eventually, if you are on the ViewPager, you can get the image based on current position using getAdapterPosition(); (which I suppose you already do)


text:
Q: Java check - charset, encoding of html page - like browsers do
How to check what really charset, encoding of some html page ?
For example, the charset of some html page is iso-8859-1, but the content of the html written with utf8
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
...
here is content with utf8
...
</html>

How to check it, Is it possible to check with java charset, encoding of html page,
like it's done in browsers ?
Thank you !


text:
Q: Try to add maven project to tomcat server to run but can't do so In SpringToolSuit IDE, I have created a maven project (it has Spring webmvc dependency). I created this project through File --> New--> Maven project.
The pom.xml has those dependencies:
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
        <scope>provided</scope>
</dependency>

I also configured a tomcat server on the IDE. When I try to add my maven project to tomcat to run, I always get message "There are no resources that can be added or removed from server".
I did some research, people normally suggest go to Properties--> Project facet and check the "Dynamic Web Module" to resolve this issue. But for me there is no such option:

How to get rid of this issue & have my project running on tomcat server?
I am using Spring Tool Suite 4:
Version: 4.0.0.RELEASE
Build Id: 201809220817


text:
Q: Converting VB6.Format to [variable].ToString() Issues I'm currently transitioning some legacy software into VB.NET. I've gotten everything finished, except for some formatting.
When I try to change the following to [variable].ToString():
This: VB6.Format(Mid(inputrec3, 129 + (21 * I), 1), "0") & "   "
To This: Mid(inputrec3, 129 + (21 * I), 1).ToString("0") & "   "
I receive a runtime error stating: Error when converting 'String' to 'IFormatProvider'.
Both variables inputrec3 and I are declared as objects. I am unsure of what the issue is. I've already tried changing their declarations to an Int, and placing the Mid method into a variable and trying to format it that way, to no avail.
I am unsure of what else I should try to get this last piece to work. I understand I can keep it as VB6.Format but I'd prefer to use something more updated for the long-run.
Any help would be greatly appreciated.

A: The Mid function returns a string. string.ToString does not have an overload that takes a format string. The "legacy" code seems to be implicitly converting the string returned from Mid into a number when calling the Format function. In VB.NET you may need to do that explicitly:
CInt(Mid(inputrec3, 129 + (21 * I), 1)).ToString("0")

Or see if Mid gives you the string you want instead of converting it from a string to an integer and back.

A: You may just need
Mid(inputrec3, 129 + (21 * I), 1) & " "

because Mid is already returning a one character string based on the arguments. If it's a number already then you don't need to format it at all.
However, see VB6 Format which suggests that when passed a one character string, Format(string, "0") will return a one character string with

*

*If string is numeric, will return the single digit number

*If string is non-numeric, will return a "0"

So if you could have a non-number at position 129 + (21 * I), then your VB6 would return a zero, and now you'd be getting an empty string. You may want to handle this.
Dim input = 0
Integer.TryParse(Mid(inputrec3, 129 + (21 * I), 1), input)
Dim result = $"{input}   "


text:
Q: I can't format Python file on Visual Studio Code: "There is no document formatter for 'python'-files installed." I'm getting the message

There is no document formatter for 'python'-files installed.

when I try to format my Python file on Visual Studio Code.
I tryed to install some packages (autopep8, pep8, pycodestyle), but it didn't help. What's going on?

A: More than likely you installed autopep8 into a different interpreter/environment than you one have selected in VS Code. If you remove your formatter settings from your settings.json and then try formatting again, you will get prompted to choose and install a formatter (either autopep8, yapf, or black).

A: Try checking for similar extensions that you've installed. Uninstall unnecessary extensions and check in your settings for mutually exclusive settings. I had for example:
  "eslint.autoFixOnSave": true,

and
  "editor.formatOnSave": true,

which was making my auto formatting  not functioning.


text:
Q: Packer detection of PE files I want to know how detectors like Peid exe tools or protectid detect the packer/protection of pe files. I thought maybe some constant values when a program is packed, but i dont know well. Can someone explain me how that exactly works, the best way showing it in OllyDbg or other Debugers like that. Its a real mystery for me how those programs can detect that.
Thanks in advance for anything!

A: Most of these tools are signature based with some additional heuristics in place. Same goes for detecting compilers (by detecting compiler startup code and other signatures). It's even easier to detect compiler then protectors since most protectors are morphing the part of code that does decryption/decompression of packed application.


text:
Q: Paste a given variable that resembles a path instead of the path itself -- glob I want to use path as my path instead of copying my current folder path's using glob.
import  glob

path  = os.getcwd()
glob.glob(path*'.jpg')

A: I think what you are looking for is this:
import  glob
path  = os.getcwd()
glob.glob(f'{path}/*.jpg')


text:
Q: FractionallySizedBox with max size in Flutter I have this widget showing a ball in the middle of the screen:
FractionallySizedBox(
        widthFactor: 0.5,
        child: Container(
          decoration: new BoxDecoration(
            color: Helpers.hexToColor(color),
            border: new Border.all(
              color: Colors.white,
              width: 5.0,
            ),
            shape: BoxShape.circle,
          ),

For mobile I'm displaying this as 50% of the width, which is cool, but not for tablet. Here I'd like to set a max of XXXpx to avoid a huge ball in big tablets.
I could do something like this:
widthFactor: getSize()
And:
double getSize() {
 final width = MediaQuery.of(context).size.width;
 if (width  > 500) {
   return 0.2;
 }
 // other checks
 ...
 return 0.5; // the default one
}

But I'd like to know if there's a simpler widget for this

A: wrap your FractionallySizedBox with ConstrainedBox
ConstrainedBox(
  constraints: BoxConstraints(maxHeight: 50), // max height in px
  child: FractionallySizedBox(
    widthFactor: 0.5,
    child: Container(
      decoration: BoxDecoration(
        color: Helpers.hexToColor(color),
        border: Border.all(
          color: Colors.white,
          width: 5.0,
        ),
        shape: BoxShape.circle,
      ),
    ),
  ),
),

A:       FractionallySizedBox(
        widthFactor: 0.9,
        child: Center(
          child: ConstrainedBox(
              constraints: BoxConstraints(maxWidth: 70), // max height in px
              child: Text('abcabcabcabcabcabc')),
        ),
      ),

you have to first use FractionallySizedBox, and then Center, and then ConstrainedBox if you don't use Center or use ConstrainedBox first, you will get this behaviour where maxWidth/maxHeight is not working at all