text:
Q: squery not fetching the values in the batch class need some help for the batch class as i am not able to print the sQuery values in the batch class, not sure what is the correct way to do this one.
kindly some one help me for the correct sQuery in the batch class and how to print the values.
Below is my code :-
global class testbatcg implements Database.Batchable<sObject>, Database.Stateful {

    private String accountIdString;

    public testBatch(String accountId) {
        accountIdString = accountId;
        System.debug('Here in the Batch class the account ID  == '+accountIdString);
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        string query = 'SELECT Id,Name, AccountId from Contact where AccountId=:accountIdString';
        System.debug('>>>>>>Here is the contact batch list=='+Database.getQueryLocator(query));
        System.debug('>>>>>>>>>>Batch values=='+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Contact> Scope) {
    }

    global void finish(Database.BatchableContext BC) {
    }
}

A: There is a difference between executing a query (using database.query() or [SELECT ... FROM X WHERE Y]) and getting a query locator as you're doing.
A query locator doesn't give you the results directly. Instead, it allows you to obtain an iterator which can be used to obtain the results.
Depending on the query, it could be possibble to view the results from the start() method, but it's much easier (and intended) for you to view the results from within the execute() method by using system.debug() on the scope variable (inside or outside of a loop).

A: You should use this.accountIdString instead of simply accountIdString in your constructor:

    global testbatch(String accountId) {
        this.accountIdString = accountId;
        System.debug('Here in the Batch class the account ID  == '+accountIdString);
    }


text:
Q: Apex Class Not Sending SingleEmailMessages To begin, I'd like to explain that the following class works in tandem with a process that detects incoming email messages to a case and then sends the ID of that email message to the class.
The class should then get the Email Ids and send out an email to every follower of that case.
This class and process are working together beautifully in our sandbox environment, but something is going very awry in our production environment, as we haven't received any emails to our test follower accounts.
Can anyone spot something(s) that might cause this discrepancy, or should I dive further into Salesforce configurations to find the answer?
global class CaseEmailFollowersNotify {
    @InvocableMethod(label='Case Email to Followers Notify' description='emails followers of new case email')
    global static void GetCaseCommentIds(List<Id> EmailIds) {
        for(emailmessage em : [SELECT Id, ParentId, FromAddress, TextBody FROM EmailMessage WHERE Id in: EmailIds]) {
            string tbody = em.TextBody;

            string tbody2 = tbody;

            if(tbody.length() > 60) {
                tbody2 = tbody.substring(0, 59);
            }

            tbody2 = tbody2 + '...';

            List<EntitySubscription> e = [select Id, ParentId, SubscriberId from EntitySubscription where ParentId =: em.ParentId];

            for(EntitySubscription es : e) {
                List<User> u = [select Email, Id from User where Id =: es.SubscriberId];
                Case ca = [select Subject, CaseNumber from Case where Id =: es.ParentId limit 1];
                for(User us : u) {

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setHTMLBody('blahbalhblah');
                mail.setTargetObjectId(us.Id);
                mail.setWhatId(es.ParentId);
                mail.setSubject('Case Following New Email');
                mail.setSenderDisplayName('Case Following Update');
                mail.saveAsActivity = false;

                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
          }
        }
        }
    }
}

Any help is sorely appreciated!  Please note that the string manipulation is entirely to do with our email formatting and only exists to edit down the incoming email's contents to something that can be sent back out and abbreviated.

A: On production:

*

*Check that the Process Builder is activated

*Look through the debug logs to see if any governor limits are being exceeded

In the meantime, here's a bulkified version of the code (it doesn't address ensuring that you don't exceed per-transaction sendEmail call limits - for that you need some async processing):
public class CaseEmailFollowersNotify {
    @InvocableMethod(Label='Case Email to Followers Notify' Description='emails followers of new case email')
    public static void getCaseCommentIds(List<Id> emailIds) {
        // Get all the email messages using the given email IDs
        List<EmailMessage> emailMessages = [
                SELECT Id, ParentId, FromAddress, TextBody
                        FROM EmailMessage
                        WHERE Id IN :emailIds
        ];

        // Collect all the IDs for the cases associated with the email messages
        Set<Id> caseIds = new Set<Id>();

        for (EmailMessage emailMessage : emailMessages) {
            caseIds.add(emailMessage.ParentId);
        }

        // Query all entity subscriptions for these cases
        List<EntitySubscription> entitySubscriptions = [
                SELECT Id, ParentId, SubscriberId
                        FROM EntitySubscription
                        WHERE ParentId IN :caseIds
        ];

        // Build up a structure holding entity subscriptions by Case ID whilst also collecting all
        // User IDs
        Map<Id, List<EntitySubscription>> entitySubscriptionsByCaseId = new Map<Id, List<EntitySubscription>>();
        Set<Id> userIds = new Set<Id>();

        for (EntitySubscription entitySubscription : entitySubscriptions) {
            List<EntitySubscription> entitySubscriptionsForCase = entitySubscriptionsByCaseId.get(entitySubscription.ParentId);

            if (entitySubscriptionsForCase != null) {
                entitySubscriptionsForCase.add(entitySubscription);
            } else {
                entitySubscriptionsByCaseId.put(entitySubscription.ParentId, new List<EntitySubscription> { entitySubscription });
            }

            userIds.add(entitySubscription.SubscriberId);
        }

        // Neither of these are actually used here, but I have them to
        // demonstrate how you would actually manage this data in case
        // you actually need these objects in your full code
        Map<Id, Case> casesById = new Map<Id, Case>([SELECT Subject, CaseNumber FROM Case WHERE Id IN :caseIds]);
        Map<Id, User> usersById = new Map<Id, User>([SELECT Email, Id FROM User WHERE Id IN :userIds]);

        // Now process the messages
        for (EmailMessage emailMessage : emailMessages) {
            String tbody = emailMessage.TextBody.left(60);

            if (tbody.size() != emailMessage.TextBody.size()) {
                tbody += '...';
            }

            // This code is likely to fail due to exceeding the maximum number of calls allowed to sendEmail
            // per transaction (see https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_apexgov.htm)
            // You likely need to handle this via async logic, breaking this down into smaller transactions
            for (EntitySubscription entitySubscription : entitySubscriptionsByCaseId.get(emailMessage.ParentId)) {
                // Neither of these variables are actually used, but are included to demonstrate how you would
                // deal with this data if you do need it in your complete code
                User user = usersById.get(entitySubscription.SubscriberId);
                Case case = casesById.get(emailMessage.ParentId);

                // Create and send the email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

                mail.setHtmlBody('blahbalhblah');
                mail.setTargetObjectId(entitySubscription.SubscriberId);
                mail.setWhatId(entitySubscription.ParentId);
                mail.setSubject('Case Following New Email');
                mail.setSenderDisplayName('Case Following Update');
                mail.saveAsActivity = false;

                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
    }
}

I've assumed you don't actually need to have global code since this invokable method isn't being exposed across a namespace boundary. I could be wrong in that assumption. However 99.999% of the time code posted in questions here doesn't need to be global.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting all children of collection with has_many relationship If I have a collection of Posts, is there anyway to get all Comments for all of those posts using method chaining or scopes?
For example:
posts = Post.where(published: true)
comments = posts.comments

# vs
comments = []
posts.each do |post|
  comments.push(post.comments)
end

A: Best way:
Comment.joins(:post).where(post: {published: true})

or if you have a posts variable that is a ActiveRecord Relation:
Comment.joins(:post).where(post: posts)

A: Sure, there are a few ways. You can can use map and flatten, which is fine for a small number of records. Make sure you load the comments in bulk by using includes.
Post.where(published: true).includes(:comments).map(&:comments).flatten

Or you can use a join. This puts more work on the database, which is likely faster, but depends on your schema and dataset. You will typically want to use uniq to prevent duplicates.
posts = Post.where(published: true)
Comment.joins(:post).merge(posts).uniq

Also, make sure that you fully qualify any explicit fragments in any clauses on joined tables, e.g. use where('posts.created_at < ?', ...) instead of where('created_at < ?', ...).
Edit:
Another variant on the first, in case you want to return a relation (which can be further scoped down the line):
Comment.where(id: Post.where(published: true).pluck(:id))


text:
Q: How classes are loaded by .Net? As some of us know the java classes are loaded by the ClassLoader. However, I don't know what .NET uses to load classes. What does it use? I've researched through Google, and still nothing.

A: In .NET assemblies are the fundamental unit of deployment. The technology that actually loads the assemblies is called Fusion. For more details on that read the .NET Fusion Workshop. Each assembly has its own class loader to load types from that assembly.
Hosting the Common Language Runtime may also be of interest.


text:
Q: aws_key_pair.auth: Error import KeyPair: InvalidKey.Format: Key is not in valid OpenSSH public key format terraform to create an EC2 instance and use a public key to login to EC2 instance is not working.
aws_key_pair.auth: Error import KeyPair: InvalidKey.Format: Key is not in valid OpenSSH public key format
this is part of the main.tf to create a keypair
    main.tf

    resource "aws_key_pair" "auth" {
      key_name   = "${var.key_name}"
      public_key = "${file(var.public_key_path)}"
    }

declaring the variable
    variable.tf

    variable "public_key_path" {
      description = <<DESCRIPTION
    Path to the SSH public key to be used for authentication.
    Ensure this keypair is added to your local SSH agent so provisioners can
    connect.
    Example: ~/.ssh/terraform.pub
    DESCRIPTION
      default = "~/.ssh/terraform.pub"
    }

placeholder for the keys
~/.ssh/terraform.pub
resource "aws_key_pair" "deployer" {
  key_name   = "newssh"
  public_key = "ssh-rsa
}

A: You need to add your SSH key to your ssh-agent
Ensure ssh-agent is enabled and running in the background
$ eval "$(ssh-agent -s)"

Add your SSH key to the ssh-agent. If you used an existing SSH key rather than generating a new SSH key, you'll need to replace id_rsa in the command with the name of your existing private key file.
$ ssh-add ~/.ssh/id_rsa

so in your case
$ ssh-add ~/.ssh/terraform

Then run terraform apply

A: I had the same issue and I was created with unsupported encryption.
Create an RSA key. Amazon EC2 does not accept DSA keys
You can have a look at this page: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html


text:
Q: Very Slow Download Speeds from Apple Applications (Safari and Mac App Store) After I restored my computer to a clean reinstall of El Capitan, I have experienced incredibly slow download speeds in Apple applications only (Safari and the App Store). I tested downloading a file in safari, and I got around 256 kilobytes per second, but when downloading the exact same file with the exact same internet connection, I got much greater download speeds of around 5 to 6 megabytes per second. The same thing is happening in the App Store, with download speeds averaging around 256 kilobytes per second.
I have tried changing the DNS to both Open DNS and Google Public DNS, and none of them seem to fix the problem.
Again, I am having extremely slow download speeds only in Apple applications. (Strangely enough, browsing speeds are still very fast. Only download speeds are slow.) This is a very strange problem and I have no idea what is causing them.
Please let me know how to fix this.

A: Seeing as others are mentioning this issue might be related to a specific ISP, try enabling a VPN and re-running the download.
This mightn't be a long-term solution, but it should help you identify if the issue is the ISP performing traffic shaping App Store packets.

A: I'm having the same issue. Must be on Apple's side. Their status page doesn't list anything, but I've tried a number of DNS/other fixes to no avail.

A: Are you all using Time Warner for your internet? - I have several clients with the exact same slow issue and they all are on TW. I have Charter and don't see this issue at all.


text:
Q: Transform XML node I've created the following XML node + childnodes via VBScript and I'm adding it to an existing XML document.
<list name="Info">
    <item name="ViewName">Page</item>
    <item name="DBField">Text</item>
    <item name="Type">String</item>
</list>

But in the XML document, the node is inserted in 1 single line:
<list name="Info"><item name="ViewName">Page</item><item name="DBField">Text</item><item name="Type">String</item></list>

I've done some research about XSLT but I can't figure out how to transform my node properly or create a proper template.

A: What you're looking for is called "pretty-printing". A possible solution for VBScript is described here by Robert McMurray. In a nutshell:
inFile  = "C:\path\to\input.xml"
outFile = "C:\path\to\output.xml"

Set fso = CreateObject("Scripting.FileSystemObject")
Set xml = CreateObject("Msxml2.DOMDocument")
Set xsl = CreateObject("Msxml2.DOMDocument")

' Put whitespace between tags. (Required for XSL transformation.)
txt = fso.OpenTextFile(inFile).ReadAll
txt = Replace(txt, "><", ">" & vbCrLf & "<")

' Create an XSL stylesheet for transformation.
stylesheet = _
  "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">" & _
  "<xsl:output method=""xml"" indent=""yes""/>" & _
  "<xsl:template match=""/"">" & _
  "<xsl:copy-of select="".""/>" & _
  "</xsl:template>" & _
  "</xsl:stylesheet>"

' Transform the XML.
xsl.loadXML stylesheet
xml.loadXML txt
xml.transformNode xsl
xml.save outFile


text:
Q: AWS SES send mail with credentials I'm trying to send email by AWS SES sesMail. But I need to set security credentials while sending email. I read documentation of SES for grails and it states that we need to set it as following,
mailId = sesMail {
 credentials "new_access_key", "new_security_key"
 to "email@gmail.com"
 subject "test plain text mail"
 body "this is the e-mail content"
}

But it doesn't work. There is no error. the mail id it returns is NULL. And no emails are sent. Anyone has solution how to do this?

A: I couldn't send the new credentials in a way above. So there is another method to do it.
def credentialsHolder = new AWSCredentialsHolder();
credentialsHolder.accessKey = bean?.accessKey
credentialsHolder.secretKey = bean?.secreteKey
def sender = new SendSesMail();
sender.credentialsHolder = credentialsHolder;
sender.region = bean?.region
mailId = sender.send {
                from fromEmail
                to toEmail
                subject "new subject"
                body "e-mail body (plain text)"
            }

Make sure you provide correct region else it gives error of 'Email id not verified'.


text:
Q: Automatically create SQL Server local databases in other projects I have 3 projects in a single solution that uses local SQL Server database file (.mdf) from one project. I have referenced the project that contains the SQL Server .mdf file from the other two projects. Also set to copy if newer for the .mdf file.
When the project runs all the 3 projects create their own .mdf files in App_Data folder. Is there way that I can use single local database? Also when the solution runs .mdf must be exist in the specified path as in copy if newer.


text:
Q: how to order rows by nearest value in joined table I have $my_average=2.5 and I would like to display 4 rows nearest this value.
I mean in this case row_id 12,13 and 15,16
f.e
row_id  srednia wydział uid
1       -100     *       12
...      ...     ...    ...
12       -10     *        1
13       -2      *      111
14       2.5     *      107
15       4.4     *      109
16       82      *       87
17       -3      *      114
...      ...    ...     ...
200      100     *      116

The problem is that my table is joined from other tables :( Is it possible that in this query I order column srednia to get nearest value to $my_average=2.5?
SELECT t1.średnia AS srednia, t2.field_5_value AS wydział, t4.uid
FROM preferencje t1
JOIN node t4 ON t1.entity_id = t4.nid
JOIN field_data_field_5 t2 ON t2.entity_id = t1.entity_id

A: I think this is what you want:
SELECT t1.średnia AS srednia, t2.field_5_value AS wydział, t4.uid
FROM preferencje t1 JOIN
     node t4
     ON t1.entity_id = t4.nid JOIN
     field_data_field_5 t2
     ON t2.entity_id = t1.entity_id
ORDER BY abs(srednia - 2.5)
LIMIT 4;

The only issue is the LIMIT 4.  This varies by database.  It could be TOP 4 in the SELECT clause.  Or FETCH FIRST 4 ROWS ONLY.  Or even something else.


text:
Q: How to set a separate billing and shipping address using PayPal PHP REST SDK? Trying to send a separate billing and shipping address when creating a payment using the REST api for paypal.
I can successfully create a shipping address:
$shipping_address = new ShippingAddress();
$shipping_address->setCity('XXXXXX');
$shipping_address->setCountryCode('XX');
$shipping_address->setPostalCode('111111');
$shipping_address->setLine1('9811 XXXXXX Lane');
$shipping_address->setLine2('Suite 100');
$shipping_address->setState('XXXXXX');
$shipping_address->setRecipientName('Mark XXXXXX');

$itemList = new ItemList();
$itemList->setShippingAddress($shipping_address);

When I do this it ALSO replicated this address to billing. But I cannot figure out how to send a SEPARATE address to pre-populate the billing information?
Any help would be appreciated.
Thanks in advance!

A: Looks like the BillingInfo class might provide what you need.
After creating the BillingInfo object, add it to the Invoice object.


text:
Q: Text box not in centered position for the slider As the continuation of my previous Question How to make the textbox above the slider.
The textbox needs to be displayed in the centre of both slider.
How can i do this ?
Here is the Jsfiddle that i have.
http://jsfiddle.net/Cv9DM/12/
css :
.view-fifth:hover img {
   -webkit-transform: translateX(300px);
   -moz-transform: translateX(300px);
   -o-transform: translateX(300px);
   -ms-transform: translateX(300px);
   transform: translateX(300px);
}

Note : Make the Result Tab little wide to make the two slider visible in Horizontal
The horizontalized screen is given below

Edit : Expected output :

A: Check this
Changed CSS for input
<input type='text' style="z-index:999;position: absolute; top: 50%; left: 50%; margin: -11px 0 0 -82px; width:160px; padding: 4px;">

added a div to wrap both the slides .outer
.outer {
    position: relative;
    height: 200px;
    float: left
}

A: Is this what you want?
Fiddle: fiddle

    <input type='text' style="z-index:999;position: absolute;
top: 70px;
left: 230px;">

Hover Style #5

A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart.

Read More

Hover Style #5

A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart.

Read More

A: if you need to input box vertically center you can use this property. see the DEMO.
input[type="text"]{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  z-index:1;
  position:fixed;
  left:18em;
 top:9em;
}

A: According to your edit, you need to use position:fixed instead of position:absolute.

<input type='text' />

DEMO

A: You can refer this one too
with use of jQuery

    <input type='text' class='textbox' style="z-index:999;position: absolute;"/>


text:
Q: Show that, there are no integers $(m, n)$ such that, $m^2 + (m + 1)^2 = n^4 + (n + 1)^4$ . Show that, there are no integers $(m, n)$ such that, $m^2 + (m + 1)^2 = n^4 + (n + 1)^4$ .
I really don't know how to approach this one i tried factorizing but it didn't seem to help , any hint would be appreciated .


text:
Q: RSpec/Capybara check not triggering onChange event I'm testing my JavaScript with RSpec and Capybara with Webkit driver.
After I check a checkbox, JS onChange event validates the form and  disables submit button untill I check second checkbox.
Here's my test:
it "disables submit button when wrong number of players", js: true do
  visit '/matches/new'
  check 'match_player_ids_1'
  expect(page).to have_button('Create Match', disabled: true)
end

I tried using sleep 2 after checking the checkbox, used binding.pry to check if the element is being checked (it is) but the submit button is still disabled.
Any ideas?  Can it be triggered manually?

A: You can manually do it with page.execute_script
page.execute_script("$('#match_player_ids_1').trigger('change')")


text:
Q: Future perfect in a time clause I've read the sentence "After I'll have finished eating my lunch by 2 p.m, I'll go to the supermarket" and I'm confused because the rules say we should always use a present tense in a time clause but "I'll have finished" is a future tense.

A: Your example is a mouthful of a sentence and not at all idiomatic.
We don't say: After I will have done something...
More likely in this context are:

After finishing (my) lunch (by 2 p.m.), I'll go to the supermarket.
and
After I have finished (my) lunch (by 2 p.m.), I'll go to the supermarket.

To use your construction, you would have to say something like:

I will have finished my lunch by 2 p.m., after which I'll go to the supermarket.


text:
Q: Import ambiguity for PermissionStatus in Flutter I have to dynamically check for location permission in my Flutter appliaction,
For that I am using below plugins:
permission_handler: ^10.2.0
location: ^4.4.0

Now, Its needed to check for the permission status i.e. granted, denied, restricted and allowed. So, for that I am declaring PermissionStatus as below:
PermissionStatus locationPermissionStatus = PermissionStatus.denied;

But due to below two imports one is for location and one is for permission,
import 'package:location/location.dart';
import 'package:permission_handler/permission_handler.dart';

It saying me on PermissionStatus declaration:

The name 'PermissionStatus' is defined in the libraries 'package:location_platform_interface/location_platform_interface.dart (via package:location/location.dart)' and 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart (via package:permission_handler/permission_handler.dart)'. (Documentation)  Try using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.

How can I resolve this ambiguity of imported data from two different plugins?

A: use for import both packages.
import 'package:location/location.dart' as location;
import 'package:permission_handler/permission_handler.dart';

for use location Permission.
location.PermissionStatus locationPermissionStatus = location.PermissionStatus.denied;

I Hope this will solve your issue.


text:
Q: PageAsyncTask Timeout - How to stop execution of async code I'm trying to implement Async calls in a classic ASP.NET web page.
I'm following the instructions I've found here and I can get it to call asynchronously but I don't know how to cancel the execution of the async method when the request times out (which I can easily do by pausing execution of my code at a breakpoint).
My code so far is as follows:
  protected void Button_Click(object sender, EventArgs e)
    {
        PageAsyncTask task = new PageAsyncTask(OnBegin, OnEnd, OnTimeout, null);
        Page.RegisterAsyncTask(task);
        Page.AsyncTimeout = new TimeSpan(0, 0, 10);
        Page.ExecuteRegisteredAsyncTasks();
    }

    protected delegate void AsyncTaskDelegate();
    private AsyncTaskDelegate _dlgt;

    public IAsyncResult OnBegin(object sender, EventArgs e, AsyncCallback cb, object extraData)
    {
        _dlgt = new AsyncTaskDelegate(ExecuteAsyncTask);

        IAsyncResult result = _dlgt.BeginInvoke(cb, extraData);
        return result;
    }

    public void OnEnd(IAsyncResult ar)
    {
        _dlgt.EndInvoke(ar);
    }

    private void ExecuteAsyncTask()
    {
        MyObject obj = new MyObject();
        var task = obj.CompleteAsync();
        if (obj.Complete())
        {
            LabelResult.Text = "Success";
        }
        else
        {
            LabelResult.Text = "Failed";
        }
    }

    public void OnTimeout(IAsyncResult ar)
    {
        _dlgt.EndInvoke(ar);//this does not work!
    }

The main issue I have is that the code can "hang" at a certain point in the async method as I am calling an outside service and it can stop responding under certain situations.
Even if I try to EndInvoke the request the async code still runs.
Any help would be appreciated.

A: OK so I I've worked it out. It has to do with cancellation tokens.

*

*First I created a CancellationTokenSource:

private System.Threading.CancellationTokenSource tokenSource = new System.Threading.CancellationTokenSource();

*Then I pass this into a Task factory to start the async task:

var task = System.Threading.Tasks.Task.Factory.StartNew(() => myObject.AsyncMethod(Request.QueryString, tokenSource.Token), tokenSource.Token);

*And finally when the timeout occurs I simple do this:
public void OnTimeout(IAsyncResult ar)
 {
    tokenSource.Cancel();
    tokenSource.Token.ThrowIfCancellationRequested();
 }
Voilà!
This causes an exception which you then need to catch but at least this stops execution of any code.


text:
Q: titleformat - I want to separate the chapter number and title and put them on the right, one above the other Right now I'm using the default chapter formattings on Overleaf but I want to change it so that the chapter number is much larger than the title and is above and separate from the title itself.
At the moment I have the title (but not the number) aligned correctly but I can't seem to change the font or increase the size beyond what it's currently at.
current MWE, mostly the same as the titlesec template on Overleaf:
\documentclass[a4paper,12pt]{book}
\usepackage[T1]{fontenc}
\usepackage{titlesec}

\titleformat
{\chapter} % command
[display] % shape
{\bfseries\Large\itshape} % format
%{Story No. \ \thechapter} % label
{\thechapter}
{0.5ex} % sep
{
    %\rule{\textwidth}{1pt}
    \vspace{1ex}
    %\centering
    \raggedleft
} % before-code
[
\vspace{-0.5ex}%
%\rule{\textwidth}{0.3pt}
] % after-code

\titleformat{\section}[wrap]
{\normalfont\bfseries}
{\thesection.}{0.5em}{}

\titlespacing{\section}{12pc}{1.5ex plus .1ex minus .2ex}{1pc}

\begin{document}
\chapter{Let's begin}
\section{First Attempt}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris...

\end{document}

I want it to look like this

A: Get a try (and change colors and dimensiond as you like):
\documentclass[10pt,a4paper]{book}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[italian]{babel}
\usepackage{amsmath}
\usepackage{amsfonts,lmodern}
\usepackage{amssymb}
\usepackage{emptypage,graphicx}
\usepackage{xcolor}
\usepackage{titlesec}
\usepackage{microtype,lipsum}

\titleformat{\chapter}[display]
{\normalfont\bfseries\color{black}}
{\filleft\hspace*{-60pt}%
    {\setlength\fboxsep{0pt}%
        \colorbox{blue!10}{\parbox[c][3cm][c]{3cm}{%
                \centering\color{cyan}\fontsize{80}{70}\selectfont\thechapter}%
    }}%
}
{10pt}
{\filleft\LARGE\sffamily}

\begin{document}

    \tableofcontents
    \chapter{Trip in a new world}
    \lipsum[1-2]
    \section{One}
    \lipsum[3-12]
    \setcounter{chapter}{22}
    \chapter{The fantastic way of life in the new world}
    \lipsum[1-2]
    \section{Two}
    \lipsum[3-12]
\end{document}

A: \documentclass[12pt,a4paper]{report}
\usepackage[utf8]{inputenc}
\usepackage{geometry}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amsfonts,lmodern}
\usepackage{amssymb}
\usepackage{emptypage,graphicx}
\usepackage{xcolor}
\usepackage{titlesec}
\usepackage{microtype,lipsum}
\titleformat{\chapter}[display]
{\LARGE\bfseries\sffamily}
{\filleft\hspace*{-60pt}{\Huge\colorbox{white}{\parbox[c][3cm][c]{3cm}{\color{orange}\fontsize{3cm}{1cm}\selectfont\centering\thechapter}}}}
{10pt}{\LARGE\filleft}

\begin{document}
    \chapter{Trip in a new world}
\end{document}

A: It's simpler than other answer seem to imply.
\documentclass[a4paper,12pt]{book}
\usepackage[T1]{fontenc}
\usepackage{fix-cm}
\usepackage{titlesec}
\usepackage{xcolor}

\definecolor{chapternumber}{RGB}{239,107,28}
\newcommand{\makebignumber}[1]{%
  \textcolor{chapternumber}{\fontsize{80}{0}\bfseries #1}%
}

\titleformat{\chapter}[display]
  {\filleft} % format
  {\makebignumber{\thechapter}}
  {2ex}
  {\Large}

\titleformat{\section}[wrap]
  {\normalfont\bfseries}
  {\thesection.}
  {0.5em}
  {}

\titlespacing{\section}{12pc}{1.5ex plus .1ex minus .2ex}{1pc}

\begin{document}
\chapter{Let's begin}
\section{First Attempt}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris...

\end{document}

You don't need fix-cm if you use a fully scalable font like in the image.


text:
Q: How to use an external non vue script in vue I try to use an external script (https://libs.crefopay.de/3.0/secure-fields.js) which is not vue based
I added the script via -tags into index.html
But when I try to intsanciate an object, like in the excample of the script publisher.
let secureFieldsClientInstance =
      new SecureFieldsClient('xxxxx',
        this.custNo,
        this.paymentRegisteredCallback,
        this.initializationCompleteCallback,
        configuration)

Vue says "'SecureFieldsClient' is not defined"
If I use this.
let secureFieldsClientInstance =
          new this.SecureFieldsClient('xxxxx',
            this.custNo,
            this.paymentRegisteredCallback,
            this.initializationCompleteCallback,
            configuration)
        secureFieldsClientInstance.registerPayment()

Vue says: Error in v-on handler: "TypeError: this.SecureFieldsClient is not a constructor"
My Code:
methods: {
startPayment () {
  this.state = null
  if (!this.selected) {
    this.state = false
    this.msg = 'Bitte Zahlungsweise auswählen.'
  } else {
    localStorage.payment = this.selected
    let configuration = {
      url: 'https://sandbox.crefopay.de/secureFields/',
      placeholders: {
      }
    }
    let secureFieldsClientInstance =
      new SecureFieldsClient('xxxxx',
        this.custNo,
        this.paymentRegisteredCallback,
        this.initializationCompleteCallback,
        configuration)
    secureFieldsClientInstance.registerPayment()
    // this.$router.replace({ name: 'payment' })
  }
}
}

Where is my mistake?
EDIT:
Updated the hole question

A: Here is a minimal Vue app for the context your provided, which works:
https://codepen.io/krukid/pen/voxqPj
Without additional details it's hard to say what your specific problem is, but most probably the library gets loaded after your method executes, so window.SecureFieldsClient is expectedly not yet defined. Or, there is some runtime error that crashes your script and prevents your method from executing. There could be some other more exotic issues, but lacking a broader context I can only speculate.
To ensure your library loads before running any code from it, you should attach an onload listener to your external script:
mounted () {
  let crefPayApi = document.createElement('script')
  crefPayApi.onload = () => this.startPayment()
  crefPayApi.setAttribute('src', 'https://libs.crefopay.de/3.0/secure-fields.js')
  document.head.appendChild(crefPayApi)
},

A: I found the solution.
the import was never the problem.
I had just to ignore VUEs/eslints complaining about the missing "this" via // eslint-disable-next-line and it works.
So external fuctions/opbjects should be called without "this" it seems.
let secureFieldsClientInstance =
      new SecureFieldsClient('xxxxx',
        this.custNo,
        this.paymentRegisteredCallback,
        this.initializationCompleteCallback,
        configuration)

A: You could download the script and then use the import directive to load the script via webpack. You probably have something like import Vue from 'vue'; in your project. This just imports vue from your node modules.
It's the exact same thing for other external scripts, just use a relative path. When using Vue-CLI, you can do import i18n from './i18n';, where the src folder would contain a i18n.js
If you really want to use a CDN, you can add it like you normally would and then add it to the externals: https://webpack.js.org/configuration/externals/#externals to make it accessible from within webpack


text: Q: How to get id's of all the birthday posts in facebook through graph api I am trying to get id's of all the posts of birthday wishes on my timeline. When I am using graph api and sending request for me/feed all birthday posts are not showing instead there is only one node that has a story xyz and 205 others wrote on your timeline . If I take id of this node and send request it is only the post of the last person xyz in this case. How can I expand all the 206 posts to get their id's ?


text:
Q: How do I enumerate() over a list of tuples in Python? I've got some code like this:
letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
    i += 1

I've been told that there's an enumerate() function that can take care of the "i" variable for me:
for i, l in enumerate(['a', 'b', 'c']):
    print "%d: %s" % (i, l)

However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this?
letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
    (lowercase, uppercase) = tuple
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)

Or is there a more elegant way?

A: This is how I'd do it:
import itertools

letters = [('a', 'A'), ('b', 'B')]
for i, lower, upper in zip(itertools.count(),*zip(*letters)):
    print "Letter #%d is %s/%s" % (i, lower, upper)

EDIT: unpacking becomes redundant. This is a more compact way, which might work or not depending on your use case:
import itertools

letters = [('a', 'A'), ('b', 'B')]
for i in zip(itertools.count(),*zip(*letters)):
    print "Letter #%d is %s/%s" % i

A: This is a neat way to do it:
letters = [('a', 'A'), ('b', 'B')]
for i, (lowercase, uppercase) in enumerate(letters):
    print "Letter #%d is %s/%s" % (i, lowercase, uppercase)

A: You can do this way too:
letters = [('a', 'A'), ('b', 'B')]
for i, letter in enumerate(letters):
    print "Letter #%d is %s/%s" % (i, letter[0], letter[1])

A: You could also write a generator:
def enumerate_nested(nested_collection, start=0):

    for index, row in enumerate(nested_collection, start):
        yield index, *row

Which then allows you to iterate over the collection of tuple (or list) and to unpack the values:
names = [["Heinz", "Steiner"], ["Fred", "Glauser"], ["Nicole", "Hauser"]]

for index, first_name, last_name in enumerate_nested(names, 1):
    print(index, first_name, last_name)

However, there is a simpler built-in solution to achieve this. Have a look at Richie Hindle's answer:
names = [["Heinz", "Steiner"], ["Fred", "Glauser"], ["Nicole", "Hauser"]]

for index, (first_name, last_name) in enumerate(names, 1):
    print(index, first_name, last_name)


text:
Q: How do I write a regular expression to find all not commented out System.out In this project of ours the previous developers had coded throughout System.out even though told to only use the log.[debug,error etc.].
Been trying to write a RE to find all of the System.out that are not commented out but not having much luck. I did find here in the forumns information on negative lookbehind which sounds like what I need but I'm either getting all System.out including the commented ones or nothing at all in my efforts.
Appreciate any guidance on this. Here it the last regular expression I tried ((?<!\\)(?<!\s*))system.out

A: ^ and $ match the beginning and the end of the line in Java. Also \ has to be escaped in Java Strings.
This is not perfect, but gives an idea, it tries to find System.out at the beginning of a line and then matches everything until ; over multiple lines if necessary:
Pattern pattern = Pattern.compile("^[ \\t]*System\\.out[^;]+");
// or "^[ \\t]*System\\.out\\.print(?:ln)?\\(.*?\\);"

Matcher matcher = pattern.matcher(...);
while (matcher.find()) {
  System.out.println(matcher.group());
}


text:
Q: In consistent global states, what is the difference between a run and a consistent run? I am referring to global states in a distributed system as published in the paper Consistent Global States of Distributed Systems: Fundamental Concepts and Mechanisms by Ozalp Babao and Keith Marzullo (pdf).
On page 7, they define a run as follows:

A run of a distributed computation is total ordering that includes all
  of the events in the global history and that is consistent with each
  local history.

Then on page 11, they define a consistent run as follows:

A run R is said to be consistent if for all events, e happens before e' implies that e appears
  before e' in R. In other words, the total order imposed by R on the events
  is an extension of the partial order defined by causal precedence.

So far so good but then they go on to say in the following sentences there can be be two consistent global states A and B and they define some sort of leads-to operator which says A leads to B if there exists some consistent run in which this holds.
My question is, how can there be multiple runs? Won't there be a unique run (a totally ordered relation of events based on some tie breaker for concurrent events) for every system setup? How can there be multiple runs (other than the ones induced by different concurrent event tie breakers)?


text:
Q: Use a variable returned by Get-Variable Hopefully this answer isn't above me. I've created a custom object with properties and methods.  I create several of them on the fly, depending on what the user selects at the beginning.
So for this example, the script might create $PRD1, $PRD2, $TST1 and $TST4.
$PRD1, $PRD2, $TST1 and $TST4 will have some properties like DebugMode, DisableAppsStartTime, DisableAppsStopTime.  They'll have some methods like DisableApps(), EnableApps().
How can I find out which variables the script ended up creating?  I can use Get-Variable to know the ones it created (plus I DO still have the initial list of names to create).  My issue is that I'm having trouble figuring out to call the ones I've created, in a manner that allows me to use the methods and properties, without a ridiculous mash up of nested foreach/if/switch commands.
I certainly hope that made sense.
Thanks in advance,
SS

A:
I DO still have the initial list of names to create

Assuming that $list contains this list, the following creates an (ordered) hash table of those variables that were actually created from that list:
$variableMap = [ordered] @{}
(Get-Variable -ErrorAction Ignore -Scope Local $list).
  ForEach({ $variableMap[$_.Name] = $_.Value })

Note: -Scope Local limits the lookup to the current scope[1]; omit it to target all variables visible in the current scope, which includes those from ancestral (parent) scopes.
You can then loop over $variableMap.Keys to process them all, or access one by name selectively, e.g., $variableMap.PRD1 (or $variableMap['PRD1']).
You then use regular dot notation to access properties and methods of these entries; e.g., $variableMap.PRD1.DisableApps().

[1] This includes variables created with the AllScope option, e.g., $HOME, because they are copied to every scope, as the name suggests. You can find all such variables with
Get-Variable | Where-Object Options -match 'AllScope'

A: I just did this with the where-object cmdlet and the -like operator with an foreach loop.
foreach($var in (get-variable | Where-object {$_.name -like '*PRD*' -or $_.name -like '*TST*'})){
    $var
}


text:
Q: Regex code for validating credit card in JavaScript I'm looking for regex code for validate credit card in JavaScript. For example if i type first number 4 then its innerhtml print VISA
"use strict"
function $(x) { return document.querySelector(x) };

$("input").addEventListener("input", function () {

    var x = this.value;
    var patt=/\s*(\d(?:\s*)){16}\s*/

    if( patt.test(x)){

        this.nextElementSibling.innerHTML="Match"
    }
    else{
        this.nextElementSibling.innerHTML="no Match"
    }

});


text:
Q: Failed to get data from localhost using php in android Im new at Android. I'm trying to fetch some data from localhost server. My query is running perfectly on phpMyAdmin But I facing error in api. I have very little knowledge about Php so did not get what the issue is.
Code:
public function saveUserProgress($user_id,$course_id,$topic_id,$quiz_marks){

        $output = $this->con->prepare("INSERT INTO user_progress (user_id, course_id, topic_id,quiz_marks)
        VALUES (?, ?, ?,?)
        ON DUPLICATE KEY UPDATE
            user_id=?, course_id=?, topic_id=?, quiz_marks = quiz_marks + ?");

        $output->bind_param("iiii",$user_id,$course_id,$topic_id,$quiz_marks);

        if($output->execute()){
            return  PROGRESS_SAVED;
        }else{
            return ERROR_OCCUR;
        }
    }

Error:
{"error":true,"message":403}
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement

A: If as you said your unique key is user_id and course_id then you do not need to update them on duplicate key. You only need to update the remaining 2 values. Together with the 4 you wanted to add it makes 6 placeholders, so you need to bind 6 variables.
$output = $this->con->prepare("INSERT INTO user_progress (user_id, course_id, topic_id,quiz_marks)
    VALUES (?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE
        topic_id=?, quiz_marks = quiz_marks + ?");

$output->bind_param("iiiiii", $user_id, $course_id, $topic_id, $quiz_marks, $topic_id, $quiz_marks);


text:
Q: Arrays - Output has to be the months of the year Hi  I am trying to learn about arrays and our teacher gave us an extra assignment which says: "Create an array with every month of the year(January, February...). My code looks like this:
package array2;

public class Array2 {

    static String months[];
    public static void main(String[] args) {
       months = new String[13];
       months[0] = null ;
       months[1] = "January";
       months[2] = "February";
       months[3] = "March";
       months[4] = "April";
       months[5] = "May";
       months[6] = "June";
       months[7] = "July";
       months[8] = "August";
       months[9] = "September";
       months[10] = "October";
       months[11] = "November";
       months[12] = "December";
       int m = Integer.parseInt( args[0] );
       System.out.println( months[ m ] );
    }
}

But I am getting the error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at array2.Array2.main(Array2.java:33)
/Users/Mo/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

Can someone help clarify this?

A: The error is at three places:

*

*In your program. You need to make sure that args is not an empty array (make sure that the user has indeed provided at least 1 arg).

*In the way your invoke your program. You are most likely not passing any arguments. If you are running your program from command line, you can do it the following way:
java array2.Array2 5
Should print "May".

*Make sure the parsed int from the argument is within range.
if(args.length == 0) {
    System.out.println("Error, must specify one argument");
}
else {
    int m = Integer.parseInt( args[0] );
    if(m<0 || m> 12) {
        System.out.println("Invalid month specified");
    }
    else {
        System.out.println( months[ m ] );
    }
}

A: Pass arguments
As the other Answers state, you likely are failing to pass an argument when running this problem.
If using an IDE such as NetBeans, IntelliJ, or Eclipse, you must dig around to find where that tool lets you specify arguments to be passed to the main method.
For example, in NetBeans:

*

*Open your project properties.

*Select Run.

*In the Arguments field, type a month number such as 7.

*Click OK to save the change.

*Run your project.

Test arguments
For debugging, you should dump the array of arguments to the console to verify. And you should be testing for expected number of arguments. Here is example code doing both those tasks.
public class App {

    public static String months[];

    public static void main ( String[] args ) {

        months = new String[ 13 ];
        months[ 0 ] = null;
        months[ 1 ] = "January";
        months[ 2 ] = "February";
        months[ 3 ] = "March";
        months[ 4 ] = "April";
        months[ 5 ] = "May";
        months[ 6 ] = "June";
        months[ 7 ] = "July";
        months[ 8 ] = "August";
        months[ 9 ] = "September";
        months[ 10 ] = "October";
        months[ 11 ] = "November";
        months[ 12 ] = "December";

        System.out.println ( "DEBUG args: " + Arrays.toString ( args ) );
        if ( args.length == 0 ) {
            System.out.println ( "No month specified. No arguments passed to 'main' method." );
        } else if ( args.length == 1 ) {  // Else we have a single argument as expected.
            int m = Integer.parseInt ( args[ 0 ] );
            System.out.println ( months[ m ] );
        } else if ( args.length > 1 ) {  // Else we have multiple arguments, but expected only one.
            System.out.println ( "ERROR - more than one argument passed to 'main' method." );
        } else {  // Else impossible. Should not reach this point. Defensive programming.
            System.out.println ( "ERROR - Unexpectedly reached IF-ELSE. Should be impossible." );
        }
…

DEBUG args: [8, 7, 9]
ERROR - more than one argument passed to 'main' method.

You can see this code run live at IdeOne.com. Unfortunately, that web app seems to have a bug: failing to pass the input arguments. So not useful at the moment for our purpose here, but I leave the link in case the bug is fixed in the future.
java.time
While I understand you are doing exercises to learn Java programming, you should be aware that you would not need to do this definition of months in real-world work. Instead you would use the Month enum, part of the java.time classe. An enum is a grouping of static constants. Enums in Java are vastly more powerful, flexible, and useful than conventional enums.
Month month = Month.of ( 5 ); // Months are numbered 1-12 for January-December. So 5 = May.
String output = month.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );  // Automatically localize the name of the month.
String output2 = Month.DECEMBER.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );  // Refer to a `Month` object by the name of a constant. Here: Month.DECEMBER

Dump to console.
System.out.println ( "month.toString(): " + month );
System.out.println ( "output: " + output );
System.out.println ( "output2: " + output2 );

month.toString(): MAY
output: mai
output2: décembre

A: Your code is right.
Make sure that you ran it with arguments.
If you are running from Eclipse:
1. Run Configuration
2. Arguments Tab
3. Enter the number in Program Arguments.

A: I see that you are using Netbeans, so Go to your Run Configurations-> Arguments, in the Program arguments add for example "10 5 3 14", and then you need to avoid indexOutOfBoundExcepion:
   int m = Integer.parseInt( args[0] );
   if(m>=0&&m<13)
   System.out.println( months[ m ] );


text:
Q: How can I solve this path error in project 'not a valid python path' Hi guys I tried recently to create a new django project. So I run 'pipenv install django'. And this was the error I had.
  File "C:\Users\KONLAN\AppData\Local\Programs\Python\Python310\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 379, in __getattribute__
    instance_dict = self.parse_executable(executable)
  File "C:\Users\KONLAN\AppData\Local\Programs\Python\Python310\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 624, in parse_executable
    raise ValueError("Not a valid python path: %r" % path)
ValueError: Not a valid python path: 'C:/Users/KONLAN/Downloads/Anaconda/python.exe'

HOW CAN I SOLVE THIS?

A: you can use package manager pip:
pip install django

or
pip3 install django

A: Similar problems have been solved in GitHub, and solutions have also been given:
Search for Python351 in regedit (win+r , regedit) and delete the entries.


text:
Q: Laravel Query behave differently on IPv4 Vs. IPv6 Environment I have a weird situation here that I never seen before while using Laravel.
I have the same code base on different set up, 1 in IPv4 VM, 1 in IPv6 VM.
This is the data in the database.

This is how I normally query it.
// $ap = '102030405067';
$gw = Gateway::where('cpe_mac','=',$ap)->first();
dd($gw);

In my IPv4 Set up, I got :
{#541 ▼
  +"id": 1
  +"account_id": "50"
  +"cpe_mac": "102030405067"
  +"gw_id": "1956692524588882"
  +"gw_secret": "zUIyaQfCntob2thL6uR4uQfBvmlCei-5q_oVSJnyeSc"
  +"fb_wifi_enable": "1"
  +"created_at": "2017-10-10 14:41:17"
  +"updated_at": "2017-10-10 14:41:17"
}

In my IPv6 Set up, I got :
null

Try #2
dd(Gateway::all());.
Result
In IPv4, I got all the records returned.

In IPv6, I got this empty collection
Collection {#542 \u25bc
  #items: []
}

The most confusing part is, other tables seems to work fine, this gateways seems to be the only one that causing the problem.
I triple checked my Gateway model name, and table name. They spelled correclty.

*

*Have you guys seen something like this before ?

*How would one go about and debug this issue further ?

*What else should I try ?

A: To be honest - I don't think it's possible.
Make sure that in both cases $ap contains exact same value.  You can use trim($ap) just in case to be double-sure it doesn't contain extra special characters.
Also make sure on both VMs you have same data in database. Now it seems in one VM you have data in database and in second you don't.
EDIT
It's not possible there is direct problem in Laravel, so:

*

*make sure in both VMs you have data in your databases - on both VMs run SELECT * FROM gateways to verify on both you have any records (you haven't mentioned that both VMs are using same database so I assume they are different)

*make sure in both VMs you have valid database set in your .env file

*on both VMS run php artisan config:clear just to make sure you don't have cached invalid database connection

A: What is an IP address ? What are IPv6, IPv4 protocols, what is difference between them?
What is an IP address?
IP (internet protocol) is the protocol by which is sent data from one computer to another device on the internet. Each computer on the internet has different IP address identify it from all other computers on the internet. An IP address is a numeric address and identifier for a computer or device on a network. Every device has and has an IP address for communication purposes.
Internet protocol version 4 (IPv4)
Internet protocol version 4 (IPv4) is the fourth version of the internet protocol (IP). This protocol most used today in data communications over different kinds of the network because it supports all devices.IPv4 invented in 1970.
Internet protocol version 6 (IPv6)
Internet protocol version 6 (IPv6) It is the most recent update version protocol of the internet. That provides an identification and location system for computers and routes traffic across the internet. IPv6 invented in 1998.
DIFFERENCE BETWEEN IPv4 VS IPv6
IPv4
1.IPv4 is a 32-bit address.
2.IPv4 is the numbering address method.
IPv6
1.IPv6 IS 128-bit address.
2.IPv6 is the alphanumeric address method.
For more information click here


text:
Q: Ionic osmtogeojson module I am using this module osmtogeojson inside my home.ts file
import osmtogeojson from 'osmtogeojson';
I linked my project ionic link --pro-id project_id.
Pushed the code git push ionic master.
However, Build failed:

ionic-app-scripts build

[20:40:08]  ionic-app-scripts 3.1.9
[20:40:08]  build dev started ...
[20:40:08]  clean started ...
[20:40:08]  clean finished in 2 ms
[20:40:08]  copy started ...
[20:40:08]  deeplinks started ...
[20:40:08]  deeplinks finished in 65 ms
[20:40:08]  transpile started ...
[20:40:20]  typescript: node_modules/osmtogeojson/index.d.ts, line: 1
            Cannot find module 'geojson'.

       L1:  import { FeatureCollection, Feature, GeometryObject } from 'geojson';

[20:40:20]  ionic-app-script task: "build"
[20:40:20]  Error: Failed to transpile program
Error: Failed to transpile program
    at new BuildError (/usr/src/app/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at /usr/src/app/node_modules/@ionic/app-scripts/dist/transpile.js:159:20
    at new Promise ()
    at transpileWorker (/usr/src/app/node_modules/@ionic/app-scripts/dist/transpile.js:107:12)
    at Object.transpile (/usr/src/app/node_modules/@ionic/app-scripts/dist/transpile.js:64:12)
    at /usr/src/app/node_modules/@ionic/app-scripts/dist/build.js:109:82
    at
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! urbanRefuge@0.0.1 build: `ionic-app-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the urbanRefuge@0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/gitlab-runner/.npm/_logs/2018-05-19T20_40_20_995Z-debug.log
npm run build failed
Running after script...
$ run "clean-up"
Running Stage clean-up for Job: 5565766
ERROR: Job failed: exit status 1

A: Just run npm i geojson and your issue will be resolved


text:
Q: Optimal ways to read data from excel and save in sql server DB c# What is the optimal way to read data from excel and update in sql server DB.
Column name in excel is different from column name in DB.
am currently using Oledb drivers to read data from excel and ef 5.0 for db operations.
is there a better way of doing it?
excel contains close to 100 thousands rows

A: There are many libraries available to read excel data like SpreadsheetGear, NPOI, OLE DB, etc.
You can choose any.  I prefer OLE DB, you can interact with excel data in similar way you interact with database.
To store the excel data to database you can use SqlBulkCopy class.
You can store the data read from excel file in System.Data.DataTable and then use WriteToServer(DataTable) method.
Or if you have large excel file you can implement IDataReader interface and use method WriteToServer(IDataReader).
The WriteToServer(IDataReader) is optimal in case of memory utilization.


text: Q: Is there any "standards" for minimum variance of likert-type measured variables? I want to develop a questionnaire. Because the target population are children, I used 3-point likert-type scale (0 1 2) for my items. Now I want to remove invariant items (i.e. the items not having enough variance). Are there any standards for determining minimum variance value according to different likert-type scales? The issue could also be viewed from a frequency point of view. Is there any specific portion of people (e.g. 80% of them) that if they respond to an item identically (e.g. all responded 0) the item should be regarded as invariant?


text:
Q: MySql exception while doing several requests after one another I have a aspnetcore webservice which does several requests after one another. I get an exception at different times. the Error message is:

MySql.Data.MySqlClient.MySqlException: error connecting: Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at bdtFood.Controllers.FoodController.Get(Int32 id, Int32 idMeeting)
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__28.MoveNext()

How can i pervent this exception. There shouldn't be more than one request at the same time.
EDIT: code for a request.
while (cn.State == System.Data.ConnectionState.Open)
        {

        }
        cn.Close();
        cn.Open();
        Modells.Room room = new Modells.Room(-2, "dummy");
        MySqlCommand myCommand = new MySqlCommand("SELECT * FROM room WHERE idRoom = @idRoom", cn);
        myCommand.Parameters.Add("@idRoom", MySqlDbType.Int32, 11).Value = idRoom;
        using (reader = myCommand.ExecuteReader())
        {
            while (reader.Read())
            {
                room = new Modells.Room(reader.GetInt32(0), reader[1].ToString());
            }
        }

A: You need to use using around all Commands and Controllers.
See https://stackoverflow.com/a/1808056/34092 for more details.


text:
Q: How to parse numbers from an array in codes like this? I need to parse numbers from codes like this:
p1 <- c(1, 2, 100, 23, 0.12, 0.03, 0)
p2 <- c(100, 200, 1, 23, 0.12, 0.03, 0)
p30 <- c(100, 200, 1, 23, 0.12, 0.03, 0)
p300 <- c(100, 200, 1, 23, 2, 1, 0)
more variables starts with p...
other codes...

The results are like this:
1 2 100 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 2 1 0

in which each row represent an array of a variable.
I tried sed and awk, but doesn't work out it. Does anyone have ideas about this? Thanks!

A: awk one-liner:
kent$  awk -F'[()]' '{gsub(/, */," ",$2)}$0=$2' file
1 2 100 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 2 1 0

A: Using GNU sed (for -r and EREs):
$ cat file
p1 <- c(1, 2, 100, 23, 0.12, 0.03, 0)
p2 <- c(100, 200, 1, 23, 0.12, 0.03, 0)
p30 <- c(100, 200, 1, 23, 0.12, 0.03, 0)
p300 <- c(100, 200, 1, 23, 2, 1, 0)

$ sed -r 's/.*\(|[,)]//g' file
1 2 100 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 2 1 0

A: With awk and tr for readability ;-)
awk -F'[()]' '{print $2}' file | tr -d ','

A: Assuming you have it in file t.txt:
$ grep ^p t.txt|sed 's/.*[(]//; s/[)].*//; s/,//g'

1 2 100 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 2 1 0

A: You can do it in bash without calling external programmes. A bash one-liner :
#!/usr/bin/bash

while read v; do v=${v#*(}; v=${v%)*}; echo ${v//, / }; done<<XXX
p1 <- c(1, 2, 100, 23, 0.12, 0.03, 0)
p2 <- c(100, 200, 1, 23, 0.12, 0.03, 0)
p30 <- c(100, 200, 1, 23, 0.12, 0.03, 0)
p300 <- c(100, 200, 1, 23, 2, 1, 0)
XXX

Output:
1 2 100 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 0.12 0.03 0
100 200 1 23 2 1 0


text: Q: Is it possible in Oracle APEX to export a table to a file using Automation I want to export a table in an Oracle APEX application automatically on a weekly basis to a file. Is there a way to do this without using SQL developer?


text:
Q: HardHat with gas-report reports not understandable I'm using HardHat with gas-report but I'm not able to understand the following results:

*

*Optimizer enabled: false

*Runs: 200

*Block limit: 30000000 gas

*% of limit
Here I have marked with red square the fields:
enter image description here

A: Optimizer (whether it's enabled or disabled) and the target amount of contract runs, to which the optimizer should optimize the contract bytecode, are options of the Solidity compiler. When you compile the contract with an optimizer, it can decrease either the total bytecode size - or the amount of gas needed to execute some functions. (docs)
Block limit states the amount of gas units that can fit into one block. Different networks might have different values, some have dynamically adjusted limits, plus you can usually set your own limit if you're using an emulator or a private network. (docs)
% of limit states a portion of how much your contract deployment took in the total block limit. Example from your table: Deployment of HashContract cost 611k gas units, which is approx. 2% of the 30M block limit. If the number exceeds 100%, the transaction would never be included in a block - at least not in a block with the same or smaller limit. Also, if the transaction has a low gasPrice and a high % of the total block limit, some miners/validators might not be able to fit the transaction into a block (as transactions are usually ordered from highest gasPrice to lowest), so it might take longer to be included in a block.


text:
Q: How can I calculate this (rather tricky) limit? $$\lim\limits_{n \to \infty} \cos^{n^2} \left (\frac{2x}{n} \right)$$
Any hints and/or help is greatly appreciated.

A: When $n$ is large enough, $\frac {2x}n$ will be small, so $\cos\left(\frac{2x}n\right)$ will be very close to $1-\frac{2x^2}{n^2}$

A: Consider $$a_n=\cos^{n^2} \left (\frac{2x}{n} \right)\implies \log(a_n)=n^2\log\left( \cos\left (\frac{2x}{n} \right)\right)$$ Now use the series expansion
$$\cos\left (\frac{2x}{n} \right)=1-\frac{2 x^2}{n^2}+\frac{2 x^4}{3 n^4}+O\left(\frac{1}{n^6}\right)$$
$$\log\left( \cos\left (\frac{2x}{n} \right)\right)=-\frac{2 x^2}{n^2}-\frac{4 x^4}{3 n^4}+O\left(\frac{1}{n^6}\right)$$
$$\log(a_n)=-2 x^2-\frac{4 x^4}{3 n^2}+O\left(\frac{1}{n^4}\right)$$
$$a_n=e^{\log(a_n)}=e^{-2 x^2}\left( 1-\frac{4 x^4}{3 n^2}\right)+O\left(\frac{1}{n^4}\right)$$

A: $$L=\lim_{n\rightarrow}~(\cos(2x/n))^{n^2}=\lim_{n\rightarrow \infty} \left( 1-\frac{4x^2}{2n^2} \right)^{n^2}=\exp[\lim_{n\rightarrow \infty} n^2(1-2x^2/n^2-1)]=e^{-2x^2}.$$

A: Hint:
$$\lim_{n\to\infty}\cos^n\dfrac{2x}n=\left(\lim_n\left(1-2\sin^2\dfrac xn\right)^{-1/2\sin^2\dfrac xn}\right)^{\lim_n-2n^2\sin^2\dfrac xn}$$
The inner limit converges to $e$
Set $\dfrac xn=h\implies h\to0$ in the exponent

A: The limit is of $1^{\infty}$ form.
$$\therefore \lim_{n \to \infty} Cos^{n^2}(\frac{2x}{n})=e^{lim_{n \to \infty}(n^2(Cos\frac{2x}{n}-1))}$$
$$=e^{lim_{n \to \infty} (-n^2.2Sin^{2}(\frac{x}{n}))}$$
$$=e^{lim_{n \to \infty} (-2x^2.(\frac{Sin(\frac{x}{n})}{\frac{x}{n}})^2)}$$
$$=e^{-2x^2}$$


text:
Q: How to use JFrog artifact repository in a Maven project Please let me know how I could use/import/download a tool from JFrog artifact repository to my Maven project. I have not worked with artifactory before and Googling did not help much so any help on this would be much appreciated.

A: You should probably start with the Working with Maven section in the Artifactory user guide

A: If you want to work with a Jfrog Artifactory from your maven project you need to:

*

*Create maven repos in Jfrog Artifactory.
I recomend you to create a local SNAPSHOT repo and a local release repo for every type of maven repo that you want.
Example of local repos:
libsrepo-snapshot-local
libsrepo-release-local
projectsrepo-snapshot-local
projectsrepo-local-local

You can create a remote repo for external dependencies, for example, for maven central.
Example of remote repo:
maven-remote

Also, you can create a virtual repo to agrupe all your maven repo. For example, you can create the repo "maven-virtual-repo" where you can have all the repos that you want.
Example of virtual repo:
maven-virtual-repo

*Configure your settings.xml to work with your Jfrog Artifactory repos. You can get more info here: How to configure your settings.xml to work with repositories

*Deploy to Jfrog Artifactory using:
mvn deploy

If you need more help about how to create repos in Jfrog Artifactory you can visit the official guide: Configuring Repositories


text:
Q: Looping through workbook and deleting VeryHidden worksheets One of the modules in a larger project is creating redundant veryHidden sheets. I am attempting to loop through every worksheet in the workbook and delete sheets that are marked as veryHidden. I've used almost identical code in other projects and it has worked so I am unsure why it is not working in this situation. Here is what I've tried:
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
    If sheet.Visible = xlSheetVeryHidden Then
        sheet.Delete
    End If
Next sheet

I've also tried that same code using:
For Each sheet In ActiveWorkbook

And I've also tried:
Dim i As Integer
Dim sheetCount As Integer
For i = 1 To sheetCount
    If Worksheets(i).Visible = xlVeryHidden Then
        Worksheets(i).Delete
    End If
Next i

And also:
For i = sheetCount To 3 Step -1
    If Worksheets(i).Visible = xlVeryHidden Then
        Worksheets(i).Delete
    End If
Next i

In all attempts Application.DisplayAlerts is changed to False before running and changed to True after running. Results in run-time error 1004.

A: If you unhide the sheet before deleting it, it should work.
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Worksheets
    If sheet.Visible = xlSheetVeryHidden Then
        sheet.visible = xlSheetVisible
        sheet.Delete
    End If
Next sheet


text:
Q: Neo4j using optiona and null I am trying to execute this query.
OPTIONAL match
(email:EMAIL)<-[r:REGISTERED_WITH]-(customer_bseller:CUSTOMER_BSELLER)-[addr_r:ADDRESS{shipping:'true'}]->(addr:ADDRESS)
with email, customer_bseller, addr
OPTIONAL match (pedida_user:PEDIDA_DE_HOJE_USER)-[r1:REGISTERED_WITH]->(email)<-[r2:REGISTERED_WITH]-(customer_bseller)
where pedida_user IS NOT NULL
return distinct customer_bseller,
pedida_user limit 5

The problem is that the result set is comming with pedida_user NULL.
Is this the correct way to test if a id is NULL?

A: Since the pedida_user identifier is defined by an OPTIONAL MATCH, it is perfectly possible for your RETURN clause to contain a NULL pedida_user value.


text:
Q: does return object from function lead to memory leak Taking the following code for example, does return object from function lead to memory leak?
I'm very curious about what happens to the object handle after used by the function use_age.
class Demo(object):

    def _get_mysql_handle(self):
        handle = MySQLdb.connect(host=self.conf["host"],
                             port=self.conf["port"],
                             user=self.conf["user"],
                             passwd=self.conf["passwd"],
                             db=self.conf["db"])
        return handle

    def use_age(self):
        cursor = self._get_mysql_handle().cursor()

if __name__ == "__main__":
      demo = Demo()
      demo.use_age()

A: No, that code won't lead to a memory leak.
CPython handles object lifetimes by reference counting. In your example the reference count drops back to 0 and the database connection object is deleted again.

*

*The local name handle in _get_mysql_handle is one reference, it is dropped when _get_mysql_handle returns.

*The stack holding the return value from self._get_mysql_handle() is another, it too is dropped when the expression result is completed.

*.cursor() is a method, so it'll have another reference for the self argument to that method, until the method exits.

*The return value from .cursor() probably stores a reference, it'll be dropped when the cursor itself is reaped. That then depends on the lifetime of the local cursor variable in the use_age() method. As a local it doesn't live beyond the use_age() function.

Other Python implementations use garbage collection strategies; Jython uses the Java runtime facilities, for example. The object may live a little longer, but won't 'leak'.
In Python versions < 3.4, you do need to watch out for creating circular references with custom classes that define a __del__ method. Those are the circular references that the gc module does not break. You can introspect such chains in the gc.garbage object.


text:
Q: Ajax done function empty I'm having problem with this ajax function, fires always "fail" but everything is inserted into my database
$(document).ready(function () {
        $("#formacao").submit(function (e) {
            e.preventDefault();
            var formData = new FormData($(this)[0]);
            var ajaxDivAlert = $('#ajaxDivAlert');
            var ajaxDivOk = $('#ajaxDivOk');
            var ajaxDivErro = $('#ajaxDivErro');

            $.ajax({
                url: 'nova_formacaoBD.php',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    ajaxDivAlert.empty().html('A carregar o ficheiro...aguarde por favor');
                }
            }).done(function (data) {
                var result = data.status;
                console.log(result);
                if (result === 'success'){
                    ajaxDivOk.empty().fadeIn().html('Informação: ' + data.message).fadeOut(5000);
                }
            }).fail(function (xhr, status, error) {
                console.log("Status: " + status + " Error: " + error);
                console.log(xhr);
                ajaxDivErro.empty().fadeIn().html('Esta formação já está registada na base de dados').fadeOut(5000);
            });
        });
    });

From "fail" i receive this
Status: parsererror Error: SyntaxError: Unexpected token F
superNewFormacao.php:244 Object {readyState: 4, responseText:       "Formação{"status":"success","message":"Nova forma\u00e7\u00e3o gravada"}",    status: 200, statusText: "OK"}

That line is
  console.log("Status: " + status + " Error: " + error);

And my json_encode is
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));

So whats wrong?
Thanks
UPDATE
This is my php for insert
    header('Content-Type: application/json');
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');

$mysqli = new mysqli('localhost', 'xxxxx', 'xxxxxx');
if (mysqli_connect_errno()) {
    trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
mysqli_set_charset($mysqli, "utf8");
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/uploads';
$uploadfile = $uploaddir . '/' . basename($_FILES['fileToUpload']['name']);
$escola = filter_input(INPUT_POST, 'escola');
$form = filter_input(INPUT_POST, 'form');
$data = filter_input(INPUT_POST, 'data');
$horas = filter_input(INPUT_POST, 'horas');
$local = filter_input(INPUT_POST, 'local');
$dest = filter_input(INPUT_POST, 'dest');
$datas = filter_input(INPUT_POST, 'datas');
$visto = 0;
echo $form;

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {

    $target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
    $sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
    $stmt = $mysqli->prepare($sql);
    if ($stmt === false) {
        trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
    }
    $stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
    if (!$stmt->execute()) {
        echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
    }
} else {
    echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));


text:
Q: Why sessions data in my db differ from sessions data when i use session->all? I'm trying to use sessions (i need to save sessions in mySql db) in my application on laravel.
So when i log in (use standart LoginController. It was make with php artisan as my sessions table in db) my session save in db as i need but when i use
$value = $request->session()->all();
in my test controller i get data i don't understand
It is in my db

it is what i get when use session()->all();

and if i want to save it (for test)
$request->session()->put(['user_id'=>889900])
nothing happens
so.
What the data when i use session()->all();?
How can i save data what i need in db and when i need (i mean controllers)?
session.php
'driver' => env('SESSION_DRIVER', 'database'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',

.env
SESSION_CONNECTION=mysql
SESSION_DRIVER=database

unfortunately i can't find something use in documentation to my question.
Sorry to my english and thank you in advance

A: The payload in your db you need to decode and unserialize it so that you can have the same result.
For example:
    return Session::all();

and
    $data = DB::table('sessions')->get();

    return unserialize(base64_decode($data[0]->payload));

For Those two you should have the same result.
For pushing key and value, session(['foo' => 'bar']); should work.
Hopefully, I have answered your question.


text:
Q: Landscape is not compiling to produce pdf if i use \input{chapters/ } I'm writing my thesis by using \input{chapters/..} to add the chapters to the main .tex.
While the PDF is produced in a separate .tex file, it is not produced when I'm compiling the main file.
Here is my code
\documentclass[12pt]{report}
\usepackage[english,greek]{babel}
\usepackage[toc,page]{appendix}
\usepackage[font={bf,footnotesize},format=hang]{caption}
\usepackage[iso-8859-7]{inputenc}
\usepackage[LGR, T1]{fontenc}
\usepackage{setspace}
\usepackage{pdflscape}
\usepackage[margin=1in]{geometry}
\usepackage{emptypage}
\usepackage{lipsum,etoolbox}
\usepackage{graphicx}
\usepackage{alphabeta}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{acronym}
\usepackage{amssymb}
\usepackage{threeparttable}
\usepackage[round]{natbib}
\usepackage{hyperref}

\usepackage{longtable}
\begin{document}
\begin{landscape}
\small  % Switch from 12pt to 11pt; otherwise, table won't fit
%\setlength\LTleft{0pt}            % default: \parindent
%\setlength\LTright{0pt}           % default: \fill
\begin{longtable}{lcccccc}
  \caption{Πλήρες \textlatin{BEKK} και Πλήρες Ασύμμετρο \textlatin{BEKK}}
  \hline
 Υπόδειγμα   & \multicolumn{2}{c}{Πλήρες \textlatin{BEKK}} & &   \multicolumn{2}{c}{Πλήρες Ασύμμετρο \textlatin{BEKK}} &  \\
 \hline
    Παράμετρος & Τιμή & Τυπικο Σφάλμα & \textlatin{T-test} & Τιμή & Τυπικο Σφάλμα & \textlatin{T-test} \\
    $A_{11}$ & 0,27815^{*} & (0,08599) & 3.2348 & 0,30954^{*} & (0,08544) & 3.6231 \\
    $A_{21}$ & -0,01736  & (0,12469) & -0.13919 & -0,02746  & (0,13102) & -0.20961 \\
    $A_{31}$ & -0,01882  & (0,07312) & -0.2574 & -0,00535  & (0,02728) & 2.41526 \\
    $A_{43}$ & -0,03004  & (0,18818) & -0.15965 & -0,01201  & (0,13625) & -0.08817 \\
    $A_{14}$ & 0,00557  & (0,03539) & 0.15731 & -0,01596  & (0,0382) & -0.41788 \\
    $A_{24}$ & -0,00684  & (0,01925) & -0.35518 & -0,04397  & (0,05226) & -0.84142 \\
    $A_{34}$ & -0,026  & (0,06569) & -0.39575 & -0,01394  & (0,03309) & -0.42116 \\
    $A_{44}$ & 0,22981^{*} & (0,09845) & 2.33427 & 0,22862^{*} & (0,08114) & 2.81776 \\
    $B_{11}$ & 0,89587^{*} & (0,05047) & 17.74975 & 0,18726  & (0,31355) & 0.59722 \\
    $B_{21}$ & -0,01315  & (0,12507) & -0.10513 & -0,02587  & (0,23578) & -0.10972 \\
    $B_{31}$ & -0,00846  & (0,07539) & -0.1122 & 0,00858  & (0,06704) & 0.12796     $G_{11}$ &       &       &       & 0,89361^{*} & (0,07974) & 11.20632 \\
    $G_{21}$ &       &       &       & 0,01606  & (0,03995) & 0.40188 \\
    \hline
  \textlatin{loglikelihood} & \multicolumn{2}{c}{Πλήρες \textlatin{BEKK}} &   & \multicolumn{2}{c}{Πλήρες Ασύμμετρο \textlatin{BEKK}} &  \\
    & \multicolumn{2}{c}{21936.7} &             & \multicolumn{2}{c}{-21342.67} &  \\
\hline
\end{longtable}
\end{landscape}

\end{document}


text:
Q: "File limit of 90 seconds" is actually 90 seconds total for all the audio files in that one emit? Has anyone else ran into this problem?  I am making a skill that plays audio clips mixed into the alexa speech in each emit.  Amazon's resource site only says that the file's themselves must be under 90 seconds.  In one emit i have 4 files that together exceed 90 seconds, however individually they do not.  The amazon testing environment will return an error saying the total duration exceeds the allowed limit.  Pretty annoying. Is the only solution to break it into multiple emits?

A: The total duration cannot exceed 90 seconds. The documentation is actually pretty explicit about this:

The audio files you include within your service's response must be
  very short to ensure a good user experience. You can include up to
  five audio files in a single response. The combined total time for all
  audio files in a single response cannot be more than ninety (90)
  seconds.

https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/handling-requests-sent-by-alexa


text:
Q: Tensorflow confusion matrix using one-hot code
I have multi-class classification using RNN and here is my main code for RNN:
def RNN(x, weights, biases):
    x = tf.unstack(x, input_size, 1)
    lstm_cell = rnn.BasicLSTMCell(num_unit, forget_bias=1.0, state_is_tuple=True)
    stacked_lstm = rnn.MultiRNNCell([lstm_cell]*lstm_size, state_is_tuple=True)
    outputs, states = tf.nn.static_rnn(stacked_lstm, x, dtype=tf.float32)

    return tf.matmul(outputs[-1], weights) + biases

logits = RNN(X, weights, biases)
prediction = tf.nn.softmax(logits)

cost =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(cost)

correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

I have to classify all inputs to 6 classes and each of classes is composed of one-hot code label as the follow:
happy = [1, 0, 0, 0, 0, 0]
angry = [0, 1, 0, 0, 0, 0]
neutral = [0, 0, 1, 0, 0, 0]
excited = [0, 0, 0, 1, 0, 0]
embarrassed = [0, 0, 0, 0, 1, 0]
sad = [0, 0, 0, 0, 0, 1]

The problem is I cannot print confusion matrix using tf.confusion_matrix() function.
Is there any way to print confusion matrix using those labels?
If not, how can I convert one-hot code to integer indices only when I need to print confusion matrix?

A:
You cannot generate confusion matrix using one-hot vectors as input parameters of labels and predictions. You will have to supply it a 1D tensor containing your labels directly.
To convert your one hot vector to normal label, make use of argmax function:
label = tf.argmax(one_hot_tensor, axis = 1)

After that you can print your confusion_matrix like this:
import tensorflow as tf

num_classes = 2
prediction_arr = tf.constant([1,  1, 1, 1,  0, 0, 0, 0,  1, 1])
labels_arr     = tf.constant([0,  1, 1, 1,  1, 1, 1, 1,  0, 0])

confusion_matrix = tf.confusion_matrix(labels_arr, prediction_arr, num_classes)
with tf.Session() as sess:
    print(confusion_matrix.eval())

Output:
[[0 3]
 [4 3]]


text:
Q: What are the different types of memories which can come under shared memory? For example in a multi-threaded program, Global, volatile, extern variables, can come under critical section as they can be accessed by multiple threads at once.
Also shmget() allocates shared memory.
I'd like to know what all other memory types can be critical sections in both user space and kernel space.

A: Shared memory is generally included under critical sections. Reason being shared memory can be accessed by multiple threads at one time. To make sure certain shared memory is accessed by only one thread at one time, critical sections are used.
Not sure if shared memory is further categorized.

A: Checkout these links for a good understanding on shared memory regions and critical sections in action on real world systems.
bcook.cs.georgiasouthern.edu/cs523/critical.htm
blogs.msdn.com/b/larryosterman/archive/2005/08/24/455741.aspx
ibm.com/developerworks/linux/library/l-linux-synchronization/index.html

A: Shared memory may differ when you're talking about different concepts, i.e two processes that use a common data, a queue for example, you need to "take care" of the critical sections upon modifying/adding/removing.
As for threads, everything is shared except the stack, and the code segment, so theoretically each piece of data that's reached by the main process, is a shared memory between those threads.


text:
Q: how can i use if statement in video view if the video not work in my java code , i have VideoView and im parsing the video to him in URI From internet(i set link of video) , but after 6 Hours , they are changed the link of video , and if the old link of video has still in uri he giving me message "Can't play this video" , but now ho can i use if statement and i set inside it nearly 7 link of video and if the first link of video converted to doesn't  work .. automatically he chose the second link of video .
it is a impossible ?
my code :
Uri uri = Uri.parse("myVideoLink");

    videoView.setVideoURI(uri);
    videoView.setMediaController(new MediaController(this));
    videoView.requestFocus();
    videoView.start();

A: Try something like this:
private void play(String[] videoUrls, final int current) {
    videoView.setVideoURI(Uri.parse(videoUrls[current]));
    videoView.setMediaController(new MediaController(this));
    videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
            try {
                // try to play video from next video url
                play(videoUrls, current + 1);
            } catch (IndexOutOfBoundsException e) {
                // end is reached
            }
            return false;
        }
    });
    videoView.start();
}

For start playing
play(new String[]{"url1", "url2"}, 0);


text: Q: python can't import PyQt5 WebKitWidgets I'm running python on windows 10, and after installing PyQt5 using the command pip install pyqt5 and after that pip install pyqtwebkit and everything installed. But when I do on my program from PyQt5.QtWebKitWidgets import * it doesn't work and outputs the following error: ImportError: DLL load failed while importing QtWebKitWidgets: can't find specified module.


text:
Q: How to tell if current version was upgraded or a fresh install I have a number of installation of ubuntu 16.04.  Some of them were upgraded from a previous version.  Some of them were fresh installs.
Some of my installations have problems that that I don't experience of some of the others.
I'm trying to identify if the problems that I experience are because of problems with the upgrade and if the fresh installs are functioning better.
If the fresh installs are functioning better in every instance, I might perform fresh installs on some of the computers that I experience problem.
Thanks in advance for anyone who knows how to test if the running OS was installed initially as the version running.

A: A clean install of Ubuntu 16.04 should have no files in directory /var/log/dist-upgrade.  So you could test for the existence of main.log there to determine if the installation was a clean install or an upgrade, eg using bash
if [ -f /var/log/dist-upgrade/main.log ]
then echo upgrade
else echo clean install
fi

For more info refer to DebuggingUpdateManager


text:
Q: How to upgrade PHPmyAdmin I installed PHPmyAdmin through this code
sudo apt-get install phpmyadmin apache2-utils

I want to know how to upgrade through terminal

A: To upgrade phpmyadmin only use
sudo apt-get update
sudo apt-get install phpmyadmin

This install with an already installed package will upgrade it to the latest version.
To upgrade all packages — phpmyadmin and all others — use
sudo apt-get update
sudo apt-get upgrade


text:
Q: Allowing encoded characters in an MVC Get I have an MVC controller with the following method
    [HttpGet]
    public ActionResult Image(int image, string message)
    {

I want this to be a GET because it's the appropriate verb to use for the method I'm implementing.
I want to supply "Does this work?" as a parameter to the method. Obviously this is not going to work:
http://localhost:55197/Controller/Image/3/Does%20this%20work?

The question mark is considered part of the query string and is removed. I've read this question which suggests encoding the question mark to %3F, this makes sense to me (after all we encode our spaces). However when I call the method with this query string:
http://localhost:55197/Controller/Image/3/Does%20this%20work%3F

I get

A potentially dangerous Request.Path value was detected from the
  client (?).

I've read this question which suggests using the [AllowHtml] attribute, but this can only be used on properties (and is therefore more appropriate to POST requests.
How can I pass strings like:

Does this work?
I think so...

Into this method?

A: Try below code in web.config file :-
<system.web>
    <httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
    <pages validateRequest="false" />
</system.web>


text:
Q: mongo aggregate - group - show number fo childrens This is how my documents looks like:
[
  {
    "_id": {
      "$oid": "633a982186c443b693dc240c"
    },
    "date": "2022-09-27",
    "file": "file_1",
    "package": 1,
    "packagecode": "xy/1",
    "pshIdList": [],
    "userList": [
      {
        "userName": "user_1",
        "crDate": "2022.09.28",
        "boolId": 1
      }
    ]
  },
  {
    "_id": {
      "$oid": "633a982186c443b693dc240d"
    },
    "date": "2022-09-27",
    "file": "file_2",
    "package": 2,
    "packagecode": "xy/2",
    "pshIdList": [],
    "userList": []
  }
]

Because of the appearance of the frontend (i have to display a tree structure) i need to group by the documents this way:
db.collection.aggregate([
  {
    $set: {
      "username": {
        $filter: {
          input: "$userList",
          as: "user",
          cond: {
            "$eq": [
              "$$user.boolId",
              1
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      "username": {
        $arrayElemAt: [
          "$username",
          0
        ]
      }
    }
  },
  {
    $set: {
      "username": {
        $ifNull: [
          "$username.userName",
          "na"
        ]
      }
    }
  },
  {
    $group: {
      _id: {
        "date": {
          $concat: [
            "date: ",
            "$date",

          ]
        },
        "file": {
          $concat: [
            "file: ",
            "$file"
          ]
        },

      },
      "items": {
        $push: {
          "items": {
            $concat: [
              "$packagecode",
              " - ",
              "$username"
            ]
          }
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.date",
      "items": {
        $push: {
          "file": "$_id.file",
          "items": "$items"
        }
      }
    }
  }
])

This is the result of the aggregate:
[
  {
    "_id": "date: 2022-09-27",
    "items": [
      {
        "file": "file: file_1",
        "items": [
          {
            "items": "xy/1 - user_1"
          }
        ]
      },
      {
        "file": "file: file_2",
        "items": [
          {
            "items": "xy/2 - na"
          }
        ]
      }
    ]
  }
]

Also need to display the number of childrens of each level, so the output should look like this:
[
  {
    "_id": "date: 2022-09-27 - 2",
    "items": [
      {
        "file": "file: file_1 - 1",
        "items": [
          {
            "items": "xy/1 - user_1"
          }
        ]
      },
      {
        "file": "file: file_2 - 1",
        "items": [
          {
            "items": "xy/2 - na"
          }
        ]
      }
    ]
  }
]

I have no clue how to solve it. I was trying with $set operator, but cannot use group inside that. This is an example playground

A: You can use $map, to loop over the items array and append the number of children in file, like this:
db.collection.aggregate([
  {
    $set: {
      "username": {
        $filter: {
          input: "$userList",
          as: "user",
          cond: {
            "$eq": [
              "$$user.boolId",
              1
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      "username": {
        $arrayElemAt: [
          "$username",
          0
        ]
      }
    }
  },
  {
    $set: {
      "username": {
        $ifNull: [
          "$username.userName",
          "na"
        ]
      }
    }
  },
  {
    $group: {
      _id: {
        "date": {
          $concat: [
            "date: ",
            "$date",

          ]
        },
        "file": {
          $concat: [
            "file: ",
            "$file"
          ]
        },

      },
      "items": {
        $push: {
          "items": {
            $concat: [
              "$packagecode",
              " - ",
              "$username"
            ]
          }
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id.date",
      "items": {
        $push: {
          "file": "$_id.file",
          "items": "$items"
        }
      }
    }
  },
  {
    "$set": {
      "items": {
        "$map": {
          "input": "$items",
          "as": "element",
          "in": {
            items: "$$element.items",
            file: {
              "$concat": [
                "$$element.file",
                " - ",
                {
                  "$toString": {
                    "$size": "$$element.items"
                  }
                }
              ]
            }
          }
        }
      },
      _id: {
        "$concat": [
          "$_id",
          " - ",
          {
            "$toString": {
              "$sum": {
                "$map": {
                  "input": "$items",
                  "as": "element",
                  "in": {
                    "$size": "$$element.items"
                  }
                }
              }
            }
          }
        ]
      }
    }
  }
])

Playground link.


text:
Q: Hypersurfaces of constant phase of light and light cone I am reading Schneider's Gravitational Lenses as textbook. In Chapter 3, it says 'The hypersurfaces of constant phase or wavefronts
are thus everywhere tangent to the local light cone' with Eikonal equation:
\begin{equation}
g^{\alpha \beta} S_{, \alpha} S_{, \beta} = 0
\end{equation}
where S is the phase of the light wave.
How does one draw that conclusion from the equation?

A: The equation just says the 4-gradient of the phase is null, e.g. light like, e.g. on the light cone.
For a plane wave in a locally flat region:
$$\psi(x^{\mu})=Ae^{i(k_{\mu}x^{\mu})}\equiv Ae^{iS(x^{\mu})}$$
the phase is:
$$S(x^{\mu})=k_{\mu}x^{\mu}$$
so
$$S_{,\mu}=k_{\mu}$$
Then:
$$k^{\mu}k_{\mu} =\big(\frac{\omega}c\big)^2-||\vec k||^2=0$$
i.e.:
$$\omega=kc$$
Thus, if you pick frame and sit at $\vec x_0$ at time $t_0$, so the phase is:
$$ S_0=S(t_0, \vec x_0)=kx_0-\omega t_0$$
and move forward in time $\delta t$, to keep the phase constant you need to move $\vec{\delta}$ so that:
$$ S_1=S(t_0+\delta t, \vec x_0+\vec{\delta})=
\vec k\cdot (\vec x_0+\vec{\delta})-\omega (t_0+\delta t)
=S_0$$
$$\vec k\cdot\vec{\delta}=\omega t $$
so that:
$$||\delta||=\frac{\omega} k t= ct$$
meaning the points of constant phase move along the light cone in the direction of $\hat k$.


text:
Q: Compare Products use multiple properties I have an Excelsheet and want to compare the products by multiple values. My Excel looks like this:
+-----------+--------+------+-------+---------+-------+
|   Name| kcal   | Fat  | Carbs | Protein | €/kg  |
+-----------+--------+------+-------+---------+-------+
| Product A | 383,00 | 5,90 |  6,50 |   76,00 | 21,98 |
| Product B | 359,00 | 0,70 |  3,20 |   85,00 | 24,90 |
| Product C | 380,90 | 5,86 |  8,79 |   73,25 | 32,17 |
| Product D | 390,00 | 5,50 |  5,30 |   80,00 | 18,96 |
+-----------+--------+------+-------+---------+-------+
I would like to find the "best" product by the following criteria:

*

*lowest kcal

*lowest Fat

*lowest Carbs

*highest Protein

*lowest €/kg

Is there a way to do this with excel/google docs?
Maybe a little add-on. The highest priority is €/kg, after that Protein and the other three have the same importance.

A: It's a bit vague what would be considered the "best", however you could consider adding all these amounts together (subtract the protein) would give you a matrix in which you can get the minimum.
Try:
=INDEX(A2:A5,MATCH(MIN(INDEX(B2:B5+C2:C5+D2:D5-E2:E5+F2:F5,)),INDEX(B2:B5+C2:C5+D2:D5-E2:E5+F2:F5,),0))

Add a multiplication, e.g.: *1.05 to any of the columns if you consider them to be of more importance.


text:
Q: C# - string.IsNullOrEmpty not working for a specific textbox I'm just learning to program and I'm trying to create a program to calculate weight & balance for an aircraft. When you first load this form, I want all the textboxes specified to have a value of 0. I'm running into an issue where one of the boxes is remaining blank and not inputting 0 (Bag Weight). Maybe its something very simple I'm missing? Please see below code:
tb1legBW.text = This is the bag weight I'm referring too.
// This is setting the textbox values to 0 if they are blank.
        if (string.IsNullOrEmpty(tb1LegOEW.Text) || string.IsNullOrEmpty(tb1LegPW.Text) || string.IsNullOrEmpty(tb1LegBW.Text) ||
            string.IsNullOrEmpty(tb1LegFW.Text) || string.IsNullOrEmpty(tb1LegFuel.Text) || string.IsNullOrEmpty(tb1LegEquip.Text) ||
            string.IsNullOrEmpty(tb1LegAWI.Text) || string.IsNullOrEmpty(tb1LegFB.Text) || string.IsNullOrEmpty(tb1LegCont.Text) ||
            string.IsNullOrEmpty(tb1LegMTOW.Text) || string.IsNullOrEmpty(tb1LegGW.Text) || string.IsNullOrEmpty(tb1LegGD.Text) ||
            string.IsNullOrEmpty(tb1LegMLW.Text) || string.IsNullOrEmpty(tb1LegLW.Text) || string.IsNullOrEmpty(tb1LegLGD.Text))

        {
            tb1LegOEW.Text = "0";
            tb1LegPW.Text = "0";
            tb1LegBW.Text = "0";
            tb1LegFW.Text = "0";
            tb1LegFuel.Text = "0";
            tb1LegEquip.Text = "0";
            tb1LegAWI.Text = "0";
            tb1LegFB.Text = "0";
            tb1LegCont.Text = "0";
            tb1LegMTOW.Text = "0";
            tb1LegGW.Text = "0";
            tb1LegGD.Text = "0";
            tb1LegMLW.Text = "0";
            tb1LegLW.Text = "0";
            tb1LegLGD.Text = "0";
        }

When I run the program the bag weight textbox is blank, unlike the others. Picture is attached: When Program is ran
If someone could please give me some insight on what is happening?

A: Use string.IsNullOrWhitespace()


text:
Q: SwiftUI - Why is there a default padding on the bottom? I'm building a little card view and was adding the text views to it, when I got confused about the padding of the right text "5 / 14". I put 16 into .trailing and .bottom but noticed it was offset. When I changed bottom to 0 it actually looks symmetrical.
How does this happen?
VStack {
            ZStack(alignment: .bottomLeading) {
                Image("sky")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(height:128)
                    .cornerRadius(16)

                HStack{
                    Text("Journey")
                        .foregroundColor(Color.white)
                        .font(.title2)
                        .fontWeight(.medium)
                        .multilineTextAlignment(.leading)
                        .padding(.init(top: 0, leading: 24, bottom: 24, trailing: 0))

                    Spacer()

                    Text("5 / 14")
                        .foregroundColor(Color.white)
                        .font(.body)
                        .multilineTextAlignment(.leading)
                        // This padding here, bottom is 0 but looks like 16
                        .padding(.init(top: 0, leading: 0, bottom: 0, trailing: 16))
                }
            }
            .padding(.init(top: 0, leading: 24, bottom: 0, trailing: 24))
        }

A: It's because your HStack is center-aligned by default.
You can see this by adding .border(_:) to these views:
/* ... */

HStack {
    Text("Journey")
        .foregroundColor(Color.white)
        .font(.title2)
        .fontWeight(.medium)
        .multilineTextAlignment(.leading)
        .padding(.init(top: 0, leading: 24, bottom: 24, trailing: 0))
        .border(Color.red) // <- HERE

    Spacer()

    Text("5 / 14")
        .foregroundColor(Color.white)
        .font(.body)
        .multilineTextAlignment(.leading)
    // This padding here, bottom is 0 but looks like 16
        .padding(.init(top: 0, leading: 0, bottom: 0, trailing: 16))
        .border(Color.blue) // <- HERE
}

To fix this issue, just set the HStack's alignment to .bottom.
HStack(alignment: .bottom) {
    /* ... */
    /* Same as before, but now you may want to add the 16 padding again */
}