text:
Q: how to initialize an empty integer array in c++ how to put NULL or empty value to an integer array?
struct book{
char name;
char aut;
int det[10];
};
book bk[40];

here i want every book data type to have there det arrays have value zero for every det[] member.

A: You don't.
Your array det consists of 10 elements, each of which is an object of type int. The length of the array cannot be changed after its creation, and each element has  some int value (or contains undefined garbage if it hasn't been initialized).
For pointer types, there's a special "null pointer" value that's doesn't point to anything and is distinct from all pointer values that are the address of something.
There is no corresponding "null" or "empty" value for type int. 0 is a perfectly valid int value.
If you want to keep track of which elements are valid and which or not, you'll have to use some other method. For example, you might arbitrarily pick some value to denote an invalid entry. You can use 0 for this purpose if you like, but then you won't be able to use 0 as a valid entry. Or you can use INT_MIN, the most negative int value, which is less likely to conflict with a meaningful value. But then you have to write your code so it consistently pays attention to the special value you've chosen.
Or you can use a different data structure, such as a std::vector <int>, that lets you change the length. Which data structure you should use depends on what you're trying to accomplish, which is not clear from your question.

A: I think you mean how to zero-initialize an integer array.:)
You can define the array like
int det[10] = {};

or
int det[10] = { 0 };

You may use such a declaration in a structure.
If the array is already defined then you can use memset. For example
#include <cstring>

//...

std::memset( det, 0, sizeof( det ) );

A: For an int array, you have to initialize it to 0, not null.
int det[10] = { 0 };

For string arrays, you initialize the elements to null, but not for an int.

A: C++11 changed the semantics of initializing an array during construction of an object. By including them in the ctor initializer list and initializing them with empty braces or parenthesis the elements in the array will be default initialized.
struct foo
{
    int x[100];

    foo() : x{} {}
};

In this case each element in foo:x will be initialized to zero.
If you are not using C++11 you can initialize the elements of the array in the constructor body with std::memset.
struct foo
{
    int x[100];

    foo()
    {
        std::memset(x, 0, sizeof(x));
    }
};


text:
Q: Как сделать ресурсы модуля/библиотеки приватными? Сделать ресурсы модуля приватными для других модулей.
Пробовал, что советует официальная документация -- не работает.
Cоздал res/values/public.xml
<resources>
   <public name="app_name" type="string"/>
</resources>

Так же пробовал res/values/public.xml
 <resources>
    <public/>
 </resources>

res/values/strings.xml
<resources>
  <string name="app_name">app_name</string>
  <string name="app_name_2">app_name_2</string>
</resources>

Также пробовал без public.xml
res/values/strings.xml
  <resources>
    <public name="app_name" type="string"/>

    <string name="app_name">app_name</string>
    <string name="app_name_2">app_name_2</string>
  </resources>

<resources>
  <public />
  <string name="app_name">app_name</string>
  <string name="app_name_2">app_name_2</string>
</resources>

В App могу использовать android.example.common.R.string.app_name_2
Пожалуйста, прежде чем предлагать, проверьте, работает ли этот способ, поскольку я искал, и многие предлагают решения, которые не работают.

A: Я думаю проблема со стороны Android Developers, поскольку в ихнем видео говорится как должны работать private resources, но они так не работают.
По этому я создал запрос о проблеме, всех кого это коснулось можете проголосовать(верхнем правом углу) чтобы Google обратил внимание на ошибку.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using a large image (file size) but not hinder load time? My demo is here.
Basically, I have a HUGE image (19160px × 512px to be exact, just under 2MB) that I transition the backgroundx using javascript to make it appear as if a transformation was happening.
I cannot compress the image much more without ruining its quality dramatically. Is there another way that I can achieve this with the same level of cross-browser and not rely on plugins like flash, but have it load faster?

A: Have you considered making this a video?
It might improve loading time somewhat.
Also, another idea. Have you tried using only the first and last image, putting the last one on top of the first, give it opacity:0 and fade it in using JavaScript (e.g. jQuery)?
The effect won't be 100% identical to what you have now, but it might look good enough to please the client, and it would reduce loading time to a bare minimum.
If both ideas won't work for you, I think the first 10-12 frames could be compressed more effectively as GIF images. (It's an estimate, I haven't tried.) You would have to split the image into multiple div s to do that and change the method you use to switch the images, and you would have more requests, but it could be worth it.

A: If it is a jpeg, you can always use progressive encoding. it will become clearer as it is downloaded.

There is also an interlaced
  "Progressive JPEG" format, in which
  data is compressed in multiple passes
  of progressively higher detail. This
  is ideal for large images that will be
  displayed while downloading over a
  slow connection, allowing a reasonable
  preview after receiving only a portion
  of the data. -Wikipedia

A: Slice it like Google Maps.

A: If you want to change that many pixels on the screen at once, you'll have to get them to the client somehow.  You could chunk it into multiple images and use something other than background-x, but then you expose yourself to other potential network interruptions along the way.
The only alternative I can think of to precomputed images like this one is to do the computation on the client - start with the full-colour image and manipulate it using the client's CPU.  Your options here involve canvas or CSS3 or a plugin.

A: I'm not a big fan of Flash but in this case it seems like the right tool for the job (unless you need it work on the iPhone). If you don't have the Flash authoring tool you can use the free Flex compiler.
See http://www.insideria.com/2008/03/image-manipulation-in-flex.html

A: Make it into an animated gif? Break it up into individual parts to remove all the area that is obscured by content.


text:
Q: joining two dataframes with same columns but gives me ValueError: columns overlap but no suffix specified I'm getting errors from my input function:
from nsepy import get_history

data1 = get_history(symbol='TATAMOTORS', start=date(2018,1,1),end=date(2018,6,7))

data2 = get_history(symbol='ALSEC', start=date(2018,1,1), end=date(2018,6,7))
data3=data1.join(data2)

print(data3)

This is the ValueError output that I receive:
data3=data1.join(data2)
ValueError: columns overlap but no suffix specified:
Index(['Symbol', 'Series', 'Prev Close', 'Open', 'High', 'Low',
'Last','Close', 'VWAP', 'Volume','Turnover', 'Trades',
'Deliverable Volume','%Deliverble'],dtype='object')

Could anyone suggest why I'm getting this error?

A: pd.DataFrame.join is used for merging by index, it can be used to combine DataFrames given that they don't have any overlapping columns. What you are looking for is merge instead.
data3 = data1.merge(data2, how='outer')

Notes
There are couple of caveats, you are not importing pandas, date function is an import from datetime.datetime so this should be specified as well.


text:
Q: CMake unable to load boost 1.78.0 components in visual studio 2019 I compiled boost library 1.78.0 for visual studio community edition 2019 (vc142). The library compiled fine and I got this message.
The Boost C++ Libraries were successfully built!
The following directory should be added to compiler include paths:
C:\local\boost_1_78_0

The following directory should be added to linker library paths:
C:\local\boost_1_78_0\stage\lib

I created the environment variables to point to these BOOST_ROOT, BOOST_INCLUDEDIR to the root and BOOST_LIBRARYDIR to C:\local\boost_1_78_0\stage\lib.
In my top level CMakeLists.txt I tried to load the package.
if (POLICY CMP0074)
  cmake_policy(SET CMP0074 NEW)
endif()
find_package("Boost" 1.78.0 REQUIRED COMPONENTS system chrono unit_test_framework)
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIR})

But I am getting this error in visual studio
Severity    Code    Description Project File    Line    Suppression State Error
CMake Error at C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.20/Modules/FindPackageHandleStandardArgs.cmake:230 (message):   Could NOT find Boost (missing: system chrono unit_test_framework) (found   suitable version "1.78.0", minimum required is "1.78.0")       C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.20/Modules/FindPackageHandleStandardArgs.cmake   230

I do see that the library exists in the boost folder.

Using the comment below I added the following flag to CMakeLists.txt
set(Boost_DEBUG ON)

With this I found that following variable was not set. Since I had static libs I needed cmake to looks for lib prefix. Following flag solved the issue.
set (Boost_USE_STATIC_LIBS ON)

I needed to make another tweak to load the chrono library by referrring to it as Boost::chrono instead of boost_chrono on linux.
add_executable(timer4 timer4.cpp)
target_link_libraries(timer4 Threads::Threads Boost::chrono)


text:
Q: Why are Slaaneshi Daemonettes so Ugly If Slaanesh is the god of perfection, the lone god that looks beautiful and all daemons look similar to the form of their patron god, why are Daemonettes so ugly?

A: Daemonettes of Slaanesh do not rely on their physical looks to be beautiful because they are surrounded by a psychic haze that changes the perceptions of those they encounter.

Their true appearance matters little, however, because they are
surrounded by the bewitching aura of their Master. This supernatural
power makes them always appear as the ultimate beauty and object of
desire in the eyes of their unfortunate enemies, regardless of their
race, gender or morality.
- Codex: Chaos Daemons, page 33

They are ugly because they need to be adept at combat, for they are also the front line warriors of Slaanesh's armies. Their physical bodies need to be able to swiftly despatch enemies when they are not using their other talents:

The Daemonettes are Slaanesh's warriors and messengers beyond his
realm. [...] The Daemonettes are vicious, merciless fighters who
attack with astounding speed and grace, tearing apart their foes with
sweeping artistic strokes of their razor-sharp claws.
- Codex: Chaos Daemons, page 33

A: It is a misnomer to believe Slaanesh is only the god of physical beauty or that anyone who worships him will be beautiful. Slananesh is a shapechanger so can be as beautiful or horrifying as she/he wants to be. As a matter of fact, his worshipers come in all sizes and shapes. Slaanesh translates from the Eldar as the "Prince of Pleasure."

*

*Slaanesh is the God of hedonism and excess, not necessarily physical beauty, though he/she does not mind corrupting the physical beauty of others as part of his Chaotic motif.

*Slaanesh has also been called the God of perfection. He wants the driven, those not content to be great in a universe of millions, but to do whatever it takes to be the best. Not just physical perfection, because he does like that, but he is also demands the artisan who seeks to create ever greater objects of beauty, the warrior seeking perfection in his mastery of weapons and death-dealing, the singer who needs one more night on stage to create their finest, greatest and most beautiful song may find themselves praying to Slaanesh, their physical appearance notwithstanding.

*Slaanesh is not limited to just carnal pleasures. Those who desire to indulge in the finest culinary delights, the most beautiful artworks, even the most sensual clothing, could all be amongst Slaanesh's disciples. It is their committment to their talents/gifts/skills that matters most. But it is to the dark side of people, Slaanesh brings to the surface. If you are willing to murder your competition to be the best, you are the kind of person Slaanesh is looking for.

*Slaanesh seeks the obsessive, the compulsive, the people who are driven to the excesses of the flesh, of their craftsmanship, of their need to create. He does not care what you look like because once the touch of the Warp reaches you, you will be physically transformed. The energies of the Warp are the manifestation of dark energies of living things in our Universe; anyone who worships it or the beings who are formed from it are transformed psychically to match their inner state of mental imperfection.

*Slananesh daemonettes are ugly by human standards because once they are created by the chaotic energies of the Warp and they are forever transformed by their darkest inner natures. To Slaanesh, the most corrupted and malformed daemonette is the most beautiful. They have succumbed to their need for perfection and thus fell into his grasp.

*And let's not forget what they are made for: seducing the enemies of Chaos with their wiles, augmented with psychic illusions and when that fails ripping their enemies to bits with their horrifying claws and other weapons, but the victims will believe they were killed by the most beautiful specimens of humanity.


text:
Q: Exporting a sheet to a word table gives a weird outcome I wrote this macro to export an Excel sheet into a word table:
Private Sub Export_Click()        'export to word table
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Sheets("export").Visible = True       'make hidden sheet visible
Set objDoc = objWord.documents.Add()
LastRow = Sheets("export").Range("$G$1").Value  'number of lines to export
For i = 1 To LastRow
Sheets("export").Rows(i).EntireRow.Copy
objWord.Selection.Paste
Next i
Application.CutCopyMode = False         'clear the clipboard
Sheets("export").Visible = 2       'hide the sheet
End Sub

The result is a weird formatted table with cells getting wider and wider toward the bottom, while the original sheet has the same formatting on all the rows and columns.
How can I solve this?

A: Instead of exporting table row by row, you can copy and paste the whole table at once.
Sub Export_Click()
    'export to word table
    Dim objWord As Object
    Dim objDoc As Object
    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Sheets("export").Visible = True       'make hidden sheet visible
    Set objDoc = objWord.Documents.Add()
    lastrow = Sheets("export").Range("$G$1").Value  'number of lines to export

    Range("A1:F" & lastrow).Copy 'mention the number of columns you want to copy

    With objWord
        .Documents.Add
        .Selection.Paste
        .Visible = True
    End With

    Application.CutCopyMode = False         'clear the clipboard
    Sheets("export").Visible = 2       'hide the sheet
End Sub


text:
Q: How to refresh a progress bar in java? I have tried to create this progress bar:
public class ProgressBar extends JFrame{

private JButton fine = new JButton("Chiudi");
final JProgressBar jp;
JPanel body;
JLabel banner1;
JLabel banner2;
JPanel testo;
JTextArea areatesto;
JPanel provapannello;
JTextArea provatesto;
JPanel pannellofine;

public ProgressBar() {
     super("loading");

    setSize(440, 400);
    setResizable(true);
    Container content = getContentPane();
    content.setBackground(Color.YELLOW);
    body = new JPanel();
    body.setLayout(new FlowLayout());
    ImageIcon image1 = new ImageIcon("prova1.png");
    banner1 = new JLabel();
    banner2 = new JLabel();
    banner1.setIcon(image1);
    JTextArea prova = new JTextArea("bar", 2, 40);
    prova.setBackground(Color.LIGHT_GRAY);
    prova.setLineWrap(true);
    body.add(banner1);
    body.add(prova);
    body.add(banner2);
    banner.setBounds(30, 80, 120, 120);
    testo = new JPanel();
    areatesto = new JTextArea("Attendi Per Favore, Sto Preparando Il Tuo PDF", 2, 33);
    areatesto.setLineWrap(true);
    testo.add(areatesto);
   ImagePanel progress_background = new ImagePanel("p.jpg");

    UIManager.put("ProgressBar.background", new Color(29, 29, 29));
    UIManager.put("ProgressBar.foreground", new Color(16, 95, 173));
    UIManager.put("ProgressBar.selectionBackground", new Color(214, 214, 214));
    UIManager.put("ProgressBar.selectionForeground", new Color(29, 29, 29));

    jp = new JProgressBar();
    jp.setUI(new BasicProgressBarUI());

    jp.setBounds(0, 205, 434, 25);
    jp.setMinimum(0);
    jp.setMaximum(100);
    jp.setStringPainted(true);
    jp.setBorder(null);
    progress_background.add(jp);
    provapannello = new JPanel();
    provatesto = new JTextArea("prova", 2, 70);

    provatesto.setBackground(Color.LIGHT_GRAY);
    provapannello.setBounds(0, 226, 500, 100);
    provapannello.add(provatesto);

    content.add(provapannello);
    content.add(progress_background);

    pannellofine = new JPanel();

    pannellofine.add(fine);
    pannellofine.setBounds(340, 330, 100, 100);
    pannellofine.setVisible(false);

    content.add(pannellofine);
    content.add(testo);

    content.add(body);
    Thread runner;
    jp.setValue(0);
    setVisible(true);
    public void setValue(final int j) {

    Runnable target = new Runnable() {
        @Override
        public void run() {
            jp.setValue(j);
        }
    };

    SwingUtilities.invokeLater(target);

}
    public static void main(String Args[]) {
    ProgressBar p = new ProgressBar();

    int i = 0;
    while(true){
        System.out.println("work");
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) { }

        p.setValue(i++);
    }
}

I have tried to change the value of the ProgressBar with the method "setValue" but the bar does not increase, "while" cycles to infinity, but I see no change. what's wrong?

A: I've stripped out most of the unnecessary code (and fixed your compilation errors), and your example works (I've changed the delay and increment, because again, for reproduction purposes you shouldn't waste people's time)
import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class ProgressBar extends JFrame {

    private JProgressBar progressBar;

    public ProgressBar() {
        super("loading");
        setSize(200, 100);
        Container content = getContentPane();
        content.setLayout(new BorderLayout());
        progressBar = new JProgressBar();
        progressBar.setMinimum(0);
        progressBar.setMaximum(100);
        progressBar.setStringPainted(true);
        progressBar.setBorder(null);
        content.add(progressBar, BorderLayout.SOUTH);
        setVisible(true);
    }

    void updateProgress(final int newValue) {
        progressBar.setValue(newValue);
    }

    public void setValue(final int j) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                updateProgress(j);
            }
        });
    }

    public static void main(final String Args[]) {
        ProgressBar myProgressBar = new ProgressBar();
        int i = 0;
        while (i <= 100) {
            System.out.println("" + i + "%");
            myProgressBar.setValue(i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
            i = i + 5;
        }
    }
}

You should really have invested the time in creating an SSCCE
Also on a side note, you should follow this advice when handling InterruptedExcetions


text:
Q: Ajax динамическая загрузка данных через Datatables пытаюсь с помощью serverSide сделать динамическую загрузку данных в таблицу.
У меня есть таблица выглядит она примерно так

html

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.css">

        Корпус
        Этаж
        Комната
        Тип
        Подразделение
        Мест
        Компьютерных мест
        Действия

    {#rows}

js
$(document).ready(function()  {
        var table = $('#audience').DataTable(
            {
                "serverSide": false,

                "ajax": '/ajax/audience/zxv',
                "data": JSON,
                "columns": [
                    { "data": "Корпус" , "width":"1%" },
                    { "data": "Этаж" , "width":"2%" },
                    { "data": "Комната" , "width":"2%" },
                    { "data": "Тип" , "width":"4%" },
                    { "data": "Подразделение" , "width":"10%" },
                    { "data": "Мест" , "width":"1%" },
                    { "data": "Компьютерных мест" , "width":"1%" },
                    { "data": "Действия" , "width":"1%" }

                ],

                language: tables_lang,
                pageLength: 10,
                orderCellsTop: true,
                fixedHeader: true,

                dom: 'l<"toolbar">frtip',
                initComplete: function(){
                    $("div.toolbar")
                        .html('<button class="btn btn-success ml-3 add_audience">Добавить</button>');
                }

            });
        $('#audience thead tr').clone(true).appendTo( '#audience thead' );
        $('#audience thead tr:eq(1) th').each( function (i) {
            var title = $(this).text();
            $(this).html( '<input type="text" placeholder="Поиск" />' );

            $( 'input', this ).on( 'keyup change', function () {
                if ( table.column(i).search() !== this.value ) {
                    table
                        .column(i)
                        .search( this.value )
                        .draw();
                }
            } );
        } );

Когда я задаю значение в serverSide - true
У меня загружаются сразу все данные и происходит примерно следующее

php
if($request->hasValue("zxv")){

    $data = array(
        'data'=>
            array()
    );

    //получаем данные из бд
    $AudienceHome = $audienceHome->getDataRoom();

    if(is_array($AudienceHome)) {
        foreach($AudienceHome as $row) {

            //беру кнопки из шаблона
            $a = $templateHome->parse($modules_root . "audience/tpl/audience_row_table.tpl", $row);
            //формируем строки в таблице
            array_push($data['data'], array("Корпус" =>  $row['body'],"Этаж"=> $row['floor'],"Комната"=>$row['room'],
                                                  "Тип"=>'лекц.',"Подразделение"=>$row['dep'],"Мест"=>$row['places'],
                                                  "Компьютерных мест"=>$row['places_work'],"Действия"=>$a));
        }
    }

    echo json_encode($data);
}

сам json возвращается в таком виде

Что именно я делаю не так? Может нужно как-то по-другому формировать данные на сервере?


text:
Q: Correct and secure manner of storing in-app-purchases What is the best way to store an in-app-purchase on a device,
so that the purchases can also be accessed offline but
the security of the purchases are not compromised?

A: Do not store anything valuable on the device as it cannot be trusted and it can easily be compromised by someone motivated.
Now, all of this depends on the type and value of the item that is being purchased and what happens if its compromised.
If its truly valuable then use a remote secure server for managing secure items. In app purchases include a receipt that can be verified by your remote secure server talking to apple's servers directly through a secure connection. See this link to verifying store receipts.

A: As far as I know, the most convenient way to securely store a purchased asset would be to use some form of encryption.
The user should be able to download an encrypted asset, and the app should decrypt it on the fly.
However, make sure that you store the key in a secure fashion as well, as string keys (within the app binary) can easily be recovered by a skilled hacker. A good way to secure the key would be to use some sort of authentication with a server-based system. The app would get the key off the server and keep it only for the few moments required to decrypt the asset.
This defense mechanism is not impregnable; I feel that it is sophicaticated enough to discourage most users from attempting to undermine it.
To decrypt your assets on the device, a good idea would be to use CommonCrypto. It's provided by Apple (with the iOS SDK), so you don't have to build it from scratch and you don't have to provide documentation (required by US law) for your app. I find Jim Dovey's Common Crypto wrapper the easiest way to use it.
Hope that helps. :)

A: You'll want to encrypt the file, for which your best bet is probably Common Crypto. In order to be able to access the data offline, you need to store the encryption key on the device.
The solution is to use the keychain: Use SecRandomCopyBytes to generate a key of sufficient length, and store it in the keychain using SecItemAdd. Then use that key to encrypt the data and write it to the device's local storage in the normal manner. When it comes time to read the file back from disk, use SecItemCopyMatching to load the key from the keychain and use it to decrypt the data.


text:
Q: login into android app via google I have a problem with loging into android app.
I try implementing this in my app, but I was try looking for "library" or function example.. I try download some project from github and launch in device, but unsuccesfull.. app stard but when I try login, select account and nothing.. some application write on toast "not log in" some not.. and I can't login into app via google..
For last I try https://www.youtube.com/watch?v=n2XgERPfMcU this.
https://github.com/googlesamples/google-services same "error"
I try 5-6 projects. The same problem..
I thing so problem it's in my phone, but I don't know where,thise app permissions not want not special..
Please help :)
I try on 2 mobiles.
Xiaomi Mi3, Xiaomi Mi4

or I need write some ID's in downdload projects? or:...


text:
Q: Bigquery and financial calculations I'm trying to calculate IRR and NPV for over 600 million records in bigquery. Since bigquery does not have any looping mechanism, or have any IRR functionality or storing values in variables; we are stuck. We are running out of options and are considering calling it quits with bigquery :((
What would be the best way to read each of the 600 million rows, perform certain calculations (IRR) and write them back to a table? Our current option is to take it out of bigquery upload it to oracle, run the calculations, export and put it back in Bigquery. Doing it within bigquery is timing out after running for a few hours.
We are in a conundrum and any advice/tips will be really appreciated.

A: You may have seen the demo of user-defined functions from the Cloud Platform Live event in march. We're currently looking for trusted testers for this functionality. Essentially, you can write a javascript function that can read and emit rows of data. While this is still an early preview of this functionality, it is pretty robust, using the V8 Javascript execution engine.
If you're interested, please contact your cloud support representative and ask about joining the UDF trusted-tester program. If you don't get a response, please feel free to e-mail me at tigani at google, and I'll route to the right place. (we are limiting the number of trusted testers that we sign up, at least at first, however).


text:
Q: Add custom size fields to product in big cartel I have an online store on big cartel and some of the products may require an optional field where the user can type in his/her measures so that the product can be specifically designed for him/her. Although I am familiar on how to implement the front-end part of this, I am not quite sure how to make it comfortable for the vendor to have these extra info attached to each product so that when they visualize the order all these extra info are immediately attached to it.
My best case scenario is this:
The user picks a product and selects on the Size drop down choice the "Custom" option. At this point a little form will appear that they can fill with all the custom size they need. Now instead of attaching the string "Custom" to the product summary in the cart, I would like to have whatever they typed attached to it so that in the cart it will look something like:
[ PICTURE OF THE PRODUCT ] : product name - sizes typed by the user
This would make it easier for the vendor to understand what the user wants and will allow the user to purchase an item with custom size instead of the standard ones that might not be suitable for him/her (XS, S, M, L, XL).
Right now the code part that handles the size choice and submits to the cart looks like this:
<form id="product-form" method="post" action="/cart">

        {% if product.has_default_option %}

        {{ product.option | hidden_option_input }}

        {% else %}

                        {{ Product_Options_Title }}
                      {{ product.options_in_stock | options_select }}

        {% endif %}

        <button id="product-addtocart" name="submit" type="submit">{{ Add_to_Cart_Text }}</button>

    </form>

I thinks this is Angular which I am not very familiar with. But I think here is where I should make any change, I am also not very familiar with the big cartel framework, this is why I could use some pointers.
So my question would be, how do I edit the code so that the user can type in custom sizes and then attach what they typed to the product in the cart as the size they ordered ?
I understand my question might not be very clear so feel free to comment for clarifications. Keep also in mind that I would know how to implement the front-end part but I don't know how to interact with the back-end to make what I described happen. Thanks in advance.

A: Sorry, but something like this isn't possible with Big Cartel - the platform doesn't support passing any additional information through the order process beyond what's already attached to the Product and the Product's Options.
Your best option is likely to instruct customers to add their custom information to the "Notes to seller" field at Checkout: https://blog.bigcartel.com/2014/04/22/introducing-notes-at-checkout/
You can find more information on editing Big Cartel themes here: https://help.bigcartel.com/developers/themes/

A: Bigcartel now coming with grouped option. It's only active on paid plan. So you can add now size, color, design. Yes, you can add maximum three option variant.


text:
Q: Cannot Select ul li after append jquery I want to create a select option box after the user chooses the select option before.
the first select option variable is printed by php. my this code

';

$num = 0;
$q = json_decode(SysTragedyParent::ReadAll($db_config),true);
$HitungData = sizeof($q['result']['data']);

while ($HitungData > $num) {
    $data .= '
'.$q['result']['data'][$num]['nama_kejadian'].'
';
$num++;
                                        }

After That I Call Ajax To call data from the first select option
like this code
/** Fungsi Untuk Mencari Data Tragedy Parent Yang Ada Di Buat Laporan Data Untuk Melakukan Pencarian kategori Child ***/
$('ul.SysReportParent li').click(function () {

    //console.log($(this).attr('value'));
    $.ajax({
        url: 'https://' + window.location.hostname + '/Api',
        cache: false,
        type: 'POST',
        dataType: 'json',
        data: {
            'sys_tragedy_child': true,
            'id_sys_report_parent': $(this).attr('value')
        },
        success:function (result) {
            $('.childTragedyReport li').remove();
            var num = 0;
            var hitungChildTragedy = result.result.data.length;
            while (hitungChildTragedy > num ){
                $('.childTragedyReport').append('
'+ result.result.data[num].nama_kejadian +'
');
                num++;
            }

        },
        error:function (result) {
            $.toast({
                heading: 'Pengambilan Gagal', // Menampilkan Judul Notifikasi
                text: 'Data Kategori Tidak Ditemukan', // Menampilkan Text Notifikasi
                position: 'top-right', // Berada pada Posisi kanan Atas
                loaderBg:'#1d32ff', // background Warna Loading
                icon: 'error', // Icon Indicator Jika Berhasil dilakukan Aksi Program
                hideAfter: 5500, // Menghapus Pesan Jika Sudah Muncul Di Lakukan Data System
                stack: 6
            });
        }

    });

});

everything goes Normal. However when I want to click on select the second option.
select option cannot select the selected item
My Picture


text:
Q: What is considered 'superfluous or actively harming readability' edit and 'deviating from the original intent of the post' edit? I suggested an edit to this answer which consists of:

*

*Changing W3Schools link to an appropriate W3C one.

*Changing JSON's formatting from:
{"key1" : 0,
 "key2" : "str"}

to:
{
    "key1": 0,
    "key2": "str"
}

as that's how it is usually formatted.

*Changing 'javascript' to 'JavaScript'.
Yet the suggestion got rejected for the following reasons:

*

*
This edit does not make the post even a little bit easier to read,
  easier to find, more accurate or more accessible. Changes are either
  completely superfluous or actively harm readability.

*
This edit deviates from the original intent of the post. Even edits
  that must make drastic changes should strive to preserve the goals of
  the post's owner.

Can somebody elaborate on these reasons and whether they are legitimate in this case?

A: I do agree with the reason 1 because:
Because just including some line spacing to the brackets in JSON is really unnecessary, and doesn't make it clearer.
I don't really mind the JSON code which doesn't have a separate line for the brackets. So, the edit was unnecessary.
I know that javascript and JavaScript are the same. So again, the edit was unnecessary.
So, I would reject the edits with the reason 1.
However, I don't think your edits would lie in the Reason 2's category.


text:
Q: How to get Client machine time on server on pageload event I want to use client system date on page load event,
How can I do that.
Since this is not a post back so please let me know how to do it.
Thanks

A: var currentDate = new Date()

The currentDate object will have the methods:
getMonth()
getDate()
getFullYear()

This should give you what you need.
Edit:
Since you mentioned time in the title of the post, it's probably worth mentioning that currentDate will also have:
getHours()
getMinutes()

should you want to display the current time as well.
Edit 2:
To tie into page loading
<script type="text/javascript">
  function buildDate() {
    var date = new Date();
    /*build date string here*/
  }
</script>

<body onload="buildDate()">
Other stuff here...
</body>

A: var a = "&date=" + (new Date().replace(/\s+/g, ""));

Just append the value of a to all your links back to the server.  On the serverside you will see the datetime come across in the HTTP request.


text:
Q: Run Flask app with arguments in command line I have a flask app that works fine. However I need to include arguments when running the app in the command line. I can use python app.py arg1 but when I try using flask run arg1 it throws the error:
Error: Got unexpected extra argument (arg1)

Is there any way to add arguments to the flask run command?

A: Instead of using flask run you could define your entrypoint like so
import sys
from flask import Flask

if __name__ == '__main__':
  foo = sys.argv[1]
  app = Flask(__name__)
  app.config['foo'] = foo
  app.run()

However, it's probably wiser to create a custom cli command to take arguments for you and start up the flask app.
Read more about custom cli commands here.


text:
Q: Katalon Studio: Multiple keywords mapped in one we're trying to evaluate some automation tools right now. We are currently looking at Katalon Studio. And sadly we didn't find a way to accomplish a very simple task: Mapping multiple keywords into one.
Let's say we have the following keywords for login in to our web interface:
click_on_username
send_keys "user1"
click_on_password
send_keys "password1"

So let's imagine I have multiple times (e.g. tests) I need to log in. As I dont want to be repetitive: How can I map those four keywords into just one, for example in a "login_with_credentials "user1, password1" without coding everything again, but just by simply bind those keywords together in a hierachial way.
Let's say:
login_with_credentials "user1, password1" -> click_on_username
                                             send_keys "user1"
                                             click_on_password
                                             send_keys "password

How do I do that?

A: You can create Custom Keywords in Katalon Studio. See:
https://www.katalon.com/resources-center/tutorials/create-custom-keyword/

A: If you are comfortable with Cucumber you can use it in Katalon Studio since version 5.7.0: https://www.katalon.com/resources-center/blog/cucumber-bdd-automation-testing/.


text:
Q: Mysql query statement to find how many time I am the max amount for a listing Here is my tabel structure.
id
veh_id
user_id
amount
...

I have other tables to relate the user_id and veh_id as well.
I want to know how many times a user has put an amount on each veh_id and on how many occasions, this amount is actually the highest amount received.  I would like to have those 2 counts for each user available.
id, veh_id, user_id, amount
1    1       30        100
2    1       32        105
3    2       30        100
4    2       32        95
5    2       33        90

I would like the select statement to give me:

user 30 as bid 2 times and 1 time is the higest bidder
user 32 as bid 2 time ans 1 time is the higest bidder
user 33 bid 1 time and 0 time the highest bidder

I don't know if it is possible to get those numbers.

A: This might be close, not sure exactly how you're relating vehicles together.
select
  user_id,
  count(*) as num_bids,
  SUM(is_highest) as max_bids
from ( select
  a.user_id,
  COALESCE((select
      MAX(b.amount) < a.amount
    from bid as b
    where b.id < a.id
    and b.veh_id=a.veh_id
  ), 1) as is_highest
from bid as a
) as c
group by user_id

My understanding is user 30 has 2 max bids (2 first bids on a vehicle).
EDIT: If you're just looking for total 1 max bid per vehicle, let me know.  That's actually a lot easier than rolling back to see who's bids were max when they came in...
EDIT2: Solution for only 1 max counts per vehicle:
Seems like this should be simpler for some reason:
select
 user_id,
 count(*) as num_bids,
 count(vamt) as num_max
from bid
left join (
  select veh_id as vid, max(amount) as vamt
  from bid
  group by veh_id
) as a on vid = veh_id and vamt <= amount
group by user_id

A: Try this,
select x.user_id, x.bid_times, COALESCE(y.max_times,0) as max_times from
(select user_id, count(*) as bid_times from testt group by user_id) as x
 LEFT JOIN
(select user_id, count(*) as max_times  from testt a where 0=( select count(*) from testt where amount > a.amount and veh_id=a.veh_id ) group by user_id) as y
ON x.user_id=y.user_id


text:
Q: Heroku assets precompile error I did a heroku push for an application and it worked fine earlier. Tried pushing minor updates that did not include modification of any asset file to the same app and now Sprockets is saying it can't find a jquery file that is not missing. I've not found it easy pinpointing the error so every help is welcomed.
Here's the stack trace before the error:
remote:        Using rake 10.4.2
remote:        Using i18n 0.7.0
remote:        Using json 1.8.3
remote:        Using minitest 5.8.0
remote:        Using thread_safe 0.3.5
remote:        Using tzinfo 1.2.2
remote:        Using activesupport 4.2.3
remote:        Using builder 3.2.2
remote:        Using erubis 2.7.0
remote:        Using mini_portile 0.6.2
remote:        Using nokogiri 1.6.6.2
remote:        Using rails-deprecated_sanitizer 1.0.3
remote:        Using rails-dom-testing 1.0.7
remote:        Using loofah 2.0.3
remote:        Using rails-html-sanitizer 1.0.2
remote:        Using actionview 4.2.3
remote:        Using rack 1.6.4
remote:        Using rack-test 0.6.3
remote:        Using actionpack 4.2.3
remote:        Using globalid 0.3.6
remote:        Using activejob 4.2.3
remote:        Using mime-types 2.6.1
remote:        Using mail 2.6.3
remote:        Using actionmailer 4.2.3
remote:        Using activemodel 4.2.3
remote:        Using arel 6.0.3
remote:        Using activerecord 4.2.3
remote:        Using acts-as-taggable-on 3.5.0
remote:        Using acts_as_indexed 0.8.3
remote:        Using addressable 2.3.8
remote:        Using awesome_nested_set 3.0.2
remote:        Using babosa 1.0.2
remote:        Using bcrypt 3.1.10
remote:        Using bundler 1.9.7
remote:        Installing coffee-script-source 1.9.1.1
remote:        Using execjs 2.6.0
remote:        Using coffee-script 2.4.1
remote:        Using thor 0.19.1
remote:        Using railties 4.2.3
remote:        Using coffee-rails 4.1.0
remote:        Using decorators 2.0.1
remote:        Using orm_adapter 0.5.0
remote:        Using responders 2.1.0
remote:        Using warden 1.2.3
remote:        Using devise 3.5.2
remote:        Using multi_json 1.11.2
remote:        Using dragonfly 1.0.10
remote:        Using excon 0.45.4
remote:        Using formatador 0.2.5
remote:        Using net-ssh 2.9.2
remote:        Using net-scp 1.2.1
remote:        Using fog-core 1.32.1
remote:        Using fog-json 1.0.2
remote:        Using fog-xml 0.1.2
remote:        Using ipaddress 0.8.0
remote:        Using fog-aws 0.7.4
remote:        Using dragonfly-s3_data_store 1.2
remote:        Using filters_spam 0.5
remote:        Using friendly_id 5.1.0
remote:        Using friendly_id-globalize 1.0.0.alpha2
remote:        Using globalize 5.0.1
remote:        Using jbuilder 2.3.1
remote:        Using jquery-rails 4.0.4
remote:        Using jquery-ui-rails 5.0.5
remote:        Using pg 0.18.2
remote:        Using sprockets 3.3.2
remote:        Using sprockets-rails 2.3.2
remote:        Using rails 4.2.3
remote:        Using rails-i18n 4.0.4
remote:        Using rails_autolink 1.1.6
remote:        Using rdoc 4.2.0
remote:        Using routing-filter 0.5.0
remote:        Using refinerycms-i18n 3.0.1
remote:        Using sass 3.4.16
remote:        Using tilt 1.4.1
remote:        Using sass-rails 5.0.3
remote:        Using truncate_html 0.9.3
remote:        Using will_paginate 3.0.7
remote:        Using zilch-authorisation 0.0.1
remote:        Using refinerycms-core 3.0.0 from https://github.com/refinery/ref
inerycms (at master)
remote:        Using refinerycms-images 3.0.0 from https://github.com/refinery/r
efinerycms (at master)
remote:        Using seo_meta 2.0.0.rc.1
remote:        Using speakingurl-rails 1.1.5
remote:        Using refinerycms-pages 3.0.0 from https://github.com/refinery/re
finerycms (at master)
remote:        Using refinerycms-resources 3.0.0 from https://github.com/refiner
y/refinerycms (at master)
remote:        Using refinerycms 3.0.0 from https://github.com/refinery/refinery
cms (at master)
remote:        Using refinerycms-acts-as-indexed 2.0.1
remote:        Using refinerycms-authentication-devise 1.0.4
remote:        Using refinerycms-settings 3.0.0
remote:        Using refinerycms-blog 3.0.0 from https://github.com/refinery/ref
inerycms-blog (at master)
remote:        Using refinerycms-image_slideshows 3.0.0 from https://github.com/
bisscomm/refinerycms-image-slideshows (at master)
remote:        Using refinerycms-inquiries 3.0.0 from https://github.com/refiner
y/refinerycms-inquiries (at master)
remote:        Using refinerycms-page-images 3.0.0 from https://github.com/refin
ery/refinerycms-page-images (at master)
remote:        Using refinerycms-portfolio 3.0.0 from https://github.com/refiner
y/refinerycms-portfolio.git (at qa-3-0-0)
remote:        Using refinerycms-wymeditor 1.0.6
remote:        Using sdoc 0.4.1
remote:        Using turbolinks 2.5.3
remote:        Using uglifier 2.7.1
remote:        Bundle complete! 23 Gemfile dependencies, 98 gems now installed.
remote:        Gems in the groups development and test were not installed.
remote:        Bundled gems are installed into ./vendor/bundle.
remote:        Bundle completed (16.19s)
remote:        Cleaning up the bundler cache.
remote:        Removing coffee-script-source (1.8.0)
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        I, [2015-08-21T16:42:59.088361 #483]  INFO -- : Writing /tmp/buil
d_d6313583d1a6da7773bae66db2a32634/public/assets/ahyhor-63767739ac2e0fcaff837cab
66db3919e77e067c03368a3616af175e0a46539b.css

Here's the stack trace for the error:
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        I, [2015-08-21T16:42:59.088361 #483]  INFO -- : Writing /tmp/buil
d_d6313583d1a6da7773bae66db2a32634/public/assets/ahyhor-63767739ac2e0fcaff837cab
66db3919e77e067c03368a3616af175e0a46539b.css
remote:        rake aborted!
remote:        Sprockets::FileNotFound: could not find file: /tmp/build_2f5ca9ff
4027e36c413404990f7b3a33/vendor/bundle/ruby/2.0.0/gems/jquery-rails-4.0.4/vendor
/assets/javascripts/jquery.js
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:95:in `load_from_unloaded'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:60:in `block in load'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:286:in `fetch_asset_from_depend
ency_cache'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:44:in `load'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/cached_environment.rb:20:in `block in ini
tialize'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/cached_environment.rb:47:in `yield'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/cached_environment.rb:47:in `load'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/bundle.rb:23:in `block in call'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/utils.rb:183:in `dfs'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/bundle.rb:24:in `call'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/processor_utils.rb:75:in `call_processor'

remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/processor_utils.rb:57:in `block in call_p
rocessors'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/processor_utils.rb:56:in `reverse_each'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/processor_utils.rb:56:in `call_processors
'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:126:in `load_from_unloaded'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:60:in `block in load'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:286:in `fetch_asset_from_depend
ency_cache'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/loader.rb:44:in `load'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/cached_environment.rb:20:in `block in ini
tialize'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/cached_environment.rb:47:in `yield'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/cached_environment.rb:47:in `load'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/base.rb:66:in `find_asset'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/base.rb:73:in `find_all_linked_assets'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/manifest.rb:130:in `block in find'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/manifest.rb:129:in `each'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/manifest.rb:129:in `find'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/sprockets/manifest.rb:162:in `compile'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-rails-2.3.2/lib/sprockets/rails/task.rb:70:in `block (3 level
s) in define'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-3.3.2/lib/rake/sprocketstask.rb:147:in `with_logger'
remote:        /tmp/build_d6313583d1a6da7773bae66db2a32634/vendor/bundle/ruby/2.
0.0/gems/sprockets-rails-2.3.2/lib/sprockets/rails/task.rb:69:in `block (2 level
s) in define'
remote:        Tasks: TOP => assets:precompile
remote:        (See full trace by running task with --trace)
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:
remote:  !     Push rejected, failed to compile Ruby app

A: The problem was due to an issue in Sprockets version 3.3.2. A version update a day later to Sprockets(3.3.3) fixed this problem.


text:
Q: Firestore simple node script on pc doesn't work even though same code runs perfectly on firebase functions Hello I am running a small script that I want to run locally since max timeout of firebase functions is 9 minutes and that is not enough for me (I have to run a large scale update on data types).
So the code is basically:
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

db.collection('users')
  .get()
  .then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
      // update doc
    });
  });

But querySnapshot.docs has 0 elements. I checked the same code in functions and it works properly. What could be the cause of this?  If this is not possible are there any workarounds where I can bypass timeout using cloud functions?
Firebase is initialized correctly both in my machine and directory. I tried a clean initialized directory too. Same code when passed to an firebase function endpoint and ran once works perfectly fine.

A: If you run a script written with the Admin SDK locally on your computer you need to initialize the SDK with an exported service account key file as explained in the doc.
The doc details how to:

*

*Generate a private key file in JSON format from the Firebase console

*Set an environment variable to the file path of the JSON file that contains your service account key.

Then you can do as follows:
const admin = require('firebase-admin');
admin.initializeApp({
    credential: applicationDefault()
});

const db = admin.firestore();

db.collection('users')
    .get()
    .then(querySnapshot => {
        return Promise.all(querySnapshot.docs.map(doc => doc.ref.update( {...} ))):
    })
    .then(() => {...})
    .catch(...)

Note that to update several docs within a loop via the asynchronous update() method you'll need to use Promise.all(), as shown above.

A: When I initialized like this everything seemed to work fine. The reason why applicationDefault doesn't work is I think because doc says it works in google environments.
const admin = require('firebase-admin');
var serviceAccount = require('path/to/key.json')

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});


text:
Q: Como se pasan datos de un json a un constructor para q los guarde en getter y setters en java? Aqui saco los datos del json de una url
JSONObject json = readJsonFromUrl("http://ddragon.leagueoflegends.com/cdn/12.7.1/data/es_ES/champion.json");
Set<String> nombres = json.getJSONObject("data").keySet();

for (String  nombre: nombres) {

      JSONObject jsondata = json.getJSONObject("data");
      JSONObject jsname = jsondata.getJSONObject(nombre);

      System.out.println( "http://ddragon.leagueoflegends.com/cdn/12.10.1/img/champion/"+nombre+".png");
      System.out.println(jsname.get("name"));
      System.out.println(jsname.get("title"));

      }
}

Entonces quiero pasar esos datos a un constructor con los getter y setter para guardarlos ahi y llamarlos en otra parte.
Ayuda por favor
EDIT
Esta es la clase donde queiro gaurdar los datos generados anteriormente
public class Campeones {
}
PErdon estoy muy perdido


text:
Q: Intersection of conic and a line in $\mathbb{P}^2$ Let $C \subseteq \mathbb{P}^2$ be defined by $A x^2 + B y^2 + C z^2 = 0$ and let $P$ be a point on $C$ with $\mathbb{Q}$ coordinates.
I was wondering what assumptions do I need to establish that there is a bijection between lines defined over $\mathbb{Q}$ going through $P$ and the rational points of $C \backslash \{P\}$?
Thank you!

A: The correct statement here is that for a smooth conic $C\subset \Bbb P^2_k$ with a $k$-rational point $P$, there's a bijection between $k$-rational lines through $P$ and $k$-rational points on $C$. This is a consequence of Bezout's theorem: the intersection of any $k$-rational line $L$ with $C$ is two points counted with multiplicity. As $C$ is smooth, it has a unique tangent at each point - if $L$ is the tangent at $P$, this means it intersects $C$ with multiplicity two at $P$, and this gives you $P$. If $L$ is not the tangent, then it intersects $C$ with multiplicity one at $P$ and has a unique other $k$-rational point of intersection with $C$.
In order to get the correct statement from your post, we should require that $C$ is smooth, which means that $A,B,C\neq 0$, and then also make one of the following changes: either replace $C\setminus \{P\}$ with $C$, or replace "lines through $P$" with "non-tangent lines to $C$ through $P$".


text:
Q: MSpec runs under ReSharper fine, but TD.NET throws exception I've been receiving this exception when trying to run mspec specification tests with TD.NET.
------ Test started: Assembly: DesignRightWeb.Specs.dll ------

Error: Runner failure: System.Runtime.Serialization.SerializationException: Type is not         resolved for member 'Machine.Specifications.Runner.RunOptions,Machine.Specifications,     Version=0.3.0.0, Culture=neutral, PublicKeyToken=null'.
   at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
   at     Machine.Specifications.Runner.Impl.AppDomainRunner.CreateRunnerAndUnloadAppDomain(String     runMethod, AppDomain appDomain, Assembly assembly, Object[] args) in d:\BuildAgent-    01\work\340c36596c29db8\Source\Machine.Specifications\Runner\Impl\AppDomainRunner.cs:line     81
Test 'T:DesignRightWeb.Specs.given_a_string_calculator' failed: Type is not resolved     for member 'Machine.Specifications.Runner.RunOptions,Machine.Specifications,     Version=0.3.0.0, Culture=neutral, PublicKeyToken=null'.
    System.Runtime.Serialization.SerializationException: Type is not resolved for member 'Machine.Specifications.Runner.RunOptions,Machine.Specifications, Version=0.3.0.0, Culture=neutral, PublicKeyToken=null'.
    at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes)
    at Machine.Specifications.Runner.Impl.AppDomainRunner.CreateRunnerAndUnloadAppDomain(String runMethod, AppDomain appDomain, Assembly assembly, Object[] args)
    at Machine.Specifications.Runner.Impl.AppDomainRunner.RunMember(Assembly assembly, MemberInfo member)
    at Machine.Specifications.TDNetRunner.SpecificationRunner.RunMember(ITestListener testListener, Assembly assembly, MemberInfo member)
    at TestDriven.TestRunner.AdaptorTestRunner.Run(ITestListener testListener, ITraceListener traceListener, String assemblyPath, String testPath)
    at TestDriven.TestRunner.ThreadTestRunner.Runner.Run()

0 passed, 1 failed, 0 skipped, took 1.12 seconds (MSpec).

I've tried installing MSpec straight from Github and also installed it using NuGet.  After that - while receiving this same exception - I uninstalled TD.NET and re-installed TD.NET.  Still receiving this exception.
Any ideas?  Thoughts?  Solutions?

A: Could be you need to register the MSpec test runner into TestDriven.NET? Check out this post to help you:
http://eduncan911.com/blog/registering-mspec-runners-for-testdriven-net-on-windows-x64.aspx

A: If you registered the TD.Net runner before, please unregister it (some Registry hacking might be needed - see InstallTDNetRunner.bat how to undo).
Please make sure you run TD.Net >= 2.24. Add the NuGet package to your project and run tests through TD.Net. The NuGet package also contains an updated ReSharper runner that you might want to install.
If the error still persists, you very likely have an old version of MSpec referenced somewhere. The old version is 0.3.0.0 whereas NuGet is currently at 0.4.7.0.
(I might add - by the time you posted your question we had a NuGet package contributed by someone. That package didn't contain the appropriate TD.Net runner. The issue you described should be resolved now that we have a new NuGet package containing all runners.)


text:
Q: A faster way of building a Pandas.Dataframe from list of dictionaries than loop? [Python 3.9] I have a list of 5000 dictionaries where each dictionary has around 40 items, I have built a for loop that is extreeeemly slow - it needs a couple of minutes.
        # symbol_list_final is the list of dictionaries
        symbols_dataframe = pd.DataFrame([symbols_list_final[0]])

        for i in range(len(symbols_list_final) - 1):
             symbol_df_temp = pd.DataFrame([symbols_list_final[i + 1]])
             symbols_dataframe = pd.concat((symbols_dataframe, symbol_df_temp), axis=1)
             print(i)

Is there any way of doing it faster?
EDIT: It's way slower, My program is running rn, and it takes 1 seconds to make 4-5 iterations.

A: It seen like you are trying to formulate multiple dict dataframes and concatenate then into a single variable, containing your end_df.
Firstly, the correct approach envolves not concatenating them all the time, only running such command once. So would recommend stacking the df objects on a list, and them concatenating
list_of_dfs = []
for i in list_dict:
    list_of_dfs.append(pd.DataFrame(i))

So pd.concat(list_of_dfs ) would be wise than redefining your variable all the time in your loop
Now if creating the df object is taking a while (give us the time). Well there are other ways of approaching this issue, such as  the library pyarrow (which can be faster depending on your cpu).


text:
Q: How to add support of multi-line arguments for Python scripts using argparse? I've just created a Python project that uses argparse for parsing arguments. But it seems that it does not support multi-line arguments. One can check the example/command-line.sh in the project, and will find it does not understand the following style
#!/bin/bash
../scripts_gen.py --template template.txt \
                  --save-to scripts \
                  --param "{'data':'datasets.txt', \
                            'lambda':[`echo 0.{0..9}|sed -E 's/\s+/,/g'`], \
                            'seed':[233,874]}" \
                  --format "{data}_lambda={lambda}_seed={seed}.sh" \
                  --delete

Note that this is legal in shell script: one can always write
$ ls -l \
> -f

in console or shell script file (no prompt in this case). So can I add support for this via argparse? Thank you.

A: Post-facto answer, based on my comments:

*

*The problem is in your bash script. If it worked as intended, python wouldn't even know there's a newline between arguments--the shell handles that and removes the newline. Most likely there's a space after the first backslash.

*But since the same file works properly on Debian but fails under cygwin, it was not a space after the backslash. Perhaps it's a problem with the line endings in your script?

*So, the problem was automatic CR/LF conversion by git, combined with a strange refusal by cygwin to understand the line-ending conventions of its host operating system. Though you fixed it by hand-converting the script back to unix line endings, I would recommend a more robust solution: You could enable CR/LF support in cygwin (since you imply that it is an option), but my preference would be to also disable git's CR/LF mapping. And check that all your common tools and editors are configured to handle both kinds of line ending properly.


text:
Q: Retrieve @Authorization swagger codegen java I work with swagger 2.0 to define a back end and trying to define security.
I end up with :
---
swagger: "2.0"
info:
  version: 1.0.0
  title: Foo test
schemes:
- https
paths:
  /foo:
    get:
      security:
        - Foo: []
      responses:
        200:
          description: Ok
securityDefinitions:
  Foo:
    type: apiKey
    name: X-BAR
    in: header

Everything good till now, java codegen give me :
@ApiOperation(value = "", nickname = "fooGet", notes = "", authorizations = {
        @Authorization(value = "Foo")
    }, tags={  })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Ok") })
    @RequestMapping(value = "/foo",
        method = RequestMethod.GET)
    default ResponseEntity<Void> fooGet() {
        if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
        } else {
            log.warn("ObjectMapper or HttpServletRequest not configured in default FooApi interface so no example is generated");
        }
        return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
    }

I'm wondering, in the interface, how to retrieve "properly" the X-BAR header value.
I end up with :
@Autowired
private HttpServletRequest httpServletRequest;

httpServletRequest.getHeader("X-BAR")

which works , but is there a more proper way ?
Define a class "Foo" ? a doFilter ?
Thanks


text:
Q: how to write a future that wait for an event I have a client/server socket that does some rpc things. I know a bit about finagle and I find the isolation with a Future very elegant. So my question would be how to write a Future in scala that wait for an event (the server reply of my client request). The implementation would probably use identified request but what I lack is the way to ask the future to wait for the event without a busy wait.

A: Create a Promise instead of Future and add a listener to your event which fulfills the promise. Return the promise's future to your client (in Twitter Util future library it's the promise itself, in Scala 2.10 it's p.future).

A: For this purpose you need to take a look at Akka Actors
Here is example of an actor
class MyActor extends Actor {
   val log = Logging(context.system, this)
   def receive = {
      case "test" ⇒ log.info("received test")
      case _      ⇒ log.info("received unknown message")
   }
}


text:
Q: The rotations of bidiagonal matrices Let $B$ is upper bidiagonal matrix. Consider the algorithm:
$ B_0 = B, C_k = B_{k-1}Q_k, B_k = Z_kC_k $,
where $B_k$ is upper bidiagonal, $C_k$ is lower bidiagonal and $Q_k$ and $Z_k$ are unitary. So at each iteration, we change the upper bidiagonal matrix to the lower and vice versa. Prove that matrices $B_k$ and $C_k$ converges to the same diagonal matrix.
Really I have no ideas how to prove it. I suppose that matrices $Q_k$ and $Z_k$ can be implemented as a Givens rotations. But maybe there are another variants of transforms $Q_k$ and $Z_k$.
Also I noticed that after each iteration the absolute value of $\{B_k\}_{11}$ and $\{C_k\}_{11}$ is growing because the unitary transform saves the second norm. And because of the same reasons the absolute value of $\{B_k\}_{nn}$ and $\{C_k\}_{nn}$ is decreasing. But I can not say anything about the intermediate diagonal elements.
Maybe this statements is a part of some algorithm of constructing SVD, but I do not know this algorithm. Thanks for any help of ideas!

A: Remind that unitary transforms save the second norm of the vector. So, we have $$ Z\begin{bmatrix}
\times & 0 & 0 & \dots & 0 \\
\times & \times & 0 & \dots & 0 \\
0 & \times & \times & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & \times \\
\end{bmatrix} = \begin{bmatrix}
\times & \times & 0 & \dots & 0 \\
0 & \times & \times & \dots & 0 \\
0 & 0 & \times & \dots & 0 \\
\dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & \times \\
\end{bmatrix}$$
Hence for the first column we have $ |\{C_n\}_{11}|^2 + |\{C_n\}_{21}|^2 = |\{B_{n+1}\}_{11}|^2 $ and similarly $ |\{B_n\}_{11}|^2 + |\{B_n\}_{12}|^2 = |\{C_{n}\}_{11}|^2 $. Since $\{B_n\}_{11}$ and $\{C_n\}_{11}$ does not tense to infinity, $|\{C_n\}_{21}|, |\{B_n\}_{12}| \to 0$. Using it and writing the same equations for the second column and row we can state that  $|\{C_n\}_{32}|, |\{B_n\}_{23}| \to 0$ and so on. All nondiagonal elements tense to $0$.


text:
Q: Efficient way to send data onActivityResult to another activity So I want to load an image from gallery with overriding onActivityResult . What is an efficient way to send intent data to another activity?
Currently using this code to to get image path before sending it to the other activity:
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {

        Uri selected_image = data.getData();
        if (selected_image.toString().substring(0, 21).equals("content://com.android")) {
            String[] photo_split = selected_image.toString().split("%3A");
            String imageUriBasePath = "content://media/external/images/media/" + photo_split[1];
            selected_image = Uri.parse(imageUriBasePath);

        }
        String[] file_path_column = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selected_image, file_path_column, null, null, null);
        cursor.moveToFirst();
        int column_index = cursor.getColumnIndex(file_path_column[0]);
        image_path = cursor.getString(column_index);
        cursor.close();

        Intent intent = new Intent(MainActivity.this, ImageActivity.class);
        intent.putExtra("imagePath", image_path);
        startActivity(intent);

    }
}

The problem is that this code does not seem to work in a good way, since after selecting an image from gallery app, the gallery lags for few seconds before loading the image into the other activity.

A: Try this, following is for getting image from both camera and gallery:
    ImageView photo;
    Bitmap bmp;
    static int GET_PICTURE = 1, CAMERA_PIC_REQUEST = 2;
    static String selectedImagePath = "";
 @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if (requestCode == CAMERA_PIC_REQUEST) {
                    // deleteDialog.dismiss();
                    bmp = (Bitmap) data.getExtras().get("data");
                } else if (requestCode == GET_PICTURE) {

                    if (bmp != null) {
                        bmp.recycle();

                    }
                    // deleteDialog.dismiss();
                    Uri selectedImageUri = data.getData();
                    selectedImagePath = getRealPathFromURI(selectedImageUri);
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(selectedImagePath, options);
                        options.inSampleSize = calculateInSampleSize(options, 200,
                                200);
                    options.inJustDecodeBounds = false;
                    bmp = BitmapFactory.decodeFile(selectedImagePath, options);
                }
                if (bmp != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

                        Bitmap outputs = getRoundedBitmap(bmp,10);
                        last = Bitmap.createScaledBitmap(outputs, 200, 200, false);
                    if (last != null) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        last.compress(Bitmap.CompressFormat.PNG, 100, baos);
                        byte[] b = baos.toByteArray();
                        String temp = Base64.encodeToString(b, Base64.DEFAULT);

                         photo.setImageBitmap(last);
                        // userimage.setBackgroundResource(android.R.color.transparent);
                    }

                } else {
                    Toast.makeText(getBaseContext(), "Invalid image",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }

    public static Bitmap getRoundedBitmap(Bitmap bitmap,int pixels) {
        final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(output);
        final int color = Color.RED;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        //canvas.drawOval(rectF, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        bitmap.recycle();
        return output;
    }
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null,
                null, null);
        if (cursor == null) {
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor
                    .getColumnIndex(MediaStore.Images.ImageColumns.DATA);

            result = cursor.getString(idx);

        }
        cursor.close();
        return result;
    }
    public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

A:
// Opening gallery
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), Keys.PICTURE_REQ_CODE);

public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == RESULT_OK) {
                switch (requestCode) {

                    // Gallery
                    case Keys.PICTURE_REQ_CODE:

                        Uri fileUri = data.getData();
                        cropIntent = new Intent(this,CropActivity.class);
                         cropIntent.setData(fileUri);
                       startActivityForResult(cropIntent,Keys.CROP_REQ_CODE);
                        break;
                }

            }
        }


text:
Q: My SQL MERGE statement runs for too long I have this Hive MERGE statement:

MERGE INTO destination dst
USING (
  SELECT

   -- DISTINCT fields
      company
    , contact_id as id
    , ct.cid as cid

     -- other fields
    , email
    , timestamp_utc
    -- there are actually about 6 more

    -- deduplication
    , ROW_NUMBER() OVER (
         PARTITION BY company
       , ct.id
       , contact_id
         ORDER BY timestamp_utc DESC
    ) as r

  FROM
    source
  LATERAL VIEW explode(campaign_id) ct AS cid
) src
ON
        dst.company = src.company
    AND dst.campaign_id = src.cid
    AND dst.id = src.id

-- On match: keep latest loaded
WHEN MATCHED
    AND dst.updated_on_utc < src.timestamp_utc
    AND src.r = 1
THEN UPDATE SET
    email =  src.email
  , updated_on_utc = src.timestamp_utc

WHEN NOT MATCHED AND src.r = 1 THEN INSERT VALUES (
    src.id

  , src.email

  , src.timestamp_utc

  , src.license_name
  , src.cid
)
;

Which runs for a very long time (30 minutes for 7GB of avro compressed data on disk).
I wonder if there are any SQL ways to improve it.
ROW_NUMBER() is here to deduplicate the source table, so that in the MATCH clause we only select the earliest row.
One thing I am not sure of, is that hive says:

SQL Standard requires that an error is raised if the ON clause is such
  that more than 1 row in source matches a row in target.  This check is
  computationally expensive and may affect the overall runtime of a
  MERGE statement significantly.  hive.merge.cardinality.check=false may
  be used to disable the check at your own risk.  If the check is
  disabled, but the statement has such a cross join effect, it may lead
  to data corruption.

I do indeed disable the cardinality check, as although the ON statement might give 2 rows in source, those rows are limited to 1 only thanks to the r=1 later in the MATCH clause.
Overall I like this MERGE statement but it is just too slow and any help would be appreciated.
Note that the destination table is partitioned. The source table is not as it is an external table which for every run must be fully merged, so fully scanned (in the background already merged data files are removed and new files are added before next run). Not sure that partitioning would help in that case
What I have done:

*

*play with hdfs/hive/yarn configuration

*try with a temporary table (2 steps) instead of a single MERGE, the run time jumped to more than 2 hours.

A: Option 1: Move where filter where src.r = 1 inside the src subquery and check the merge performance. This will reduce the number of source rows before merge.
Other two options do not require ACID mode. Do full target rewrite.
Option 2: Rewrite using UNION ALL + row_number (this should be the fastest one):
insert overwrite table destination
select
company
, contact_id as id
, ct.cid as cid
, email
, timestamp_utc
, -- add more fields
from
(
select --dedupe, select last updated rows using row_number
s.*
, ROW_NUMBER() OVER (PARTITION BY company, ct.id , contact_id ORDER BY timestamp_utc DESC) as rn
from
(
select --union all source and target
company
, contact_id as id
, ct.cid as cid
, email
, timestamp_utc
, -- add more fields
from source LATERAL VIEW explode(campaign_id) ct AS cid
UNION ALL
select
company
, contact_id as id
, ct.cid as cid
, email
, timestamp_utc
,-- add more fields
from destination
)s --union all
where rn=1 --filter duplicates
)s-- filtered dups

If source contains a lot of duplicates, you can apply additional row_number filtering to the src subquery as well before union.
One more approach using full join: https://stackoverflow.com/a/37744071/2700344


text:
Q: Parallax de Materialize no funciona Estoy intentando incluir el Parallax de Materialize, pero la imagen simplemente no aparece, pero sí se genera el espacio en donde debería estar.
He leído en un montón de sitios, incluso en stackoverflow en ingles donde hago lo que dicen y pero el problema persiste, incluso vi vídeos en youtube donde hago exactamente lo mismo que ellos, pero nada.

A: Hola hice pruebas con materializecss en mi pc y funciona perfecto.
La clase parallax oculta la imagen via css y se muestra despues de inicializar el componente. podrias probar sacando class="parallax" para ver si se carga bien la imagen.
Pueden estar pasando 4 cosas:

*

*Que el querySelectorAll no haga match con la clase (que no veo que sea el caso).

*Que la url de la imagen no sea valida.

*Que no hayas incluido la libreria css de materializecss.

*Que la imagen la estes cargando desde JS entonces la imagen se carga luego de ejecutar la instancia. Lo cual deberia asociar un evento load a la imagen para ejecutar el codigo materializecss una vez cargue la imagen. quizas puedas probar con un setTimeout para verificar

        document.addEventListener('DOMContentLoaded', function() {
         var elems = document.querySelectorAll('.parallax');
           var instances = M.Parallax.init(elems);

        });

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

Parallax

Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling.


text:
Q: Is GoldenEye: Source free? I can't tell if you have to buy anything to play GoldenEye: Source. Is it free? Are there any good tutorials on getting this up and running?

A: Yes here is the link to the current download version if you already own HL-2

GoldenEye: Source Beta 4 is the first major release since Beta 3.1.4 in March of 2009. Beta 4 brings us many steps closer to a final version of the mod and introduces a tremendous amount of polish in both gameplay, coding, and presentation. Some of the major changes include Rolling Explosions, Bullet Penetration, and Living Daylights, Capture the Key, and Live and Let Die gameplay scenarios. Please see the Beta 4 Change List for a complete list of changes in Beta 4.

Their wiki is a good source for tutorials
If you don't have HL-2 you can get it on either Steam (digital) or for $10 online (hardcopy disk)

A: As with all Half-Life 2 mods, you need to own Half Life 2 (or any other source game, eg. CS:S) to play it.


text:
Q: Django Admin import_export module used for custom IMPORT I was trying to follow official doc of import-export:
https://django-import-export.readthedocs.org/en/latest/import_workflow.html#import-data-method-workflow
But I still do not know how to glue it to my admin assuming that:

*

*I want only subset of fields (I created Resource model with listed fields, but It crashes while importing anyway with: KeyError full stack bellow.

*Where - in which method - in my admin class (inheriting of course ImportExportModelAdmin and using defined resource_class) should i place the code responsible for some custom actions I want to happen after validating, that import data are correct but before inserting them into database.
I am not very advanced in Django and will be thankful for some hints.
Example of working implementation will be appreciated, so if you know something similar on github - share.

A: you can override it as
to create a new instance
def get_instance(self, instance_loader, row):
    return False

your custom save
def save_instance(self, instance, real_dry_run):
    if not real_dry_run:
            try:
                obj = YourModel.objects.get(some_val=instance.some_val)
                # extra logic if object already exist
            except NFCTag.DoesNotExist:
                # create new object
                obj = YourModel(some_val=instance.some_val)
                obj.save()

def before_import(self, dataset, dry_run):

    if dataset.headers:
        dataset.headers = [str(header).lower().strip() for header in dataset.headers]

      # if id column not in headers in your file
    if 'id' not in dataset.headers:
        dataset.headers.append('id')


text:
Q: Bootstrap buttons I am using the bootstrap v3, and trying to add the href to a button:
<button type="button" class="btn btn-default" href="http://www.example.com" aria-label="Left Align">

demo site</button>

However when clicking the button nothing happens, am I doing something wrong?

A: Why not use an anchor tag...

    demo site

Demo: http://bootply.com/SbX40AknyT

A: Either use anchor tag, or handle the redirection in onClick handler

A: You cannot just use a href attribute for a button. You have 3 possibilities to solve this.
Option 1 with Javascript
    <button type="button" class="btn btn-default" onclick="window.location.href='http://stackoverflow.com/'" aria-label="Left Align">

                    demo site
    </button>

Option 2 without javascript
<form action="http://stackoverflow.com/">
    <button type="submit" class="btn btn-default" aria-label="Left Align">

                    demo site
    </button>
</form>

Option 3 with another tag (especially for bootstrap)
Furthermore you could just change your button to an anchor tag.

A: Your answer is great. You can use these Buttons in an Page, Post or even a Text Widget.
http://www.bootply.com/GCHTzGZ5K0
Success (Green) Button
Warning (Orange) Button
Primary (Blue) Button

Have more questions? Please post a support topic in the forum. http://cyberchimps.com/forum/

A: The href attribute is an attribute of the anchor tags. This is why Twitter bootstrap allow you to add the .btn classes to anchor tags also. Therefore, whenever you need to create a link, and you intend to style it as a button, Use the anchor "" tags and for forms that you'd need to submit, or just lunch a modal dialog, you can use the button.
So we can modify your code thus;
OLD:
<button type="button" class="btn btn-default" href="http://www.example.com"
 aria-label="Left Align">

  demo site</button>

New:

  demo site

A: Learn More!


text:
Q: ¿Mathematical induction GRE math? Im studing for the GRE math subject test...i can´t get the followin problem:
Using Mathematical Induction, show that it is possible to color with only two colors the regions formed by n lines in the plane.
Any idea on how to aproach it?

A: HINT: When you add an $(n+1)$-st line to a plane that already has $n$ lines and has been suitably colored, you can invert the colors on one side of the new line. (By invert the colors I mean change blue regions to red and red to blue, if blue and red are the two colors.)


text:
Q: Finding Greatest Common Divisor through iterative solution (python 3) I am trying to find the great common divisor by using a function and solving it iteratively. Though, for some reason, I am not sure why I am not getting the right output.
The greatest common divisor between 30 & 15 should be 15, however, my output is always giving me the wrong number. I have a strong feeling that my "if" statement is strongly incorrect. Please help!
def square(a,b):
    '''
    x: int or float.
    '''
    c = a + b

    while c > 0:
        c -= 1
        if a % c == 0 and b % c == 0:
            return c
        else:
            return 1

obj = square(30,15)
print (obj)

A: You should return a value only if you finished iterating all numbers and found none of them a divisor to both numbers:
def square(a, b):
    c = a + b

    while c > 0:
        if a % c == 0 and b % c == 0:
            return c
        c -= 1
    return 1

However, the last return will be unneeded in this case, as c would go from a + b to 1, and mod 1 will always bring a common divisor, so the loop will always terminate with 1, for the worst case.
Also, a number greater than a and b can not be a common divisor of them. (x mod y for y > x yields x), and gcd is the formal name for the task, so I would go with
def gcd(a, b):
    for c in range(min(a, b), 0, -1):
        if a % c == b % c == 0:
            return c

for iterational solution.

A: You might be interested to know that there is a common recursive solution to the GCD problem based on the Euclidian algorighm.
def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

print(gcd(30, 15))
# 15


text: Q: How to enable ECN marking in IP header in Linux? Is the ECN marking in the IP header is performed by default in Ubuntu (4.15.x kernel) or should the kernel be recompiled with a special option? I configured a RED ingress queue at an Ubuntu machine, net.ipv4.tcp_ecn is set to 1 in all hosts of the network and ECN is enabled in the tc qdisc command. I see dropped packets due to congestion but there are no marked packets.


text:
Q: Iptables: how to drop incoming pings from host but allow ping responses? I am practicing with iptables and... I need a rule that will block a certain host from pinging me but will let me to ping the host if needed (so I need to accept ping responses right?). Can you help me?

A: You can block ping (icmp echo requests) from all hosts using this
iptables -I INPUT -j DROP -p icmp --icmp-type echo-request

If you want to block a particular host then
iptables -I INPUT -s 192.168.1.139 -j DROP -p icmp --icmp-type echo-request

A: Allow single ip using

iptables -A INPUT -s x.x.x.x -p ICMP --icmp-type 8 -j ACCEPT

Now drop ICMP packets from rest

iptables -A INPUT -p ICMP --icmp-type 8 -j DROP

Reference http://www.trickylinux.net/ping-single-ip-linux/

A: If we start with everything blocked:
Allow OUTPUT ICMP (to host only if you like)
allow established ICMP connections INPUT (from host only if you like)


text:
Q: Inheritance, a parent accesing children in c++ I am making a chess game and when I click on a square I want to know what piece is there. Since there are more than 1 type of pieces it would be annoying to have more variables in the Square structure.
So I have though about a class named Piece which is the parent of each type of Piece.
Example.
class Pawn : public Piece

I want to achieve a Square structure that looks something like this :
struct Square { Piece *piece };

Now, I want to initialize the piece variable like this :
piece = new Pawn(); // or what type of piece it should be.

My problem is that by doing this I can still only access Piece's class functions and not the Pawns ones.
How do I achieve such thing as having only 1 parent which can access everything his children have?

A: You can make virtual functions.
Define virtual function in base class and override it in child class.
For Example
class Base
{
public:
    const char* SayHi() { return "Hi"; } // a normal non-virtual function

    virtual const char* GetName() { return "Base"; } // a normal virtual function

    virtual int GetValue() = 0; // a pure virtual function
};
class Child:public Base{
{
    int GetValue(){
    //write any code here
    //return something;
    }
}

For more refer to link:
http://www.learncpp.com/cpp-tutorial/126-pure-virtual-functions-abstract-base-classes-and-interface-classes/

A: The best approach by far is try avoiding this situation: can you make the interface of the Piece uniform for all subclasses? If this can be done, choose this design without much hesitation, because what I describe below is a lot more complex, and also much harder to read.
Since you cannot access member functions of derived types through a pointer to the base type, you need to work around this in one of several ways:

*

*Use dynamic_cast<Derived> - This is very simple, but extremely fragile. Changes to the inheritance structure can break an approach based on frequent dynamic casts.

*Use VisitorPattern - This is a good choice when the class structure is not expected to change (you're in luck here: the list of types that you plan to model has not changed in many centuries)

*Use Runtime Type Information and maps of function objects - This approach is very flexible, but it is somewhat hard to read. Lambdas of C++11 make it easier, though.


text:
Q: What's the correct driver to use with a GeForce 6150SE nforce 430 on Ubuntu and Ubuntu flavours? I've  tried three other posts about how to install drivers for

*

*NVIDIA GeForce 6150SE nForce 430

*Video Drivers for Onboard GeForce 6150SE

*Nvidia geforce 6150-unity 3d won't work
The problem is I've tried installing all the drivers suggested, one by one, test them, remove them, install another and until now the one which is working best is nouveau, but It also freezes the screen on random actions, most notably when I start Firefox.
If you have this card installed and working well please tell us what driver/distribution/configuration you are using. Thank you.
Xorg.0.log file: http://pastebin.com/8HLG59y7
syslog tells me this:
Feb 23 11:55:19 xxxxxxx kernel: [   48.418101] systemd-logind[1202]: Failed to start unit user@1000.service: Unknown unit: user@1000.service
Feb 23 13:22:30 xxxxxx kernel: [ 5286.305415] nouveau E[    PBUS][0000:00:0d.0] MMIO write of 0x00000000 FAULT at 0x00b010

A: I found that the correct driver (working well now for two days) is the nvidia-304 which can be installed from repositories. This might be problematic if you are making a clean install because the Geforce 6150SE will not work well when installing from the Ubuntu DVD: the Ubuntu live session will freeze, so follow this sequence:

*

*Boot from the DVD and press Space to choose different methods of installation.

*Choose Experienced Install.

*Install Ubuntu.

*After install is done, press CTRL+ALT+F1 and login.

*Update your system:
sudo apt-get update
sudo apt-get upgrade

*Install the driver:
sudo apt-get install nvidia-304

*DO NOT run nvidia-xconfig (THIS IS IMPORTANT).

*Reboot the system (just press CTRL+ALT+DEL)

*Login normally.

*Open Nvidia X server settings from the dash.

*Backup your configuration (you can copy and paste it to a txt file)

I hope this helps others, it's worked for me (so far).

A: Correct can mean lots of things.
The nvidia drivers are proprietary and do not integrate well with the rest of the free software ecosystem and community.  The nouveau driver is the preferred one, but in Debian testing and unstable it has a bug with the 6150SE, which you can workaround by inserting into /etc/modprobe.d/local-video.conf:
options nouveau noaccel=1

A: I have tried all the steps above with no results. I have tried everything. Finally Got it to work. Here's the problem with random screen freezes using any flavor of Linux with a older Nvidia graphics card, especially an integrated one like the Nvidia G force 430 series. Permanently add the Nomodeset.
As mention by user NikTh on Oct 27 '12 at 14:02, The newest kernels have moved the video mode setting into the kernel. So all the programming of the hardware specific clock rates and registers on the video card happen in the kernel rather than in the X driver when the X server starts..
This makes it possible to have high resolution nice looking splash (boot) screens and flicker free transitions from boot splash to login screen.
Unfortunately, on some cards this doesnt work properly and you end up with a black screen or in my case black screens and random freezes when watching a youtube video when using Firefox.
Adding the nomodeset parameter instructs the kernel to not load video drivers and use BIOS modes instead until X is loaded.
For help in adding these parameters, check out http://ubuntuforums.org/showthread.php?t=1613132

A: I had the same experience with Linux Mint 19.0. The fix was to avoid the update to kernel 4.15 or to install Linux Mint 18.2 which works for me. I can do all of the updates and still have my video driver, Nvidia Geforce 1650 SE Nforce working.
I wanted to dual boot with either Debian or PCLinuxOS but since those are rolling releases, the updates break the system since the X driver gets moved into the kernel.
Another fix would be to just buy a cheap video card.


text:
Q: Android Design - How to get this card view effect? I am creating a weather app.
How do I get this card effect ? How do I get a textView in a card like that ?

This is my status:

Can someone show how to make this or something at least similar

A: frist of all below dependencies add in your build.gradle
compile 'com.android.support:cardview-v7:24.2.1'

and in xml you can write this code. its just sample design according to your need...
this will solve your question... How do I get this card effect ? How do I get a textView in a card like that ?
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView android:id="@+id/card1"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="5dp"
    app:cardBackgroundColor="@android:color/white"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">
        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Detail"
            android:textSize="20dp"
            android:textColor="@color/colorPrimary"
            android:layout_alignParentTop="true"
            android:layout_marginRight="10dp"/>
        <TextView
            android:id="@+id/line"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/colorPrimary"
            android:layout_below="@id/text1"/>
        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TUE"
            android:textColor="@color/colorGrey"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_below="@+id/text1"/>
        <TextView
            android:id="@+id/text3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NOON"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_toRightOf="@+id/text2"
            android:layout_marginLeft="10dp"
            android:layout_below="@+id/text1"
            android:textColor="@color/colorTextBlackLight"/>
        <TextView
            android:id="@+id/text4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EVE"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_toRightOf="@+id/text3"
            android:layout_marginLeft="30dp"
            android:layout_below="@+id/text1"
            android:textColor="@color/colorTextBlackLight"/>
        <TextView
            android:id="@+id/text5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NIGHT"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_toRightOf="@+id/text4"
            android:layout_marginLeft="30dp"
            android:layout_below="@+id/text1"
            android:textColor="@color/colorTextBlackLight"/>
        <TextView
            android:id="@+id/text6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="WED"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_toRightOf="@+id/text5"
            android:layout_marginLeft="30dp"
            android:layout_below="@+id/text1"
            android:textColor="@color/colorGrey"/>
        <TextView
            android:id="@+id/text7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="WED"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_toRightOf="@+id/text6"
            android:layout_marginLeft="5dp"
            android:layout_below="@+id/text1"
            android:textColor="@color/colorTextBlackLight"/>

        <TextView
            android:id="@+id/text8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="21"
            android:layout_marginTop="10dp"
            android:textSize="16dp"
            android:layout_marginLeft="5dp"
            android:layout_below="@+id/text2"
            android:textColor="@color/colorTextBlackLight"/>

        <ImageView
            android:id="@+id/img1"
            android:layout_width="30dp"
            android:layout_height="25dp"
            android:src="@drawable/ic_like_icon"
            android:scaleType="fitXY"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/text3"
            android:layout_toRightOf="@+id/text8"/>

        <TextView
            android:id="@+id/textmore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MORE"
            android:textSize="18dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:textColor="@color/colorTextBlackLight"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>

you can use this xml in row.xml for using in recyclerview to create multiple use
for listing read tutorial:
http://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view

hope it will helpfull for you. dont forgot to accept it if helpfull