text:
Q: How to add data into 2 separate tables in django rest_framework? I have created a simple API and want to add data into 2 tables.
For example, I have created 2 tables in models.py
class User(models.Model):
    userid = models.AutoField(primary_key=True)
    name = models.CharField(max_length= 100)
    age = models.IntegerField()
    gender = models.CharField(max_length=100)
    class Meta:
        db_table = 'user'

class Detail(models.Model):
    address = models.CharField(max_length=100)
    phone = models.IntegerField()
    details = models.CharField(max_length=100)
    class Meta:
        db_table = 'detail'

serializers.py
class UserSerializer(serializers.ModelSerializer):
    name=serializers.CharField(required=True)
    age = serializers.IntegerField(required=True)
    gender = serializers.CharField(required=True)
    class Meta:
        model = User
        fields= '__all__'

class DetailSerializer(serializers.ModelSerializer):
    address = serializers.CharField(required=True)
    phone = serializers.IntegerField(required=True)
    details= serializers.CharField(required=True)
    class Meta:
        model = Detail
        fields= '__all__'

suppose I am passing the JSON data as
{
"name" : "abc",
"age" : 20,
"gender" : "Male",
"address" : "xyz",
"phone" : 454545454,
"details" : "lorem epsum"
}

is it possible to insert data into both tables?.
name, age & gender should be inserted into the User table & and address, phone & details in the Detail table.
I have tried many things hence I have nothing to show in views.py

A: Ye, this is completely possible, I have two solutions for this problem-
Assuming User and Detail are not correlated, models. You can simply create an API View like given below and save the data manually to both the tables.
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import (
    UserSerializer,
    DetailSerializer
)

class UserAPIView(APIView):
    def post(self, request, format=None):

        name = request.data.get('name')
        age = request.data.get('age')
        gender = request.data.get('gender')
        address = request.data.get('address')
        phone = request.data.get('phone')
        details = request.data.get('details')

        user_serializer = UserSerializer(data={"name": name, "age": age, "gender": gender})
        detail_serializer = DetailSerializer(data={"address": address, "phone": phone, "details": details})

        if user_serializer.is_valid(raise_exception=True):
            user_serializer.save()

        if detail_serializer.is_valid(raise_exception=True):
            detail_serializer.save()

        return Response({'status': 'Success'})

I would suggest you connect your User and Detail tables through One to One relation, if both are used for storing user information, your task of storing the information in single-shot request would become easier with the help of nested serializers.
Otherwise do not separate the information in one table, just put everything in one table if the information belongs to all the users.


text:
Q: grails 2.4.2 optimistic locking seems not to work I have a few grails apps, that all currently running under grails 2.4.2.
In every of these apps, it seems, that the optimistic-locking feature is not working.
I have my domain classes and generated controllers.
I use 2 different browsers (opera and firefox) for the tests and open the same domain-instance in both of the browsers.
In both edit-dialogs, I updated the fields to different values and save then the record in one of the browsers and afterwards in the other one.
My problem is, that I don't get a hint of the concurrent update which has taken place.
(Because the version-no from the original record is passed around in the views etc.)
Do I have to do the check for the version-no by myself? I thought, that would be handled by hibernate? (optimistic locking through the version field is default in grails...)
Thanks in advance!

A: In your case you have to check it by yourself. You can take a look at scaffolded views for the reference.
Read this answer for the details: https://stackoverflow.com/a/24051451/4769188

redpajama_set_name: RedPajamaStackExchange


text:
Q: Precision Tracking filter required I don't mind if it's a band-pass or low pass filter (although I think low-pass will give a better result). Input operating frequency range is 100Hz to 1kHz. Input amplitude will be about 1Vp-p and although it will be a bit noisy and not very square-wave-ish it'll be good enough to feed into a comparator to get a decent square-wave should that be required.
Basically I need a design that will take a noisy square-wave output from a strain gauge amplifier, determine the frequency of said square-wave and filter out the high frequency noise and harmonics leaving a sinewave.
EDIT - the end game is to measure the amplitude of the squarewave accurately - by filtering-in the fundamental frequency it becomes easier to measure because the squarewave amplitude is very accurately linked to the sine amplitude (4/Pi from memory)
This is for a test box where the strain gauge (connected to the amplifier) is supplemented with a FET switching a large value resistor connected across the strain gauge - this simulates a small but predictable amount of strain. The output from the amplifier needs to be converted to a sinewave for measurement purposes. I'm aware that this signal could be taken into a PC running a Fourier analysis on it but it's not always convenient to have a PC handy.
I suspect, for this tracking filter a switched-cap filter like the MF10 (or based on similar) will be required and a phase-locked-loop to track the actual input frequency to generate a clock at a much higher rate.
Currently, I have a 12th order low-pass filter that is good for a small range of frequencies around 600Hz (with minor adjustments) but this is no good for lower or higher frequencies.
Please let me know if there is information missing that would help answers. I am looking for quite high precision and if it needs a select-on-test components that's not a problem.


text:
Q: Codeception 404 on Plesk Shared Hosting I'm just trying to get myself going with Codeception.
Got it all installed and have a basic acceptance test to see if it works.
So I run...
php codecept.phar run
...and it goes through all the motions, but the test fails because it 404s.
When I hit the same URL in a browser or wget it from another server it works just fine.
If it makes any difference, the place I'm trying to get this running is on a shared hosting environment running Plesk 11.5.30. The server belongs to the agency I'm working for, so I should be able to get changes made if necessary.
Can anyone help here?
UPDATE
There's definitely an issue using curl, wget etc. on a Plesk server when the URL is pointing to the same server. Same commands work just fine from other servers. I've got our server admin looking at this and I reckon that once the curl issue is sorted, the acceptance tests will probably work.

A: Well, this is what made it work on our server...
Edit /etc/hosts
Then add a line for the domain NATing it through the local IP:
123.123.123.123  domain.com


text:
Q: How to get call back url value without actual server Our third party company provide me link to get authcode for integrated their Api.When we call that link on browser , we get callback url as https://return.mytest.com/?code=my1234&scope= although getting error message as "This site can't be reached" .Actaully https://return.mytest.com is no have our side. It is fake url we set to get their callback result.
When we implement in our program to call that link , we get errors as "The remote name could not be resolved: 'return.mytest.com'". I know that error because return.mytest.com does not exist our side. I just want to get callback url value.How can I implement with c#.

A: In an OAuth2 setup, the callback URL must exist.
The other party will pass the details of the token to that URL so if your callback URL does not exist then they will get an error and you will not get the token.
So either add an endpoint to an existing app, or create a new one, but the bottom line is clear. The callback URL must be a real thing. Otherwise how is another party supposed to communicate with you?


text:
Q: Using dbgview with java I am writing java code and would like to use dbgview (and log4j if possible). By searching the documentation of log4j it seems that unlike log4net, log4j does not support the OutputDebugStringAppender which redirect output to what dbgview listens to.
How can one create a log file that dbgview can parse?
How can one send string to the debug stream from java?
Is there any debugview alternative for java?
I am using eclipse, Windows 7 and latest log4j jar.

A: Java does not have a native functionality to send over debug prints to Windows debug output.
However you can easily do it by importing the Windows OutputDebugString function using JNA. It will break any multi-platform functionality (you will only be able to run on windows) but it will work.
You can do something like this :
import com.sun.jna.Library;
import com.sun.jna.Native;

public interface Kernel32 extends Library
{
    public void OutputDebugStringA(String Text);
}

When calling OutputDebugString you need to do this :
 Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32″, Kernel32.class);
 lib.OutputDebugStringA(message);


text:
Q: Attempting to insert characters via shell script bound to hotkey I added the following to /root/.config/openbox/rc.xml:
<keybind key="C-A-t">
        <action name="Execute">
            <command>/root/my-applications/test1.sh</command>
        </action>
</keybind>

The test1.sh file consists of an executable shell script which outputs ñ.
The idea being to tie the key combination to the output, so when I press C-A-t it will output an ñ. However, it doesn't work; pressing it in (for example) Geany does nothing. I have reconfigured openbox. What am I doing wrong?

A: First off, why are you running X as root? That's a really bad idea considering all of the security implications.
Secondly, binding a key to a script that outputs "ñ" is not the same as giving that to a program (on the contrary, it likely just goes straight to /dev/null). You need to look into using something like xdotool.


text:
Q: Select product from mysql where array $key = id I have a session containing an array with key and value assigned to each array. After the array is set and stored in the session, I would like to fetch and echo out all information from mysql table where the $key of the array is = to the id in my table.
I am using a foreach loop to echo each $key and $value of each array already, but i want to echo the data from the mysql table which equals each key as well.
My table
id         |       name       |      animalheight     |
-------------------------------------------------------
2012dog                dog                    1m
2022cat                cat                    0.3m

So I would like to echo the name and animalheight, if the session key is set and equals to the id of the table.
The part of the code that gives an error
///////////////DUMPING EVERYTHING FROM DATABASE////////////////////////////////////

$sql = "select * from products where $key =$id";
$myData =  mysql_query($sql,$con);

if($record = mysql_fetch_array($myData))
{
    echo "
";
    echo "||||||||||||||||". $row['name']. "||||||||||||||||";
    echo "
";
}
/////////////////////DUMPING EVERYTHING FROM DATABASE/////////////////////////////////////

My Full Code
//code
<?php
//////////////////////////////////////////////
$con = mysql_connect("localhost","****","");
mysql_select_db("*********",$con);
//////////////////////////////////////////////
 session_start();

// create an array
$my_array=array( '2012dog' => 1 , '2022cat' => 2);

// put the array in a session variable
if(!isset($_SESSION['animals']))
    $_SESSION['animals']=$my_array;

 // move submit code outside of foreach loop
 if (isset($_POST["submit"]))
{
for ($i = 0; $i < count($_POST['aaa']); $i++) {
    $aaa = $_POST['aaa'][$i];
    $key_var = $_POST['ke'][$i];

    // setting the session spesific session array value different for each     key
    $_SESSION['animals'][$key_var] = $aaa;
}
}
?>

<form method="post" action="">
<?php
// loop through the session array with foreach
foreach($_SESSION['animals'] as $key=>$value)
{

////////////////////////////DUMPING EVERYTHING FROM     DATABASE////////////////////////////////////////////////

$sql = "select * from products where $key =$id";
$myData =  mysql_query($sql,$con);

if($record = mysql_fetch_array($myData))
{
    echo "
";
    echo "||||||||||||||||". $row['name']. "||||||||||||||||";
    echo "
";
}
////////////////////////////DUMPING EVERYTHING FROM     DATABASE////////////////////////////////////////////////

    // and print out the values

    echo "Product ID is " .$key. " Quantity is ";

    // getting the updated value from input box
    ?>
        <input type="text" name="aaa[]" value="<?php echo $value ; ?>"     size="2" />

        <input type="hidden" name="ke[]" value="<?php echo $key; ?>">

    <?php
}
?>

<input type="submit" value="Update value of key" name="submit"/>
</form>

THANKS IN ADVANCE!

A: you can do something like this,
// First get all the keys
$key_array = array_keys($_SESSION['animals']);

// Get all records
$sql = "select * from products";
$myData =  mysql_query($sql,$con);

// Loop through each record and see if $row['id'] is present in the $key_array or not
while($row = mysql_fetch_array($myData)){
    if(in_array($row['id'], $key_array)){
        // display records
    }
}


text:
Q: Oracle BMCS object store bandwidth cost If my application that run in oracle bare metal compute nodes access oracle bare metal object storage service using the http apis provided, would it incur bandwidth cost? In other words, is there a way the compute nodes can route the traffic through an internal network rather than going through public IPs of the bare metal object storage service.

A: There is no charge for network traffic between OBMCS compute and the object store.


text:
Q: Python web app setup I have a python script (2.7) that queries an API and returns information to the user (.csv file).  I'd like to make this script available to people that visit my website, which is based on wordpress.
What is the best way to go about this task?  People tell me to use django, but I'm not sure where to start:
Do I incorporate my python script into django somehow and have my pages access the DB?
Do I have the script on my server, django in another place, and have all three talking to each other?
Is there a better option?
I just need a "recipe" to help me along my path.

A: For something simple like what you're mentioning above, there's probably no better place for you to dive in than Flask (http://flask.pocoo.org/) -- it's a simple, minimalistic web framework for Python that will help get your stuff up and running quickly.
Here's a full Flask application (an example) that simply returns a CSV file called 'test.csv' to the user who visits the homepage of the site:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def serve_csv():
    return app.send_static_file('test.csv')

if __name__ == '__main__':
    app.run()

This example assumes you've got a project that looks like this:
project
├── app.py
└── static
    └── test.csv

You should probably head over to the Flask website to read a bit more about it: http://flask.pocoo.org/


text:
Q: Django change foreign keys to BigInt I have two models (store and products) the primary key in both are BigInt but the relation column in products (store_id) is still integer. I dont want to use raw sql, how can I fix this issue using django?
Example:
class Product:
  id = models.BigAutoField(primary_key=True, editable=False)
  store = models.ForeignKey(
          to='stores.Store', on_delete=models.CASCADE
      )

class Store:
  id = models.BigAutoField(primary_key=True, editable=False)

store_id in model Products is still data type integer

A: You could remove default auto field and use BigAutoField instead by naming primary_key field
id = models.BigAutoField(primary_key=True)


text:
Q: Google Genomics API Callsets Search "Unknown field name: datasetIds" I've been using the Google Genomics API for about a day now.  I've successfully called many of the APIs like Datasets.list, Datasets.get, and even Readsets.search but I'm having a problem with the Callsets.search.
I'm making POST request to:
POST https://www.googleapis.com/genomics/v1beta/callsets/search?key=MY_KEY_HERE

And my request body is:
{
    "datasetIds" : [
        "376902546192"
    ]
}

But the response I'm getting back is:
{
    "error" : {
        "errors": [
            {
                "domain": "global",
                "reason": "invalid",
                "message": "Unknown field name: datasetIds",
                "locationType": "other",
                "location": ""
            }
        ],
        "code": 400,
        "message": "Unknown field name: datasetIds"
    }
}

According to the documentation: https://developers.google.com/genomics/v1beta/reference/callsets/search datasetIds is a perfectly valid parameter.
The crazy thing that's perplexing me is this identical request works just fine on the readsets/search endpoint but not the callsets/search endpoint? I'm almost wondering if it's a bug in the API. Can anyone help?

A: Received this from Google:

The variants and callsets APIs just went
  through some breaking changes so that they'll be compliant with GA4GH
  v0.5 when they go fully public.
All breaking changes should be done now - and I'll try to get all the
  docs and code samples updated today or tomorrow.
Until then, you can see the real parameters in the API explorer (it
  can't lie :) - in this case, the datasetId field has now changed to
  "variantSetIds" (still using that same value, just a rename)

A: I just tested it, and it works.  Below are the results:
$ java -jar target/genomics-tools-client-java-v1beta.jar searchcallsets --dataset_id 376902546192

Getting call sets from: 1000 Genomes
{"created":"1410541777431","id":"376902546192-0","name":"HG00345","sampleId":"HG00345","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-1","name":"HG00369","sampleId":"HG00369","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-2","name":"HG01085","sampleId":"HG01085","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-3","name":"HG01107","sampleId":"HG01107","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-4","name":"NA12347","sampleId":"NA12347","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-5","name":"NA18579","sampleId":"NA18579","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-6","name":"HG00372","sampleId":"HG00372","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-7","name":"HG01134","sampleId":"HG01134","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-8","name":"NA18532","sampleId":"NA18532","variantSetIds":["376902546192"]}
{"created":"1410541777431","id":"376902546192-9","name":"NA18597","sampleId":"NA18597","variantSetIds":["376902546192"]}

Hope it helps,
Paul


text:
Q: How to Generate .xlsx file using PdfReport I'm using PdfReport library for generating reports as .pdf files.
PdfReport is a library built on Epplus and iTextsharp, that is why we chose this library- as we want to generate PDF and EXCEL files.
Currently we are able to generate the PDF file built can't seem to generate the Excel file.
There is not much help on Google related to this library.
PdfReport
Here is my code
public class IListPdfReport
{
    public IPdfReportData CreatePdfReport(DataSet mTables)
    {
        return new PdfReport().DocumentPreferences(doc =>
        {
            doc.RunDirection(PdfRunDirection.LeftToRight);
            doc.Orientation(PageOrientation.Portrait);
            doc.PageSize(PdfPageSize.A4);
            doc.DocumentMetadata(new DocumentMetadata { Author = "Vahid", Application = "PdfRpt", Keywords = "IList Rpt.", Subject = "Test Rpt", Title = "Test" });
            doc.Compression(new CompressionSettings
            {
                EnableCompression = true,
                EnableFullCompression = true
            });
            doc.PrintingPreferences(new PrintingPreferences
            {
                ShowPrintDialogAutomatically = true
            });
        })
        .DefaultFonts(fonts =>
        {
            fonts.Path(System.IO.Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "fonts\\arial.ttf"),
                       System.IO.Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "fonts\\verdana.ttf"));
            fonts.Size(9);
            fonts.Color(System.Drawing.Color.Black);
        })
        .PagesFooter(footer =>
        {
            footer.DefaultFooter(DateTime.Now.ToString("MM/dd/yyyy"));
        })
        .MainTableTemplate(template =>
        {
            template.BasicTemplate(BasicTemplate.AppleOrchardTemplate);
        })
        .MainTablePreferences(table =>
        {
            table.ColumnsWidthsType(TableColumnWidthType.FitToContent);
            table.NumberOfDataRowsPerPage(10);
        })
        .MainTableDataSource(dataSource =>
        {
            dataSource.DataTable(mTables.Tables[2]);
        })
        .MainTableSummarySettings(summarySettings =>
        {
            summarySettings.OverallSummarySettings("Summary");
            summarySettings.PreviousPageSummarySettings("Previous Page Summary");
            summarySettings.PageSummarySettings("Page Summary");
        })
        .MainTableColumns(columns =>
        {
            columns.AddColumn(column =>
            {
                column.PropertyName("AssetSummaryReportDetailId");
                column.IsRowNumber(true);
                column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                column.IsVisible(true);
                column.Order(0);
                column.Width(1);
                column.HeaderCell("AssetSummaryReportDetailId");
            });

            columns.AddColumn(column =>
            {
                column.PropertyName("AssetId");
                column.IsRowNumber(true);
                column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                column.IsVisible(true);
                column.Order(1);
                column.Width(2);
                column.HeaderCell("AssetId");
            });

            columns.AddColumn(column =>
            {
                column.PropertyName("CategoryId");
                column.IsRowNumber(true);
                column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                column.IsVisible(true);
                column.Order(1);
                column.Width(2);
                column.HeaderCell("CategoryId");
            });

        })
        .MainTableEvents(events =>
        {
            events.DataSourceIsEmpty(message: "There is no data available to display.");
        })
        .Export(export =>
        {

// This line here should generate the Excel file, but it is not creating the Excel file
            export.ToExcel(description: "Demo", fileName: "usmandemo.xlsx", worksheetName: "worksheet1", footer: "footer");
        })
        .Generate(data => data.AsPdfFile(string.Format("{0}\\A_RptIListSample-{1}.pdf", AppPath.ApplicationPath, Guid.NewGuid().ToString("N"))));

    }

A: i've never used that particular library, so can't make any suggestions on how to use it,
However if you want to create an xlsx file with the data you can do so with out going through their service
The new Office File format is called Office Open XML Format, and its common between all office applications there is a MSDN guide here that will help you
Creating Documents by Using the Open XML Format


text:
Q: Installing ubuntu alongside windows 8 without partitioning My disk partitions are as follow:
c:6.88/49.1GB
d:159/270GB
e:239/292GB
f:164/319GB

Windows 8 is running from c:
The problem is that windows doesn't allow me to partition my disk further,stating that I have exceed the maximum number of partitions.
Could anyone tell me how to go about dual-booting?
And also my windows is 32 bit and linux is going to 64 bit.This isn't gonna pose any problems right?(my hardware is 64 bit capable)

A: You can create an extended partition to contain all partitions (except Windows) as logical partitions. An extended partition counts as one primary partition and a logical partition can boot Linux and not Windows.
So the drive should look like:

*

*Primary - Windows

*Primary - Extended

*
*

*Logical - Ubuntu

*
*

*Logical - Swap

*
*

*Logical - Data 1

*
*

*Logical - Data 2

*
*

*Logical - Data 3


text:
Q: How to handling cookies to keep user logged in with Swift? Im new to Swift and not very advanced.
I have WKWebView that loads my school's Moodle page. I log in and do stuff inside, but after I kill the app and start it again; it asks for the log in details again, instead of staying logged in.
I tried with a different website (youtube) and it keeps me logged in even after I kill the app. So Im assuming its in the way website cookies work
This is the response I get from the request.
    Optional(<NSHTTPURLResponse: 0x14f734f10> { URL: https://moodle.ucl.ac.uk/ } { status code: 200, headers {
"Accept-Ranges" = none;
"Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, no-transform";
Connection = close;
"Content-Language" = en;
"Content-Script-Type" = "text/javascript";
"Content-Style-Type" = "text/css";
"Content-Type" = "text/html; charset=utf-8";
Date = "Wed, 02 Dec 2015 14:35:47 GMT";
Expires = "Mon, 20 Aug 1969 09:23:00 GMT";
"Last-Modified" = "Wed, 02 Dec 2015 14:35:47 GMT";
Pragma = "no-cache";
Server = "Apache/2.2.15 (Red Hat)";
"Set-Cookie" = "MoodleSessionuclmoodle2=pn5n2akomeen3qgkjdel5fspv2; path=/; secure";
"Transfer-Encoding" = Identity;
"X-Frame-Options" = sameorigin;
"X-UA-Compatible" = "IE=edge";

A: You can use NSDefaultUser or Keychain to store user logged in and once they tapped just delete the key.
NSUserDefault
Now this method is good if you want to keep your data live as long as the app is installed, once the app is removed this will reset automatically. You also have the option to update the value of the key if you wish, here is how you do NSUserDefault:
I always like to register my NSUserDeafult to default setting,  a lot of people just continue with the second step without registering.
Register NSUserDefault in AppDelgate.swift
NSUserDefaults.standardUserDefaults().registerDefaults(["valueName": AnyObject])

Set Value to your NSUserDefault, this depends on what type of data you're storing, should match the one with your registration if you did register. (Example of Boolean data type below)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "valueName") //Bool Data Type

Make sure you synchronize once you set the value to the NSUserDefault, this way it will update instantly, otherwise it will update when it get a chance.
NSUserDefaults.standardUserDefaults().synchronize()

Receive Value: this will receive boolean value since we set boolean and register boolean.
let Variable: Bool! = NSUserDefaults.standardUserDefaults().boolForKey("valueName")

Keychain,
Sergey Kargopolov will walk you through how to use a third party to use swift keychain. Otherwise, you can take even harder challenge and create one yourself.

Please ask any question you may have. :)


text:
Q: How are entities stored in unreal engine 3? I am currently trying to create a hack for Borderlands 2. One of the features I am trying to create is a Kill All feature which will iterate through each entity saved to my vector entity struct and set their health to 0. This is easy for me to do on other games but I am having major trouble on this game.
I found a pointer that shows me the true health value of the entity I am looking it but I noticed that in certain regions of the map the addresses change vastly. For example, I may find 7-8 entity's near me that start with the same address (Ex. 0x79C8000+)
But after I leave to go to another area the entity's I find here are vastly different in memory location. (Ex. 0x01CD0000+)
And I understand that such a large map would require things like that to happen, especially if I move to far away from a certain region of entity's they are unloaded from the world and the address value is set to 0 and no longer correctly points to the entity's health when I move back to said region and they are loaded back in.
The things that bothers me is that there has to be an array that stores every entity that is CURRENTLY loaded in memory, regardless if its just an object entity and non NPC because I'm almost certain there is one because other people are able to find it.
Any ideas??


text:
Q: Identify all outliers from regression analysis I have a file with about 17000 rows and I preformed a simple linear regression on
    Gene_id expA expB
    GeneA 5.462109    5.006181
    GeneB 2.667692    4.208152
    GeneC 4.796976    4.122660
    GeneD 3.127125    3.676322
    GeneE 4.500583    4.104575
    GeneF 4.598430    4.853717

And I preformed the regression analysis using
plot(log2(data$expA)~log2(data$expB))
regression <- lm(log2(moved.data$expA)~log2(moved.data$expB))
abline(regression)

I am interested in what Genes which are outliers are from my regression analysis.
I tried using the identify(log2(data$expA)~log2(data$expB), row.names(data)) function but I have a lot of points in my graph so to go click over them one by one doesn't seem feasible to me.
I also looked here:
Outliers with robust regression in R
but that doesn't tell me how to figure out the Gene names of the outliers

A: Aren't you really interested in the residuals (how much the results for each gene differs from the regression)? Residuals tell you how closely your data fits your model. In this case, you have a simple linear model. Having many large residuals would indicate that you need a better model.
I would never remove outliers if at all possible. If you do remove them, please be honest and report that they were removed and the criteria for their removal. To be completely honest and transparent, make your data and R script available.
Anyway, keeping what I just said in mind, here is a way to name the "outliers":
# Create sample data
Gene_id <- c("GeneA", "GeneB", "GeneC", "GeneD", "GeneE", "GeneF")
expA    <- c(5.462109, 2.667692, 4.796976, 3.127125, 4.500583, 4.598430)
expB    <- c(5.006181, 4.208152, 4.122660, 3.676322, 4.104575, 4.853717)

# Calculate log base two for results from each experiment
log2_A <- log2(expA)
log2_B <- log2(expB)

# Plot data
plot(log2_A~log2_B)

# Calculate and display the regression line
regression <- lm(log2_A~log2_B)
abline(regression)

# Show regression formula
print(regression)

# Create data frame for sample data
data <- data.frame(Gene_id, expA, expB)

# Calculate residuals
data$residuals <- residuals(regression)

# Choose a threshhold
outlier_threshold <- 0.3

# Print only names of outliers
outliers <- data[ abs(data$residuals) > outlier_threshold, ]
print(outliers$Gene_id)


text:
Q: Check string for substring with "Wild Character" Is it possible to check a string for a substring plus a wild character?
I am checking a url for a substring and I know there is the substring function but I am wondering if you can use the * character?  Below is my function so far.
function press_getUrl(){

$valid = true;
$current_url = $_SERVER['REQUEST_URI'];
//This is where I am checking for a substring plus whatever is after.
if ($current_url == "/search/node/*"){$valid = false;}

return $valid;

}

$pressValid = press_getUrl();

A: You don't need no wild characters for substring.
function press_getUrl(){
  return (strpos($_SERVER['REQUEST_URI'], "/search/node/") === 0);
}

However, I see no use for such a function at all. what you're trying to get?
It would make sense for me if it was at least
function press_check_url($check){
  return (strpos($_SERVER['REQUEST_URI'], $check) === 0);
}

and then called
if (press_check_url("/search/node/"))...

but I am not sure of the use of this function.
also a note on the name. your function  return no urls. so, don't use "get" in it's name.
and don't mix naming conventions.

A: This code checks if string starts with /search/node/:
if (strpos($current_url, "/search/node/") === 0){$valid = false;}

A: No, you cannot. Use strpos() or similar for that example.
If you want to do more complex matching (wildcards in the middle of strings, et cetera), you can use regular expressions.

A: You just search for position of /search/node, if position != 0, this statements fails
if (0 === strpos($current_url, "/search/node/")) return false; else return true;


text:
Q: Reactive Styled Templates with Parameterised Async Pipe I would like to change my code towards a Reactive style, however I am struggling with the syntax when attempting to pass through parameters within the async pipe to an Observable.
My current working code that is not Reactive (stydent.component.ts):
deleteStudent(id: number) {
  this.uniCrudService.deleteStudent(id)
  .subscribe( res => {
    console.log(`deleteStudent: ${JSON.stringify(res)}`);
    this.getStudents();
  });
}

In my student.component.html template I am calling the deleteStudent like:
Delete

The problem is that I need to use the async pipe on an observable function that receives a parameter (for a Reactive style?).
For example:
deleteStudent(id: number): Observable<Student> {
return this.deleteStudent$ = this.uniCrudService.deleteStudent(id)
  .pipe( tap (res => {
    console.log(`deleteStudent: ${JSON.stringify(res)}`);
    this.getStudents();
  }));

and in the template:
Delete

However this throws the error: Cannot have a pipe in an action expression. Looking at this answer I am understanding that I cannot make this piece of my code Reactive, and I will be forced to keep the unwanted subscription. Is this the case? How do I make my deleteStudent Reactive and get rid of the subscription?

A: I think you have a design issue there. The deleteStudent(id: number) is an event handler, so it should not return any values or have any subscribers. Your initial code is correct.
If you want a more "reactive" approach you could create a Subject:
public students$: Subject<any>;

constructor(){
   this.students$ = new Subject<any>();
}

ngOnInit() {
   this.students$.subscribe(() => {
      // do something with students
   });
}

deleteStudent(id: number) {
 this.uniCrudService.deleteStudent(id)
 .subscribe( res => {
   console.log(`deleteStudent: ${JSON.stringify(res)}`);
   this.students$.next();
 });


text:
Q: A more agile alternative to Java EE In a nutshell, I'm trying to find a process/technology stack for web applications development, that is easy/fast/flexible to prototype, but has a clear upgrade path to a robust production platform.
I apologize for a lengthy description below, but the problem is between the tech and the process and I can't find any easy/short way to express it. And yes I read "Good Subjective, Bad Subjective" article.
Currently we are using Java EE with all the blows and whistles (agile, continuous integration, issue tracking, unit testing, hibernate/spring/stripes/jquery stack ...). We also use a flexible project definition/analysis process with feature gathering in parallel with GUI mockups (kudos to Balsamiq Mockups) creation and later HTML static pages prototype. During the development, we do frequent intermediate builds with client reviews. So once we get to the testing phase the functionality is 90% on target and all is needed is some bugfixing and the final robustness polish.
For our traditional clients ie banks and pharmaceuticals, the above process/technology stack works like a charm.
Lately though, we are developing for the internet startups. In this case the process is quite different. We start with some basic mockups, then the first very raw prototype is made (lots of static pages + some basic functionality to cover the core scenarios). Then we start developing the full blown application.
Critical step here! When the application goes public, the marketing/business guys receive the feedback from the early birds, observe competition, they make their conclusions and want to change the application. A LOT!
But at this point we are not in the prototype mode any more, we have a nice robust, production quality Java EE application with hundreds of unit test built in. We can evolve it, but it certainly is neither easy nor agile.
1) On the process side, we tried to nail down the spec with all the visual and formal tools available, but in vain; nobody is able to fix the spec before the market speaks.
2) We tried more "flexible" environments like RubyOnRails and PHP.
2.a) For the production grade quality, those still seem a little bit week compared to Java EE (yes, I know that some of the most important services/apps are written in PHP)
2.b) If we use them in "flexible" way, they are great for prototyping, but then we obtain the code that is difficult to rise to the production quality.
2.c) If we implement all the best practices (layering, unit testing ...), the complexity becomes comparable to the standard Java EE's complexity that we already have.
3) When the app goes live, it has to be polished and robust, so an easy to make prototype is no option.
4) If we propose to make a throwaway prototype, the client refuses to see it as a throwaway and asks to bring it to production quality (not willing to pay the start-from-scratch development).
So basically, we are putting "quality" (intending structure, robustness) too early in the process, when it is not needed and when it stays in the way of change and flexibility.
Any ideas?

A: Become flexible.
Seriously, you also need to look at yourself and the team, rather than just the 'technology stack'.
Many have stood where you are, just take the leap and take on a 'flexible' alternative.
You'll be surprised with the power you can yield. We all know that with power comes responsibility so its not just knowing about how to use a tool. Its a lot more than just that.
It may be that you don't need an alternative, you just need to dig deep into your current troubles and fix them. Isn't that what we're supposed to do? Improve our craftsmanship?
Oh, its not just the internet start ups, the banks and pharmaceuticals you mention are also moving to the flexible alternatives.


text:
Q: Number of occurrences of the digit 1 in the numbers from 0 to n We have a function:
$f(n)$ = number of occurrences of the digit $1$ in the numbers from $0$ to $n$.
Example: $f(12) = 5$
It is obvious that $f(1)=1.$
Question: Which is the next number for which $f(n) = n$?

A: So I dug up my notes on this problem (for those interested this is project euler problem # 156) There is an analytical form for the solution to this problem (but alas, even the analytical form is too slow to solve the big problem, which requires finding ALL numbers that satisfy this condition for ALL digits 1-9). I will state my result first (to avoid hiding it in the text) and provide explanation for it after.
SOLUTION
Define a list representation of a number $n$ to be (following a notation I borrowed from continued fractions)
$$n = r_k*10^k + r_{k-1}*10^{k-1} + ... + r_0*10^0 \equiv [r_k,r_{k-1},...,r_0]$$
The function $f(d,n)$ which gives the number of occurances of a digit $d$ up to the number $n$ is given by
$$ f(d,n) = \sum_{j=0}^k\left(\sum_{i=0}^{r_j} (10^j\delta_{i-1,d})+ r_jE(j)  +\delta_{r_j,d}(n[j:]+1)\right)$$
where the notation $n[j:]$ is used to signify the number formed by the last $j$  digits  (e.g. for $n=1234=[1,2,3,4]$, $n[1] = 4$, $n[3] = 234$) and $E(j) = j*10^{j-1}$
Typing this into mathematica (and checking ($f(1,n) = n$ gives the next result of $\mathbf{199981}$).
NOTE: This can be generalized even further to any base $B$ by replacing occurrences of $10^k$ with $B^k$
MOTIVATION
First observe that in the number  0-9 any digit appears only 1 time.
In the numbers 0-99 any digit appears 10 + 10 times (10 times as the ones digit and 10 times in the range x0-x9)
In the numbers 0-999 any digit appears 20*10+100 = 300 times (20 times in each range of 100+ plus 100 in the range x00-x99)
It is not difficult to prove that this pattern continues, for any number given as $10^k-1$ there are $k*10^{k-1}$ appearances of any digit in that range.
This motivates my definition of the function
$$E(j) = j*10^{j-1}$$
However, the number given is unlikely to be as nice as $10^k-1$ we have to learn a clever way to add up the parts of that range. For a number (given in the above notation) like $[4,0,0,0]$. We see that the range $0-999$ occurs 4 times ($0-999$,$1000-1999$,$2000-2999$,$3000-3999$. So we are left with $4*E(3) = 1200$ occurrences of the digit $1$ (this motivates the $r_jE(j)$ term). However, in the range 1000-1999 the digit one occurs an extra 1000 (or $10^j$) times, this extra term only happens if $r_j$ is greater then the digit we are summing over (e.g. if we are adding occurrences of the digit $9$ the answer would be 1200 and not 2200), the best way I could think of to express this conditional statement analytically was with the sum $\sum_{i=1}^{r_j}(10^j\delta_{i-1,d})$
Calculating a number like $[4,1,2,4]$ is not much more difficult, we simply iterate over the sequence $[4,0,0,0]$, $[3,0,0]$, $[2,0]$,$[4]$ following the formula in the previous paragraph. However, the method above will miscount because it ignores the extra occurrence of the digit $1$ in the range $4100-4124$. So at every step of the iteration we have to make sure there aren't any tails that we are forgetting to count, which motivates the $\delta_{r_j,d}(n[j:]+1)$ term.

A: Ok this is simple to do with Mathematica.
For[i = 0; j = 0, i <= 200000,
 i++, j += (Plus @@ Cases[IntegerDigits[i], 1]); If[j == i, Print[i]]]

The result is
0,1,199981,199982,199983,...,199990,200000

Therefore the number you search has to be 199981.

A: I think I have the beginning of an idea to solve this. We can start by noticing that $f(10^{n+1}-1)= 1+10^n+10\times f(10^n-1)$ because when you list all the numbers from 1 to $10^{n+1}$ you get: 1... $10^n-1$, $10^n$,..., 1999...99, 20...00,...$10^{n+1}-1$. from  $10^n$ to 1999...99 you can see $10^n+f(n)+1$ the digit '1', and from 20...00 to $10^{n+1}-1$ you get $9\times f(10^n-1)$ the digity '1'.
So let's call  $u_n=10^n-1$ and $v_n=f(u_n)$.
I can see that $u_9 >v_9$ and $u_{10} < v_{10}$, so the anwswer should be in beetween (or at least smaller than $10^{10}-1$.


text:
Q: C# Passing cast arrays to receiver of array of dynamic type array Okay, so I had something working at one point, but all my old test code has been accidentally deleted, and I can't get this working again...  Help!
I have a function in a library:
public int SetData( dynamic[] p_a )
    {
    int successful_count = 0;
    int _save_selected_row;

    //It goes on...
    }

The users will call this function, and I thought I remembered it being called this way:
    struct MyStruct
        {
        public String Name;
        public String Home_Address;
        }
    MyStruct[] UseArray = new MyStruct[2];

    private void button1_Click(object sender, EventArgs e)
        {
        UseArray[0].Name = "Override name 1";
        UseArray[0].Home_Address = "Override address 1";
        UseArray[1].Name = "Override name 2";
        UseArray[1].Home_Address = "Override address 2";

        ncflsDisplay1.SetData( UseArray );
        }

But I get the error "Cannot convert from MyStruct[] to dynamic[]".
Same error for
ncflsDisplay1.SetData( (dynamic[]) UseArray );

I know I had something like this working a month ago, but in a code clean-up, my test programs got deleted.
Any idea what the call the user will need to make would have to look like to call "SetData" with an array of whatever type they have?
Update:
Got it working with this monstrosity, but I know I didn't have to do this before...
 UseArray.Cast<dynamic>().ToArray()

There was much cleaner code at one point - like a simple call using UseArray, but that doesn't work now.
Marked as duplicate because the one who marked it says we should use classes instead of structures, and using classes to pass objects of subclasses is well documented. While the suggestion is well intentioned, it is not applicable here.
First solution has been overtaken by events. We have a newer solution!
Changed the parameters of the display function to
 public int SetData<T>( T[] p_a )

which allows a call by the user of
ncflsDisplay1.SetData( UseArray );

A: If you really have to use that function and can't update its signature, you can try copying the array:
MyStruct[] UseArray = new MyStruct[2];

dynamic[] newArr = new dynamic[UseArray.Length];

Array.Copy(UseArray, newArr, UseArray.Length);

SetData(newArr);

Otherwise you can change it to something like SetData<T>(T data) or SetData(object data)

A: Well, we're moving forward with this, even though I know I didn't have to do this before.
UseArray.Cast<dynamic>().ToArray()

Newer solution: See end of the edited question, but basically it's now
public int SetData<T>( T[] p_a )

so the call is a simple
ncflsDisplay1.SetData( UseArray );


text:
Q: Why same fonts looks blurred in Google Chrome and Safari compare to Firefox? I am developing site using Drupal CMS. To check the look and feel I often check in firefox, Chrome and Safari. But I always find that the fonts looks deem and blurred in Chrome and safari compare to Firefox as you can see in following images.
Is there any solution for that? Thanks.
Chrome: Version 52.0.2743.116 (64-bit)

Sarafi: Version 9.1.2 (11601.7.7)

Firefox: 48.0


text:
Q: woocommerce product attributes empty I am having problems understanding the following:
I created a custom field in the woocommerce products by the code below.
The custome field shows up and I can fill it as expected.
I don't know how to access the data though.
if I call $product->get_attributes() it returns an empty array.
when I echo $product though I get an json like return value where all expected values are presented.
But how do I access them?
Thanks in advance
function
 woocom_general_product_data_custom_field() {
  // Create a custom text field

  // Textarea
  woocommerce_wp_textarea_input(
     array(
       'id' => '_textarea',
       'label' => __( 'textarea' ),
       'placeholder' => '',
       'description' => __( '',
'woocommerce' )
     )
 );

}
add_action(
'woocommerce_process_product_meta',
'woocom_save_general_proddata_custom_field' );

function woocom_save_general_proddata_custom_field( $post_id ) {

  // Save Textarea
  $textarea = $_POST['_textarea'];
  if( ! empty( $textarea ) ) {
     update_post_meta( $post_id, '_textarea', esc_html( $textarea ) );
  }
}

A: got it now.
I found the info in
$product->get_meta('_textarea');

not in the attributes


text:
Q: how to reset recipient list from javax.mail.internet.MimeMessage I have a scenario in which I need to send bulk emails to senders. I can send only 10 mails at a time.
So I set all my mail contents in variable and then add only ten recipients at a time.
Then after I send email, I again add ten next receipients to it.
private void addRecipients(Message pMessage, List pRecipients, Message.RecipientType pType, int pNum, int pOffset, int pBulkSize){
for (int i = 0; i < pRecipients.size(); i++) {
        int offset = pNum + i;
        if (pBulkSize != 0 && (offset < pOffset || offset >= pOffset + pBulkSize)) {
            continue;
        }
Address a;
Object r = pRecipients.get(i);
pMessage.addRecipient(pType, a);
}

But the problem is I am not able to remove the last ten receipients from the variable.
Transport.send(message);

After this line, my loop restarts and again the addRecipients method is called. But now the object
MimeMessage message = getIntialEmailConfiguration();

message  has previous recipients as well.
I want to know how to reset that one property and remove existing recipients.

A: Use the Message.setRecipients which will remove and apply multiple addresses.
Your code example won't compile because 'Address a' is never assigned a value.


text:
Q: How to Align Banner Ad to bottom of screen in JetPack Compose I am trying to position a composable to remain at the bottom of the screen. In my case a banner ad.
I tried puting it inside a column and giving it a vertical arrangement of bottom, still no difference.
...
    Column(
            verticalArrangement = Arrangement.Bottom,
            modifier = Modifier
                .fillMaxWidth()
        ) {
            // calling method to display banner UI
            AdvertView()
        }
...

For some reason this doesn't show the banner ad.

I even tried using weights (which I'm not familiar with) still no difference.
AdvertView(Modifier.weight(1f))

@Composable
fun HomeText() {
    Column(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                //.fillMaxHeight()
        ) {
            Text(
                text = stringResource(R.string.home_text),
                style = MaterialTheme.typography.h2,
                modifier = Modifier
                    .paddingFromBaseline(top = 24.dp, bottom = 18.dp)
                    .padding(horizontal = 18.dp)
                    .heightIn(min = 56.dp)

            )
        }
        AdvertView(Modifier.weight(1f))
    }
}

For some reason this actually makes the banner ad come down a little but still not there yet.

I'd like to think I'm the one not including something or doing something wrong. If that's the case please I'd appreciate your correction. Or if not, I'd like to know how to position the banner at the bottom of the screen.
Please remember this is a banner ad so it overlays the content at the bottom, I think. (this is my first time.. I stand corrected)
Thanks for your help in Advance.. I sincerely appreciate it. Thanks.

A: You have to use a Column and then set the main content's modifier to use weight(1f) and then add the banner after the main content. Using weight will ensure that the content takes all available space after the banner has been measured.
@Preview(widthDp = 420)
@Preview(widthDp = 420, uiMode = UI_MODE_NIGHT_YES)
@Composable
private fun ComposeSandboxPreview() {
    Theme {
        Surface(color = Theme.colors.background) {
            Column(
                modifier = Modifier.fillMaxSize(),
            ) {
                Content(
                    modifier = Modifier
                       .fillMaxWidth()
                        .weight(1f),
                )
                AdvertView(modifier = Modifier.fillMaxWidth())
            }
        }
    }
}

@Composable
fun Content(modifier: Modifier = Modifier) {
    Box(
        modifier = modifier.background(Color.Red),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "This is the content"
        )
    }
}

@Composable
fun AdvertView(modifier: Modifier = Modifier) {
    Text(
        text = "This is the banner",
        textAlign = TextAlign.Center,
        modifier = modifier.background(Color.Blue),
    )
}


text:
Q: python assistance with 'if filename[-4]=="B" ' can anyone tell me what the purpose of the if filename[-4]=="B" is in an if statement in some code I came across plz?
(Using py 2.7.5)
Cheers, Peter

A: This somewhat depends on the context, but it effectively means "the element of the variable 'filename' at the fourth position from the end."
So, if filename is a string with the value of 'Test string.' then filename[-4] will be 'i'.
In this particular case, the expression would evaluate to False, because "i" is not "B".

A: negative index in python refers to reverse indexing. i.e) Traversing the string/list in a reverse manner
Eg)
>>> a="hello"
>>> a[-1]
'o'
>>> a[-2]
'l'

So, a[-4] refers to the fourth character from the last. In your example, the fourth element from the last is checked to be 'B'. The if block is executed if filename[-4] is 'B'


text:
Q: Center Alignment breaks in IE version only I want to center align menu on an overlay, which is working fine in Chrome & FF, but same breaks in IE 11, i am not sure if this issue is due to latest version of IE.
Not sure why it breaks in IE http://jsbin.com/wobumugaxi/edit?html,css,output
I want to center align menu simply

*overlay*/
.overlay {
display:none;
position:fixed;
top:0;
height:100%;
width:100%;
background:rgba(0,0,0,0.70);
overflow:auto;
z-index:9999;
}
body{background-color:green;}
/*.wrap {
color:#fff;
text-align:center;
max-width:100%;
margin:0 auto;
width:100%;
}*/
.wrap {
align-items: center;
color: #fff;
display: flex !important;
height: 100% !important;
margin: 0 auto;
max-width: 100%;
text-align: center;
width: 100%;
}
/*.wrap ul.wrap-nav {
border-bottom:0px solid #575757;
text-transform:capitalize;
padding:150px 0px 100px;
}*/
.wrap ul.wrap-nav {
border-bottom: 0 solid #575757;
display: table-cell;
height: 170px;
margin: auto !important;
padding: 0;
position: relative !important;
text-transform: capitalize;
}
.wrap ul.wrap-nav li {
font-size:14px;
text-transform:uppercase;
display:inline-block;
vertical-align:top;
width:70px;
padding:14px;
position:relative;
margin:0 7px;
}

.menu-img{
border-radius:100px;
width:60px
}
.wrap ul.wrap-nav li a {
font-family:"Lato",sans-serif;
font-weight:600;
color:#fff;
display:block;
padding:10px 0;
width:60px;
text-decoration:none;
transition-property:all .2s linear 0s;
-moz-transition:all .2s linear 0s;
-webkit-transition:all .2s linear 0s;
-o-transition:all .2s linear 0s;

}
.wrap ul.wrap-nav li a:hover {
color:#f0f0f0;
}
.wrap ul.wrap-nav ul {
padding:20px 0;
}
.wrap ul.wrap-nav ul li {
display:block;
font-size:13px;
width:100%;
color:#e9e9e9;
}
.wrap ul.wrap-nav ul li a {
color:#f0f0f0;
}
.wrap ul.wrap-nav ul li a:hover {
color:#34B484;
}
.footer-hp{
background-color:#282F20;
width:100%;
height:28px;
position:absolute;
bottom:0;
text-align:center;
font-size:13px;
font-family:"Josefin Sans","Roboto Condensed",sans-serif !important;
color:#fff;
padding:3px;
}
.footer-hp p{
margin:0;
margin-top:2px;
}
.home-h1{
color: #fff !important;
font-size: 50px !important;
font-weight: 500;
margin-top:0px;
-vendor-animation-duration: 3s;
-vendor-animation-delay: 3s;
-vendor-animation-iteration-count: infinite;
}
.home-h3{
color: #fff !important;
-vendor-animation-duration: 3s;
-vendor-animation-delay: 3s;
-vendor-animation-iteration-count: infinite;
}
.nivo-lightbox-theme-default.nivo-lightbox-overlay {
background: rgba(0, 0, 0, 1) none repeat scroll 0 0;
}
.nivo-lightbox-theme-default .nivo-lightbox-close {
display: block;
text-indent: -9999px;
}
.nivo-lightbox-theme-default a.nivo-lightbox-close::before, .nivo-lightbox-theme-default a.nivo-lightbox-close::after {
background-color: #000;
content: " ";
height: 33px;
left: 15px;
position: absolute;
width: 0px;
}
.btnplayvideo{
background-color:#fff;
padding:7px 30px;
color:#000;
font-size:14px;
display:inline-block;
}
.btnbrochure{
background-color:#fff;
padding:7px 30px;
color:#000;
font-size:14px;
display:inline-block;
}

Home

 One

Two

Four

Three

A: Change This CSS
.wrap ul.wrap-nav {
border-bottom: 0 solid #575757;
display: block;/*Remove table-cell*/
}

/*overlay*/
.overlay {
display:none;
position:fixed;
top:0;
height:100%;
width:100%;
background:rgba(0,0,0,0.70);
overflow:auto;
z-index:9999;
}
body{background-color:green;}
/*.wrap {
color:#fff;
text-align:center;
max-width:100%;
margin:0 auto;
width:100%;
}*/
.wrap {
align-items: center;
color: #fff;
display: flex !important;
height: 100% !important;
margin: 0 auto;
max-width: 100%;
text-align: center;
width: 100%;
}
/*.wrap ul.wrap-nav {
border-bottom:0px solid #575757;
text-transform:capitalize;
padding:150px 0px 100px;
}*/
.wrap ul.wrap-nav {
border-bottom: 0 solid #575757;
display: block;
height: 170px;
margin: auto !important;
padding: 0;
position: relative !important;
text-transform: capitalize;
}
.wrap ul.wrap-nav li {
font-size:14px;
text-transform:uppercase;
display:inline-block;
vertical-align:top;
width:70px;
padding:14px;
position:relative;
margin:0 7px;
}

.menu-img{
border-radius:100px;
width:60px
}
.wrap ul.wrap-nav li a {
font-family:"Lato",sans-serif;
font-weight:600;
color:#fff;
display:block;
padding:10px 0;
width:60px;
text-decoration:none;
transition-property:all .2s linear 0s;
-moz-transition:all .2s linear 0s;
-webkit-transition:all .2s linear 0s;
-o-transition:all .2s linear 0s;

}
.wrap ul.wrap-nav li a:hover {
color:#f0f0f0;
}
.wrap ul.wrap-nav ul {
padding:20px 0;
}
.wrap ul.wrap-nav ul li {
display:block;
font-size:13px;
width:100%;
color:#e9e9e9;
}
.wrap ul.wrap-nav ul li a {
color:#f0f0f0;
}
.wrap ul.wrap-nav ul li a:hover {
color:#34B484;
}
.footer-hp{
background-color:#282F20;
width:100%;
height:28px;
position:absolute;
bottom:0;
text-align:center;
font-size:13px;
font-family:"Josefin Sans","Roboto Condensed",sans-serif !important;
color:#fff;
padding:3px;
}
.footer-hp p{
margin:0;
margin-top:2px;
}
.home-h1{
color: #fff !important;
font-size: 50px !important;
font-weight: 500;
margin-top:0px;
-vendor-animation-duration: 3s;
-vendor-animation-delay: 3s;
-vendor-animation-iteration-count: infinite;
}
.home-h3{
color: #fff !important;
-vendor-animation-duration: 3s;
-vendor-animation-delay: 3s;
-vendor-animation-iteration-count: infinite;
}
.nivo-lightbox-theme-default.nivo-lightbox-overlay {
background: rgba(0, 0, 0, 1) none repeat scroll 0 0;
}
.nivo-lightbox-theme-default .nivo-lightbox-close {
display: block;
text-indent: -9999px;
}
.nivo-lightbox-theme-default a.nivo-lightbox-close::before, .nivo-lightbox-theme-default a.nivo-lightbox-close::after {
background-color: #000;
content: " ";
height: 33px;
left: 15px;
position: absolute;
width: 0px;
}
.btnplayvideo{
background-color:#fff;
padding:7px 30px;
color:#000;
font-size:14px;
display:inline-block;
}
.btnbrochure{
background-color:#fff;
padding:7px 30px;
color:#000;
font-size:14px;
display:inline-block;
}

Home

 One

Two

Four

Three

A: you simply need to add display: -ms-flexbox; to your .wrap class

*overlay*/
.overlay {
display:none;
position:fixed;
top:0;
height:100%;
width:100%;
background:rgba(0,0,0,0.70);
overflow:auto;
z-index:9999;
}
body{background-color:green;}
/*.wrap {
color:#fff;
text-align:center;
max-width:100%;
margin:0 auto;
width:100%;
}*/
.wrap {
align-items: center;
color: #fff;
display: flex !important;
display: -ms-flexbox; /* to support IE */
height: 100% !important;
margin: 0 auto;
max-width: 100%;
text-align: center;
width: 100%;
}
/*.wrap ul.wrap-nav {
border-bottom:0px solid #575757;
text-transform:capitalize;
padding:150px 0px 100px;
}*/
.wrap ul.wrap-nav {
border-bottom: 0 solid #575757;
display: table-cell;
height: 170px;
margin: auto !important;
padding: 0;
position: relative !important;
text-transform: capitalize;
}
.wrap ul.wrap-nav li {
font-size:14px;
text-transform:uppercase;
display:inline-block;
vertical-align:top;
width:70px;
padding:14px;
position:relative;
margin:0 7px;
}

.menu-img{
border-radius:100px;
width:60px
}
.wrap ul.wrap-nav li a {
font-family:"Lato",sans-serif;
font-weight:600;
color:#fff;
display:block;
padding:10px 0;
width:60px;
text-decoration:none;
transition-property:all .2s linear 0s;
-moz-transition:all .2s linear 0s;
-webkit-transition:all .2s linear 0s;
-o-transition:all .2s linear 0s;

}
.wrap ul.wrap-nav li a:hover {
color:#f0f0f0;
}
.wrap ul.wrap-nav ul {
padding:20px 0;
}
.wrap ul.wrap-nav ul li {
display:block;
font-size:13px;
width:100%;
color:#e9e9e9;
}
.wrap ul.wrap-nav ul li a {
color:#f0f0f0;
}
.wrap ul.wrap-nav ul li a:hover {
color:#34B484;
}
.footer-hp{
background-color:#282F20;
width:100%;
height:28px;
position:absolute;
bottom:0;
text-align:center;
font-size:13px;
font-family:"Josefin Sans","Roboto Condensed",sans-serif !important;
color:#fff;
padding:3px;
}
.footer-hp p{
margin:0;
margin-top:2px;
}
.home-h1{
color: #fff !important;
font-size: 50px !important;
font-weight: 500;
margin-top:0px;
-vendor-animation-duration: 3s;
-vendor-animation-delay: 3s;
-vendor-animation-iteration-count: infinite;
}
.home-h3{
color: #fff !important;
-vendor-animation-duration: 3s;
-vendor-animation-delay: 3s;
-vendor-animation-iteration-count: infinite;
}
.nivo-lightbox-theme-default.nivo-lightbox-overlay {
background: rgba(0, 0, 0, 1) none repeat scroll 0 0;
}
.nivo-lightbox-theme-default .nivo-lightbox-close {
display: block;
text-indent: -9999px;
}
.nivo-lightbox-theme-default a.nivo-lightbox-close::before, .nivo-lightbox-theme-default a.nivo-lightbox-close::after {
background-color: #000;
content: " ";
height: 33px;
left: 15px;
position: absolute;
width: 0px;
}
.btnplayvideo{
background-color:#fff;
padding:7px 30px;
color:#000;
font-size:14px;
display:inline-block;
}
.btnbrochure{
background-color:#fff;
padding:7px 30px;
color:#000;
font-size:14px;
display:inline-block;
}

Home

 One

Two

Four

Three


text:
Q: Present Continuous instead of Present Perfect Continuous? Is it possible to simplify sentences like:

"I've been having soy milk for 10 yrs now"
"I've been standing here for an hour"*

into:

"I'm having soy milk for 10 yrs now"
"I'm standing here for an hour"?

Seems like I've just heard something like that on TV, but I may have missed or misheard the "vbin" part.

A: You cannot do that without changing the meaning.
The present perfect continuous gives a sense of a continuing thing you've done on and off in the past up until now.
The present continuous makes the sentence mean that you are intending to do this activity for the specified time period.
In other words:
You are going to drink soy milk for 10 years (from this point forward).
You are going to stand here for one hour (from this point until one hour has passed).
You may hear this colloquially, though.

A: The second form works in other languages like French and German, but is not idiomatic English (certainly not British English and probably not American English either).
In fact it sounds like a slightly imperfect translation from a non-native speaker of English.


text:
Q: what are the inner angles of a tetragonal trapezohedron I am making a 3D wooden lantern in the shape of a Tetragonal Trapezohedron. Think of a hollow Tetragonal Trapezohedron 3D object, where each face is a plank of wood. I am trying to determine the angles between the two planes, I should cut plank of wood at.
For example the kite has the following dimensions, Short edge: 236 mm, Long edge: 403 mm. Face angles: 55°, 102°, 101°, 102°. The thickness of each face is 25 mm.
I have tried cutting the long edges at 45° then taping them all together, but there is a gap, meaning that 45° is too large. The angle for the long edge should be less then 45°.
How do you determine the angle between the long edges and the short edges?

A: This site
(to which @Aretino already pointed)
lists the dihedral angles as $105.14^\circ$,
as illustrated below.
(I verified that this angle is same at every edge.)
So you should bevel at half this angle, $52.6^\circ$.

Side view illustrating the dihedral angle.

Front view of Tetragonal Trapezohedron.


text:
Q: Finding the absolute minimum of $f(x,y) = (x^2+y^2)^{1/2} *e^{-(x^2+y^2)}$ I made the substitution $x=r\cos(\theta)$ , $y =r\sin(\theta)$. And I obtained $re^{-r^2}$. I then used the first derivative test to obtain $r=+-1/(2^{1/2})$. Is this right?

A: The function being the product of two non-negative quantities is non-negative. Since f(0,0)=0, 0 is the absolute minimum and is attained at (0,0). As is written in many books, "it is left to the reader to verify that there can be no other absolute mimima."


text:
Q: Unknown provider: $uploadProvider <- $upload Anyone know why I'm getting Unknown provider on this Angular code ?
I am using the Angular File Upload directive and are using this example :
http://www.mono-software.com/blog/post/Mono/233/Async-upload-using-angular-file-upload-directive-and-net-WebAPI-service/
Just cannot seem to figure out why I'm getting this error...
module.js file :
angular.module('photoApp', ['ngRoute']);

scripts.js file :
    // configure our routes
    angular.module('photoApp').config(function ($routeProvider) {
    $routeProvider

            // route for the home page
            .when('/', {
                templateUrl: 'Pages/home.html',
                controller: 'mainController'
            })

            // route for the contact page
            .when('/uploadphoto', {
                templateUrl: 'Pages/photoupload.html',
                controller: 'photoUploadController'
            });
});

// create the controller and inject Angular's $scope

    angular.module("photoApp").controller('photoUploadController',
    function ($scope, $http, $timeout, $upload) {
        $scope.message = 'Upload your photo';

        $scope.upload = [];
        $scope.fileUploadObj = { testString1: "Test string 1", testString2: "Test string 2"
    };

        $scope.onFileSelect = function($files) {
            //$files: an array of files selected, each file has name, size, and type.
            for (var i = 0; i < $files.length; i++) {
                var $file = $files[i];
                (function(index) {
                    $scope.upload[index] = $upload.upload({
                        url: "./api/file/upload", // webapi url
                        method: "POST",
                        data: { fileUploadObj: $scope.fileUploadObj },
                        file: $file
                    }).progress(function(evt) {
                        // get upload percentage
                        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
                    }).success(function(data, status, headers, config) {
                        // file is uploaded successfully
                        console.log(data);
                    }).error(function(data, status, headers, config) {
                        // file failed to upload
                        console.log(data);
                    });
                })(i);
            }
        }

        $scope.abortUpload = function(index) {
            $scope.upload[index].abort();
        }
    });

A: Just add the dependancy on angularFileUpload and be sure to reference the JS files in the correct order, and you should be good to go
index.html
<script src="angular-file-upload-shim.min.js"></script>
<script src="angular.min.js"></script>
<script src="angular-file-upload.min.js"></script>

module.js
angular.module('photoApp', ['ngRoute', 'angularFileUpload']);


text:
Q: vis.js Chronological set of items in Timeline View Instead of having actual time mapping with the items in Timeline View, is there a way by which we can have items arranged chronologically in sequence of timestamps. This feature will help me eliminate gaps between items with greater timestamp difference.
For Example
E1: 1
E2: 6
E3: 9
Current Timeline View would represent it as
[1 - E1] 2 3 4 5 [6 - E2] 7 8 [9 - E3]
What I want is chronological order
[1 - E1] [2 - E2] [3 - E3]

A: you can achieve what you are asking for by using the hiddenDates option of the timeline
{
 "option": "hiddenDates",
 "type": "object|Array",
 "default": "none",
 "description": "This option allows you to hide specific timespans from the time axis. The dates can be supplied as an object: {start: '2014-03-21 00:00:00', end: '2014-03-28 00:00:00', [repeat:'daily']} or as an Array of these objects. The repeat argument is optional. The possible values are (case-sensitive): daily, weekly, monthly, yearly. To hide a weekend, pick any Saturday as start and the following Monday as end and set repeat to weekly."
}

In your case you can specify hiddenDates as
var options = {hiddenDates: [{start: '2', end:'6'},{start:'7',end: '9'}]}

If this doesn't answer your question, I can provide a jsfiddle with a solution.
Best regards,
Betim.


text:
Q: Read perf counters of a specific userspace process from the kernel I'm using perf to measure tlb misses of a userspace process. Then, when a system call comes, I want to read userspace misses, i have a syscall handler at the kernel and i need to read or extract from kernel module. (I don't want to use strace). I examined the task_struct and saw a variable named perf_event_ctxp. I wonder if it would be possible for me to read the miss numbers from here, I couldn't find any information in the documentation. or do you have any idea where I can read the counter values specific to a process on the kernel side (started with perf).

A: First, there is a flag for measuring only in-kernel events. From perf-record(1),
 --all-kernel
       Configure all used events to run in kernel space.

Next, there are several hardware events on x86 for different kinds of TLB misses. For example, on my machine, the following hardware events are available:
# perf list
...
dTLB-load-misses
dTLB-loads
dTLB-store-misses
dTLB-stores
iTLB-load-misses
iTLB-loads
...

So, you can use any of these events, and the --all-kernel flag. For example, if you want to measure the number of dTLB load and store misses in the kernel for ls(1), the following command should suffice:
perf record --all-kernel -e dTLB-store-misses -e dTLB-load-misses -- ls


text:
Q: Drupal 7, implement jQuery UI Combobox widget My name is Stefano.
I'd like to implement the jQuery UI Combobox widget in a Drupal 7 site.
I have jQuery Update module installed and enabled, configured with jQuery1.8 version and Google as jQuery and jQuery UI CDN.
In a random page filtered with php i put, at the top of the page, this php code:
<?php
    drupal_add_library('system', 'ui.core');
    drupal_add_library('system', 'ui.widget');
    drupal_add_library('system', 'ui.mouse');
    drupal_add_library('system', 'ui.button');
    drupal_add_library('system', 'ui.position');
    drupal_add_library('system', 'ui.autocomplete');
    drupal_add_js('themes/bartik/autocomp.js', 'file');
?>

and then, right next the php, i put the select required with relative items:
<div class="ui-widget">
<label>Your preferred programming language: </label>
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Clojure">Clojure</option>
<option value="COBOL">COBOL</option>
<option value="ColdFusion">ColdFusion</option>
<option value="Erlang">Erlang</option>
<option value="Fortran">Fortran</option>
<option value="Groovy">Groovy</option>
<option value="Haskell">Haskell</option>
<option value="Java">Java</option>
<option value="JavaScript">JavaScript</option>
<option value="Lisp">Lisp</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
<option value="Ruby">Ruby</option>
<option value="Scala">Scala</option>
<option value="Scheme">Scheme</option>
</select>
</div>

the script included at the top in php, contained in autocomp.js, copied and pasted from jQuery UI widget page, is this:
(function( $ ) {
$.widget( "custom.combobox", {
  _create: function() {
    this.wrapper = $( "<span>" )
      .addClass( "custom-combobox" )
      .insertAfter( this.element );

    this.element.hide();
    this._createAutocomplete();
    this._createShowAllButton();
  },

  _createAutocomplete: function() {
    var selected = this.element.children( ":selected" ),
      value = selected.val() ? selected.text() : "";

    this.input = $( "<input>" )
      .appendTo( this.wrapper )
      .val( value )
      .attr( "title", "" )
      .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
      .autocomplete({
        delay: 0,
        minLength: 0,
        source: $.proxy( this, "_source" )
      })
      .tooltip({
        tooltipClass: "ui-state-highlight"
      });

    this._on( this.input, {
      autocompleteselect: function( event, ui ) {
        ui.item.option.selected = true;
        this._trigger( "select", event, {
          item: ui.item.option
        });
      },

      autocompletechange: "_removeIfInvalid"
    });
  },

  _createShowAllButton: function() {
    var input = this.input,
      wasOpen = false;

    $( "<a>" )
      .attr( "tabIndex", -1 )
      .attr( "title", "Show All Items" )
      .tooltip()
      .appendTo( this.wrapper )
      .button({
        icons: {
          primary: "ui-icon-triangle-1-s"
        },
        text: false
      })
      .removeClass( "ui-corner-all" )
      .addClass( "custom-combobox-toggle ui-corner-right" )
      .mousedown(function() {
        wasOpen = input.autocomplete( "widget" ).is( ":visible" );
      })
      .click(function() {
        input.focus();

        // Close if already visible
        if ( wasOpen ) {
          return;
        }

        // Pass empty string as value to search for, displaying all results
        input.autocomplete( "search", "" );
      });
  },

  _source: function( request, response ) {
    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
    response( this.element.children( "option" ).map(function() {
      var text = $( this ).text();
      if ( this.value && ( !request.term || matcher.test(text) ) )
        return {
          label: text,
          value: text,
          option: this
        };
    }) );
  },

  _removeIfInvalid: function( event, ui ) {

    // Selected an item, nothing to do
    if ( ui.item ) {
      return;
    }

    // Search for a match (case-insensitive)
    var value = this.input.val(),
      valueLowerCase = value.toLowerCase(),
      valid = false;
    this.element.children( "option" ).each(function() {
      if ( $( this ).text().toLowerCase() === valueLowerCase ) {
        this.selected = valid = true;
        return false;
      }
    });

    // Found a match, nothing to do
    if ( valid ) {
      return;
    }

    // Remove invalid value
    this.input
      .val( "" )
      .attr( "title", value + " didn't match any item" )
      .tooltip( "open" );
    this.element.val( "" );
    this._delay(function() {
      this.input.tooltip( "close" ).attr( "title", "" );
    }, 2500 );
    this.input.data( "ui-autocomplete" ).term = "";
  },

  _destroy: function() {
    this.wrapper.remove();
    this.element.show();
  }
});
})( jQuery );

$(function() {
    $( "#combobox" ).combobox();
    $( "#toggle" ).click(function() {
      $( "#combobox" ).toggle();
    });
});

The result is this one:
Image
A normal, ugly select.
Where am I wrong?
Thanks evrybody for your help!

A: Shouldn't you targeting
$.widget('select#combobox')

on your line 2 of autocomp, instead of custom.combobox ?


text:
Q: Spring-JSON Used in Spring MVC I came across the library Spring-JSON while looking to add Ajax Support in my spring mvc webapp 2.5.
My question is, has anybody here have used this library and what are your experiences?
Is there any better alternative than this?

A: Maybe this post - http://www.jroller.com/kaiulrich/entry/a_mappingjacksonjsonview_springframework_and_spring can give you a good insight about which Json View you should choose.
UPDATE
Suppose here goes my MultiActionController
import static org.springframework.validation.ValidationUtils.*;

@Component
public class PersonController extends MultiActionController {

    /**
      * Notice my own JsonView implementation
      */
    private JsonView jsonView = new JsonView();

    public PersonController() {
        setValidators(new Validator[] {new Validator() {
            public boolean supports(Class clazz) {
                return clazz.isAssignableFrom(Person.class);
            }

            public void validate(Object command, Errors errors) {
                rejectIfEmpty(errors, "age", "", "Age is required");
                rejectIfEmptyOrWhitespace(errors, "name", "", "Name is required");
            }

        }});
    }

    public ModelAndView add(HttpServletRequest request, HttpServletResponse response, Person person) throws Exception {
        // do something (save our Person object, for instance)

        return new ModelAndView(jsonView);
    }

    /**
      * If something goes wrong (validation, data-binding)
      * This method takes care of handling "what goes wrong"
      */
    public ModelAndView hanldeBindException(HttpServletRequest request, HttpServletResponse response, ServletRequestBindingException bindingException) {
        BindException bindException = (BindException) bindingException.getRootCause();

        /**
          * Notice i am using jsonView to handle the response
          */
        return new ModelAndView(jsonView).addAllObjects(bindException.getModel());
    }

}

JsonView implementation is shown as follows
public class JsonView implements View {

    @Autowired
    private MessageSource messageSource;

    public String getContentType() {
        return "application/json";
    }

    public void render(Map model, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = response.getWriter();

        response.setContentType("text/plain; charset=UTF-8");

        JSONObject jsonObject = new JSONObject();
        for (Object object : bindingResult.getAllErrors()) {
            if(object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;

                jsonObject.put(fieldError.getField(), messageSource.getMessage(fieldError, null));
            }
        }

        writer.print(jsonObject.toString());
        writer.close();
    }

}

I hope it can be useful to you
Here you can see a nice Tutorial about Json by using DOJO (i do not use DOJO)


text:
Q: How to Loop Through formData & POST requests I'm trying to make a post request each time one of the files I have in 'this.photos' is appended to formData. Right now, I have the correct number of API calls being made, but they're all just the last photo uploaded being repeated.
My Backend doesn't allow for multiple items in one field, so I need to make as many API calls as there are files added on the frontend
<template>

        Files
        <input type="file" id="files" ref="photos" multiple v-on:change="handleFilesUpload()" />

      <button v-on:click="submitFiles()">Submit</button>

</template>

I feel like it's just something simple that I'm missing , so thanks for the help!

A: Try this:
submitFiles(axios) {
let formData = new FormData();
for (var i = 0; i < this.photos.length; i++) {
let photo = this.photos[i];

formData.append("photos", photo);
const config = {
  headers: {
    "content-type": "multipart/form-data; "
  }
};
}
this.$axios
  .post(`/api/v1/photos/`, formData, config)
  .then(response => {
    console.log("Successfully Submitted Images");
  })
 .catch(error => {
console.log(error);
});
},

A:   //let formData = new FormData();
      for (var i = 0; i < this.photos.length; i++) {
        let formData = new FormData();

Fix: Move the formData declaration inside of the for loop. If it's outside, the final photo gets queued 3 times before being posted. The fix makes sure only the photo in question is queued and sent


text:
Q: android kotlin pubnub sdk sometimes does not work I am using pubnub android kotlin sdk for chat function. However i have 3 different fragments on which i use pubnub's functions. H
ence i have created a service which listens to incomings events from pubnub and post it on fragments as a part of ui.
There are multiple channels on 3 different fragments. One fragment is for one to one messaging and another fragment is for group messaging. I subscribe channels on the each fragment whenever i open the fragment but do not unsubscribe when i leave the fragment. Currently my pubnub works well whenever i open the first fragment for one to one messaging but when i open another fragment for group messaging the listener on the first fragment stops listening to incoming messages or events.
My question here is, shall i subscribe all the channels once in the first time or subscribe each on their corresponding fragment page. Also i would like to know what is the best practice to use pubnub in android kotlin. Sharing the code is little bit difficult for me.

A: PubNub client object and SubscribeCallback listener scope
If you want to stay subscribed to the channels with each Fragment you enter and leave, you need to create your PubNub client object and * SubscribeCallback listener* at the app scope (MainActivity, perhaps, as a singleton) or some scope that is above the Fragments' scope, like the View that contains those Fragments, assuming the Fragments are in the same View, if not then move to the next highest scope (Activity).
So as you subscribe to new channels when you enter a Fragment, those channels are just added to the single subscribe request of the higher-scoped PubNub client object, and messages published to those channels will be received in the listener in that higher scope.
If you wanted to leave those channels as you leave the Fragment they belong to, of course, you can just unsubscribe from those channels.
In a nutshell, your PN client and listener need to NOT go out of scope and get GC'ed.


text:
Q: Intel intrinsics assembly code I am considering simple problem - speeding up the calculation of component-wise product of two arrays of doubles. I have noticed that using AVX commands I get only around 20% speedup, comparing to sequential multiplication in a loop.
I decided to check the latencies for the both cases and became confused with the assembly code of the load operation:
### __m256d pd;
### pd = _mm256_load_pd(a);
    movq      -112(%rbp), %rax    //Pushing the pointer to the stack
    vmovapd   (%rax), %ymm0       //Pushing 32 bytes from memory to ymm
    vmovapd   %ymm0, -80(%rbp)    //What is
    vmovapd   -80(%rbp), %ymm0    //happening here?
    vmovapd   %ymm0, -48(%rbp)    //Quite slow down, since vmovapd cost ~ vmulpd

Above is part of assembly for the following C code:
inline int test(double * a) {
    __m256d pd;
    pd = _mm256_load_pd(a);
    return 1;
}

In the description of __m256_load_pd it is said that it is done in this way:
dst[255:0] := MEM[mem_addr+255:mem_addr]
dst[MAX:256] := 0

i.e. in reverse order? But how these 2 lines of assembly code have to do anything with that?

A: It is very hard to answer this question without a bit more context, beyond compilation flags. Depending on the number of threads operating, and the size of the arrays of double, it might be that your problem is memory bound, that is performance is limited by memory access.
VERY LARGE DATA
You want to have a look at Stream benchmark. Using AVX intrinsics will help software and hardware prefetch as well as data alignment which might explain the +20%. Anyways, you will be memory bound (loading data from system memory to L1 cache), and performing operations sequantialy will be irrelevant compared to AVX operations, and probably hidden by the data loading occurring in parallel (thanks to the magic of prefetch).
DATA IN L2 CACHE
Depending on the number of concurrent threads, data may be fed at a higher pace. However, performing a mul on the data is not complex enough compute on the data to take the lead on cost of memory marshalling.
DATA IN L1 CACHE
For this case, you may see some improvement in the performance, but there might be other suprises such as execution dependency and latency induced by the L1 Cache loads. However, loading aligned data in 256bits registers is probably the best performing.


text:
Q: kexec and USE_GRUB_CONFIG I find kexec very useful to speed-up the reboot of Linux servers.
One parameter into /etc/default/kexec is USE_GRUB_CONFIG.
This parameter is meant to "read Grub configuration file". But I don't understand what governs the choice between setting it to true or false.
What I understand: in Debian, the /etc/init.d/kexec-load file contains the code used to reboot with kexec. When USE_GRUB_CONFIG is set to true, then the Grub configuration file is read and its parameters are used to reboot.
If USE_GRUB_CONFIG is set to false, then the current kernel is reloaded with its current parameters.
So USE_GRUB_CONFIG set to true always reboot with the "normal" kernel.
And USE_GRUB_CONFIG set to false always reboot without changing anything, ignoring whatever could be done to Grub.
Then I deduce I should set it to true in order to take advantage of updates into Grub config.
So why is the default value false? Am I wrong somewhere, or do most admins prefer to slow-boot with special parameters then fast-reboot with them?

A: With the default "false" the init script uses the kernel image und initrd from /etc/default/kexec. That is usually /vmlinuz and /initrd.img - normally the last installed kernel.
When you set to "true", it is parsing the /boot/grub/grub.cfg file to find the default kernel image and initrd. Mostly that is the same. When you configure your grub to use a other kernel as default (e.g. a older one) kexec cannot recognise that except you set the option to "true".


text:
Q: What is the practice for nesting xml namespaces? In programming languages, I'm used to
namespace foo
{
    namespace bar
    {
        void DoIt()
        {
        }
    }
}

int main()
{
    foo::bar::DoIt()
}

In a schema(xsd), I'd like to do similar things when defining complexTypes
<xsd:schema targetNamespace="http://www.stackoverflow.com/foo">
 <xsd:complexType name="bar1">
    ...
 </xsd:complexType>
 <xsd:complexType name="bar2">
 </xsd:complexType>
   ...
 <xsd:complexType name="foo1" type = "bar1">
   ...
 </xsd:complexType>
</xsd:schema>

Conceptually I would like bar1 and bar2 to be nested in a http://www.stackoverflow.com/foo::bar namespace (:: borrowed from C++). I've seen examples of what seems to be a completely second namespace defined for the bar stuff. In these examples, the bar stuff will be defined in a second namespace, "http://www.stackoverflow.com/foo/bar", as in the example below. This is the closest I've seen to a "nested" namespace.
So one thing I can kind of do is import the bar stuff from a different schema
<xsd:schema targetNamespace="http://www.stackoverflow.com/foo"
  xmlns:bar = "http://www.stackoverflow.com/foo/bar">
<xsd:schema namespace="http://www.stackoverflow.com/foo/bar"
 <xsd:complexType name="foo1">
   <xsd:element name="bar1Instance" type="bar:bar1"/>
   ...
 </xsd:complexType>
</xsd:schema>

Part of this is that I'm just trying to grok how namespaces are different in XML vs say C++. Is there a concept of nested namespaces in XML or is each namespace independent? How is the concept of nested namespaces implemented or typically done? Is it done like my example above? Are namespaces completely independent or is there anyway of creating a nesting relationship?

A: In XML, each namespace is entirely independent.  The actual string of a namespace is not parsed in any meaningful way.  It just is.  XML Namespace strings are typically URLs because this makes a good chance that people won't accidentally pick the same namespace for unrelated schemas.
If you Google, you will find examples of "nested XML namespaces."  These examples aren't talking about what you're asking about, not in the sense of C++ (or Java or C#...) namespaces.  These examples show XML documents with multiple namespaces in use.
An XML namespace string is simply an opaque and unique string that represents the schema.  If two namespace strings happen to be very similar, it doesn't mean anything.


text:
Q: How i can split two users in laravel? I already tried many ways, but not how I can not do the routes and redirect correctly. I want that, if the administrator comes in, they do a re-direct to the dashboard, and if this is just a user, then to home. I ran out of ideas on how to do this. Help me please
role_user_table
public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->integer('role_id');
            $table->integer('user_id');

            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->primary(['user_id', 'role_id']);
        });
    }

roles_table
1. Admin
2. Register user
public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
        });
    }

users table
Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->tinyInteger('role_id')->unsigned()->nullable();
            $table->string('name');
            $table->string('email');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('roles');
        });

Middleware
 namespace App\Http\Middleware;

 use Closure;

  class CheckIfAdmin{
  public function handle($request, Closure $next)
  {
    $user = $request->user();

    if (!isset($user)) {
        return redirect('admin/login');
    }

    if (!$user->isAdmin()) {
        return redirect('/');
    }

    return $next($request);
}

}
Kernel.php
protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\CheckIfAdmin::class,
    ];

Role.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name'];

    public $timestamps = false;

    public function users()
    {
        return $this->hasMany(User::class);
    }
}

User.php
namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Role;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function isAdmin()
    {
        return (boolean)$this->roles->where('name', 'admin')->count();
    }
}

web.php
      Route::group(['prefix'=>'admin', 'namespace'=>'Admin', 'middleware'=>
   ['auth']], function(){

      Route::resource('/category', 'CategoryController', ['as'=>'admin']);
      Route::resource('/article', 'ArticleController', ['as'=>'admin']);
      Route::group(['prefix' => 'user_managment', 'namespace' =>
   'UserManagment'], function() {
      Route::resource('/user', 'UserController', ['as' =>
    'admin.user_managment']);
      });
    Route::group(['middleware' => 'admin'], function() {
        Route::get('/', 'DashboardController@dashboard')-
   >name('admin.index');
    });
    });
    Route::get('/', function () {
        return view('blog.home');
    });

    Auth::routes();

    Route::get('/home', 'HomeController@index')->name('home');

Now he goes to the admin if the admin is registered in the url admin line, if a simple user does it, he won't miss it, but I need him to automatically throw on the dashboard. dashboard is located in the admin folder

A: Since you have most of the code already written this should work:
Route::group(['prefix'=>'admin', 'namespace'=>'Admin', 'middleware'=>['admin']], function(){
  Route::get('/', 'DashboardController@dashboard')->name('admin.index');
  Route::resource('/category', 'CategoryController', ['as'=>'admin']);
  Route::resource('/article', 'ArticleController', ['as'=>'admin']);
  Route::group(['prefix' => 'user_managment', 'namespace' => 'UserManagment'], function() {
  Route::resource('/user', 'UserController', ['as' => 'admin.user_managment']);
  });
});

Route::get('/', function () {
    return view('blog.home');
}); // Not sure if you want this behind the middleware or not

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

And I would change this line in your middleware:
if (!$user->isAdmin()) {
    return redirect('/home');
}

So that the non-admin uses are redirect to /home per your comment. There's no need to use Auth and admin middleware here since the admin one will handle non admin users. It should allow all admins to reach the group wrapped inside of the admin middleware and redirect non admins to the /home route. Let me know if this is what you were looking for or if I can refine this for you.
For the redirect issue:
check out: https://codeburst.io/learn-how-to-redirect-authenticated-users-to-corresponding-path-in-laravel-dd613e2f9e3 You can change protected $redirectTo = 'admin'; to a function: public function redirectTo(){}. It'll end up like:
public function redirectTo(){

    // User role
    $role = Auth::user()->role->pluck('name')->toArray();

    if(in_array('admin', $role)){
        return '/admin/login';
    }else{
        return '/home';
    }
}


text:
Q: how to find when the API call is finished in angular I have a API call which i have to find when its finished to start calling the second api,I dont want to set timer because its not clear when the job is done,
this.http.get(`http://localhost:44301/consentinitiation/${this.qid}`)
.pipe(retryWhen(_ => {
  this.showIt=true
  return interval(1000)
}))
.subscribe(result => {result
console.log(result);
this.qrcodelink=result["qrCodeLink"];
setTimeout(() => {
    this.loadingSpinner=false;
}, 5000);

})

when the above call is finished i need to call the second API
        setTimeout(() => {
      this.http.get(`http://localhost:44301/consentinitiation/${this.qid}`)
        .pipe(retryWhen(_ => {
          this.showIt=true
          return interval(1000)
        }))
        .subscribe(result => {result
        console.log(result);
        this.edited=false;
        this.qrcodelink=result["qrCodeLink"];
        setTimeout(() => {
            this.loadingSpinner=false;

        }, 5000);

        })

    }, 30000);

its kind of conditional calling,when the first one is over start the second one

A: You shouldn't nest Observables inside each other. Use a SwitchMap instead.
this.http.get(`http://localhost:44301/consentinitiation/${this.qid}`).pipe(
    tap((result1) => {
        /* use the result of first call here */
    }),
    switchMap((result1) => this.http.get(`http://localhost:44301/otherCall`))
).subscribe(result2 => {
    /* use result of second call here */
})

A: If you want to call the second one after you get the result of first one, you may try:
firstapi.subscribe(
  (res) => {
    secondapi.subscribe();
  }
)


text:
Q: make rules with existing target, existing prerequisites but no recipe I was looking at the net-snmp code and I found something odd in the Makefile of the snmplib itself. The last couple of thousands of lines are nothing but rules in this form:
./dir_utils.lo: ../include/net-snmp/output_api.h

for EVERY library object and header file. Even those that are not compiled, depending on which flags are selected in the configure script.
I looked at the "make" manual but I didn't find this exact case. It may be (as stated in 5.9) that they do this to exclude the possibility that an implicit recipe is called on the target, but other than that I have no idea.
Another reason might be to "break" the compilation if the library is tampered with (deleting whatever header in the project causes in fact the makefile to crash because it can't execute the rule).
This is an educated guess but I would like to know the theory behind this. I mean the makefile already builds whatever it has to build, why include all these rules in explicit form?
Thanks

A: As I expect you know, the Makefile is generated by the ./configure script.
All the lines that interest you are auto-generated dependencies. Actually,
they are just the appended contents of the file Makefile.depend in the same
directory, which is part of the distribution and was generated with the aid
of gcc ahead of time.
So e.g.
./dir_utils.lo: ../include/net-snmp/output_api.h

just informs make of the vitally important fact that ./dir_utils.lo
depends on ../include/net-snmp/output_api.h. Then if ./dir_utils.lo
is older than ../include/net-snmp/output_api.h, make will re-make
./dir_utils.lo provided it has some recipe to do that, which it has.
Here is a project:
main.c
#include "hw.h"
#include <stdio.h>

int main(void)
{
    puts(HW);
    return 0;
}

hw.h
#ifndef HW_H
#define HW_H
#define HW "Hello World"
#endif

Makefile
CC := gcc

.PHONY: all clean

all: hw

hw: main.o
    $(CC) -o $@ $<

clean:
    rm -f hw main.o

Build and run it:
$ make && ./hw
gcc    -c -o main.o main.c
gcc -o hw main.o
Hello World

But there's a bug in the makefile. It doesn't know that main.o
depends on hw.h:
$ touch hw.h
$ make
make: Nothing to be done for 'all'.

Append that dependency to the makefile:
main.o: hw.h

and retry:
$ make
gcc    -c -o main.o main.c
gcc -o hw main.o

Bug fixed.