text:
Q: How can I select specific values from a table using Python? So, I currently have this which pulls data from finviz and outputs the whole stats table for a stock. However, I'd like to be able to only pull the amount or percentage from a specific "cell:
    #---------- Pretend to be a browser. ----------#
headers = {
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
  "X-Requested-With": "XMLHttpRequest"
}

#---------- Import needed modules. ----------#
import pandas as pd
from bs4 import BeautifulSoup
import requests

#---------- Choose your ticker. Takes input. ----------#
ticker = input("Please choose a ticker symbol: ")
print("Loading data for " + ticker.upper())

#---------- Pulling the data from chosen stock ticker ----------#
url = ('https://finviz.com/quote.ashx?t=' + ticker.upper())

req = requests.get(url,headers=headers)
table = pd.read_html(req.text, attrs = {"class":"snapshot-table2"} )
df = table[0]
print(df)

Which gives me (I cut off some of the output as to not make the question so long):
Please choose a ticker symbol: ko
Loading data for KO
0            1              2       3              4           5   \
0        Index  DJIA S&P500            P/E   30.02      EPS (ttm)        1.87
1   Market Cap      242.71B    Forward P/E   23.00     EPS next Y        2.44
2       Income        8.08B            PEG    2.97     EPS next Q        0.58
3        Sales       36.41B            P/S    6.67     EPS this Y     -13.30%
4      Book/sh         5.16            P/B   10.85     EPS next Y       7.84%
5      Cash/sh         3.01            P/C   18.61    EPS next 5Y      10.12%
6     Dividend         1.68          P/FCF   93.97    EPS past 5Y       1.40%
7   Dividend %        3.00%    Quick Ratio    1.30  Sales past 5Y      -5.70%
8    Employees        80300  Current Ratio    1.50      Sales Q/Q      41.70%
9   Optionable          Yes        Debt/Eq    1.89        EPS Q/Q      47.70%
10   Shortable          Yes     LT Debt/Eq    1.79       Earnings  Jul 21 BMO
11       Recom         2.20          SMA20  -1.44%          SMA50       0.48%

How can I pull only one "cell"? Say I wanted the current PE ratio, how can I just get the "30.02"? Thanks!

A: You can simply print any selective data in this way:
#---------- Pretend to be a browser. ----------#
headers = {
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
  "X-Requested-With": "XMLHttpRequest"
}

#---------- Import needed modules. ----------#
import pandas as pd
from bs4 import BeautifulSoup
import requests

#---------- Choose your ticker. Takes input. ----------#
ticker = input("Please choose a ticker symbol: ")
print("Loading data for " + ticker.upper())

#---------- Pulling the data from chosen stock ticker ----------#
url = ('https://finviz.com/quote.ashx?t=' + ticker.upper())

req = requests.get(url,headers=headers)
table = pd.read_html(req.text, attrs = {"class":"snapshot-table2"} )
df = table[0]
print(f'{df[2][0]}: {df[3][0]}')

Output:
Please choose a ticker symbol: ko
Loading data for KO
P/E: 30.02

A: You can do like this.
Since the 'P/E' value is in the 4th <td> inside the first row, you can select the first <tr> and extract the required info.
headers = {
  "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
  "X-Requested-With": "XMLHttpRequest"
}

#---------- Import needed modules. ----------#
from bs4 import BeautifulSoup
import requests

#---------- Choose your ticker. Takes input. ----------#
ticker = input("Please choose a ticker symbol: ")
print("Loading data for " + ticker.upper())

#---------- Pulling the data from chosen stock ticker ----------#
url = ('https://finviz.com/quote.ashx?t=' + ticker.upper())

req = requests.get(url,headers=headers)
soup = BeautifulSoup(req.text, 'lxml')
table = soup.find('table', attrs = {"class":"snapshot-table2"} )
tr = table.find('tr')
PE = tr.select_one('td:nth-of-type(3)').text.strip()
PE_val = tr.select_one('td:nth-of-type(4)').text.strip()

print(f'{PE}: {PE_val}')

Please choose a ticker symbol: ko
Loading data for KO
P/E: 30.02

Please choose a ticker symbol: MS
Loading data for MS
P/E: 13.72


text:
Q: rails 3 creating an index from two models using where clause quick rails section, say I have two models Users and Roles and I want to create an index/list of Users based on a certain Role, how do I go about building that in my controller
is it something like
#first create the association
@user = role.build

#then build the index based on a Role of role_id = 2
@userrole = @user.where(@user.role_id == 2)

I know this is pseudo code, but is this correct? And what is the proper rails code?

A: roles = Role.where(id: [1, 2])
users = User.where(role_ids: roles.collect(&:ids))

This is just an example because obviously if we already know the ids we wouldn't need the first query but if our roles had an editable column (as an example) we could do:
roles = Role.where(editable: true)
users = User.where(role_ids: roles.collect(&:ids))

And if we wanted to order these we could simply add:
users = User.where(role_ids: roles.collect(&:ids)).order("created_at DESC")

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to query two models under a class view, get specific attributes associated with each models and compare one record against another I have two models Job and Applicants, the Job model has an attribute years_of_experience and the Applicants model has an attribute applicant_experience. I want to get the applicants years of experience and compare it the required years of experience for each particular job, and return only those that meet the requirement under a view.
models.py
class Job(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    years_of_experience = models.IntegerField(blank=True, null=True)

class Applicants(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants')
    experience = models.IntegerField(blank=True, null=True)

views.py
class QualifiedApplicantPerJobView(ListView):
    model = Applicants
    template_name = 'qualified_applicants.html'
    context_object_name = 'applicants'
    paginate_by = 2

    @method_decorator(login_required(login_url=reverse_lazy('login')))
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(self.request, *args, **kwargs)

    def get_queryset(self):
        return Applicants.objects.filter(job_id=self.kwargs['job_id']).order_by('-id')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['job'] = Job.objects.get(id=self.kwargs['job_id'])
        return context

applicants.html
{% for applicant in applicants %}
   {% if applicant.experience >= job.years_of_experience %}

{{ applicant.user.get_full_name }}

{{ applicant.user.email }}

   {% endif %}
{% endfor %}

I don't want to do it like this, I want to be able to do it in my views, get the number of qualified applicants(count) and return the qualified applicants. What is the best way to approach this. Thanks

A: You can add an extra argument to filter.
Of course, you'll need to get the job for which you want to get available applicants first, so you can determine the years_of_experience required for the job with the specified ID.
You can then use the __gte filter argument to filter for applicants with an experience field greater than the required number of years. This is specified under 'Field lookups' in the docs.
To sum it all up:
def get_queryset(self):
    # First we get the job itself.
    job = Job.objects.get(pk = self.kwargs['job_id'])

    # Add an extra argument to the filter method.
    return Applicants.objects
                .filter(job=job, experience__gte = job.years_of_experience)
                .order_by('id')

You can then leave out the
{% if applicant.experience >= job.years_of_experience %} ... {% endif %}
statement from your template.


text:
Q: How can I run my project on client pc without installing SQL server on client pc I have developed a c# windows application which uses SQL server 2012 database in Visual Studio 2015 which is running well on my pc.
I am to install this application on a number of computers without SQL server installed on it, but when I run the application, its gives me database connection error.
My question is, how can I create the setup file to be able to run the app on those clients pc without installing SQL server on all those computers. Please I need your help.
Thank you.
Am Emmanuel.

A: Use an Azure database and have the clients connect to that.
Have a look at https://azure.microsoft.com/en-us/services/sql-database/
Alter your application connection string and make sure you keep the connection string secret.
Server=tcp:myserver.database.windows.net,1433;Database=myDataBase;User ID=mylogin@myserver;Password=myPassword;Trusted_Connection=False;Encrypt=True;MultipleActiveResultSets=True;

An important fact is that the clients need to allow communication via port 1433.
If this is not an option create an API application and query the database via that.
If you need a private database per client you can use a database file and connect to the file
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-express-localdb?view=sql-server-ver15
Update based on reply
You can create a pop-up on the application allowing the users to add valid settings and credentials when your appsettings.json is blank or "a test connect" to the database fails.


text:
Q: MVC3 Handling of exceptions in catch blocks and throw Exceptions I want to understand how can we handle rest service specific exceptions in MVC3. Any pointers?
Basically, I have a Controller and there might be multiple try catch blocks and throw statements for exceptions.
I'm a little confused after reading all posts.
Edit:
public ActionResult Index()
    {
        IConsumerRequest conReq = oSession.Request();
        conReq = conReq.Get();
        conReq = conReq.ForUrl(Session["ServiceEndPoint"].ToString());
        try
        {
            conReq = conReq.SignWithToken();
        }
        catch (Exception ex)
        {
            throw ex;
        }

       return View();
    }

On throw exception, I need to be able to redirect to custom error page.
I read through this post too:
Custom error pages on asp.net MVC3
but how do i handle for different error codes like 302 or anything else if my application is not running on IIS.

A: Bellow is nice link for custom exp handling
Click Here


text:
Q: What do the difficulty levels do in Sir Benfro's Brilliant Balloon? In Sir Benfro's Brilliant Balloon, (a free adventure game on iOS), there are three difficulty levels:

*

*Beginner Balloonist

*Brilliant Balloonist

*Bonkers Balloonist

What are the differences between each difficulty level?

A: From what I found, the difficulty levels make it easier or harder to pass through a level. NBC an article about Sir Benfro's Brilliant Balloon.
The following quote is what led me to believe this.

Some parts of each stage do get tough, but you can control that by choosing from adjustable difficulty settings — from Beginner to Bonkers.


text:
Q: Flutter raster crash: recursive_mutex unlock crash in FontStyle::registerLanguageList Recently, Many uses of my app crash, The stack tells me something like multi-threads sync goes wrong. Does anybody know the reason?
My flutter SDK version is Flutter 1.17.5 • channel stable, and the flutter doctor results are
[✓] Flutter (Channel stable, v1.17.5, on Mac OS X 10.15.6 19G2021, locale zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
[✓] Android Studio (version 3.6)
    [✓] Connected device (1 available)

Here is the complete stack trace details of crashed thread below:
    Thread 13 name: io.flutter.1.ui Thread 13 Crashed:
    0 libsystem_kernel.dylib ___pthread_kill (in libsystem_kernel.dylib) 8
    1 libsystem_c.dylib _abort (in libsystem_c.dylib) 140
    2 libc++abi.dylib ___cxa_bad_cast (in libc++abi.dylib) 0
    3 libc++abi.dylib default_terminate_handler() (in libc++abi.dylib) 284
    4 libobjc.A.dylib _objc_terminate() (in libobjc.A.dylib) 140
    5 libc++abi.dylib std::__terminate(void ()()) (in libc++abi.dylib) 16
    6 libc++abi.dylib ___cxa_get_exception_ptr (in libc++abi.dylib) 0
    7 libc++abi.dylib __cxxabiv1::exception_cleanup_func(_Unwind_Reason_Code, _Unwind_Exception) (in libc++abi.dylib) 0
    8 libc++.1.dylib std::__1::__throw_system_error(int, char const*) (in libc++.1.dylib) 88
    9 libc++.1.dylib std::__1::recursive_mutex::unlock() (in libc++.1.dylib) 0
    10 Flutter minikin::FontStyle::registerLanguageList(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&) (in Flutter) (mutex:499) 12
    11 Flutter txt::(anonymous namespace)::GetMinikinFontStyle(txt::TextStyle const&) (in Flutter) (paragraph_txt.cc:145) 0
    12 Flutter xt::(anonymous namespace)::GetFontAndMinikinPaint(txt::TextStyle const&, minikin::FontStyle*, minikin::MinikinPaint*) (in Flutter) (paragraph_txt.cc:155) 4
    13 Flutter txt::ParagraphTxt::Layout(double) (in Flutter) (paragraph_txt.cc:311) 16
    14 Flutter flutter::Paragraph_layout(_Dart_NativeArguments*) (in Flutter) 108
    15 Flutter dart::NativeEntry::AutoScopeNativeCallWrapperNoStackCheck(_Dart_NativeArguments*, void ()(_Dart_NativeArguments)) (in Flutter) (native_entry.cc:215) 8
    16 App Precompiled_Stub_CallAutoScopeNative (in App) 72
    17 App Precompiled_Paragraph__layout_16065589_1659 (in App) 60
    18 App Precompiled_Paragraph_layout_10357 (in App) 40
    19 App Precompiled_TextPainter_layout_10753 (in App) 740
    20 App Precompiled_RenderParagraph__layoutText_509149678_4671 (in App) 316
    21 App Precompiled_RenderParagraph__layoutTextWithConstraints_509149678_4665 (in App) 92
    22 App Precompiled_RenderParagraph_performLayout_10469 (in App) 132
    23 App Precompiled_RenderObject_layout_10739 (in App) 1140
    24 App Precompiled_RenderConstrainedBox_performLayout_10491 (in App) 172
    25 App Precompiled_RenderObject_layout_10739 (in App) 1140
    26 App Precompiled_RenderFlex_performLayout_10516 (in App) 1164
    27 App Precompiled_RenderObject_layout_10739 (in App) 1140
    28 App Precompiled_RenderConstrainedBox_performLayout_10491 (in App) 172
    29 App Precompiled_RenderObject_layout_10739 (in App) 1140
    30 App Precompiled_RenderFlex_performLayout_10516 (in App) 1164
    31 App Precompiled_RenderObject_layout_10739 (in App) 1140
    32 App Precompiled_RenderPadding_performLayout_10489 (in App) 384
    33 App Precompiled_RenderObject_layout_10739 (in App) 1140
    34 App Precompiled_RenderConstrainedBox_performLayout_10491 (in App) 172
    35 App Precompiled_RenderObject_layout_10739 (in App) 1140
    36 App Precompiled_RenderFlex_performLayout_10516 (in App) 1164
    37 App Precompiled_RenderObject_layout_10739 (in App) 1140
    38 App Precompiled__RenderProxyBox_RenderBox_RenderObjectWithChildMixin_RenderProxyBoxMixin_795160605_performLayout_10500 (in App) 144
    39 App Precompiled_RenderObject_layout_10739 (in App) 1140
    40 App Precompiled__RenderProxyBox_RenderBox_RenderObjectWithChildMixin_RenderProxyBoxMixin_795160605_performLayout_10500 (in App) 144
    41 App Precompiled_RenderObject_layout_10739 (in App) 1140
    42 App Precompiled__RenderProxyBox_RenderBox_RenderObjectWithChildMixin_RenderProxyBoxMixin_795160605_performLayout_10500 (in App) 144 43 App Precompiled_RenderObject_layout_10739 (in App) 1140
    44 App Precompiled_RenderFlex_performLayout_10516 (in App) 1164
    45 App Precompiled_RenderObject__layoutWithoutResize_792266271_2092 (in App) 52
    46 App Precompiled_PipelineOwner_flushLayout_2049 (in App) 536
    47 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_PaintingBinding_SemanticsBinding_RendererBinding_24399801_drawFrame_3099 (in App) 48
    48 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_PaintingBinding_SemanticsBinding_RendererBinding_WidgetsBinding_24399801_drawFrame_3203 (in App) 232
    49 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_PaintingBinding_SemanticsBinding_RendererBinding_24399801__handlePersistentFrameCallback_779452173_3103 (in App) 32
    50 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_PaintingBinding_SemanticsBinding_RendererBinding_24399801__handlePersistentFrameCallback_779452173__handlePersistentFrameCallback_779452173_3090 (in App) 188
    51 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_24399801__invokeFrameCallback_815222615_3261 (in App) 144
    52 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_24399801_handleDrawFrame_3218 (in App) 296
    53 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_24399801__handleDrawFrame_815222615_3238 (in App) 72
    54 App Precompiled__WidgetsFlutterBinding_BindingBase_GestureBinding_ServicesBinding_SchedulerBinding_24399801__handleDrawFrame_815222615__handleDrawFrame_815222615_3224 (in App) 120
    55 App Precompiled_____rootRun_4048458_338 (in App) 232
    56 App Precompiled_____rootRun_4048458__rootRun_4048458_339 (in App) 504
    57 App Precompiled__CustomZone_4048458_run_18351 (in App) 240
    58 App Precompiled__CustomZone_4048458_runGuarded_18453 (in App) 52
    59 App Precompiled_____invoke_16065589_1362 (in App) 184
    60 App Precompiled_____drawFrame_16065589_1345 (in App) 176
    61 App Precompiled_Stub_InvokeDartCode (in App) 252
    62 Flutter dart::DartEntry::InvokeFunction(dart::Function const&, dart::Array const&, dart::Array const&, unsigned long) (in Flutter) (dart_entry.cc:190) 20
    63 Flutter Dart_Invoke (in Flutter) (object.cc:12299) 16
    64 Flutter flutter::Window::BeginFrame(fml::TimePoint) (in Flutter) 280
    65 Flutter std::__1::__function::__func<flutter::Animator::AwaitVSync()::$_3, std::__1::allocatorflutter::Animator::AwaitVSync()::$_3, void (fml::TimePoint, fml::TimePoint)>::operator()(fml::TimePoint&&, fml::TimePoint&&) (in Flutter) (animator.cc:142) 20
    66 Flutter std::__1::function<void (fml::TimePoint, fml::TimePoint)>::operator()(fml::TimePoint, fml::TimePoint) const (in Flutter) 44
    67 Flutter fml::MessageLoopImpl::FlushTasks(fml::FlushType) (in Flutter) 1960
    68 Flutter fml::MessageLoopDarwin::OnTimerFire(__CFRunLoopTimer*, fml::MessageLoopDarwin*) (in Flutter) 32
    69 CoreFoundation _CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION (in CoreFoundation) 28
    70 CoreFoundation ___CFRunLoopDoTimer (in CoreFoundation) 864
    71 CoreFoundation ___CFRunLoopDoTimers (in CoreFoundation) 248 0�Thread 14 name: io.flutter.1.raster


text:
Q: Repace blank line (LF only) in Notepad++ with text I have tried at least half a dozen suggestions for this issue but none of them are working for me.
My exact situation:
I started with a file containing text on every line (252 total lines).
I need to insert a 'y' between each line so the file should look like:
text
y
text
y
text
y

etc.
Step 1)  I used the following regex to insert a blank line between lines:
Find: \n
Replace: \n\n
This worked fine.  At this point I have:
text

text

text

etc.
NOTE  When I go into View\Show Symbol\Show End of Line, there are CRLF at the end of every line
containing text, but only LF for the new blank lines.
At this point I want to replace the blank lines (LF only) with the letter 'y'.
NOTE 2  The 'text' lines are commands for a piece of networking equipment.  This particular command
then comes back with the verbose equivalent of 'Are you sure?'.  I want to feed it a 'y'.
I have tried numerous suggestions from several different posts but nothing I do will replace the LF lines with a 'y' AND leave the other lines alone.
I have tried things like: ^\n$ to isolate the blank lines but even this does not work.
Several other suggestions from this and other sites are also not giving me the result I require.

A: You might do it in 1 step, searching for the end of the line and replace with a newline followed by y
If you want to skip completely empty lines, you can assert a char to the left
(?<=.)$

A: *

*Press ctrl + H in notepad++ file where you want to replace blank line with y.

*Select the Extended mode.

*Search for \n\r and add y in replace with, then click on replace All.
Please reference this link https://www.screencast.com/t/92d1J4QW


text:
Q: Log whether a global variable has been read or written Requirement:
Given a C program I have to identify whether the functions accessing global variables are reading them or writing them.
Example code:
#include <stdio.h>

/* global variable declaration */
int g = 20;

int main()
{

    /* writing the global variable */
    g = 10;

    /* reading the global variable */
    printf ("value of g = %d\n",  g);

    return 0;
}

Executing the above code I want to generate a log file in the below format:
1- Global variable a written in function main() "TIME_STAMP"
2- Global variable a read in function main() "TIME_STAMP"

Research:
I am cetainly able to acheive this by doing a static analysis of source code as per below logic:

*

*Go through the c code and identify the statements where the global
variable is read.

*Then analysis the c code statement to identify if
it is a read or write statement.(Checking if ++ or -- operator is
used with global variable or any assignemnt has been made to the
global variable)

*Add a log statement above the identified statement which will execute
along with this statement execution.

This is not a proper implementation.
Some studies:
I have gone through how debuggers are able to capture information.
Some links in the internet:
How to catch a memory write and call function with address of write

A: Not completely answering your question, but to just log access you could do:
#include <stdio.h>

int g = 0;

#define g (*(fprintf(stderr, "accessing g from %s. g = %d\n", __FUNCTION__, g), &g))

void foo(void)
{
  g = 2;
  printf("g=%d\n", g);
}

void bar(void)
{
  g = 3;
  printf("g=%d\n", g);
}

int main(void)
{
  printf("g=%d\n", g);
  g = 1;
  foo();
  bar();
  printf("g=%d\n", g);
}

Which would print:
accessing g from main. g = 0
g=0
accessing g from main. g = 0
accessing g from foo. g = 1
accessing g from foo. g = 2
g=2
accessing g from bar. g = 2
accessing g from bar. g = 3
g=3
accessing g from main. g = 3
g=3

A: Below is the way i solved this problem:

*

*I created a utility(In java) which works as below(C program source file is the input to my utility):

*

*Parse the file line by line identifying the variables and functions.

*It stores global variables in a separate container and look for lines using them.

*For every line which access the global variable i am analyzing them identifying whether it is a read operation or write operation(ex: ==, +=, -+
etc are write operation).

*For every such operation i am instrumenting the code as suggested by @alk(https://stackoverflow.com/a/41158928/6160431) and that in turn will generate the log file when i execute the modified source file.

I am certainly able to achieve what i want but still looking for better implementation if anyone have.
For further discussion if anybody want we can have have a chat.
I refer the source code and algos from the below tools:
http://www.dyninst.org/
https://software.intel.com/en-us/articles/pin-a-dynamic-binary-instrumentation-tool


text:
Q: Progress counter Page Method call is aborted I have a fairly long process running in a standard postback.  Then I have the following page method to return progress to a repeating JavaScript function that is supposed to report on progress.
My simple page method:
[WebMethod]
public static int GetProgress()
{
    return (int)(HttpContext.Current.Session["ActivationResources.ImportProgress"] ?? 0);
}

My clientside script:
function startProgress() {
    window.setInterval(updateImportProgress(), 500);
}

var importProgress = 0;
function updateImportProgress() {
    //debugger;
    PageMethods.GetProgress(function (result, response, context) {
        if (result == importProgress) {
            $("#messageLabel").append(" .");
        }
        else {
            $("#messageLabel").html("Busy importing resources - " + result + "%");
        }
        importProgress = result;
    });
}

The updateImportProgress function is called, but Firebug reports that the POST for GetProgress is 'aborted'.  Why could this be?  I suspect that this is because the call to the static method is blocked by the actual executing method whose progress I am trying to monitor.  A breakpoint in the GetProgress method is never hit.

A: I had this issue before. As a workaround I've implemented the code in an ashx file and avoided that way to touch the same page. Should work for your code as well, as you simply report a session variable.
Btw, note that your code breaks when you have 2 requests running in a single session. That can happen when you open multiple tabs of the same page in the browser.


text:
Q: Extract list elements between lists in Haskell I have the following list:
[[a,b,c],
 [d,e,f],
 [g,h,i]]

and would like to get the following (e.g. if I extract 0th element of a list within the list):
[[a],[d],[g]]

I've been able to do it for one element (e.g. ([[a,b,c],[d,e,f],[g,h,i]])!!0!!0 = a) but I can't seem to get the function to work for all elements in that column.

A: You already know that you can use !! i to get the ith element of a list. So how do you get the ith element of each list in a list of lists? By applying (!! i) to each list in the list of lists. And how do you do that? By using map which can apply any function to each element in a list.
So by using map with (!! i) we get a list containing the ith column of each row, which would be [a, d, g] in your example. From that you can get to your expected output easily enough.
Though if you want to access your matrix by column a lot, you might be better off transposing your matrix once and then using the transposed matrix.

A: To extract first element of list, you can use head function, so if you want to extract first elements of lists contained within a list, you should write
extract_first :: [[a]] -> [a]
extract_first = map head

A: you can write a second function to get the second of the list, and use the cool map snd'!
snd' :: [a] -> a
snd' [] = error "can't call the second on an empty list!"
snd' [x] = error "can't call the second when the list has only one value!"
snd' (_:x:_) = x


text:
Q: How to redirect any route like "http://myweb.com/event/12" to my index.html using php? I am trying to deploy my project on my heroku. My problem is that if I directly reload any route from the browser like:
http://mywebpage.com/event/12

I get "not found 404". I would like to do something so that by default I redirect to the index.php/index.html of my project. If I enter directly from my index in an internal navigation, I don't have any problem, like:
http://mywebpage.com

this is the structure of my folder:
index.php  this file is required by heroku and contains:
<?php header("Location: index.html"); ?>

index.html
css/
assets/
js/

Example of my index.html
<!doctype html>

  <meta charset="utf-8">
  <title>SGC</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="/styles.0f20b4a1e9dce59276ba.css">

  <app-root></app-root>


text:
Q: Three.js local and global coordinates Is there a function in the Three.js that converts local coordinates to/from global coordinates?  I understand the mathematics behind it but I would rather use a function from Three.js if it is available.

A: See https://github.com/mrdoob/three.js/issues/1752
and check out the most recent development build (v.50).


text:
Q: Asymptotic variance of estimators of regression coefficients When doing multiple linear regression,
$\boldsymbol{Y} = X\boldsymbol{\beta}+\boldsymbol{\epsilon}$
where
$\boldsymbol{\epsilon} \sim N(0, \Sigma)$
The best estimates of the coefficients can be found using the generalised least squares formula:
$\boldsymbol{\hat{\beta}} = (X'\Sigma^{-1}X)^{-1}X'\Sigma^{-1}\boldsymbol{Y}$.
From this we can find:
$Var(\boldsymbol{\hat{\beta}}) = (X'\Sigma^{-1}X)^{-1}$
Alternatively, we know that the asymptotic distribution of the estimators is given by
$\boldsymbol{\hat{\beta}} \sim N(\boldsymbol{\beta}, I^{-1})$
where I is the information matrix, and hence
$Var(\boldsymbol{\hat{\beta}}) = I^{-1}$
I have been working through a problem and have been calculating the best estimates of the coefficients using two methods, either by maximising the log-likelihood numerically, or by using generalised least squares (GLS).  In both cases I get the same estimates for the parameters, however the covariance matrices are very different, ie I would expect
$(X'\Sigma^{-1}X)^{-1} \approx I^{-1}$
however I am finding that the variances are much smaller when using the Information matrix.  This is obviously causing issues when doing hypothesis tests etc.  I am simulating my own data and so know what to expect when doing these tests, and it works nicely when using GLS, but the lower variance from the Information matrix is giving me inconsistent results.
Any ideas why this is happening?


text:
Q: c++0x standard library reference manual I've been coding in C++ for years and recently heard that there's a new revision of the C++ standard coming along. I've studied the standard drafts and found out that there's a lot of new stuff that will make my programming easier. So I want to get accustomed to the new standard before it comes out. However, it's pretty hard to code using the new standard library without having a decent reference manual around. I've googled and found only some pages like Wikipedia's C++0x page which are not reference manuals. Does anybody know any C++0x standard library reference manual? I'm looking for something similar to MSDN's Standard C++ Library Reference.

A: There's been some good progress in getting the new features of C++0x on the wiki-based cppreference.com.  The documentation is primarily based on the November 2010 draft standard (N3225).
It's still far from complete, but it's getting better every day.

A: Check your compiler's website/reference manual. Some compiler manufacturers have started adding the C++0x features, especially the ones already pre-finalized in the Technical Report 1. For example, see http://msdn.microsoft.com/en-us/library/bb982198.aspx for the TR1 features Microsoft already included in Visual Studio 2010.

A: A slightly older version of the C++0x draft can be found here. It's the same link you provided, but for VS2010 which implements some of the new standard. So far the only things I've found missing (not to say these are the only) are a for-each loop structure, and the C++0x multi-threading stuff.
I didn't look too much into this, but there's a list of features supported by GCC here.

A: I don't think there would be a reference manual for C++0x, because this standard is still experimental. C++0x is expected to be published by ISO around the end of 2011, so then there would be a reference manual (nutshell, etc.)

A: Why not simply try the features by using a recent compiler? Gcc implements a lot already (depending on the version) and Visual Studio 10 implements 5 new features.
I'm playing with lambda, auto and initializer lists at the moment at work and at home and it's really the kind of features that simplify everything you've write before.


text:
Q: github: initiate code review without pull request? it is a bad way to do code reviews after pull request has been initiated. sometimes we want to do code reviews before the whole thing is ready for integration. is there any tools out there that will allow code review without pull request? I prefer cloud based solution such as reviewable but it only works with pull request...

A: Fastforward to 2019. Github now offers "draft pull requests":
https://github.blog/2019-02-14-introducing-draft-pull-requests/

A: WIP (Work in Progress) pull requests are pretty common. GitHub doesn't have a built-in feature like GitLab or Gerrit have, but it's pretty easy to just do this by consensus: Open a PR that's prefixed with WIP: to indicate it isn't ready for being merged, but is open to feedback, and keep updating it (with git push --force most probably) as you go. Once you're done, you can remove the WIP: prefix.
EDIT:
While it isn't a built-in feature, the WIP third party app seems to help automate this for you, and prevent you from merging a WIP branch by mistake.


text:
Q: Disable tsserver for Visual Studio Code? While editing a React project in Visual Studio Code (1.28.2, Mac OS 10.14, all extensions disabled), the entire system often slows to a crawl. It's not clear what triggers this, but it's seems to be just normal text editing.
Usually when I look in VSCode's Process Explorer, the electron_node tsserver.js process is using the most CPU.
Is it possible to disable whatever it is that makes this process run? I don't mind losing features; I just want to be able to edit files.

A: I have the problem when updating npm packages while VSCode is open.
For me this works: By turning on the setting typescript.disableAutomaticTypeAcquisition tsserver.js can be tamed and CPU usage drops to 0% almost immediately.

A: Disable the "TypeScript and JavaScript Language Features" built-in extension to Visual Studio Code (for your current workspace or globally, as you desire).  You can find this extension by going to the extension manager, selecting "Show Built-in Extensions" from the "..." menu, and looking in the "Features" section.


text:
Q: Github project import into my own project Here it goes.. I am a bloody beginner in programming! So i am also new to android studio..
Here is what i've got:
I am playing around with those fragments and the navigation drawer, everything works just fine, but is it possible to import, lets call it a "whole" github project as fragment class ? Just copy and paste gave me too many errors for me to understand..
(A bit more detailed, i want to build a calendar app, and the android studio calendarview gives me no access to customize the view, so i wanted to use CompactCalenderView just for some testing..
Greetings PatPat!

A: Add this line to your app's build.gradle's dependency block
compile 'com.github.sundeepk:compact-calendar-view:1.7.9'
EDIT:
From Gudin's comment:
On the left side in your android studio open the "Project" tab, if its already open then you should see a file/folder structure on the left side, in the same tab there is a drop down which when you open there should be an option called android just click on it, Now you will be able to see a folder called Gradle scripts, expand it and open the build.gradle(Module:app)

A:
First get take a good look the image ive provided
can you see that there are 2 build.gradle files? Saw that ??Good..
Now select that Gradle build with module:app file
Next put the dependencies in the dependency section just as i have done sync or rebuild the project and that pretty much it ..Hope this helps


text:
Q: What is the webpack command to build my Laravel and Vue js SPA so that I can deploy it to Live Server? I know that I need to run npm run build to build my assets so they are minified for the web. My problem is I'm missing the script in my package.json file and I don't know what the correct code is for this.
package.json:
"scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },

After I run the command it should create the dist folder. This is what I need. I'm not sure why my project is missing that script.

A: You can check the Laravel Mix section of the documentation.
As it states:

Mix is a configuration layer on top of Webpack, so to run your Mix
tasks you only need to execute one of the NPM scripts that is included
with the default Laravel package.json file:
// Run all Mix tasks...
npm run dev

// Run all Mix tasks and minify output...
npm run production

This will generate your files in the public directory, by default:
/public/js/app.js
/public/css/app.css

Of course, you can customize this in the ./webpack.mix.js to do a bunch of other operations (like copying files, customizing the Webpack config, extracting vendors, etc) that you can see in the docs.


text:
Q: Rails 4 with Devise - nested form fields in user registration form I'm trying to build a user registration process in rails using devise.
I have models for User and OrganisationRequest.
The associations are:
User:
has_one :organisation_request, through: :profile
accepts_nested_attributes_for :organisation_request

OrganisationRequest:
belongs_to :profile
# no explicit association on user

In my users/registrations controller, I have:
class Users::RegistrationsController < Devise::RegistrationsController

  before_action :configure_permitted_parameters, if: :devise_controller?

  def new
    resource = build_resource({})
    resource.build_organisation_request
  end

  def create
    super do |user|
      if user.persisted?
        User::CompleteRegistrationService.call(user: user)
      end
    end
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, :first_name, :last_name,
      :organisation_request_attributes => [:organisation_id ] ) }
  end

  # TODO not sure we still need this
  def after_sign_up_path_for(resource)
    finish_signup_path(resource)

  end

end

In my registrations new form, I have:
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>

<%= render partial: 'organisation_request/fields', locals: { f: f } %>

The partial has:
<%= f.simple_fields_for :organisation_request do |f| %>
  <%= f.error_notification %>

          <%= f.input :organisation_id, collection: @all_organisations << ['other', 100000] %>

<% end %>

When that didn't work, I tried moving the form element directly into the user new registration form as follows:
<%= f.simple_fields_for :organisation_request do |f| %>
  <%= f.error_notification %>

          <%= f.input :organisation_id, collection: @all_organisations << ['other', 100000] %>

<% end %>

In each case, when I save all this and try it, I get an error that says:
undefined method `build_organisation_request' for #<User:0x007ff583259858>

Can anyone see what's gone wrong?


text:
Q: salesforce lightning error in Chrome Since yesterday in Chrome browser I am getting the following error when I am trying to open process builder page or trying to install a managed package in the developer org. Below screenshot when trying to install a unmanaged package.
Anybody else facing the same issue. Please see screenshot. Working fine in safari or firefox.

Error while trying to open process builder page


text:
Q: How do I return a boost::asio::deferred from a virtual function Simplified example for the question below:
#include <boost/asio.hpp>
#include <chrono>
#include <memory>
#include <iostream>
using namespace std::literals::chrono_literals;
using namespace boost;

std::error_code do_run(int run){
    asio::io_context ctx{};
    asio::steady_timer timer1(ctx);
    timer1.expires_after(std::chrono::duration<int, std::milli>(300 - (run*100)));
    auto defer1 = timer1.async_wait(asio::deferred);

    std::error_code res{};
    defer1([run,&res](auto &&ec){
        std::cout << "Finished " << run << " " << ec.message() << std::endl;
        res = ec;
    });
    std::cout << "Prepare run " << run << " " << std::endl;
    ctx.run();
    std::cout << "Return to main " << run << " " << std::endl;
    return res;
}

auto do_run2(asio::io_context &ctx, int run){ // <- is there a generic type signature here?
    auto timer1 = std::make_shared<asio::steady_timer>(ctx);
    timer1->expires_after(std::chrono::duration<int, std::milli>(300 - (run*100)));
    return timer1->async_wait(asio::append(asio::deferred,std::move(timer1)));
}

int main(){
    asio::io_context main_context{};
    for(int idx = 0; idx < 3; idx++){
        std::cout << "Run result {" << do_run(idx) << "}" << std::endl;
    }
    for(int idx2 = 0; idx2 < 3; idx2++){
        do_run2(main_context,idx2)([idx2](auto &&ec, auto &&tm){
            std::cout << "Run result deferred " << idx2 << " {" << ec << "}" << std::endl;
        });
    }
    main_context.run();
}

I have some code that is calling an interface method that uses Boost Asio calls internally.  Right now it returns an error code, but it blocks until completion.  I really want to pass in a completion token but since templates cannot be virtual that is not an option. The function do_run is the moral equivalent of what I have now.
I am able to use asio::use_future for a generic return and that works (save for the new thread every time).  Currently asio::use_awaitable is not an option.  Until then I was looking at asio::deferred as a completion token.  That would allow for some flexibility when coroutines are then an option. The example do_run2 is what I am thinking.  If I play games with decltype() and copy/paste the result type from vscode's code completion I get this insane template expansion.  So my question in the end is how can I get a generic return type so that can be made a virtual method?

A:
So my question in the end is how can I get a generic return type so that can be made a virtual method?

Background
Beware, while this may have limited use. All associated entities (executor, allocator, cancellation_slots, more?) will all need to be delegated, with type-erasure.
The completion tokens concept aims to

*

*have zero-overhead abstraction by building all parameterization into the type system

*have the same function template support syntactically different call sites

Even though 1. has less appeal if type-erase it, there are valid reasons to hiding all completion tokens by type-erasure: compilation firewalling (e.g. pimpl idiom).
Note that if you want to retain the call-site syntactical variation (including support for e.g. use_awaitable) you will always need a "trampoline" template function to dispatch into your type-erased interface.
The Good News: any_completion_handler
There is some very recent work to implement a type erased any_completion_handler¹. It was recently added to the develop branch²
There is an example

*

*in c++11 https://www.boost.org/doc/libs/develop/doc/html/boost_asio/examples/cpp11_examples.html#boost_asio.examples.cpp11_examples.type_erasure

*in c++20 https://www.boost.org/doc/libs/develop/doc/html/boost_asio/examples/cpp20_examples.html#boost_asio.examples.cpp20_examples.type_erasure

Applying To Your Code
Your type-erased implementation could look like:
extern void do_run_impl(asio::any_completion_handler<void(error_code)> handler,
                        asio::any_io_executor ex, int run);

You would typically add an initiating function template like:
template <typename Token>
inline auto async_do_run(asio::any_io_executor ex, int run, Token&& token) {
    return asio::async_initiate<Token, void(error_code)>(
        do_run_impl, token, std::move(ex), run);
}

Now you can use it in every way:
asio::awaitable<void> coro(int run) {
    try {
        co_await async_do_run(co_await asio::this_coro::executor, run,
                              asio::use_awaitable);
        std::cout << "async operation using co_await completed successfully" << std::endl;
    } catch (boost::system::system_error const& se) {
        std::cout << "async operation resulted in error: " << se.code().message()
                  << std::endl;
    }
}

template <typename T> bool is_ready(std::future<T> const& f) {
    return (f.wait_for(0ms) == std::future_status::ready);
}

int main(){
    asio::thread_pool ioc;
    auto ex = make_strand(ioc);

    std::future<void> fut = async_do_run(ex, 0, asio::use_future);

    asio::co_spawn(ex, coro(1), asio::detached);

    async_do_run(ex, 2, [](error_code ec) {
        std::cout << "callback completed: " << ec.message() << std::endl;
    });

    std::cout << "ready? " << std::boolalpha << is_ready(fut) << std::endl;

    fut.wait();
    std::cout << "ready? " << std::boolalpha << is_ready(fut) << std::endl;

    ioc.join();
}

To make it link, you have to make sure some TU defines the implementation function, e.g.:
void do_run_impl(asio::any_completion_handler<void(error_code)> handler,
                 asio::any_io_executor ex, int run) //
{
    auto tim = std::make_shared<asio::steady_timer>(ex, 300ms - run * 100ms);
    tim->async_wait(
        [tim, h = std::move(handler)](error_code ec) mutable { std::move(h)(ec); });
}

Note, though, that you can also use to brand-new asio::consign token adaptor to write it more succinctly:
auto timer = std::make_shared<asio::steady_timer>(ex, 300ms - run * 100ms);
timer->async_wait(asio::consign(std::move(handler), timer));

It will print:
ready? false
callback completed: Success
async operation using co_await completed successfully
ready? true

Live Demo
No online compilers has Boost develop, so here's the listing and local demo:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/asio/append.hpp>
#include <chrono>
#include <iostream>
using namespace std::literals::chrono_literals;
namespace asio = boost::asio;
using boost::system::error_code;

extern void do_run_impl(asio::any_completion_handler<void(error_code)> handler,
                        asio::any_io_executor ex, int run);

template <typename Token>
inline auto async_do_run(asio::any_io_executor ex, int run, Token&& token) {
    return asio::async_initiate<Token, void(error_code)>(
        do_run_impl, token, std::move(ex), run);
}

asio::awaitable<void> coro(int run) {
    try {
        co_await async_do_run(co_await asio::this_coro::executor, run,
                              asio::use_awaitable);
        std::cout << "async operation using co_await completed successfully" << std::endl;
    } catch (boost::system::system_error const& se) {
        std::cout << "async operation resulted in error: " << se.code().message()
                  << std::endl;
    }
}

template <typename T> bool is_ready(std::future<T> const& f) {
    return (f.wait_for(0ms) == std::future_status::ready);
}

int main(){
    asio::thread_pool ioc;
    auto ex = make_strand(ioc);

    std::future<void> fut = async_do_run(ex, 0, asio::use_future);

    asio::co_spawn(ex, coro(1), asio::detached);

    async_do_run(ex, 2, [](error_code ec) {
        std::cout << "callback completed: " << ec.message() << std::endl;
    });

    std::cout << "ready? " << std::boolalpha << is_ready(fut) << std::endl;

    fut.wait();
    std::cout << "ready? " << std::boolalpha << is_ready(fut) << std::endl;

    ioc.join();
}

void do_run_impl(asio::any_completion_handler<void(error_code)> handler,
                 asio::any_io_executor ex, int run) {
    auto timer = std::make_shared<asio::steady_timer>(ex, 300ms - run * 100ms);
    timer->async_wait(asio::consign(std::move(handler), timer));
}

Running locally:

¹ branch from here https://github.com/chriskohlhoff/asio/issues/1100#issuecomment-1205062267
² beware: there were fixes as recent as Wed Dec 7 07:34:26 2022 +1100; That's less than 2 days ago at the time of this writing. You will want to keep an eye on updates


text:
Q: ¿Cómo pasar una serie de datos por ajax a php? Buen día. Les explico: quiero pasar una serie de datos por AJAX a PHP desde una lista de elementos que se van agregando.
    var hora;
    var izq;
    var clase;
    var idEntrada;
    var datos;
    $('#publicar').on('click',function() {
        hora = $('#horaDesp').val();
        izq = $('#despIzq').children('section');
        izq.each(function() {
            clase = $(this).attr('class');
            idEntrada = $(this).children('div').attr('id');
            clase = clase.substr(8,2)
            datos = {
                'hora': hora,
                'id': idEntrada,
                'clase': clase
            }
        console.log(datos);
        });
        $.ajax({
            method: 'POST',
            url: 'includes/funciones/programar.php',
            data: datos
        }).done(function(response) {
            console.log(response);
        });
    });

Este es el JQuery para esa función, los elementos se crean dinámicamente desde otra función JQuery al <div id="despIzq"> perfectamente. Y los datos del mismo se recorren cada uno desde el .each() hasta la consola mostrando los datos que necesito.
Mi problema es que cuando envío los datos mediante un objeto desde AJAX a PHP solo se envían los valores del último elemento. Por ejemplo:
    {hora: "01:01", id: "18", clase: "_b"}
    {hora: "01:01", id: "3", clase: "_n"}
    _n

Este sería el resultado obtenido del console.log(datos) y el último dato _n se obtiene mediante PHP
    <?php
    $clase = $_POST['clase'];
    echo $clase;
    ?>

No sé mucho sobre AJAX, imagino que debo pasar los datos en otro formato para que se lean todos los elementos con sus respectivos valores y no los valores del último elemento.
Gracias de antemano a quien pueda ayudarme.

A: Cada loop que hace el each remplaza al anterior valor de data, por lo tanto debes cambiar su tipo de dato y trabajarlo asi
var datos = [];

.each(function () {
datos.push({
'hora' : hora,
...
});

A la hora de enviar datos por ajax, envia un objeto de la siguiente forma
datos = {
    datos: datos,
};
$.ajax({
            method: 'POST',
            url: 'includes/funciones/programar.php',
            data: datos
        }).done(function(response) {
            console.log(response);
        });

PHP obtendrá un array o bien, un json que deberas parsearlo con json_decode
$datos = json_decode($_POST['datos']);

//Si se enviar directamente el array, obten el valor directamente asi
$datos = $_POST['datos'];

//La variable $datos ahora es un array, para recorrerlo hay diferentes métodos como for o foreach, te recomiendo este último
foreach($datos as $dato) {
  //fn para $dato
}


text:
Q: ffmpeg: concat videos and merge with one audio I am trying to concatenate multiple videos priorly reencoded and merge an audio file on top of it all.
I have tried
ffmpeg -y  -i  ../../video_editing_input_dir/part_00.mp4 -i ../../video_editing_input_dir/part_01.mp4 -i ../../video_editing_input_dir/part_02.mp4 -i ../../video_editing_input_dir/part_03.mp4 -i ../../video_editing_input_dir/part_04.mp4 -i ../../video_editing_input_dir/part_05.mp4 -i ../../video_editing_input_dir/part_06.mp4 -i ../../video_editing_input_dir/part_07.mp4 -i ../../video_editing_input_dir/part_08.mp4 -i ../../video_editing_input_dir/part_09.mp4 -i ../../video_editing_input_dir/part_10.mp4 -i ../../video_editing_input_dir/part_11.mp4 -i ../../video_editing_input_dir/new_audio.mp3 -filter_complex " [0:v:0] setsar=1/1 [v0]; [1:v:0] setsar=1/1 [v1]; [2:v:0] setsar=1/1 [v2]; [3:v:0] setsar=1/1 [v3]; [4:v:0] setsar=1/1 [v4]; [5:v:0] setsar=1/1 [v5]; [6:v:0] setsar=1/1 [v6]; [7:v:0] setsar=1/1 [v7]; [8:v:0] setsar=1/1 [v8]; [9:v:0] setsar=1/1 [v9]; [10:v:0] setsar=1/1 [v10]; [11:v:0] setsar=1/1 [v11]; [v0] [v1] [v2] [v3] [v4] [v5] [v6] [v7] [v8] [v9] [v10] [v11] [12:a:0] concat=n=13:v=1:a=1 [v] [a] " -map [v] -map [a] -c:v h264 -pix_fmt yuv420p -c:a aac ../../video_editing_input_dir/tmp_output_video.mp4

( the setsar=1/1 is mandatory otherwise the concat doesn't work)
And get the following error
ffmpeg version 3.4.6-0ubuntu0.18.04.1 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 7 (Ubuntu 7.3.0-16ubuntu3)
  configuration: --prefix=/usr --extra-version=0ubuntu0.18.04.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --enable-gpl --disable-stripping --enable-avresample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librubberband --enable-librsvg --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libopencv --enable-libx264 --enable-shared
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libavresample   3.  7.  0 /  3.  7.  0
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_00.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_01.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:03.02, start: 0.000000, bitrate: 29 kb/s
    Stream #1:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 17 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #1:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #2, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_02.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #2:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #2:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #3, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_03.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:01.02, start: 0.000000, bitrate: 29 kb/s
    Stream #3:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 10 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #3:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #4, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_04.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:03.02, start: 0.000000, bitrate: 62 kb/s
    Stream #4:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 2813:2814 DAR 22504:12663], 50 kb/s, SAR 5625:5627 DAR 10000:5627, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #4:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #5, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_05.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #5:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #5:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #6, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_06.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #6:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #6:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #7, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_07.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:06.82, start: 0.000000, bitrate: 600 kb/s
    Stream #7:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 465 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #7:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #8, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_08.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #8:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #8:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #9, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_09.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #9:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #9:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #10, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_10.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:03.02, start: 0.000000, bitrate: 33 kb/s
    Stream #10:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 21 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #10:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #11, mov,mp4,m4a,3gp,3g2,mj2, from '../../video_editing_input_dir/part_11.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 00:00:00.27, start: 0.000000, bitrate: 74 kb/s
    Stream #11:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x360 [SAR 1:1 DAR 16:9], 29 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #11:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 2 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
Input #12, mp3, from '../../video_editing_input_dir/new_audio.mp3':
  Metadata:
    encoder         : Lavf57.83.100
  Duration: 00:00:18.89, start: 0.025057, bitrate: 128 kb/s
    Stream #12:0: Audio: mp3, 44100 Hz, stereo, s16p, 128 kb/s
    Metadata:
      encoder         : Lavc57.10
[Parsed_setsar_1 @ 0x56545b465880] Media type mismatch between the 'Parsed_setsar_1' filter output pad 0 (video) and the 'Parsed_concat_12' filter input pad 1 (audio)
[AVFilterGraph @ 0x56545b66ad40] Cannot create the link setsar:0 -> concat:1
Error initializing complex filters.
Invalid argument

I am in this kind of situation but am willing to use only one audio file.
Any idea ?
Thanks in advance

A: All segments to be concatenated must have the same number and types of streams. Your audio input has nothing to concatenate to, so remove it from the concat filter and map it directly:
ffmpeg -i input0 ... -i input12 -filter_complex "[v0] [v1] [v2] [v3] [v4] [v5] [v6] [v7] [v8] [v9] [v10] [v11] concat=n=12:v=1:a=0,format=yuv420p [v]" -map "[v]" -map 12:a:0 -c:v libx264 -c:a aac -movflags +faststart -shortest output.mp4


text:
Q: How to cache the results in the simple autocomplete I am write a simple textarea tag completer script. So how to can i cache the old results?
I try following code:
                var lastQuery = term.toLowerCase();

                if(fallback[0]){

                                var dl = [];

                        for(k=0; k<fallback.length; k++){

                                var name = fallback[k].name.toLowerCase();

                                if( name.substr(0, lastQuery.length) == lastQuery ){

                                    dl.push(fallback[k]);

                                }

                        }
                                if(dl[0]){
                                    callback(dl); // "callback" Dropdown trigger
                                    return false;
                                }
                                else
                                    return true;

              // .......... following the autocomplete function ...........

I'm using for merge: fallback.concat(dl) , "dl" is a succesfully data on the autocomplete.
But array not unique and this a problem.
It full codes:
                var lastQuery = term.toLowerCase();

                if(fallback[0]){

                                var dl = [];

                        for(k=0; k<fallback.length; k++){

                                var name = fallback[k].name.toLowerCase();

                                if( name.substr(0, lastQuery.length) == lastQuery ){

                                    dl.push(fallback[k]);

                                }

                        }
                                if(dl[0]){
                                    callback(dl);
                                    return false;
                                }
                                else
                                    return true;
                }

            // Here is autocomplete function

            $.ajax({
                url: homeurl+'/api/hashtag/index.php',
                type: "POST",
                dataType: 'json',
                data: { query: term },
                success: function (data) {
                    var x = data;

                    if(x.hashtag){

                                var dl = [];

                        for(i=0; i<x.hashtag.length; i++){

                                var name = x.hashtag[i].name.toLowerCase();

                                if( name.substr(0, lastQuery.length) == lastQuery ){

                                    dl.push(x.hashtag[i]);

                                }

                        }
                        if(dl[0]){
                            fallback = fallback.concat(dl);
                            callback(dl);
                        }
                        else
                        callback(null);

                    } else {
                        callback(null);
                    }

                }
            });

Footnote: return false; get wrong (not in dom, just script stop work) after the a few keystroke...
                       if(dl[0]){
                           callback(dl);
                           return false;
                       }
                       else
                           return true;

A: Uhhh, try try try finally i am solved it: function arrayUniqueForHashtag()
function arrayUniqueForHashtag(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i].name == a[j].name)
                a.splice(j--, 1);
        }
    }

    return a;
}

call the cache key search: return false;
Finally code:
            var lastQuery = term.toLowerCase();

            if(fallback[0]){

                            var dl = [];

                    for(k=0; k<fallback.length; k++){

                            var name = fallback[k].name.toLowerCase();

                            if( name.substr(0, lastQuery.length) == lastQuery ){

                                dl.push(fallback[k]);

                            }

                    }
                            if(dl[0]){
                                callback(dl);
                                return false;
                            }
                           // else
                           //     return true;
            }

        // Here is autocomplete function

        $.ajax({
            url: homeurl+'/api/hashtag/index.php',
            type: "POST",
            dataType: 'json',
            data: { query: term },
            success: function (data) {
                var x = data;

                if(x.hashtag){

                            var dl = [];

                    for(i=0; i<x.hashtag.length; i++){

                            var name = x.hashtag[i].name.toLowerCase();

                            if( name.substr(0, lastQuery.length) == lastQuery ){

                                dl.push(x.hashtag[i]);

                            }

                    }
                    if(dl[0]){
                        fallback = arrayUniqueForHashtag(fallback.concat(dl));
                        callback(dl);
                    }
                    else
                    callback(null);

                } else {
                    callback(null);
                }

            }
        });

Working now on the caching data.


text:
Q: Sorting a list into multiple vertical columns Does anyone have a good algorithm for re-sorting an array of values (already pre-sorted) so that they can be displayed in multiple (N) columns and be read vertically? This would be implemented in .Net but I'd prefer something portable and not some magic function.
A good example of it working is the ASP.Net CheckBoxList control rendering as a table with the direction set to vertical.
Here's an example of the input and output:
Input:
Columns = 4
Array = {"A", "B", "C", "D", "E", "F", "G"}
Output:
ACEG
BDF
Thanks!
Updated (More Info):
I think I might have to give a little more information on what I'm trying to do... Mostly this problem came about from going from using a CheckBoxList's automatic binding (where you can specify the columns and direction to output and it would output a table of items in the correct order) to using jQuery/AJAX to create the checkbox grid. So I'm trying to duplicate that layout using css with div blocks with specified widths (inside a container div of a known width) so they wrap after N items (or columns.) This could also be rendered in a table (like how ASP.Net does it.)
Everything works great except the order is horizontal and when you get a large number of items in the list it's easier to read vertical columns.
If the array doesn't have enough items in it to make an even grid then it should output an empty spot in the correct row/column of the grid.
And if an array doesn't have enough items to make even a single row then just output the items in their original order in one row.
Some other input/ouput might be:
Columns = 3
Array = {"A", "B", "C", "D"}
ACD
B
Columns = 5
Array = {"A", "B", "C", "D", "E", "F", "G", "H"}
ACEGH
BDF
Columns = 5
Array = {"A", "B", "C", "D"}
ABCD

A: Okay, I'm sorry for my initial statement, but when you want it to work as you described in the comment to my first answer, you need in fact re-sort the data... well somewhat. It could maybe be done without the helper matrix, however the resulting code is probably very complex and as long as the matrix will only use a couple of bytes of memory, why not using this little helper construct?
What my code does below is creating a matrix. We write the matrix from top to bottom and then from left to right (and stop filling up anything but the first row when we run out of elements to fill up all columns of the first row). Then we read it in a different order, left to right and top to bottom. Basically what we do here is transposing a matrix, by writing it in one order, but reading it in another order. Transposing a matrix is a very elementary mathematical operation (lots of 3D programming works by using matrix calculations and transposing is actually a simple operation). The trick is how we initially fill up the matrix. To make sure we can fill up the first column in any case, independently of number of desired columns and size of the array, we must stop filling the matrix in the normal order if we run out of elements and reserve all elements left over for the first row. This will produce the output you have suggested in your comment.
The whole thing is bit complicated to be honest, but the theory behind it should be sane and it works lovely :-D
int Columns;
char * Array[] = {"A", "B", "C", "D", "E", "F", "G"};

int main (
    int argc,
    char ** argv
) {
    // Lets thest this with all Column sizes from 1 to 7
    for (Columns = 1; Columns <= 7; Columns++) {

        printf("Output when Columns is set to %d\n", Columns);

        // This is hacky C for quickly get the number of entries
        // in a static array, where size is known at compile time
        int arraySize = sizeof(Array) / sizeof(Array[0]);

        // How many rows we will have
        int rows = arraySize / Columns;

        // Below code is the same as (arraySize % Columns != 0), but
        // it's almost always faster
        if (Columns * rows != arraySize) {
            // We might have lost one row by implicit rounding
            // performed for integer division
            rows++;
        }

        // Now we create a matrix large enough for rows * Columns
        // references. Note that this array could be larger than arraySize!
        char ** matrix = malloc(sizeof(char *) * rows * Columns);

        // Something you only need in C, C# and Java do this automatically:
        // Set all elements in the matrix to NULL(null) references
        memset(matrix, 0, sizeof(char *) * rows * Columns );

        // We fill up the matrix from top to bottom and then from
        // left to right; the order how we fill it up is very important
        int matrixX;
        int matrixY;
        int index = 0;
        for (matrixX = 0; matrixX < Columns; matrixX++) {
            for (matrixY = 0; matrixY < rows; matrixY++) {
                // In case we just have enough elements left to only
                // fill up the first row of the matrix and we are not
                // in this first row, do nothing.
                if (arraySize + matrixX + 1 - (index + Columns) == 0 &&
                        matrixY != 0) {
                    continue;
                }

                // We just copy the next element normally
                matrix[matrixY + matrixX * rows] = Array[index];
                index++;
                //arraySize--;
            }
        }

        // Print the matrix exactly like you'd expect a matrix to be
        // printed to screen, that is from left to right and top to bottom;
        // Note: That is not the order how we have written it,
        // watch the order of the for-loops!
        for (matrixY = 0; matrixY < rows; matrixY++) {
            for (matrixX = 0; matrixX < Columns; matrixX++) {
                // Skip over unset references
                if (matrix[matrixY + matrixX * rows] == NULL)
                    continue;

                printf("%s", matrix[matrixY + matrixX * rows]);
            }
            // Next row in output
            printf("\n");
        }
        printf("\n");

        // Free up unused memory
        free(matrix);
    }
    return 0;
}

Output is
Output when Columns is set to 1
A
B
C
D
E
F
G

Output when Columns is set to 2
AE
BF
CG
D

Output when Columns is set to 3
ADG
BE
CF

Output when Columns is set to 4
ACEG
BDF

Output when Columns is set to 5
ACEFG
BD

Output when Columns is set to 6
ACDEFG
B

Output when Columns is set to 7
ABCDEFG

This C code should be easy to port to PHP, C#, Java, etc., there's no big magic involved, so it's pretty much universal, portable and cross-platform.

One important thing I should add:
This code will crash if you set Columns to zero (division by zero, I don't check for that), but what sense would 0 Columns make? And it will also crash if you have more columns than elements in the array, I don't check for this either. You can easily check for either right after you got the arraySize:
if (Columns <= 0) {
   // Having no column make no sense, we need at least one!
   Columns = 1;
} else if (Columns > arraySize) {
   // We can't have more columns than elements in the array!
   Columns = arraySize;
}

Further you should also check for the arraySize being 0, in which case you can jump out straight away of the function, as in that case there is absolutely nothing to do for the function :) Adding these checks should make the code rock solid.
Having NULL Elements in the Array will work, BTW, in that case there are no holes in the resulting output. NULL elements are just skipped like not being present. E.g. lets use
char * Array[] = {"A", "B", "C", "D", "E", NULL, "F", "G", "H", "I"};

The output will be
ADFI
BEG
CH

for Columns == 4. If you want holes, you need to create a hole element.
char hole = 0;
char * Array[] = {"A", "B", &hole, "C", "D", "E", &hole, "F", "G", "H", "I"};

and modify the painting code a bit
    for (matrixY = 0; matrixY < rows; matrixY++) {
        for (matrixX = 0; matrixX < Columns; matrixX++) {
            // Skip over unset references
            if (matrix[matrixY + matrixX * rows] == NULL)
                continue;

            if (matrix[matrixY + matrixX * rows] == &hole) {
                printf(" ");
            } else {
                printf("%s", matrix[matrixY + matrixX * rows]);
            }
        }
        // Next row in output
        printf("\n");
    }
    printf("\n");

Output samples:
Output when Columns is set to 2
A
BF
 G
CH
DI
E

Output when Columns is set to 3
ADG
BEH
  I
CF

Output when Columns is set to 4
AC H
BDFI
 EG

A: A small UPDATE:
The algorithm I'm using here is a modified one you'd use for painting images. I'm pretending the array entries to be pixel data of an image and then I'm painting the image from left to right (1. LtoR) and from top to bottom (2. TtoB), however, the image data is stored from top to bottom (1. TtoB) and then from left to right (2. LtoR); IOW in a different order. Since an image can't have holes, this is the reason why it will not work with 5 or 6 columns. With 4 columns the output is
ACEG
BDF

As an image this looks like this
OOOO
OOO.

With O being a pixel of the image and . being an undefined pixel (a missing one). Missing ones may only be at the end of the image, not in the middle of it. That means it could also look like this
OOO
OO.
OO.
OO.

All missing pixels are always at the end, if you read first from top to bottom and then from left to right, because in that case all missing pixels follow directly each other at the end. If I read the diagram TtoB and then LtoR, it must read like this "Pixel, Pixel, Pixel, Pixel, ..., Pixel, Missing, Missing, Missing, ..., Missing", it might never read "Pixel, Missing, Pixel" or "Missing, Pixel, Missing". All pixels are together and all missings are, too.
With 5 columns, as the comment suggests, it should look like this
ACEFG
BD

However, as image this would look like this
OOOOO
OO...

And this is not allowed by the algorithm. If I read it TtoB and then LtoR, it will read: "Pixel, Pixel, Pixel, Pixel, Pixel, Missing, Pixel, Missing, Pixel, Missing". And as stated above, this is not allowed by the algorithm. So this simple pixel painting approach will not paint as many columns as requested if painting that many columns leads to holes in the image. In that case it will simply fill up the holes, however, this will cause less columns to be drawn.
Let me think of a solution that will always paint the requested numbers of pixels (in a separate reply).

You don't have to re-arrange the data in memory for that at all. Just print it in the desired order.
Some C Code (I'm doing it extremely verbose, so everyone understands what I'm doing so. Of course this can be much more compact):
int Columns = 4;
char * Array[] = {"A", "B", "C", "D", "E", "F", "G"};

int main (
    int argc,
    char ** argv
) {
    // This is hacky C for quickly get the number of entries
    // in a static array, where size is known at compile time
    int arraySize = sizeof(Array) / sizeof(Array[0]);

    // How many rows are we going to paint?
    int rowsToPaint = (arraySize / Columns) + 1;

    int col;
    int row;

    for (row = 0; row < rowsToPaint; row++) {
        for (col = 0; col < Columns; col++) {
            int index = col * rowsToPaint + row;

            if (index >= arraySize) {
                // Out of bounds
                continue;
            }

            printf("%s", Array[index]);
        }
        printf("\n"); // next row
    }
    printf("\n");
    return 0;
}

Note: This works fine with a value of 8 (so everything is painted within one row) and values of 4 and below (works fine with 3, 2 and 1), but it can't work with 5. This is not the fault of the algorithm, it is the fault of the constrain.
ACEFG
BD

The constraint says the columns are read top to bottom to get the corrected sorted data. But above "EFG" is sorted and it's not top to bottom, it is left to right. Thus this algorithm has a problem. Using Columns = 3 will work
ADG
BE
CF

Using two will work as well
AE
BF
CG
D

And one will put everything into one column.

A: This looks like homework assignments
anyway
array<String^>^  sArray = {"A", "B", "C", "D", "E", "F", "G"};
double Columns = 4;
double dRowCount = Convert::ToDouble(sArray->Length) / Columns;
int rowCount = (int) Math::Ceiling(dRowCount);
int i = 0;
int shift = 0;
int printed = 0;
while (printed < sArray->Length){
    while (i < sArray->Length){
        if (i % rowCount == shift){
            Console::Write(sArray[i]);
            printed++;
        }
        i++;
    }
    Console::Write("\n");
    i = 0;
    shift++;
}


text:
Q: Ubuntu 16.04 updating Google Chrome gets weak digest and hash sum mismatch messages So for a while now whenever I run sudo apt-get update I have been getting some output regarding google-chrome similar to:
W: http://dl.google.com/linux/chrome/deb/dists/stable/Release.gpg: Signature by key 4CCA1EAF950CEE4AB83976DCA040830F7FAC5991 uses weak digest algorithm (SHA1)
W: http://dl.google.com/linux/chrome/deb/dists/stable/Release.gpg: Signature by key 3B068FB4789ABE4AEFA3BB491397BC53640DB551 uses weak digest algorithm (SHA1)

Which I understand means something along the lines of Google is being lazy about their package signing, and that it shouldn't impact updating, as explained here. However, just today I've started getting the following additional message when updating:
E: Failed to fetch http://dl.google.com/linux/chrome/deb/dists/stable/main/binary-amd64/Packages.bz2  Hash Sum mismatch
E: Some index files failed to download. They have been ignored, or old ones used instead.

I have attempted to fix the hash sum mismatch as described in the answer here, but the problem persists. So my main question is, is this an error with Google Chrome's package repository or my own computer?
Just in case it is pertinent, here is the full output from sudo apt-get update:
Hit:1 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:2 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease
Ign:4 http://dl.google.com/linux/chrome/deb stable InRelease
Get:5 http://dl.google.com/linux/chrome/deb stable Release [1,189 B]
Hit:6 http://security.ubuntu.com/ubuntu xenial-security InRelease
Get:7 http://dl.google.com/linux/chrome/deb stable Release.gpg [916 B]
Hit:8 http://archive.canonical.com/ubuntu xenial InRelease
Hit:9 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Get:10 http://dl.google.com/linux/chrome/deb stable/main amd64 Packages [1,343 B]
Err:10 http://dl.google.com/linux/chrome/deb stable/main amd64 Packages
  Hash Sum mismatch
Fetched 3,439 B in 2s (1,566 B/s)
Reading package lists... Done
W: http://dl.google.com/linux/chrome/deb/dists/stable/Release.gpg: Signature by key 4CCA1EAF950CEE4AB83976DCA040830F7FAC5991 uses weak digest algorithm (SHA1)
W: http://dl.google.com/linux/chrome/deb/dists/stable/Release.gpg: Signature by key 3B068FB4789ABE4AEFA3BB491397BC53640DB551 uses weak digest algorithm (SHA1)
E: Failed to fetch http://dl.google.com/linux/chrome/deb/dists/stable/main/binary-amd64/Packages.bz2  Hash Sum mismatch
E: Some index files failed to download. They have been ignored, or old ones used instead.

Also, somewhat of a side question, how do you suppress the warning messages from apt-get (if you can), and is it wise to do so?


text:
Q: Code coverage for GUI based functional tests I am trying to get bytecode coverage analysis using a code coverage tool (like Emma or Jacoco) after testing with a GUI based functional testing tool (like HP QuickTest Pro or Selenium).
Anyone who has done this could please give me an idea to start this project?

A: I am doing this now.  My approach is to use JaCoCo ant tasks to instrument the binary byte-code files, and use a specific CLASSPATH to execute the instrumented binaries from an ant build.xml from Jenkins.
The reason for doing the code coverage from byte-code is that there is an existing set-up that runs test scripts for a large application using HP QuickTest Pro .  I would imagine that the test coverage is in the single digits, but we need an empirical baseline to demonstrate the possible improvements in code coverage from doing unit tests during a build.


text:
Q: RedBeanPHP добавить переменную в SQL запрос У меня есть запрос:
$location = R::getAll( 'SELECT * FROM post WHERE location = :location',
    [':location' => $_POST["search-location"]]
);

Нужно подставить переменную здесь: ... 'SELECT * FROM $variable_name ...


text:
Q: How to handle clicks / touches on repeated custom components? So, I have a screen that has from 0 to 6 of the same user interface components included via XML.  Something similar to this:
<TableRow android:layout_height="150px">

    <include android:id="@+id/p1" android:layout_width="fill_parent"
        android:layout_height="wrap_content" layout="@layout/numerics_component"
        android:onClick="onClick" />

</TableRow>

<TableRow android:layout_height="150px">

    <include android:id="@+id/p2" android:layout_width="fill_parent"
        android:layout_height="wrap_content" layout="@layout/numerics_component"
        android:layout_below="@id/p1" android:onClick="onClick" />

</TableRow>

... etc
Each of those included UI's is a collection of several widgets and custom components that I am reusing.
I want to detect clicks on components in those included bits in my Activity and respond appropriately.  The problem is, in my onClick method if I follow the common pattern, I can never tell which of the views got a click:
public void onClick(View view) {

    Log.d(loggingName, "Got onClick event on view: " + view);

    // Identify the view, and handle appropriately:
    switch (view.getId()) {

    ...

With the above code I can never tell which of the 6 copies of the component got clicked.  There must be a good way to do this, but I am not seeing it.
Further, I don't want to hard code the reusable component to one activity because I want to reuse it throughout multiple activities in my app.  So ideally, I'd be able to setup the listeners in my Activity.
Any ideas on how I can do this?
Thanks!

A: 1) The Android View class allows you to tag each instance of a view via the setTag method.
So, just setTag() on each view with some unique Integer, or even perhaps an object with a method that you will invoke.  Then in your click listener, just do a getTag() to differentiate between the various view instances.
2) You can put a unique onClickListener on each of the view instances.
3) You could do a findViewById() on each of the view instances, and store them in member variables, an array, or some other data structure.  Then in your onClickListener, you simply compare the View reference passed to onClick() against your list of saved references.

A: You could search the hierarchy to figure out which sub-component has been clicked. I see that each row of your table has a unique id. Thus, even though the layout is being repeated with identical ids, the view hierarchy does not have identical ids in any sub-tree.
Thus, to identify which sub-component has been clicked obtain the id of the parent view (which in your case is a row) and see which one of the 6 rows the view belongs to. Does that make sense?


text:
Q: How to make Popcorn.js work with Video.js on iPad I can't use the native video player on the iPad because it steals all touch events and I need show interactive elements over the video. Using Video.js works for this purpose but, strangely, it stops Popcorn.js events from firing on iPad.

A: It's not entirely a solution but I found that MediaElement.js is a good replacement for Video.js and plays nicely with Popcorn.

A: The problem is not a specific video library. It is when you have your controls enabled for video player you cannot do any interactivity on any HTML element on top of video.
I had the same problem and i solved it by doing
p.controls(false); //where p is the object of popcorn js player

I did that when displaying any interactive element such as BUTTON on top of video and when my button was no longer needed on top of video i enabled the controls again.
p.controls(true);

And it worked like a charm!


text:
Q: GCM notifications not triggered on device I'm trying to develop an hybrid app with Cordova using this ngcordova plugin http://ngcordova.com/docs/plugins/pushNotifications/
I was able to receive notifications and they appear if the data array sent includes a "message" field. From the GCM docs https://developers.google.com/cloud-messaging/http-server-ref?hl=en I read that if you had a "notification" array inside data you could customize the notification with icon, body etc... However notifications only work and show what's inside "message", all other fields in notification field are ignored.
So what I'm asking is if the client app always has to manually show notifications on the client side. If this is the case then what is the point of the standard notification array and the requires if they're ignored?
This is the array I'm sending which triggers no notification on the device.
    [data] => Array
        (
            [notification] => Array
                (
                    [title] => New notification
                    [icon] => myicon
                    [body] => Geology
                )

        )

)

EDIT: ok so apparently notification must be outside of data!
So I changed to this:
Array
(
    [to] => APA91bG73Bp8AfHbOJRRkfp9axq1HgNtaG...
    [notification] => Array
        (
            [title] => New notification
            [icon] => myicon
            [body] => Geology
        )

    [data] => Array
        (
            [Nick] => Sandro
        )

)

But it still doesn't trigger anything, but it should according to the docs.

To send notifications, set notification with the necessary predefined
  set of key options for the user-visible part of the notification
  message. Optionally, set data with custom key/value pairs to pass
  additional payload to the client app. GCM will display the
  notification part on the client app's behalf. When optional data is
  provided, it is sent to the client app once user clicks on the
  notification and opens the client app.


text:
Q: Why do Android captured PNG's throw errors on attempt to render into Prawn PDF I have an ios/android app that requires a user to sign something on screen then the app captures a screenshot of this signature.  In most situations, this process works fine.  In a few situations, usually related to Samsung Android phones, on the server when I attempt to render the S3 stored screenshot from the phone, PRAWN PDF throws the below error.
Zlib::Inflate.inflate(@img_data)
Zlib::DataError: incorrect data check

I wasn't able to get any more error information from this so I decided to dig in and look more closely at the underlying data of the file.  My first attempt was to open the file with ImageMagick.
ImageMagick will create an image file object as referenced below,
#<MiniMagick::Image:0x007f83b47c9bf8 @path="/var/folders/g2/57tbfl691hg1gyqjkgy4vd6m0000gn/T/mini_magick20150713-2121-6y1as5.png", @tempfile=#<Tempfile:/var/folders/g2/57tbfl691hg1gyqjkgy4vd6m0000gn/T/mini_magick20150713-2121-6y1as5.png (closed)>, @info=#<MiniMagick::Image::Info:0x007f83b47c9bd0 @path="/var/folders/g2/57tbfl691hg1gyqjkgy4vd6m0000gn/T/mini_magick20150713-2121-6y1as5.png", @info={"raw:%m %w %h %b"=>"PNG 2560 970 59926B", "format"=>"PNG", "width"=>2560, "height"=>970, "dimensions"=>[2560, 970], "size"=>59926}>>

When I attempted the most basic image file operation I could think of, ie, convert from png to jpg, I received the below error, which references the IDAT data check as being incorrect, this behavior is consistent with the error from PRAWN ie, 'incorrect data check'.
MiniMagick::Error: `convert /var/folders/g2/57tbfl691hg1gyqjkgy4vd6m0000gn/T/mini_magick20150713-29731-1urceop.png[0] /var/folders/g2/57tbfl691hg1gyqjkgy4vd6m0000gn/T/mini_magick20150713-29731-10i6sg1.jpg` failed with error:
convert: IDAT: incorrect data check `/var/folders/g2/57tbfl691hg1gyqjkgy4vd6m0000gn/T/mini_magick20150713-29731-1urceop.png' @ warning/png.c/MagickPNGWarningHandler/1831.

I'm unclear how to verify the expected value of IDAT or even how to interpret any patterns that might indicate the data is corrupt.  Below is the meta data for an image that is causing the PRAWN crash.
{"x-amz-id-2"=>"BXkVr2k45L6zHSV31aq6tH3oCBp5C9Ncv0fD1zLOh5oW5D0PQHt1i+za3eAat/TezLZQfOyr43E=", "x-amz-request-id"=>"69601E81D15125AD", "date"=>"Mon, 13 Jul 2015 20:29:00 GMT", "last-modified"=>"Mon, 13 Jul 2015 19:14:49 GMT", "etag"=>"\"fe1da1ea421864ddadde17147bbb82a9\"", "accept-ranges"=>"bytes", "content-type"=>"image/png", "content-length"=>"59926", "server"=>"AmazonS3"}

The code being used on Android to capture the screenshot is below.
original_image = cropImageView.getCroppedImage()
ByteArrayOutputStream stream = new ByteArrayOutputStream();
original_image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
stream.close();

In general, the files being captured are always being successfully captured, stored and retrieved but any attempt to process these particular files causes the PRAWN error.  I'm unclear what direction to take this debugging and would really like some input on how to proceed.
An example image that was captured with a Samsung Android Galaxy Note 4 running android 5.0.1  is stored here, https://s3-us-west-2.amazonaws.com/bcamarda/original_broken.png for reference and or tinkering if so desired.


text:
Q: WPF: Bindings - Object not updated I have a an object which is set to the DataContext in a Window. I have textboxes in the window which are bound to the properties on the object. There seems to be a delay however before the properties on the object are updated.
<TextBox x:Name="txtPropertyOne" Text="{Binding Path=PropertyOne,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  />

If I change the values in a few textboxes then quickly try to access the properties to which they map, sometimes there are changes which aren't reflected in the properties of the object. I thought that was what the PropertyChanged UpdateSourceTrigger was supposed to take care of.

A:
If I change the values in a few
  textboxes then quickly try to access
  the properties to which they map

I can interpret this statement in two ways:

*

*You're trying to access the values on a background thread. In that case, you may be accessing the properties before the UI thread has had a chance to do its thing.

*You're using a separate message on the UI thread to check the values. Bindings are updated at a priority lower than Send and Normal. So if your message is priority Send or Normal it will be processed before any pending binding updates.

If this doesn't answer your question, please clarify what you mean by "quickly trying to access the properties".

A: The basic rule of WPF Databinding is simple:

*

*The target property must be a
dependency property, and you're
already correct, it's bound to Text
property of TextBox.

*The source property can be a CLR
object (other than any derived WPF's
DependencyObject), but the object
must employ or implement its own
INotifyPropertyChanged.

Have you you already implemented INotifyPropertyChanged on your object?


text:
Q: How GC collects resources in a static member in .NET? I have a piece of code like this:
Class Program
{
    static StreamReader sr = null;
    static int var=0;
    static Program()
    {
        sr = new StreamReader("input.txt")
    }

    ~Program()
    {
        sr.Dispose();
    }

    static void main(string args[])
    {
        //do something with input here
    }
}

This may not be a good practice, but I just want to use this example to ask how the deconstructor and GC works.
My question is: Will ~Program() get called at a non-determined time or it won't be called at all in this case. If the deconstructor won't get called, then how GC collect the unmanaged resources and managed resources.

A: Your case is quite unclear, as the finalizer would not be called without creating an instance of the class.
However, only calling dispose does nothing towards garbage collection of the object itself, it merely tells the object to release any resource (especially handles etc.). So if you want the GC to collect the instance, you need to set the reference to null, and if there is no other live reference to the instance it will eventually be collected.
Basically each static reference can be seen as root reference, which is included in the GC checks for live references. All instances which cannot be reached through a live reference (directly or indirectly) are candidates for collection. It does not matter if the reference "variable" was static or not.

A: A static reference will root an instance until it is explicitly set to null or its assembly is unloaded. If neither of these happens the instance a static reference points to will remain in use and thus will not be collected. If it isn't eligible for garbage collection its finalizer will not be called either.
Btw GC only handles managed memory. It doesn't handled unmanaged resources. For that you need IDiposable and/or finalizers.

A: There is no such thing as a static finalizer (destructor) in C#. Therefore, unless an instance of Program is ever actually created, ~Program() will never be called.
When (if) it is called, it only calls the Dispose() method of the StreamReader; because a reference to the StreamReader is still retained after the finalizer is called, the instance will never be garbage collected until the program exits.

A: It probably wouldn't reclaim those resources until the AppDomain or process is unloaded.
If you never instantiate an object, it will never be destroyed.  This is exactly why you want, probably something like a Singleton.  I believe there is a flavor called "Phoenix Singleton," that will allow a Singleton to be cleaned up and then rebuilt when it is needed again.  You could implement it using a WeakReference to the singleton object.
In any case, for a simple program that runs for a bounded period of time, I wouldn't worry about it unless it becomes a problem... the resources will be cleaned up when the process exits.