text:
Q: WindowsCryptographicException I have this problem, when I run the following code in .net 3.0, in debbuging mode VisualStudio 2019, on Windows 10 S.O.
var iat = Math.Round((DateTime.UtcNow.AddMinutes(-1) - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds, 0);
var exp = Math.Round((DateTime.UtcNow.AddMinutes(60) - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds, 0);

        var payload = new Dictionary<string, object>()
        {
            { "iat", iat },
            { "exp", exp }
        };
        var extraHeader = new Dictionary<string, object>()
        {
            { "alg", "ES256" }
        };

        // private
         var keyString = "MIGkAgEBBDAIam72yz6+Yc8oR4z3OGUp7GRnpKyo5aDDztHFCclxfND8lxCHSPrmIVyMEHiLtumgBwYFK4EEACKhZANiAATtj95dxIpKztIMNnWsT9nZISdhAAWt/aQGOWaEScwaaFGrB/3/8ISytsIcMpIqA+cr7owlF+fhYjlF50gYOewpJgTHAsJnMUHNO+TA3ghTibQsJIGZSOqCsHSNaijWzmc=";

         //TO DO  CngKeyBlobFormat.Pkcs8PrivateBlob Error during Import
         CngKey privateKey = CngKey.Import(Convert.FromBase64String(keyString), CngKeyBlobFormat.Pkcs8PrivateBlob, CngProvider.MicrosoftSmartCardKeyStorageProvider);

on the last row I receive this error:
Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'Error douring coiding or decoding.
What does it mean? How can I fix it?

A: The particular value here isn't a PKCS#8 PrivateKeyInfo payload, it looks like an ECPrivateKey value.
https://lapo.it/asn1js/#MIGkAgEBBDAIam72yz6-Yc8oR4z3OGUp7GRnpKyo5aDDztHFCclxfND8lxCHSPrmIVyMEHiLtumgBwYFK4EEACKhZANiAATtj95dxIpKztIMNnWsT9nZISdhAAWt_aQGOWaEScwaaFGrB_3_8ISytsIcMpIqA-cr7owlF-fhYjlF50gYOewpJgTHAsJnMUHNO-TA3ghTibQsJIGZSOqCsHSNaijWzmc
SEQUENCE (4 elem)
  INTEGER 1
  OCTET STRING (48 byte) 086A6EF6CB3EBE61CF28478CF7386529EC6467A4ACA8E5A0C3CED1C509C9717CD0FC97…
  [0] (1 elem)
    OBJECT IDENTIFIER 1.3.132.0.34 secp384r1 (SECG (Certicom) named elliptic curve)
  [1] (1 elem)
    BIT STRING (776 bit) 0000010011101101100011111101111001011101110001001000101001001010110011…

That looks like ECPrivateKey
ECPrivateKey ::= SEQUENCE {
  version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
  privateKey     OCTET STRING,
  parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
  publicKey  [1] BIT STRING OPTIONAL
}

VS a PKCS#8 PrivateKeyInfo
PrivateKeyInfo ::= SEQUENCE {
    version                   Version,
    privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
    privateKey                PrivateKey,
    attributes           [0]  IMPLICIT Attributes OPTIONAL }

Version ::= INTEGER
PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
PrivateKey ::= OCTET STRING
Attributes ::= SET OF Attribute

For it to be a PKCS#8 you'd have the current value (ECPrivateKey) as the value of the PrivateKeyInfo.privateKey field.
--
Also, please note that you've posted a private key to the internet, so it's now compromised and shouldn't be used for anything other than testing now.


text:
Q: How to get originals date and time in java Actually
Date date = new Date();

will give us date of that server where application is running.
if particular server has set date and time wrong in that case how we can get real date and time?

A: I would not worry to much about the server's correct date. I mean a server is usually administrated by you, so just set the time correctly or use NTP to automatically set the correct time.
It is more the client's date/time you should worry about since this is set by your users and can be wrong all the time. If you need to trust the time on client and need it to be reliable and comparable for several users, then retrieve the time from your server and account for latency, if need be.

redpajama_set_name: RedPajamaStackExchange


text: Q: VSCode API get language comment delimiter Is there any way to get the comment delimiters ( eg "#" for Py & "//" in case of Js ) from the vscode api ? I can use the actions "editor.action.addCommentLine" to comment the line, but I am looking for a way to get the delimiter as a string. I don't care about the block comment, I just need single line comment delimiter.


text:
Q: Evaluating numbers that include thousand separators I understand that if the parseFloat function encounters any character other than numeric characters (0-9+-. and exponents) it just evaluates the number up to that character, discarding anything else.
I'm having a problem where I need to be able to validate numbers with thousand separators like so:
var number = "10,000.01"; //passes
var numberWithoutThousand = "10000.01"; //fails

//i.e:
if(parseFloat(number) <= 10000) {
     return true;
}
//passess

problem is the above code returns true when technically that number is larger than 10,000.
What's the best way to get around this? I've considered stripping out the comma before testing the number, but not sure that is a good strategy.

A: You don't have numbers, you have strings, so just removing the comma is the way to go
number = number.replace(/\,/g, '');

A: Your "stripping the comma" strategy seems good to me.
if ( parseFloat( number.replace(",","") ) ) { etc(); }

A: As has been suggested, to have , in the number it must be a string and so do a search and replace. If you are having to do this on a regular basis then make yourself a reusable function.
Javascript
function myParseFloat(value) {
    if (typeof value === 'string') {
        value = value.replace(/,/g, '');
    }

    return parseFloat(value);
}

var number1 = "10,000.01",
    number2 = "10000.01",
    number3 = 10000.01;

console.log(myParseFloat(number1), myParseFloat(number2), myParseFloat(number3));

Output

10000.01 10000.01 10000.01

On jsFiddle


text:
Q: I've been editing a json file but the file itself isn't updating (python) I'm trying to edit a dictionary I put in a json database and have simplified the code down to just the simple code but it isn't working:
(python)
with open ("./userdata/" + str(int(author.id)) + ".json", "r") as f:
                fileLoaded = json.load(f)
            fileLoaded["dollars"] -= cost

But the file isn't being modified. I know for a fact I'm accessing the correct file because it's not throwing up any errors and I can read fileLoaded. What am I doing wrong?
Thanks friends

A: You need to open the file, and then dump the file after you have edited it in order for it to save. Try adding this to the bottom of the code:
with open ("./userdata/" + str(int(author.id)) + ".json", "w") as f:
        json.dump(fileLoaded, f)

A: You're not writing it to the file. json.load doesn't give a "magical reference" which can be used to edit the file. After modifying the dictionary, save it with json.dump. Like this:
f.close()
with open("./userdata/" + str(int(author.id)) + ".json", 'w' as f):
    json.dump(fileLoaded, f)


text:
Q: Sorry that the following is not at all specific. I upgraded my desktop from Ubuntu 18.04 to 20.04.3 LTS the other day. Now nautilus does not work Here are the main problems:

*

*Whenever I try to open a folder, it displays for about 1/2 second, then closes. But when I open a program (e.g. Document viewer, Open office...) it can browse to find files and work on/save them.

*The file-browsers embedded in programs can also find shortcuts which I have created to folders, but these don't appear on the graphical desktop.

*Firefox and Thunderbird work, as do other programs I have installed. But in all programs the buttons for minimizing/maximizing/closing are just blank spots (or a kind of miniture blank terminal screen). The pull down menu for system admin is also improperly populated.

*At irregular intervals, moving the cursor around suddenly opens the Activities panel without apparant reason.
I have opened a terminal and tried update, upgrade and various other things the web suggests for repairing problems like corrupted dependancies. I have even tried to deinstall/purge nautilus itself using dpkg in the terminal, but that would probably just kill the console process itself. At the moment I cannot even manage to download a disk image of 20.04 to a usb-stick so that I can reinstall it from scratch.
These problems may be unrelated and some are probably the result of my clumsy attempts to fix things. Any suggestions?


text:
Q: How to clear the previous search results once you clear the textbox I am trying to implement Autocomplete using JSP and AJAX and jquery. The search results inside div tag are not clearing even after I clear contents within the text-box
HTML snippet:

  Employee Name:
  <input ng-model="names" align="left" type="text" name="name" id="name" class="form-control" autocomplete="off" placeholder="Enter a Name" required />

Jquery code:
$(document).ready(function() {

    $('#name1').keyup(function() {
        var query = $(this).val();
        if(query != '') {

            $.ajax({
                url: "names.jsp",
                method: "POST",
                data: { query: query },
                success: function(data) {
                    $('#nameList1').fadeIn();
                    $('#nameList1').html(data);
                }
            });
        }
    });

    $(document).on('click','li',function() {
        //alert($(this).text());
        $('#name1').val($(this).text());
        $('#nameList1').fadeOut();
    });

});

I want to clear all the search results ,after i clear the textbox. Can someone help me how to do this?

A: You're already checking if (query != ''), so you can just add an else which clears the nameList1 from its content:
if(query != '')
{
    $.ajax({
        url:"names.jsp",
        method:"POST",
        data:{query:query},
        success:function(data) {
            $('#nameList1').fadeIn();
            $('#nameList1').html(data);
        }
   });
}
else {
    // clear the results
    $('#nameList1').html('');
}


text:
Q: Android can't find view by ID in fragment I have a custom EditText MomentumEditText that I have in a layout in xml (fragment_edit_text.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.frazerm.momentum.MomentumEditText
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/writing_edittext"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

I can successfully inflate and display the layout in a fragment, but trying to get the MomentumEditText using View.findViewById(R.id.writing_edittext) returns null.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_edit_text, container, true);
    MomentumEditText editText = (MomentumEditText) root.findViewById(R.id.writing_edittext);
}

I have also tried to get the MomentumEditText from onStart(), but it still returns null.
Edit = I tried replacing the custom EditText in the xml with a plain EditText, and findViewById() works! here is MomentumEditText:
package com.frazerm.momentum;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.EditText;

public class MomentumEditText extends EditText  {

boolean moveCursorDisabled = true;
boolean deleteCharsDisabled = true;

private static Paint linePaint;
private static Paint marginPaint;
MomentumEditText thisEditText = this;

Editable currentText;

public MomentumEditText(Context context, AttributeSet attrs) {
    super(context);

    setCursorVisible(true);
    this.setGravity(Gravity.TOP);
    TextWatcher inputTextWatcher = new TextWatcher() {
        CharSequence textToAdd = "";
        boolean charWasDeleted = false;
        public void beforeTextChanged(CharSequence s, int start, int count, int after)  {
            if (moveCursorDisabled) {
                if( count > after ) {
                    textToAdd = s.subSequence(start + after, start + count);
                    charWasDeleted = true;
                }
            }
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s)    {
            if (moveCursorDisabled) {
                if (charWasDeleted == true) {
                    charWasDeleted = false;
                    s.append(textToAdd);
                }
                else    {
                    thisEditText.setSelection( thisEditText.getText().length() );
                }
            }
        }

    };
    this.addTextChangedListener(inputTextWatcher);

}

//disables ability to move the cursor to other parts of the text
@Override
public boolean onTouchEvent(MotionEvent event)
{
    if (deleteCharsDisabled)    {
        final float eventX = event.getX();
        if( getSelectionStart() != eventX )
        {
            super.onTouchEvent(event);
            thisEditText.setSelection( thisEditText.getText().length() );
            return true;
        }
        return super.onTouchEvent(event);
    }
    return super.onTouchEvent(event);
}

@Override
protected void onDraw(Canvas canvas) {
    linePaint = new Paint();
    linePaint.setColor(0x77777777);
    //linePaint.setStyle(Style.STROKE);

    marginPaint = new Paint();
    marginPaint.setColor(0x99FF4444);
    //marginPaint.setStyle(Style.STROKE);

    Rect bounds = new Rect();
    int firstLineY = getLineBounds(0, bounds);
    int lineHeight = getLineHeight();
    int totalLines = Math.max(getLineCount(), getHeight() / lineHeight);

    for (int i = 0; i < totalLines; i++) {
        int lineY = firstLineY + i * lineHeight + dip(2);
        canvas.drawLine(0, lineY, bounds.right, lineY, linePaint);
    }

    canvas.drawLine( (float) dip(64), (float) 0, (float) dip(64), getHeight(), marginPaint );

    super.onDraw(canvas);
    setPadding(dip(64), 0, 0, 0);
}

public void setCursorMoveAllowed(boolean allowed)   {
    moveCursorDisabled = !allowed;
    setCursorVisible(allowed);
    return;
}

public void setBackspaceAllowed(boolean allowed)    {
    deleteCharsDisabled = !allowed;
    return;
}

public boolean superTouchEvent(MotionEvent event)   {
    return super.onTouchEvent(event);
}

public int dip ( int dip )  {
    float d = this.getResources().getDisplayMetrics().density;
    int pixels = (int)(dip * d);
    return pixels;

}

}

A: Try setting attach to root false, since you are the root!
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_edit_text, container, false);

    MomentumEditText editText = (MomentumEditText) root.findViewById(R.id.writing_edittext);

    return root;
}

A: Try moving this line of code into your onActivityCreated method instead:
MomentumEditText editText = (MomentumEditText) findViewById(R.id.writing_edittext);

A: Because you are extending a current view you need to override all the constructors that can be used. Try:
public class MomentumEditText extends EditText  {

    public MomentumEditText(Context context) {
        super(context);
        init();
    }

    public MomentumEditText(Context context, AttributeSet attrs) {
        super(context, attrs); // This is the constructor used by XML (you were missing the super call)
        init();
    }

    public MomentumEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defstyle);
        init();
    }

    private void init(){
         setCursorVisible(true);
         // your other code
    }
}

Reference: http://developer.android.com/reference/android/widget/EditText.html (Public Constructors)

A: I'm guessing that fragment_edit_text.xml is the layout file you have shown in your question?
If yes, check if there is no other layout with the same name in some folders that specify some configurations (like language, density, etc).
For example you may have:
/layout/fragment_edit_text.xml
and
/layout-land/fragment_edit_text.xml
but only have your custom view within the layout-land directory, therefore it will compile ok but when in portrait mode your findViewById will return null


text:
Q: Prove $3^{n−2} n (n − 1) = \sum_{k=2}^{n} \binom{n}{k} (k)(k − 1)2^{k−2}$ for $n\ge3$ The question asks for a combinatorial proof only.
In my attempt, I rewrote $3^{n-2}$ as $(1+2)^{n-2}$. Then using binomial theorem, i was able to get  $(1+2)^{n-2} = \sum_{k=2}^{n} \binom{n}{k}  2^k$.
I don't know how to proceed from here.

A: Hint: Consider the second derivative of $(1+x)^n$ at $x=2$.

A: This can be done combinatorially.  Consider $n$ objects.  The left is the number of ways to Color one red, one blue, and label each of the others a number from $1$ to $3$.  We could also do this by choosing $n - k$ numbers to label $3$; there are $\binom{n}{k}$ ways to do this.  From the numbers not labeled $3$, we must color one red, one blue and label the rest $1$ or $2$.


text:
Q: AiogramBOT Python + SQLite3 Написал для своего бота на Paython базу данных (SQLite3), бот работает минут 10, после чего все команды и другие функции перестают работать. Что делать? Подскажите где ошибка? Иногда выбивает ошибку AcyncioError Time (чет такое)

@dp.message_handler(commands='start')
async def create_deeplink(message: types.Message):
    connect = sqlite3.connect('bot.db')
    cursor = connect.cursor()

    cursor.execute("""CREATE TABLE IF NOT EXISTS users(
        name TEXT,
        lastname TEXT,
        nickname TEXT
)""")

    connect.commit()

    checker = message.from_user.username
    cursor.execute(f"SELECT nickname FROM users WHERE nickname = '{checker}'")
    data = cursor.fetchone()
    if data is None:
        username = message.from_user.first_name
        surname = message.from_user.last_name
        nickname = message.from_user.username
        cursor.execute("INSERT INTO 'users' (name, lastname, nickname) VALUES (?, ?, ?)", (username, surname, nickname))
        connect.commit()
    else:
        await message.answer("Вы уже забронировали перерыв! Пожалуйста, не занимайте более одного раза.")

@dp.message_handler(commands='del')
async def create_deeplink(message: types.Message):
    connect = sqlite3.connect('bot.db')
    cursor = connect.cursor()

    people_name = message.from_user.first_name
    cursor.execute(f"DELETE FROM 'users' WHERE name = '{people_name}'")
    connect.commit()

@dp.message_handler(commands='check')
async def create_deeplink(message: types.Message):
    connect = sqlite3.connect('bot.db')
    cursor = connect.cursor()

    people_name = message.from_user.first_name
    surname = message.from_user.last_name

    cursor.execute(f"SELECT * FROM users")
    massive = cursor.fetchall()

    for i in range (len(massive)):
        await message.answer(f"{massive[i][0]}")
    #results = cursor.fetchall()
    #for row in results:
    #    outcome = str(row)
    # await message.answer(outcome)
        #print(row)


text:
Q: Which is probability that the student enter at least one university? A student give exams to 3 universities. The chance to enter the first is: 80%, to the second is 70% and in the third 60%.

Which is probability that the student enter at least one university?

A: The probability he doesn't get into any is (1-.8)(1-.7)(1-.6) = .2*.3*.4 = 3/125
The probability you're looking for is the compliment of the above probability. So the probability he gets into at least 1 university is 1- 3/125= 122/125.


text:
Q: "Resolve" functions in JavaScript promises I am reading this documentation about how to use promises, and frequently "resolve" and "reject" are passed in as arguments to the Promise constructor, even though nobody ever defined the "resolve" or "reject" functions.  How is that possible?  Don't we have to define functions before using them?
Here's an example: (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Browser_compatibility)
var p1 = new Promise(
        // The resolver function is called with the ability to resolve or
        // reject the promise
        function(resolve, reject) {
            log.insertAdjacentHTML('beforeend', thisPromiseCount +
                ') Promise started (Async code started)
');
            // This only is an example to create asynchronism
            window.setTimeout(
                function() {
                    // We fulfill the promise !
                    resolve(thisPromiseCount);
                }, Math.random() * 2000 + 1000);
        });

A: They are not passed in as arguments to the Promise constructor.
They are passed as arguments by the Promise constructor into your resolver callback function that declares them as parameters.
This is similar to the parameters of other callbacks, for example
array.sort(function(a, b) { … })
//                  ^  ^
array.map(function(element, index) { … })
//                 ^^^^^^^  ^^^^^

only that the values are functions in the case of the Promise constructor callback.


text:
Q: Retrieving average cost UPDATE: yes, the result is for a single record. I want to put this on a "computed by" field in firebird (PRODUCTS.PRODU_AVGCOST). It just takes the last 3 buyings for a product and calculates the average cost of it.
I have three tables, witch follows the revelant fields:
PRODUCTS
PRODU_ID PK,
PRODU_AVGCOST calculated

BUYINGS
BUYIN_ID PK

BUYING_ITENS
ITEN_ID PK,
ITEN_BUYING_ID FK
ITEN_COST numeric

I want to take the average cost of last three buyings from ITEN_COST field, using "select" for the PRODU_AVGCOST field of the PRODUCTS table
I tried as follows on table PRODUCTS, but this didn't work
select avg(iten_cost) from buying_itens b
where (select first 3 (iten_cost) from buying_itens where c.iten_id = produ_id)
order by b.iten_id desc

A: Assuming you want this for a single product (assuming ACTUAL_PRODU_ID is that value), you can do:
select avg(a.iten_cost)
from (
  select first 3 iten_cost
  from buying_itens
  where produ_id = ACTUAL_PRODU_ID
  order by iten_id desc
) a

As far as I can tell the datamodel in your question is not complete (or I fail to see how products and buying_itens are linked), so I have 'added' produ_id to buying_itens.
If you want to do this for all products in a single query, things get more complicated.


text:
Q: Browser rendered code instead of page I Hosted .Net application in Local IIS Server. I did't manage error case in MVC. I used IIS .NET Error for page redirection for particular page.
ASP.Net error page display error
page in Edge but
Chrome and Firefox display
content instead of page.
My procedure are as follow:

*

*Internet information services (IIS) Manager

*mysite> Asp.NET> .Net Error Page

and content inside Error.html

Coming Soon

Page Under Construction

Is it required page redirection handling in MVC?

A: I dont know how you call redirecting page.
Try this(MVC form of Code):
 public ActionResult Index()
 {
    return View("~/Views/error.cshtml");
 }

A: You need to follow below steps in order to redirect the error pages in MVC.Please note no need to configure anything in IIS server.
Step 1: Create a blank asp.net mvc 4 application.
Step 2: Add a HomeController. Copy and paste the following code.
public ActionResult Index()
{
    throw new Exception("Something went wrong");
}

Step 3: Enable custom errors in web.config file, that is present in the root directory of your mvc application. "customErrors" element must be nested under "".
<customErrors mode="On">
</customErrors>

Step 4: Add "Shared" folder under "Views" folder. Add Error.cshtml view inside this folder.
For more detailed explanation,follow the link http://csharp-video-tutorials.blogspot.in/2013/08/part-72-handleerror-attribute-in-mvc.html


text:
Q: Pythons Elasticsearch-DSL filter for exactly one match from list of values I saw some realted posts but none of them match my exact issue.
Using Python 2.7 with Elasticsearch-dsl (6.3, that is also my Elasticsearch version).
I want to do something like,
s = Search(using=elastic_conn, index='my_index').filter("match", service_name=['exmp_name1', 'exmp_name2'])
This syntax doesn't work though.
I wish to get back all documents with service_name == 'exmp_name1' OR service_name == 'exmp_name2'
I prefer to use the filter context rather then query context as from my understanding it's faster and scoring really isn't important to me, just an absolute match (or mismatch).
How can I achieve this behavior?
Thanks

A: Ok. All I needed is to filter by terms rather then match.
The terms syntax supports several values.
Working code:
s = Search(using=elastic_conn, index='audit').filter("terms", service_name=['exmp_name1', 'exmp_name2'])


text:
Q: Bootstrap 3 extra large (xl) columns In Bootstrap's LESS build can someone please tell me how to add a fifth device size, extra large (col-xl-#)?

A: You can download a simple small CSS file from GitHub using this link:
https://github.com/marcvannieuwenhuijzen/BootstrapXL
If you add this CSS file to the HTML after the Bootstrap CSS file you will be able to use col-xl-{size}, col-xl-push, hidden-xl, etc. The media-query breakpoint is 1600px;
Update
The alpha release for Bootstrap 4 is available now with native support for extra large screens.
http://blog.getbootstrap.com/2015/08/19/bootstrap-4-alpha/ but it's breakpoint for extra large is still 1200px.
Update 2 (july 2017)
Stop using bootstrap and start using standard CSS grids, TODAY. You can find an introduction here.

A: You can create a other less file (for instance bootstrapxl.less), containing the following code and compile that file:
@import "bootstrap.less";

// XLarge screen
@screen-xlg:                  1600px;
@screen-xlg-min:              @screen-xlg;
@screen-xlg-hughdesktop:      @screen-xlg-min;

// So media queries don't overlap when required, provide a maximum
@screen-lg-max:              (@screen-xlg-min - 1);

//== Container sizes
// Large screen / wide desktop
@container-xlarge-desktop:      ((1540px + @grid-gutter-width));
@container-xlg:                 @container-xlarge-desktop;

// Container widths
//
// Set the container width, and override it for fixed navbars in media queries.

.container {
  @media (min-width: @screen-xlg-min) {
    width: @container-xlg;
  }
}

.make-grid-xlgcolumns() {
  // Common styles for all sizes of grid columns, widths 1-12
  .col(@index) when (@index = 1) { // initial
    @item: ~".col-xlg-@{index}";
    .col((@index + 1), @item);
  }
  .col(@index, @list) when (@index =< @grid-columns) { // general; "=<" isn't a typo
    @item: ~".col-xlg-@{index}";
    .col((@index + 1), ~"@{list}, @{item}");
  }
  .col(@index, @list) when (@index > @grid-columns) { // terminal
    @{list} {
      position: relative;
      // Prevent columns from collapsing when empty
      min-height: 1px;
      // Inner gutter via padding
      padding-left:  (@grid-gutter-width / 2);
      padding-right: (@grid-gutter-width / 2);
    }
  }
  .col(1); // kickstart it
}
.make-grid-xlgcolumns();
.make-grid(xlg);

// Generate the large columns
.make-xlg-column(@columns; @gutter: @grid-gutter-width) {
  position: relative;
  min-height: 1px;
  padding-left:  (@gutter / 2);
  padding-right: (@gutter / 2);

  @media (min-width: @screen-xlg-min) {
    float: left;
    width: percentage((@columns / @grid-columns));
  }
}
.make-xlg-column-offset(@columns) {
  @media (min-width: @screen-xlg-min) {
    margin-left: percentage((@columns / @grid-columns));
  }
}
.make-xlg-column-push(@columns) {
  @media (min-width: @screen-xlg-min) {
    left: percentage((@columns / @grid-columns));
  }
}
.make-xlg-column-pull(@columns) {
  @media (min-width: @screen-xlg-min) {
    right: percentage((@columns / @grid-columns));
  }
}

Notice that instead of the .make-grid-xlgcolumns mixin in the above code you could also modify the .make-grid-columns() mixin in the less/minins/grid-framework.less file by adding the .col-xlg- class prefix.
Since BS 3.2.0 you should use the autoprefixer to make sure that your new compiled version has the same browser support as the original compiled version, see also: https://github.com/twbs/bootstrap/issues/13620
To run the autofixer for your new code replace the bootstrap.less file reference with a reference to your new bootstrapxl.less in Gruntfile.js and run grunt dist after your changes.
update
Please notice that the above solution only works when you add column classes for a larger grid. See https://stackoverflow.com/a/26963773/1596547 to add columns or grids that overlap the default grids.

A: Twitter Bootstrap has listened You #V4
Support for Extra Large Devices Now --> http://v4-alpha.getbootstrap.com/layout/grid/#grid-options

A: https://github.com/shenders13/bootstrap-grid-100cols-with-xl-and-xxl
A CSS file that contains the bootstrap grid with additional xlg ( > 1500px width ) and xxlg ( > 2000 px width) classes. The grid is split into columns with 1/100 width of the parent div.


text:
Q: UILabel смена текста каждые 3 секунды Здравствуйте.
У меня есть таблица, ячейки которой содержат по одному UILabel.
Я пытаюсь научить UILabel менять текст по требованию. Для этого написал вот такой класс:
@interface HSIntervalLabel ()

@property (nonatomic) BOOL isFirstTextShowed;
@property (nonatomic) NSString *firstText;
@property (nonatomic) NSString *secondText;

@end

@implementation HSIntervalLabel

- (void)prepare
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeText:) name:NOTIFICATION_INTERVAL_LABEL_SHOULD_CHANGE_TEXT object:nil];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self prepare];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self prepare];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepare];
    }
    return self;
}

- (void)setText:(NSString *)firstText beforeText:(NSString *)secondText
{
    self.firstText = firstText;
    self.secondText = secondText;
    self.text = firstText;
    self.isFirstTextShowed = YES;
}

- (void)changeText:(NSNotification *)notification
{
    if (self.isFirstTextShowed) {
        self.text = self.secondText;
        self.isFirstTextShowed = NO;
    }
    else {
        self.text = self.firstText;
        self.isFirstTextShowed = YES;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

Но текст почему-то не меняется, хотя, если смотреть в дебаггере, то все меняется.
Сами сообщения в NSNotificationCenter посылаются с помощью NSTimer:
dispatch_once(&kOnlyOnce, ^{
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(preparePostingNotificationsForIntervalLabel:) userInfo:nil repeats:YES];
});

A: текст то вы поменяли, но вам надо еще перерисовать вьюшки либо так     [self.tableView reloadData]
либо если вьюшку сами рисуете то setNeedsDisplay
A: Проверьте во время брекпоинте, где вы сетите текст, в каком потоке вы находитесь? Так как с графикой можно работать только в главном потоке main. Все остальное называется можно грубо назвать offscreen-rendering. Если это так, что у вас не тот поток, просто передайте управление UI в мэейн поток, удобным способом.
Я, к стати, тоже не вижу где вы лейблу текст меняете?


text:
Q: Vertices behind are being drawn infront - XNA Well, I am creating a minecraft terrain thing just for the heck of it. The problem I have is that if you look on a certain angle some faces which are actually behind others are drawn in front of them, thus not showing the actual ones which are there. Like minecraft I have the terrain seperated into regions, and when the vertexbuffer is built, only the "outside" faces are shown. It is also for some reason is not drawing the very top nor the left blocks. In addition to all of these problems faces seem to be overlapping ie (only half of a face can be seen)
Here is what it looks like (note I am only drawing the top faces because I have to fix the others up): http://s1100.photobucket.com/albums/g420/darestium/?action=view&current=minecraftliketerrain.png
I am also drawing all the regions in one go with the following method (i'm using reimer's effect file until I can write my own :):
public void Draw(Player player, World world)
    {
        effect.CurrentTechnique = effect.Techniques["TexturedNoShading"];
        effect.Parameters["xWorld"].SetValue(Matrix.Identity);
        effect.Parameters["xProjection"].SetValue(player.Camera.ProjectionMatrix);
        effect.Parameters["xView"].SetValue(player.Camera.ViewMatrix);
        effect.Parameters["xCamPos"].SetValue(player.Camera.Position);
        effect.Parameters["xTexture"].SetValue(world.TextureAlias.SheetTexture);
        effect.Parameters["xCamUp"].SetValue(player.Camera.UpDownRotation);

        for (int x = 0; x < world.regions.GetLength(0); x++)
        {
            for (int y = 0; y < world.regions.GetLength(1); y++)
            {
                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    Region region = world.regions[x, y];

                    if (player.Camera.BoundingFrustum.Contains(region.BoundingBox) != ContainmentType.Disjoint)
                    {
                        device.SetVertexBuffer(region.SolidVertexBuffer);
                        //device.Indices = region.SolidIndices;
                        device.DrawPrimitives(PrimitiveType.TriangleList, 0, region.VertexCount);
                        //device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, region.VertexCount, 0, region.SolidIndices.IndexCount / 3);
                    }
                }
            }
        }
    }

Help would be much appreciated thanks :)

A: Looks like the Z-buffer is disabled. Try setting:
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

The issue with it not drawing the top/left blocks, that you mention, is probably an issue to do with your vertex buffer generation code (if so, try asking another question specifically about that issue).


text:
Q: AWS RDS PostgreSQL cross region replication streaming or back slot window I am trying to do the PoC for RDS PostgreSQL replication across multi-region
I went though these links [replication, streaming ] docs and found the streaming info, in order to create a read replication , AWS RDS PostgreSQL uses Postgres native streaming replication. Data changes at the source instance stream to Read Replica using streaming replication.
But I am not able to understand the configuration on what is the stream slot window to stream the WAL logs..
is it every second or as soon as each transnation is written to WAL or is it based on the count like after 'n' transaction WAL logs etc?


text:
Q: Python converting recursive permutation function to iterative I have an unknown number of Integer variables say that can range from [0,9]
I want to iterate over all permutations of these values.
If the number of variables was constant, it would be easy to write nested for loops.  I came up with a recursive function that does what I want, but was curious if there was a way to do it iteratively.
def nested(array,index):
    n = len(array)
    for i in range(10):
        array[n-index]=i
        #len(array-1) end of array
        if(index == 1):
            print(array)
            #do something later
        else:
            nested(array,index-1)

#generate all permutations, change n to change size of list.
n = 4
array = [0]*n
nested(array,len(array))

I tried using the so called "Simple Method" found here -> http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html
But I couldn't get it to work.

A: As was mentioned by another commenter, the key is to simulate your tail recursion using a stack.
Take note I append() a tuple of (array, index) into the stack, which mirrors the call to recursive function in your original recursive solution. At the start of the iteration, it does stack.pop(), which mimics the body of your recursive function. Recursive call becomes stack.append().
def nested(array):
    stack = []
    n = len(array)
    stack.append((array.copy(), n))
    while(stack):
        array, index = stack.pop()
        for i in range(10):
            array[n-index]=i
            #len(array-1) end of array
            if(index == 1):
                print(array)
                #do something later
            else:
                stack.append((array.copy(), index-1))

#generate all permutations, change n to change size of list.
n = 4
array = [0]*n
nested(array)

A: Please refer to itertools. There is a Class "permutations" that could solve your problem perfectly.


text:
Q: priority queue with constant time successor operation I'm looking for a linked data structure (because I don't know how many items I'm dealing with at run time) that can be used both as a priority queue and as a linked list. In other words: searching, inserting and deleting each should not take longer than logarithmic time, but every node should also have a next-pointer which should always point to the smallest element that is bigger than itself (at every insert and delete at least one of these have to get updated at each insert and delete, of course).
(I want the pointers so I can for example print a random node and a given number of its immediate successors.)
For me that's a pretty common problem, that shouldn't be that hard to solve even for a novice programmer like me, but I don't know a data structure that can do that:
It seems like I can't use binary heaps, because finding the next element is not trivial, unless I convert the whole heap into a list by removing every single item in linear time while loosing the ability to ever insert or delete in log time again.
Searching for every successor key in balanced search trees is better than converting the heap, but logarithmic time for each successor still seems to be quiet a waste of cycle for such a trivial task.
Thanks in advance for any suggestions :).

A: This is easily done with a skip list. Insert and find are O(log n) (amortized). Remove first is O(1). Finding the successor is O(1).
You could also create a threaded search tree, in which case finding the successor is O(1).

A: You can use balanced search trees. To provide O(1) neighbor access, you can maintain direct neighbor links in logarithmic time during modifying operations which are O(log(n)) anyway.


text:
Q: C# TPL how to know that all tasks are done? I have the Loop which generates tasks.
Code:
Task task = null;
foreach (Entity a in AAAA)
{
  // create the task
  task = new Task(() => {
    myMethod(a);
  },  Token, TaskCreationOptions.None);
  task.Start();
}

As you can see in each iteration task object has new initialization (..new Task(() =>..)
    How can I know that all tasks done?

A: You'll need to keep references to all the tasks created in the loop. Then you can use the Task.WaitAll method (see MSDN reference). You can either create an array and assign tasks to elements of the array (in C# 2.0) or you can use LINQ:
var tasks =
   AAAA.Select((Entity a) =>
      Task.Factory.StartNew(() => { myMethod(a); },
         Token, TaskCreationOptions.None)).ToArray();
Task.WaitAll(tasks)

If you don't need to use tasks (explicitly) then Henk's suggestion to use Parallel.ForEach is probably a better option.

A: I f you replace this with a
 Parallel.ForEach(...,  () => myMethod(a), ...)

Then you get an automatic Wait on all tasks at the end of the ForEach.
And maybe run the ForEach from a separate Task.

A: var allTasks = new List&ltTask&gt();
foreach (Entity a in AAAA)
{
  // create the task
  task = new Task(() => {
    myMethod(a);
  },  Token, TaskCreationOptions.None);

  // Add the tasks to a list
  allTasks.Add(task);
  task.Start();
}

// Wait until all tasks are completed.
Task.WaitAll(allTasks.ToArray());


text:
Q: AS3 Video COMPELETE event handler not working? addEventListener(Event.COMPLETE hi i am using FLVPlayback 2.5 component and getting this error, please help! - cannot convert fl.video: to flash.events.VideoEvent.
as3 code using -
            comp.addEventListener(Event.COMPLETE, videoComplete);

            function videoComplete(event:VideoEvent):void {
                trace("videoComplete");
            }

full error -

TypeError: Error #1034: Type Coercion failed: cannot convert
  fl.video::VideoEvent@6e974dd1 to flash.events.VideoEvent.     at
  flash.events::EventDispatcher/dispatchEventFunction()     at
  flash.events::EventDispatcher/dispatchEvent()     at
  fl.video::FLVPlayback/http://www.adobe.com/2007/flash/flvplayback/internal::handleVideoEvent()
    at flash.events::EventDispatcher/dispatchEventFunction()    at
  flash.events::EventDispatcher/dispatchEvent()     at
  fl.video::VideoPlayer/http://www.adobe.com/2007/flash/flvplayback/internal::httpDoStopAtEnd()
    at
  fl.video::VideoPlayer/http://www.adobe.com/2007/flash/flvplayback/internal::httpNetStatus()

fix thanks to ronnie! cheers man. this works for me..
            import fl.video.VideoEvent;

            comp.addEventListener(Event.COMPLETE, videoComplete);

            function videoComplete(event:Event):void {
                trace("videoComplete");
            }

A: lostPixels was right for the most part in explaining what the error means but it isn't VideoEvent, its simply Event
 comp.addEventListener(Event.COMPLETE, videoComplete);

 function videoComplete(event:Event):void //event:Event not event:VideoEvent
 {
     trace("videoComplete");
 }

A: I made a comment up there but I wanted to give you a full explaination here.  When you said:
addEventListener(Event.COMPLETE, videoComplete);

it does in fact call your function... but with a different event than you expect.  This is because it is actually firing a fl.video.VideoEvent which ALSO has a constant called COMPLETE.  Both Event.COMPLETE and VideoEvent.COMPLETE = a string value "complete" so it calls you function.
Second problem is the function:
function videoComplete(event:VideoEvent):void {

is listening for a flash.events.VideoEvent.  This was probably an accident when you used the code complete.  But when you function get called, it is receiving a fl.video.VideoEvent... thus the error
so do these:
import fl.video.VideoEvent;

addEventListener(VideoEvent.COMPLETE, videoComplete);

function videoComplete(event:VideoEvent):void {

And you are all set!

A: I think this might have something to do with the flash player version you are targeting.
Can you target FP9 or FP10? (in the properties panel in Flash Professional)

A: Type Coercion fails are the result of you trying to convert one strictly typed variable to another. What that means (it's not written to be easily understandable) is this:
Say we have two variables, one is a number, and one is a string. If we try and say number = string, Flash will spit out that error, because a string can't be a number.
What this has to do with your code is that you're trying to convert an Event to a VideoEvent.
To remedy this, change your code to this line:
  comp.addEventListener(VideoEvent.COMPLETE, videoComplete);

A: You could add a cue point to the end of your video and listen for that.
Assuming comp is the instance name of your flvPlayback component...
import fl.video.FLVPlayback;
import fl.video.MetadataEvent;

comp.addEventListener(MetadataEvent.CUE_POINT, video_cp_listener, false, 0, true);

function video_cp_listener(eventObject:MetadataEvent):void {

//run code here when a cue point is found
trace(eventObject.info.name);

}


text:
Q: DataGrid with editable ComboBox for possible values in many-to-many relationship Here are some simple classes which have a many-to-many relationship:
using System.Collections.ObjectModel;
using System.Data.Entity;

namespace NodesLabels
{
    public class Node
    {
        public int ID { get; set; }
        public string Title { get; set; }

        public virtual ObservableCollection<NodeLabel> Labels { get; set; }

        public Node() { Labels = new ObservableCollection<NodeLabel>(); }
    }

    public class NodeLabel
    {
        public int ID { get; set; }
        public string Title { get; set; }

        public virtual ObservableCollection<Node> Nodes { get; set; }

        public NodeLabel() { Nodes = new ObservableCollection<Node>(); }
    }

    public class GraphContext : DbContext
    {
        public DbSet<Node> Nodes { get; set; }
        public DbSet<NodeLabel> NodeLabels { get; set; }
    }
}

I've added Node and NodeLabel as data sources:

If I drag in Node, I get a DataGrid where I can create new Node objects, specifying their title. If I drag in Labels I get another DataGrid where I can add Label objects which will be associated with the selected Node.
Here, the Node DataGrid is on top and the Labels DataGrid is on the bottom. I've added "Dune" as a Node and given it a Label of "Book".

Now, I'd like to be able to select the node "Abstract Algebra" and associate it with the same "Book" Label. However, if enter "Book" into the Labels DataGrid, a new instance of Label will be created, with the "Book" title; i.e. the original instance of "Book" will not be reused.
Ideally, I'd like to have a Labels DataGrid with an editable ComboBox which will allow me to select from existing Label instances, instead of always creating new ones.
What's a good way to set this up?


text:
Q: Cant Fetch Tags From Single Post Page I cant seem to retrieve any Tags from a Single Product Page, Despite the Product having at-least 1 tag
            <?php

                $postid = $post->ID;
                get_the_tags($postid);

                if ($posttags) {
                  foreach($posttags as $tag) {
                    echo $tag->name . ' ';
                  }
                }
                if ( has_tag( 'cattle' ) ) : ?>

                     <img src="<?php echo home_url()?>/wp-content/uploads/2022/08/Asset-4.png" alt="img">;

                <?php endif; ?>

I tried a Variety of different approaches It just seems asif I cant fetch the array, I wish to just Look to see if it contains specific tag then output a small image for it:
As such:
 <?php

    $post_tags = get_the_tags();
    if ( $post_tags ) {
            echo $post_tags[0]->name;
    }

    switch($post_tags){
          case "cattle":
          echo "";
          break;
          case "sheep":
          echo "";
          break;
          case "goats":
          echo "";
          break;
          case "horse":
          echo "";
          break;
          case "pigs":
          echo "";
          break;
          case "wildlife":
          echo "";
          break;
          case "poultry":
          echo "";
          break;
}

//

if($tags){
$tagNames = array_map(function($tag){return $tag->name;},$tagObjects);
}
?>

Page Template:
Single-product.php (Using Woocommerece) & using standard Taxonomy on products nothing unique


text:
Q: connect mikrotik router hotspot default login.html to external database I have created a hotspot server in mikrotik router. Its successfully redirecting the users to default login.html and accepting the users I have added in the hotspot users.
I want to open the default login.html only, but I want it to use my database (mongo database hosted on mlab). Any insights on how to proceed?
(add users via api)
PS: I have downloaded all the files from hotspot folder but couldn't figure out a way yet to connect it to a remote database.

A: Use an external radius server which will be connected to the mongodb database. You will need something like FreeRadius configured with mongodb connector to use your database as authentication source.
Then add a radius client in Mikrotik device, add "Radius" authentication type in hotspot profile parameters and it should work.
Some useful links:
https://wiki.mikrotik.com/wiki/Manual:RADIUS_Client
https://wiki.mikrotik.com/wiki/Manual:Customizing_Hotspot


text:
Q: UITableView borders not show with AccesoryTypeNone I have a Grouped Style table view in my application. When I set the accessoryType to UITableViewCEllAccessoryCheckmark everything is OK, but when i set it as UITableviewAccesoryTypeNone the right border is not shown, as it can be seen in the next image:

As it can be seen the two firs rows has Checkmark and are seen right, but the other can be seen the round corner that ends de section, and the other ones has not border.
Any suggestion to resolve the problem??
Best Regards.


text:
Q: como puedo pasar el valo de mi litbox en ajax== function insertar() {

    var data = {
        objpersona: {

            licencia: $("#Licencia").val(),
            categoriaid: $("#categoria").val(),
            p_ci: $("#carnet").$(this).val()
        }
    }

    $.ajax({

        type: "POST",
        url: "Conductor.aspx/Registrapersona",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (data) {

            $('#myModal').modal('hide'),
                $('#tablapersona').show()
          ///  fillLimpiar();
            $('#tx').val("");
            location.reload();

            console.log("hola")

        },
        error: function (msg) {
            console.log(msg);
            alert(msg);
        }

    }).done(function (info) {
        console.log(info);
    })
}

A: No entiendo cual es realmente tu duda pero unos consejos, si quieres usar promises, dentro del objeto ajax no necesitas pasar las funciones success y error ya que done y fail son equivalentes
const request = $.ajax({
    type: "POST",
    url: "Conductor.aspx/Registrapersona",
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});
request.done(function (result) {
   $('#myModal').modal('hide');
   $('#tablapersona').show();
   $('#tx').val("");
   location.reload();
});
request.fail(function (msg) {
  console.log(msg);
  alert(msg);
});

tambien existe always, te agradecería que explicases un poco más cual es tu duda y pusieses más código html.
Un slaudo


text:
Q: Extracting time zone from Oracle JDBC TIMEZONETZ object Is there a way to extract timezone information directly from an oracle.sql.TIMESTAMPTZ object (selected from a TIMESTAMP WITH TIME ZONE column)?
Ideally, I'd like to be able to pull the time zone information directly out of the object without jumping through potentially expensive or fragile hoops (like converting things into strings and parsing those).
You would think that there is an easy way to do this, but I have yet to find one. Oracle's documentation is not very helpful. It claims the last two bytes returned by TIMESTAMPTZ#toBytes() encode the timezone information, but there is no description of our to actually decode this information.
Anyone out there have any experience dealing with this stuff?

A: Oracle has specific date format elements for these: TZD, TZH, TZM and TZR.
An example:
SQL> create table t (col timestamp with time zone)
  2  /

Tabel is aangemaakt.

SQL> insert into t values (sysdate)
  2  /

1 rij is aangemaakt.

SQL> select col
  2       , to_char(col,'TZD') time_zone_daylight_info
  3       , to_char(col,'TZH') time_zone_hour
  4       , to_char(col,'TZM') time_zone_minute
  5       , to_char(col,'TZR') time_zone_region
  6    from t
  7  /

COL                             TIME_Z TIM TI TIME_ZONE_REGION
------------------------------- ------ --- -- --------------------------------
22-05-09 09:12:33,000000 +02:00        +02 00 +02:00

1 rij is geselecteerd.

Or using the EXTRACT function:
SQL> select col
  2       , extract(timezone_abbr from col)   time_zone_abbr
  3       , extract(timezone_hour from col)   time_zone_hour
  4       , extract(timezone_minute from col) time_zone_minute
  5       , extract(timezone_region from col) time_zone_region
  6    from t
  7  /

COL                             TIME_ZONE_                         TIME_ZONE_HOUR                       TIME_ZONE_MINUTE
------------------------------- ---------- -------------------------------------- --------------------------------------
TIME_ZONE_REGION
----------------------------------------------------------------
22-05-09 09:15:24,000000 +02:00 UNK                                             2                                      0
UNKNOWN

1 rij is geselecteerd.

A: The format of TIMESTAMPTZ is well documented. We currently use the following code to extract the time zone information.
If you are on Java SE 8 you can use getObject(int, OffsetDateTime.class), if you use getObject(int, ZonedDateTime.class) you may be affected by bug 25792016.


text:
Q: How to convert a LiveCD into a vmlinuz and initrd to PXE Boot Load Slowly I need to make a emergency PXE bootloader for a LIVECD (not the ubuntu netboot small cd, but rather a desktop livecd to boot from the command line). Will this work:
# Create a cpio archive of just the ISO and append it to the initrd image.
( echo "ubuntu-13.10-desktop-amd64.iso" | cpio -H newc --quiet -o ) |  gzip -9 |   cat ubuntu-13.10-desktop-amd64.iso_EXTRACTED/casper/initrd0.img - > tftpboot/initrd0.img

# Kernel image.
cp ubuntu-13.10-desktop-amd64.iso_EXTRACTED/isolinux/vmlinuz0 tftpboot/vmlinuz0

# pxelinux bootloader part:
LABEL pxeboot
    KERNEL vmlinuz0
    APPEND initrd=initrd0.img root=/ubuntu-13.10-desktop-amd64.iso             rootfstype=iso9660 rootflags=loop
ONERROR LOCALBOOT 0

What am i doing wrong?

A: That configuration loads the whole image through a slow protocol like TFTP.

*

*Try other option using NFS protocol.
apt-get install nfs-kernel-server

mkdir /mnt/ubuntu
mount -o loop ubuntu-13.10-desktop-amd64.iso /mnt/ubuntu-desktop-cd

*Share it through NFS
sudo nano /etc/exports

Add this line
/mnt/ubuntu-desktop-cd 192.168.0.0/24(ro,insecure,no_root_squash,async,no_subtree_check)

*Start NFS service
service nfs-kernel-server restart

*In APPEND line, replace root, rootfstype and rootfstype with:
netboot=nfs nfsroot=192.168.0.10:/mnt/ubuntu-desktop-cd

Note: I used these IP's just as an example.
192.168.0.10 is IP of the NFS server
192.168.0.0/24 Is local network range.
See https://help.ubuntu.com/community/Installation/LocalNet#A_variation:_Booting_the_.22Live_CD.22_image


text:
Q: map, double> used in this offload region is not bitwise copyable I am using Intel C++ Compiler v14.0.3. This following code troubles me:
#include <tinyxml/tinyxml.h>
#include <memory>
#include <map>
#include "offload.h"
using namespace std;
typedef map<shared_ptr<TiXmlDocument>, double,
        less<shared_ptr<TiXmlDocument> >,
        __offload::shared_allocator<pair<shared_ptr<TiXmlDocument>, double> > > xmlanddbl;
__declspec(target(mic)) _Cilk_shared xmlanddbl m;
int main(void)
{
  const int maxct = 10;
  for(int i = 0; i < 10; i++){
    shared_ptr<TiXmlDocument> doc(new TiXmlDocument);
    if(doc && doc->LoadFile("something.xml")){
      m.insert(make_pair(doc, 0.0));
    }
  }
  for(int ct = 0; ct < maxct; ct++){
#pragma offload target(mic) mandatory
#pragma omp parallel
#pragma omp single
    {
      for(auto it = m.begin(); it != m.end(); it++){
#pragma omp task firstprivate(it)
        {
          someclass obj(it->first);
          it->second = obj.eval();
        }
      }
#pragma omp taskwait
    }
    somefunction(m);
  }
  return 0;
}

Compiler gives this message:
$ icpc -c thiscode.cpp -O2 -openmp -parallel -std=c++11 -I./include
thiscode.cpp(24): error: variable "m" used in this offload region is not bitwise copyable
  #pragma offload target(mic) mandatory
  ^

compilation aborted for thiscode.cpp (code 2)

I've read this page. But I could not think of how to transfer this data.
What can I do?
Sorry for my poor english.
Thank you.

A:
I could not think of how to transfer this data. What can I do?

From the document you linked:

"If the data exchanged between CPU and coprocessor is more complex than simple scalars and bit-wise copyable arrays, you may consider using the _Cilk_shared/_Cilk_offload constructs."

#pragma offload will not work because std::map is too complex to be bitwise copyable.


text:
Q: SDO_GEOMETRY not accepting variables I'm trying to display the distance between to locations, however, when using l_lng and l_lat variables that are processed from a postcode a user enters, I'm getting the following error - ORA-13032: Invalid NULL SDO_GEOMETRY object
It's not a problem with the UPDATE as when I input latitude and longitude values, the distance is calculated. Also, when displaying the latitude and longitude values held in the l_lng and l_lat variables, they are also correct.
DECLARE

  l_lat VARCHAR2(100);
  l_lng VARCHAR2(100);
  l_postcode VARCHAR2(8) := :P2_POSTCODE;

BEGIN

    brian.GEOCODE_GM_XML (:P2_POSTCODE, l_lat, l_lng);

    UPDATE RESTAURANTS
    SET DISTANCE =     (SELECT SDO_GEOM.SDO_DISTANCE(
                            restaurants.location,
                            SDO_GEOMETRY(2001, 4326, SDO_POINT_TYPE(l_lng, l_lat, null), null, null),
                            0.005, 'unit=mile') distance
                       FROM restaurants WHERE restaurants.restaurant_id = 36);
    htp.p(l_lat);
    htp.p(l_lng);

END;

Is there any mistake I'm making?

A: *

*Change variable declarations for l_lat and l_lng from varchar2
to number.

*I presume the restaurants.distance column is of type number.

*Verify that the geometries have valid fields. To specify a NULL
geometry, specify the whole SDO_GEOMETRY as
NULL instead of setting each field to NULL.  It seems you may have  some values are NULL at the same time for both l_lat and
l_lng of SDO_POINT_TYPE.


text:
Q: Python Altair Vega chart not displaying I have the following code snippet:
import altair as alt
import pandas as pd

alt.renderers.enable('default')

data = pd.DataFrame({'a': list('CCCDDDEEE'),
                     'b': [2, 7, 4, 1, 2, 6, 8, 4, 7]})

chart = alt.Chart(data)

alt.Chart(data).mark_point().encode(
    x='a',
    y='b'
)

I have installed Altair and Vega and Notebook already:
Altair version: 4.1.0
Notebook version: 6.4.0
Vega version: 3.5.0
Python version: 3.7.8
http://localhost:8889/tree#notebooks is open in a tab.
When I run my Python program, nothing happens.
What am I missing?

A: Try moving the enable line to just after importing altair, e.g.
import altair as alt
alt.renderers.enable('default')

then restarting the kernel and re-running. That seems to work for me.


text:
Q: loading into 2d array from file in c++ I am having trouble reading numbers from a file into a 2d array in c++.  It reads the first row just fine but the rest of the rows are populated with 0's.  I have no idea what I'm doing wrong.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int myarray[20][20];

    int totRow = 20, totCol = 20, number, product, topProduct = 0, row, col, count;
    char element[4];

    ifstream file;

    file.open( "c:\\2020.txt" );

    if( !file )
    {
        cout << "problem";
        cin.clear();
        cin.ignore(255, '\n');
        cin.get();

        return 0;
    }

    while( file.good())
    {
        for( row = 0; row < totRow; row++ )
        {
            for( col = 0; col < totCol; col++ )
            {
                file.get( element, 4 );
                number = atoi( element );
                myarray[row][col] = number;
                cout << myarray[row][col] << " ";
            }
            cout << endl;

        }
        file.close();
    }

A: If there are only numbers in your file, you can just read them with the >> operator. Change your inner loop to:
for( col = 0; col < totCol; col++ )
{
    file >> myarray[row][col];
    cout << myarray[row][col] << " ";
}

The problem with file.get() is, it doesn't read beyond newline \n. See: std::basic_istream::get

A: You're closing the file inside the while loop:
while( file.good())
    {
        for( row = 0; row < totRow; row++ )
        {
            for( col = 0; col < totCol; col++ )
            {
                file.get( element, 4 );
                number = atoi( element );
                myarray[row][col] = number;
                cout << myarray[row][col] << " ";
            }
            cout << endl;

        }
        file.close();   // <------ HERE
    } // end of while loop is here

You obviously can't read from a closed stream. Now, because you're trying to read all the data in the first iteration of the while loop, this doesn't seem to be your immediate problem. Note however, that the stream can still be good() even after you've read all the meaningful data (for example if there's a traling new-line character) and in that case, you'll enter the loop for the second time. That's a bug.


text:
Q: Problems linking header files with Rust bindgen According to the Rust bindgen tutorial at https://rust-lang.github.io/rust-bindgen/tutorial-3.html, I am trying to generate the FFI for existing C header files. However, I am having trouble linking the header files.
The repository at https://github.com/studersi/rust-test-apache holds all the files necessary to reproduce the issue including a README file containing the necessary commands. The most relevant files are listed at the end of the question.
I am using a Docker container to build the project (see Dockerfile below). The C header files are downloaded from the Internet and placed in the subdirectory downloads/.
The includes for the linker (see build.rs below) are based on the includes the apxs tool uses to build a similar C example according to the Apache httpd module development guide on which my project is based.
$ apxs -a -c mod_example.c
/usr/share/apr-1.0/build/libtool  --mode=compile --tag=disable-static x86_64-linux-gnu-gcc -prefer-pic -pipe -g -O2 -fstack-protector-strong -Wformat -Werror=format-security  -Wdate-time -D_FORTIFY_SOURCE=2   -DLINUX -D_REENTRANT -D_GNU_SOURCE  -pthread  -I/usr/include/apache2  -I/usr/include/apr-1.0   -I/usr/include/apr-1.0 -I/usr/include  -c -o mod_example.lo mod_example.c && touch mod_example.slo
libtool: compile:  x86_64-linux-gnu-gcc -pipe -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -DLINUX -D_REENTRANT -D_GNU_SOURCE -pthread -I/usr/include/apache2 -I/usr/include/apr-1.0 -I/usr/include/apr-1.0 -I/usr/include -c mod_example.c  -fPIC -DPIC -o .libs/mod_example.o
/usr/share/apr-1.0/build/libtool  --mode=link --tag=disable-static x86_64-linux-gnu-gcc -Wl,--as-needed -Wl,-z,relro -Wl,-z,now    -o mod_example.la  -rpath /usr/lib/apache2/modules -module -avoid-version    mod_example.lo
libtool: link: x86_64-linux-gnu-gcc -shared  -fPIC -DPIC  .libs/mod_example.o    -Wl,--as-needed -Wl,-z -Wl,relro -Wl,-z -Wl,now   -Wl,-soname -Wl,mod_example.so -o .libs/mod_example.so
libtool: link: ( cd ".libs" && rm -f "mod_example.la" && ln -s "../mod_example.la" "mod_example.la" )

After starting the container and building the Cargo project, I get errors that the header files to be converted cannot be found.
$ cargo build
   Compiling mod_rs v0.1.0 (/home/rustacian/mod_rs)
error: failed to run custom build command for `mod_rs v0.1.0 (/home/rustacian/mod_rs)`

Caused by:
  process didn't exit successfully: `/home/rustacian/mod_rs/target/debug/build/mod_rs-a68981041b3e3908/build-script-build` (exit code: 101)
  --- stdout
  cargo:include=/home/rustacian/downloads/httpd-2.4.46/include
  cargo:include=/home/rustacian/downloads/apr-1.7.0/include
  cargo:include=/usr/include/apache2
  cargo:include=/usr/include/apr-1.0
  cargo:rerun-if-changed=wrapper.h

  --- stderr
  wrapper.h:2:10: fatal error: 'apr_hash.h' file not found
  wrapper.h:2:10: fatal error: 'apr_hash.h' file not found, err: true
  thread 'main' panicked at 'Unable to generate bindings: ()', build.rs:34:10
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Note that I already tried including the header files using different commands (cargo:include and .clang_arg) and from different locations (downloaded manually and installed using system packages) but nothing has worked so far.
[...]
    println!("cargo:include=/home/rustacian/downloads/httpd-2.4.46/include");
    println!("cargo:include=/home/rustacian/downloads/apr-1.7.0/include");
    println!("cargo:include=/usr/include/apache2");
    println!("cargo:include=/usr/include/apr-1.0");
[...]
        .clang_arg("-I/usr/include/apache2 -I/usr/include/apr-1.0 -I/home/rustacian/downloads/httpd-2.4.46/include -I/home/rustacian/downloads/apr-1.7.0/include")
[...]

Why is bindgen unable to find the header files? Any help would be appreciated.

Dockerfile
FROM rust

ARG USERNAME="rustacian"

RUN apt-get update
RUN apt-get -y install --no-install-recommends apache2-dev llvm librust-bindgen-dev

RUN groupadd -r ${USERNAME} && useradd -s /bin/bash -g ${USERNAME} ${USERNAME}
USER ${USERNAME}

WORKDIR /home/${USERNAME}

build.rs
extern crate bindgen;

use std::env;
use std::path::PathBuf;

fn main() {
    // Tell cargo to tell rustc to link the
    // shared library.
    println!("cargo:include=/home/rustacian/downloads/httpd-2.4.46/include");
    println!("cargo:include=/home/rustacian/downloads/apr-1.7.0/include");
    println!("cargo:include=/usr/include/apache2");
    println!("cargo:include=/usr/include/apr-1.0");

    // Tell cargo to invalidate the built crate whenever the wrapper changes
    println!("cargo:rerun-if-changed=wrapper.h");

    // The bindgen::Builder is the main entry point
    // to bindgen, and lets you build up options for
    // the resulting bindings.
    let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header("wrapper.h")
        // Add the includes for C header files.
        // Derived from https://httpd.apache.org/docs/2.4/developer/modguide.html
        // $ apxs -a -c mod_example.c
        .clang_arg("-I/usr/include/apache2 -I/usr/include/apr-1.0 -I/home/rustacian/downloads/httpd-2.4.46/include -I/home/rustacian/downloads/apr-1.7.0/include")
        // Tell cargo to invalidate the built crate whenever any of the
        // included header files changed.
        .parse_callbacks(Box::new(bindgen::CargoCallbacks))
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .expect("Unable to generate bindings");

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}

wrapper.h
#include "stdio.h"
#include "apr_hash.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"

Cargo.toml
[package]
name = "mod_rs"
version = "0.1.0"
authors = ["studersi <*****@******.***>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libc = "*"

[build-dependencies]
bindgen = "*"

A: Found the answer shortly after posting the question here.
The problem lies with the .clang_arg() call. There must be only one include per call to that function but multiple calls to the function are allowed.
The working build.rs would then include the following calls:
        .clang_arg("-I/usr/include/apache2")
        .clang_arg("-I/usr/include/apr-1.0")

No further includes are necessary and I can now build the project, generating the bindings.
$ cargo build
   Compiling mod_rs v0.1.0 (/home/rustacian/mod_rs)
    Finished dev [unoptimized + debuginfo] target(s) in 9.24s

$ find . -name bindings.rs
./target/debug/build/mod_rs-ba1afe54e266aa8f/out/bindings.rs

$ head -c 1000 ./target/debug/build/mod_rs-ba1afe54e266aa8f/out/bindings.rs
/* automatically generated by rust-bindgen */

# [repr (C)] # [derive (Copy , Clone , Debug , Default , Eq , Hash , Ord , PartialEq , PartialOrd)] pub struct __BindgenBitfieldUnit < Storage , Align > { storage : Storage , align : [Align ; 0] , } impl < Storage , Align > __BindgenBitfieldUnit < Storage , Align > { # [inline] pub const fn new (storage : Storage) -> Self { Self { storage , align : [] } } } impl < Storage , Align > __BindgenBitfieldUnit < Storage , Align > where Storage : AsRef < [u8] > + AsMut < [u8] >, { # [inline] pub fn get_bit (& self , index : usize) -> bool { debug_assert ! (index / 8 < self . storage . as_ref () . len ()) ; let byte_index = index / 8 ; let byte = self . storage . as_ref () [byte_index] ; let bit_index = if cfg ! (target_endian = "big") { 7 - (index % 8) } else { index % 8 } ; let mask = 1 << bit_index ; byte & mask == mask } # [inline] pub fn set_bit (& mut self , index : usize , val : bool) { debug_assert ! (index / 8 < self . storage . as_ref ()


text:
Q: Can't mutate a variable local to a function in another function I am trying to manipulate the lists inside the dictionary clean_txt in another function, but its not working and I end up with empty lists inside the dict.
My understading is that both lists and dicts are mutable objects so what is the problem here?
def process_questions(i, question_list, questions, question_list_name):
    ''' Transform questions and display progress '''
    print('processing {}: process {}'.format(question_list_name, i))
    for question in questions:
        question_list.append(text_to_wordlist(str(question)))

@timeit
def multi(n_cores, tq, qln):
    procs = []
    clean_txt = {}
    for i in range(n_cores):
        clean_txt[i] = []

    for index in range(n_cores):
        tq_indexed = tq[index*len(tq)//n_cores:(index+1)*len(tq)//n_cores]
        proc = Process(target=process_questions, args=(index, clean_txt[index], tq_indexed, qln, ))
        procs.append(proc)
        proc.start()

    for proc in procs:
        proc.join()

    print('{} records processed from {}'.format(sum([len(x) for x in clean_txt.values()]), qln))
    print('-'*100)

A: Your are using Processes not threads.
When the process is created the memory of your program is copied and each process work on its own set, therefore it is NOT shared.
Here's a question that can help you understand: Multiprocessing vs Threading Python
If you want to share memory between processes you should look into semaphores or use Threads instead. There are also other solutions to share data, like queues or database etc.

A: You are appending to clean_txt[index] from a different Process. clean_txt[index] belongs to the main python process who created it. Since a process can't access or modify another process's memory, you can't append to it. (Not really. See edit below)
You will need to create shared memory.
You can use Manager to create shared memory, something like this
from multiprocessing import Manager
manager = Manager()
...
    clean_txt[i] = manager.list()

Now you can append to this list in the other process.
Edit -
My explanation about clean_txt wasn't clear. Thanks to @Maresh.
When a new Process is created the whole memory is copied. So modifying the list in the new process won't affect the copy in the main process. So you need a shared memory.


text:
Q: Does heat damage computers while turned off? I'm well aware that overheating is a common source of damage to computers, but can high heat damage them even while powered off? And if it is possible, is it likely?
I ask due to some old components that have been sitting in the trunk of my car for several weeks now, in 90°F+ mid-summer heat, and in the sun. I originally planned on recycling them, and stuck them in the trunk for transport, but today I thought of a new use for them, and I'm trying to decide if they're worth the trouble of re-purposing. If there's a good chance they're fried, then no, they're not.

A: You should be okay if you left them in there one or two times. However, prior to booting them up, I would recommend letting them cool down naturally. Otherwise, you may get condensation built up internally which could cause issues. Same way in the reverse (taking a cold laptop into a warm environment).
Think of it like a cold glass of water, taken outside. Most likely, it will sweat. Laptops do not like to sweat.

A: If the temperature goes above 70-80 Celsius (158 to 176 Fahrenheit) chances are that the capacitors become unstable.
A car-trunk in full sunlight can reach that high a temperature.
They can take some heat but not for days on end.
Problem is made worse by old capacitors (old being pre- 2006). They have less tolerance for heat.
Just run the oldest newest of those machines with Memtest86 for 1 hour. If it's unstable it will fail the test.
If one fails I wouldn't bother testing the others and throw the whole batch into recycling.
If it comes through fine you can work your way down the list to older machines or do a binary search.
As soon as you find a bad one you can throw away anything older too.

A: If it's enough heat it may melt come capacitors, especially if the hardware (mainly the motherboard) is old, causing shot circuits.
In 32 degrees (Celsius) I don't think it's damaged.

A: no, a mid heat summer cannot damage your components. It will work 100%
Many components can withstand heat upto 200deg F such as a cpu and a graphics card.


text:
Q: change or add letter in text file -C++ QT I`m working with text file,
and I want to read a text file line by line,
and if line start with # I want to write before it *
for example I have this file:
hello
world
#house
tree

I want it to be:
hello
world
*#house
tree

and if it easier I dont mind to do :
*house
or instead all the line to do that:
hello
world
*
tree

Do you know how to do it?
thank:)

A: thanks for your replies:)
I understood that the best way is to Read the file line by line and write the modified version out into a new file. Then close and remove the old file and rename the new one.
have a nice day:)


text:
Q: whether the quotient of continued fraction of algebraic irrational number is bounded or not is similar or equivalent to Collatz conjecture? I vaguely recall that whether the quotient of continued fraction of algebraic irrational number is bounded or not is similar or equivalent to Collatz conjecture, could any one give the reference? or proof?
Thank you in advance.


text:
Q: Dragon souls not activating new words So if I understand correctly you can learn new words and the souls will activate these words. I just killed a dragon and when it died it looked like I absorbed the soul but it didn't unlock any of the words I have.
I noticed some dragons actually have a name so do certain dragons unlock certain words?

A: After you absorb the soul, open the magic menu and click shouts. On the PS3, you hit X on the shout, then square to apply the soul to the shout.

A: Dragon souls can be saved, so don't worry that the effort in killing the dragon is lost.
Please note that you need to discover additional shouts if you have learned/activated all your current words, this way you can use your saved dragon souls on the new words of the new shouts.

Shouts are discovered on the walls of old ruins, and gained by slaying and absorbing the souls of dragons. As more are slain the users ability to learn and use new shouts increases.
— Wikia - Elder Scrolls V: Skyrim - Dragon Shouts

In order to learn new shouts, you need to find all these word walls; you can get a quest to the next:

Although finding word walls can be very challenging try and use shouts in major cities. Whenever you do this you should receive a note from a courier which tells you "a note for your hands only" this note starts a quest to find a source of power and the current location of the next word wall.
— Wikia - Elder Scrolls V: Skyrim - Word Wall (Contains more details on all the locations)

To actually learn a new shout, once you have discovered the word wall and have a dragon soul to use, you need to manually activate it in the shouts menu. Select the shout and press the Activate button. It should be shown on your screen, but I believe the buttons are:

*

*R on PC

*X on Xbox

*□ on PS3

A: You have to spend the saved up dragon souls on unactive words to learn and activate them from the shouts submenu in the magic menu. I just found this out after being very confused also. On the pc this is done by highlighting the unactive shout and then pressing R.  On the PS3, it is done with the Square button.
New shouts can be learned all over the world from finding word walls.
Dragon souls are absorbed and saved after killing a dragon.
To get some early new shouts you can ask the greybears for a few word wall locations, it will start up a small quest.


text:
Q: Como puedo usar un string de un activity, en otra activity Tengo un valor tipo String en mi clase encuesta.java, y quiero usar ese String en la clase res8.java, ambas son Activity.
Las dos clases se encuentran en el mismo paquete.
Manifest:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pablo.myapplication">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Resultados" />
    <activity android:name=".encuesta" />
    <activity android:name=".resProfesores" />
    <activity android:name=".res11" />
    <activity android:name=".res9" />
    <activity android:name=".res8"></activity>
</application>

</manifest>

En el monitor de Android:
03-06 14:51:24.403 7172-7172/com.example.pablo.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pablo.myapplication/com.example.pablo.myapplication.res8}: java.lang.NullPointerException
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
                                                                               at android.app.ActivityThread.access$700(ActivityThread.java:134)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                               at android.os.Looper.loop(Looper.java:137)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:4867)
                                                                               at java.lang.reflect.Method.invokeNative(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:511)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                                               at dalvik.system.NativeStart.main(Native Method)
                                                                            Caused by: java.lang.NullPointerException
                                                                               at com.example.pablo.myapplication.res8.onCreate(res8.java:20)
                                                                               at android.app.Activity.performCreate(Activity.java:5047)
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
                                                                               at android.app.ActivityThread.access$700(ActivityThread.java:134)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                               at android.os.Looper.loop(Looper.java:137)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:4867)
                                                                               at java.lang.reflect.Method.invokeNative(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:511)

A: Sería enviar enviar un dato tipo String entre Activities.
El envió de datos entre Actividades se realiza generalmente mediante un Bundle en el cual se agregan valores y ese bundle se envía a través de un Intent hacia la Activity destino.
    Intent intent = new Intent(encuesta.this, res8.class);
    intent.putExtra("dato", "StackOverflow!");
    startActivity(intent);

Los valores se obtienen en la Activity destino mediante getExtras().
String datorecibido = getIntent().getExtras().getString("dato");

o simplemente:
String datorecibido = getIntent().getStringExtra("dato");

En la Activity que recibe el valor, puedes usar el valor y asignarlo a tu TextView:
String datorecibido = getIntent().getExtras().getString("dato");
TextView myTextView = (TextView)findViewById(R.id.reslt);
myTextView.setText(datorecibido);

A: Ejemplo:
Esta línea en encuesta.java
String text = textView.getText().toString();

Ahora necesitas enviar este texto a la otra Activity dónde quieres usarlo.
Esta línea en encuesta.java
startActivity(res8.buildIntent(this, text));

Cuando arranque la Activity obtienes el texto del extra que has enviado.
Este código en res8.java
public static String EXTRA_TEXT = "extra_text";

public static Intent buildIntent(Context context, String text){
    Intent intent = new Intent(context, MyActivity.class);
    intent.putExtra(EXTRA_TEXT, text);
    return intent;
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_activity);

    Bundle bundle = getIntent().getExtras();
    if(bundle != null){
        String text = bundle.getString(EXTRA_TEXT);
    }
}

From:
https://es.stackoverflow.com/a/52659/30953

En tu caso entiendo que coges el texto en encuesta.java y en algún momento quieres cambiar a la Activity res8.java y mantener el texto en la nueva Activity.
Deberías añadir el extra y el método buildIntent() a res8.java y utilizarlo desde encuesta.java dentro del startActivity()

A: Si tu string es algo que tu defines, agrégala como recurso en el archivo strings.xml
<string name="cadena">Mi cadena</string>

Si es algo que ingresa el usuario, envíala como parámetro al crear la siguiente actividad
Intent intent = new Intent(encuesta.this, res8.class);
intent.putExtra("mi_cadena", miString);
startActivity(intent);

y lo recuperas en la siguiente actividad en el onCreate
if(getIntent().getExtras() != null && getIntent().getExtras().hasExtra("mi_cadena")) {
    String miString = getIntent().getExtras().getString("mi_cadena");
}

el if es para verificar si existe el valor, si no lo tiene ya podrías poner alguna sentencia que haga algo en caso de no enviar el dato


text:
Q: Returning data from the business layer to the presentation layer I am developing an ASP.NET 2.0 website. I have created data access and business logic layers. Now in the presentation layer I am returning data from the business layer as a dataset.
My question is whether to use a dataset or object collection (for example a Category object representing the Category table in my database). I have defined all classes that are mapped to database tables (Common objects). But there are situations where I need all of the records from the category table in the presentation layer. I am just confused. What should I do?

A: You don't want to return datasets, you want to return objects.
Generally when you have a data access layer and a business logic layer you will also want to have an entity layer. The entity layer will be an in memory repersentation of the database result set. If you return one row from the database you load one entitiy object. If you return more than one row, you will load an entity for each row, and return a collection of entities to be consumed by the presentation layer.
If you're using .net 2.0 and above for example, you can create generic collections of the entity type and easily bind different types of controls to these collections.
Hope this is helpful for you.

A: I would recomend returning objects or IEnumerable/IList etc of objects.
Depending upon your DB access you can populate a list of category objects manually or using something like LINQ2SQL or ADO.NET Entity framework very quickly, and if required cache them.

A: I've used both methods depending on the situation. If you only need to display the data from a table in a grid, the dataset(or datatable) method isn't terrible because if fields are added to the table they will automatically appear in the grid...assuming you are auto populating the grid with the columns. I look at this method as more of the quick and dirty method.

A: I would not return datasets at all. You are tightly coupling you service to you database. In the future when you database evolves you will be forced to change anything that uses the datasets. You want to create an abstraction layer between the database and the service.

A: I'd go with an object/collection solution. So if you are returning one row from a table you have one object, if you are returning several you'd use a generic collection. Generic collection will avoid a boxing/unboxing hit.
[edit]seems I was beaten to it[/edit]

A: You should create an entity layer, having classes representing each table in database. And then return lists of those classes.


text:
Q: Sum of Duration Fields in Django I am having a small issue in summing up two simple duration fields.
I have two variables which contains two different duration fields. Basically, I just need to sum them in order to get the total time. The problem is that, the way the database is built, I can't use Sum or F or ExpressionWrapper because I have to accept also None values and, the calculation gives me a None value in return.
I post some code:
views. py
duration_dual = Mission.objects.filter(
    training_course_id=1, solo_flight=False)
total_dual_duration = duration_dual.aggregate(eet=Sum(ExpressionWrapper(
    F('duration_dual'), output_field=IntegerField()), output_field=DurationField()))['eet']
if total_dual_duration != None:
    total_dual_duration = duration(total_dual_duration)

duration_solo = Mission.objects.filter(
        training_course_id=1, solo_flight=True)
    total_solo_duration = duration_solo.aggregate(eet=Sum(ExpressionWrapper(
        F('duration_solo'), output_field=IntegerField()), output_field=DurationField()))['eet']
    if total_solo_duration != None:
        total_solo_duration = duration(total_solo_duration)

models.py
class Mission(models.Model):
name = models.CharField(max_length=200)
duration_dual = models.DurationField(blank=True, null=True)
duration_solo = models.DurationField(blank=True, null=True)
training_course = models.ForeignKey(
    TrainingCourse, on_delete=models.CASCADE)
note = models.TextField(null=True, blank=True)
solo_flight = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

In fact, what I need to do is just adding the total_solo_duration and total_dual_duration variables. I tried with datetime or timedelta but I can't figure out the proper way to do so.
Thank you very much in advance

A: In the end I solved in a pretty easy way.
I converted in datetime object my variables and add them to a zero time object.
    solo_dur = dt.strptime(total_solo_duration, '%H:%M')
    dual_dur = dt.strptime(total_dual_duration, '%H:%M')
    time_zero = dt.strptime('00:00', '%H:%M')
    total_duration = solo_dur - time_zero + dual_dur


text:
Q: Whenever the view of the google map is changed from map to satellite view and back, it looses poi.business labels I am trying to view the Google maps and often have to switch between Map and Satellite mode. But, whenever I switch to satellite mode, all the poi.business labels are gone. When I switch back to the Map mode, those labels are still not visible but the labels for roads and such are all visible.
How do I make sure that when the user comes back to Map mode, the poi.business labels are shown again?


text:
Q: What's the Objective-C convention for logging out/purging data? We have a way to purge data from views, a way to purge data from Core Data, a login screen view controller to present, and a way to delete our session object.
Now undoubtedly we'll need these together to logout and show the login screen. Should there be a function in the appdelegate, or another class specifically for this functionality, or handled individually by wherever we need to logout from?
What's the Objective-C convention for this?

A: You have a user object, or a user controller to manage this functionality, right? So that should do it.
The app delegate is for app level event handling, not user management.
Objective-C is a language so it has no convention for user management.
Duplicating the logout code "wherever needed" is bad design. This is really a pure OOP question and you need to define classes and allocate responsibility and ownership accordingly.


text:
Q: Socket programming between client in C#.NET and server in C Here I would like to ask how to create communication through socket programming between client  (on Windows, using C#.NET) and server (on Ubuntu, using C).
I have done successfully if the server-client both are either C#.NET or C but have no idea to do as I asked.
I have tried to find information in several sites but couldn't find the exact one.
I appreciate any comments. Thank you.
Here is simple codes on client.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        // Receiving byte array
        byte[] bytes = new byte[1024];
        Socket senderSock;

        public Form1()
        {
            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btn_connect_Click(object sender, EventArgs e)
        {
            try
            {
                // Create one SocketPermission for socket access restrictions
                    SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,    // Connection permission
                    TransportType.Tcp,        // Defines transport types
                    "",                       // Gets the IP addresses
                    SocketPermission.AllPorts // All ports
                    );

                // Ensures the code to have permission to access a Socket
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost
                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);

                // Create one Socket object to setup Tcp connection
                senderSock = new Socket(
                    ipAddr.AddressFamily,// Specifies the addressing scheme
                    SocketType.Stream,   // The type of socket
                    ProtocolType.Tcp     // Specifies the protocols
                    );

                senderSock.NoDelay = false;   // Using the Nagle algorithm

                // Establishes a connection to a remote host
                senderSock.Connect(ipEndPoint);

            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                // Sending message
                //<Client Quit> is the sign for end of data
                string theMessageToSend = text_IP.Text;
                byte[] msg = Encoding.Unicode.GetBytes(theMessageToSend + "<Client Quit>");

                // Sends data to a connected Socket.
                int bytesSend = senderSock.Send(msg);

            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }

    }
}

this is the codes in server (in C)
include "stdio.h"
#include "stdlib.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "netinet/in.h"
#include "error.h"
#include "strings.h"
#include "unistd.h"
#include "arpa/inet.h"

#define ERROR    -1
#define MAX_CLIENTS
#define MAX_DATA    1024

main(int argc, char **argv)
{
    struct sockaddr_in server;
    struct sockaddr_in client;
    int sock;
    int new,i;
    int sockaddr_len = sizeof(struct sockaddr_in);
    printf("sockaddr_len");
    int data_len;
    char data[MAX_DATA];
    char temp[MAX_DATA];

    if((sock = socket(AF_INET, SOCK_STREAM, 0)) == ERROR)
    {
        perror("server socket: ");
        exit(-1);
    }

    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[1]));
    server.sin_addr.s_addr = INADDR_ANY;
    bzero(&server.sin_zero, 8);

    if((bind(sock, (struct sockaddr *)&server, sockaddr_len)) == ERROR)
    {
        perror("bind : ");
        exit(-1);
    }

    if((listen(sock, MAX_CLIENTS)) == ERROR)
    {
        perror("listen");
        exit(-1);
    }
    printf("\nThe TCPServer Waiting for client on port %d\n",ntohs(server.sin_port));
        fflush(stdout);

    while(1) // Better signal handling required
    {
        if((new = accept(sock, (struct sockaddr *)&client, &sockaddr_len)) == ERROR)
        {
            perror("accept");
            exit(-1);
        }

        printf("New Client connected from port no %d and IP %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));

        data_len = 1;

        while(data_len)
        {
            data_len = recv(new, data, MAX_DATA, 0);
            printf("\nRecieved mesg from client: %s", data);

            for( i = 0; data[ i ]; i++)
            {
                /* if(data[i]=='a' || data[i]=='e' || data[i]=='i' ||data[i]=='o' || data[i]=='u' )
                    data[ i ] = toupper( data[ i ] );
                else */
                data[ i ] = data[ i ] ;

            }

            if(data_len)
            {

                send(new, data, data_len, 0);
                data[data_len] = '\0';
                printf("\nSent mesg to client: %s", data);
            }

        }

        printf("Client disconnected\n");

        close(new);

    }

    close(sock);

}

A: Socket is universal concept and not specific to any language.
You can go ahead and use the same C Ubuntu Server code and C# Windows Client code.
Few Things you need to take care of are :

*

*How you bind the server & client and protocol used.

*Firewall settings.

Hope you can kick start with these inputs
Happy Coding :)

A: So I am assuming your clients can at least talk to each other. But it looks like your issue is that you are sending your text in Unicode format from C# and then receiving it as ASCII on the client side. Unless the default isn't ASCII for your 'C' client.

A: In your Client Code you you call GetHostEntry with an empty hostname. This will give you the IP Address of your Client.
You should call GetHostEntry with the host name of the server:
// Resolves a host name to an IPHostEntry instance
IPHostEntry ipHost = Dns.GetHostEntry("Server.Host.Name");

// Gets first IP address associated with a localhost
IPAddress ipAddr = ipHost.AddressList[0];

// Creates a network endpoint
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);


text:
Q: Why the if statement is ignored if input is meeting the required conditions? I was generating a code which takes AM/PM format from the user and gives the output in 24-hour format. The program works fine for all inputs except when the input range of time is between "12:00:00 AM" to "12:00:00 PM"(Exclusive).
    String[] time = s.split(":");
    int hours = Integer.parseInt(time[0]);
    int minutes = Integer.parseInt(time[1]);
    if(s.endsWith("AM")){
        time[2] = time[2].replace("AM","");
    }
    if(s.endsWith("PM")){
        time[2] = time[2].replace("PM","");
        if(hours != 12)hours+=12;
    }
    int seconds = Integer.parseInt(time[2]);

    String hh,mm,ss;
    if(hours < 10 && s.endsWith("AM")){
        hh = "0"+Integer.toString(hours);
    }
    if(hours == 12 && s.endsWith("AM")){
        hh = "00";
    }else{
        hh = Integer.toString(hours);
    }

Whenever I give input like 6:05:30 AM, hh returns the string "6" but the same time in PM format returns "06".

A: To answer your question, you omitted a else statement from the last block of if statements:
if(hours < 10 && s.endsWith("AM")){
    hh = "0"+Integer.toString(hours);
}
else // This one
if(hours == 12 && s.endsWith("AM")){
    hh = "00";
}else{
    hh = Integer.toString(hours);
}