text:
Q: How to have only one consumer handle a long running task at a given point? I need to design an application which makes requests to an external API. External API has a hierarchy of entities: User which contains ListOfItemss which contain Items. I need to get data on all Items for all Users. Within a ListOfItems requests per Item can be concurrent/parallel but only one ListOfItems can be requested at a time, due to external API limitations (ListOfItems can only be accessed via a token and a token for only one ListOfItems is issued within a given User). There will be around 1000 Users max.
I need to get this data ideally once an hour but in reality this takes longer because the amount of Users and Items is quite large. I already have the code for the method processUser:
processUser(user) {
  List<ListOfItems> lists = getListsPerUser(user);
  List<Items> items;
  for (list in lists) {
    items = getItemsPerListConcurrently(list);
    processItems(items);
  }
}

Currently, I have a cron job which runs immediately after the previous job finished. The job has a thread executor which creates N threads and each thread runs processUser inside a Kubernetes pod. So Users and Items are processed in parallel but ListOfItems are processed serially. I'd like to scale the solution to multiple pods but this requires to make sure that at any given time same ListOfItems is not processed by different pods because the token to access user data can only be used for one ListOfItems at a time (if 2 pods process the same ListOfItems then we have a problem).
Initially, I thought to go with a message queue as a solution and having each consumer process some User because there's already a method processUser and this feature needs to be delivered ASAP. So a message would contain a User id. The problem is that it can take hours to process a User. As far as I know many message queues have some interval to acknowledge that a message was processed, if the interval has passed without acknowledgement then the message may be returned to the broker (Kafka has this I think, AWS SQS definitely has this). This means that a message to process User may be stuck in the queue for hours potentially even a day because all consumers are busy processing other Users. It feels like processUser is a long-running task which message queues may not be suited best for.
There're several directions I'm thinking about:

*

*Use some kind of queue/list of tasks where each task represents a User. Spin up N processUser instances, then each processUser instance pops a User from the queue. The pop operation should be atomic so that multiple processUser instances don't process same User/ListOfItems. Maybe I could use Redis BLPOP which is atomic? This solution would be the quickest to implement in my opinion because processUser code is already written. This is good because the feature needs to be delivered ASAP.

*Refactor code to use a message queue with ordering guaranteed like Kafka where each message would contain an Item id and message key = ListOfItems id to prevent more than one consumer processing the same ListOfItems. We already have Kafka infrastructure so just refactor processUser.

*Use database synchronization (we use Postgres) so each consumer checks a database table UsersInProgress for which User is available and process it. One option is to lock the whole table to make sure that multiple processUser instances don't grab the same User but I think we can just use a transaction where first we check if a User is being processed, if not then making a write to the table marking the User as being processed. Because writes are atomic we guarantee that only one instance will be able to grab a User.

I was wondering if any of the above options sound good taking into consideration that the feature needs to be delivered quickly or maybe there's another option that I didn't think of.
In case option 1 sounds good is Redis/BLPOP really the best solution or there're better solutions?
In case option 3 sounds good will using a transaction to first check if user is processed then mark it as processed work to prevent having multiple instances processing same user?


text:
Q: Maximization in l1 norm I have formulated a problem as follows.
$${max \sum_{i=1}^l\sum_{k=1}^m|\sum_{j=1}^nw_{j}*(a_{ij}-b_{kj}+r_{kij}*x_{kij})|}$$
$$s.t.w_{j}*|a_{ij}-b_{kj}+r_{kij}*x_{kij}|\leq w_{j}*|a_{ij}-b_{tj}+r_{tij}*x_{tij}|$$
$$\sum_{i=1}^l\sum_{k=1}^m\sum_{j=1}^n x_{kij}\leq m$$
$$\sum_{j=1}^nw_{j}=1$$
$$w_{j}\geq0 \forall j$$
$$x_{kij}\in \{0,1\} \forall k,i,j$$
$a_{ij}, b_{kj},r_{kij}$ values are constant. $x_{kij}$ is a binary variable, $w_{j}$ is a continuous variable.
As far as I know, maximizing absolute values is not an easy task. I have thought I could try to minimize the objective function by multiplying it by (-). But not quite sure if that would work. Would it be possible to solve this problem? I am open for recommendations.
Would using any other p norm make more sense to solve this problem?

redpajama_set_name: RedPajamaStackExchange


text:
Q: CMake's find_program / find_path / find_* and in-source build What is the right way of saying to find_* functions that a library/path/whatever they are supposed to find, are built (and therefore available) in-source?
In particular, I am trying to follow flatbuffer instructions:

If you want to use FlatBuffers in a project which already uses CMake, then a more robust and flexible approach is to build FlatBuffers as part of that project directly. This is done by making the FlatBuffers source code available to the main build and adding it using CMake's add_subdirectory() command.
Suppose you put FlatBuffers source code in directory ${FLATBUFFERS_SRC_DIR}. To build it as part of your project, add following code to your CMakeLists.txt file:

# Add FlatBuffers directly to our build. This defines the `flatbuffers` target.
add_subdirectory(${FLATBUFFERS_SRC_DIR}
                 ${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-build
                 EXCLUDE_FROM_ALL)
# Now simply link against flatbuffers as needed to your already declared target.
# The flatbuffers target carry header search path automatically if CMake > 2.8.11.
target_link_libraries(own_project_target PRIVATE flatbuffers)

It works perfectly fine, but then, to generate c++ code, I need to invoke flatc executable built in the previous step. In order not to do it manually, I would like to utilise existing cmake function defined in their codebase - CMake/FindFlatBuffers.cmake, but the problem is that in the very beginning of the file they are trying to find flatc executable:
find_program(FLATBUFFERS_FLATC_EXECUTABLE NAMES flatc)
find_path(FLATBUFFERS_INCLUDE_DIR NAMES flatbuffers/flatbuffers.h)

which, of course, fails, since I disabled installing of flatbuffers.
Is there an easy solution?


text:
Q: @Cacheable annotation, using same value in a differents methods I am trying to use the Spring @Cacheable annotation.
 @Cacheable(value="users")
public List<User> findAll() {
    System.out.println("Looking for All users : ");
    return userRepository.findAll();
}

@Override
@Cacheable(value="users")
public User findOne(String userId) {
    System.out.println("Looking for user : "+ userId);
    return userRepository.findById(userId).get();
}

When I execute the first methode List<User> I get :

*

*1st time : select all fields from DataBase

*2nd time : select all fields from Cache

*3rd time : select all fields from Cache

Which is good till now.
When I execute the second method findOne(String userId)I get the result from  :

*

*1st time : select specific field from DataBase

*2nd time : select specific field from Cache

*3rd time : select specific field from Cache

Which is good again.
When I execute the first methode List<User> I get :

select all fields Data from Cache

Question : How the both methods (List<User> and findOne(String userId) had the same cache name but they return different result.

A: When you annotate your method with @Cacheable annotation, Spring will apply the caching behavior on it. The cache name is used to group the cache data in the same cache region. But to store the values in cache region, Spring will generate the cache key.
By default the SimpleKeyGenerator is used to generate the key value in cache. SimpleKeyGenerator uses the method parameters to generate the cache key. The key value will be wrapped with the SimpleKey object.
So, in your case it will do the following:
1st call - no data in cache

*

*List<User> findAll()

*

*no parameters

*key=SimpleKey.EMPTY

*store method result in cache using the key

*User findOne(String userId)

*

*userId parameter

*key=new SimpleKey(userId)

*store method result in cache using the key

As show above, although your cache name in @Cacheable is the same in both cases, the keys used to store method results are different. When you call again your methods:
2nd call - data in cache

*

*List<User> findAll()

*

*no parameters

*key=SimpleKey.EMPTY

*get the result from cache using the key

*User findOne(String userId)

*

*userId parameter

*key=new SimpleKey(userId)

*get the result from cache using the key


text:
Q: Error: zkey file is not groth16 in circom ■ Issue Info

*

*Cohort3-Week1-Part2-4-1

1.You will encounter an error if you just change snarkjs groth16 setup to snarkjs plonk setup. Resolve this error and answer the following question - How is the process of compiling with PLONK different from compiling with Groth16?

■ My File
https://github.com/Tomosuke0930/zku3.0-week1/tree/master/Q2
https://github.com/Tomosuke0930/zku3.0-week1/blob/master/Q2/scripts/compile-Multiplier3-plonk.sh
I referred to this document https://github.com/iden3/snarkjs
■ What I want to ask

*

*How to solve this error? What materials would help with this problem?

■ Error

*

*In executing scripts/compile-Multiplier3-plonk.sh,I'm getting the following error

-------------------------------
Compiling Multiplier3_plonk.circom...
-------------------------------
template instances: 2
non-linear constraints: 2
linear constraints: 0
public inputs: 0
public outputs: 1
private inputs: 3
private outputs: 0
wires: 6
labels: 11
Written successfully: Multiplier3/Multiplier3.r1cs
Written successfully: Multiplier3/Multiplier3.sym
Written successfully: Multiplier3/Multiplier3_js/Multiplier3.wasm
Everything went okay, circom safe
[INFO]  snarkJS: Curve: bn-128
[INFO]  snarkJS: # of Wires: 6
[INFO]  snarkJS: # of Constraints: 2
[INFO]  snarkJS: # of Private Inputs: 3
[INFO]  snarkJS: # of Public Inputs: 0
[INFO]  snarkJS: # of Labels: 11
[INFO]  snarkJS: # of Outputs: 1
[INFO]  snarkJS: Reading r1cs
[INFO]  snarkJS: Plonk constraints: 3
[INFO]  snarkJS: Setup Finished
[INFO]  snarkJS: Reading r1cs
[INFO]  snarkJS: Reading tauG1
[INFO]  snarkJS: Reading tauG2
[INFO]  snarkJS: Reading alphatauG1
[INFO]  snarkJS: Reading betatauG1
[INFO]  snarkJS: Circuit hash:
                d450100e 589c0685 76e9e3ce 2e0e71e6
                f90f89fa 1f8a17ca d07b0ad4 4c044ecd
                ff825273 9185368e 1ba6de7a 349f2472
                2b974d2d 2dd40cc2 343a6a01 b6d826e6
[ERROR] snarkJS: Error: zkey file is not groth16
    at phase2verifyFromInit (/Users/tom/.nvm/versions/node/v16.13.1/lib/node_modules/snarkjs/build/cli.cjs:4429:15)
    at async phase2verifyFromR1cs (/Users/tom/.nvm/versions/node/v16.13.1/lib/node_modules/snarkjs/build/cli.cjs:4837:12)
    at async Object.zkeyVerifyFromR1cs [as action] (/Users/tom/.nvm/versions/node/v16.13.1/lib/node_modules/snarkjs/build/cli.cjs:8777:17)
    at async clProcessor (/Users/tom/.nvm/versions/node/v16.13.1/lib/node_modules/snarkjs/build/cli.cjs:304:27)

enter image description here
■ Assumption
In executing this code, "zkey" is created so I assumed this code doesn't work.
snarkjs plonk setup Multiplier3_plonk/Multiplier3.r1cs powersOfTau28_hez_final_10.ptau Multiplier3_plonk/circuit_final.zkey

These is error sentences in snark.js but I cannot understand what is problem.
    if (zkey.protocol != "groth16") {
        throw new Error("zkey file is not groth16");
    }

And I read this doc, but I can't find what I'm wrong.
https://github.com/iden3/snarkjs#15-setup

A: The snarkjs zkey verify ... command is a part of the groth16 setup. Since you used PLONK, there's no need to verify the circuit_final.zkey.
The people who updated the snarkjs readme.md forgot to update the "You can jump directly to Section 21 ..." to "... Section 22 ...". (readme.md as of commit e3bc042)


text:
Q: How to change the csproj file back to old format in VS 2017 I have the problem when I make a new class library in VS 2017 the csproj file has always the new format but I want the old format
This is the format I get
<Project Sdk="Microsoft.NET.Sdk">

but I want
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

And how can I stop that VS 2017 do this automatically?
This would help my by this question
I hope someone can help me?

A: As in the comments to solve the problem i create the project in VS 2015 and open it with VS 2017


text:
Q: Handling onClick and double click I have a messaging app similar to whatsapp where there are messages videos and images in the chat activity. Now I want to implement a double tap like feature on this but the problem is I also have a onclicklistner attached to my image and video frame that opens up a fullscreenactivity showing the image in fullscreen or playing the video in fullscreen. So on double tap instead of liking the picture or video it simply opens the video or image in the fullscreen mode. Since in messages I don't have a onclick listner attached double tap like works fine. Any ideas on how I can make the double tap like work in case of the videos or images. I am fairly new to android development using Java. So any help is appreciated.

A:
HI, I think the approach to take depends on the future of your app, using LongClick is kinda good but what if you want to achieve a zoom like onLongClick?

What I did below is that I created a subclass that extends GestureDetector.SimpleOnGestureListener and then in my GestureTest class, I an ontouchListener and return the gesture instance created before, finally I parse the listener to the button that has to perform the clicks, it can be any View object.
    Finally, I used the TextView I created to display/monitor my actions.

GestureDetector like below:

public class GestureTest extends AppCompatActivity{

    private Button btn;
    private TextView actions;
    private GestureDetector mDetector;

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

        btn = findViewById(R.id.btn);
        actions = findViewById(R.id.action);

        mDetector = new GestureDetector(this, new SampleGestureListener());
        View.OnTouchListener touchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mDetector.onTouchEvent(event);
            }
        };

        btn.setOnTouchListener(touchListener);
    }

    public class SampleGestureListener extends GestureDetector.SimpleOnGestureListener{

            @Override
            public boolean onDown(MotionEvent event) {
                Log.e("EVENT","BUTTON PRESSED DOWN, NOT YET RELEASED WILL TRIGGER ONLONG-PRESS");

                // don't return false here or else none of the other
                // gestures will work
                return true;
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                Log.e("EVENT", "SINGLE CLICK EVENT");
                actions.setText("THIS CLICK IS FOR IMAGE OR VIDEO TO OPEN ?");
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                Log.e("EVENT", "LONG PRESSED");
                actions.setText("THIS IS ZOOM LIKE NOT DOUBLE CLICK!!!");
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                Log.e("EVENT", "DOUBLE CLICKED HAPPENED");
                actions.setText("THIS CLICK IS TO LIKE IMAGE OR VIDEO ?");
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                Log.e("EVENT", "SCROLLING");
                actions.setText("YOU\" Scrolling on many images...");
                return true;
            }

            @Override
            public boolean onFling(MotionEvent event1, MotionEvent event2,
                                   float velocityX, float velocityY) {
                Log.e("EVENT", "FLINGED");
                actions.setText("THIS IS TINDER FLING LIKE ?");
                return true;
            }
        }
}

AND BELOW IS MY activity_gesture_test.xml FOR TESTING:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="100dp"/>

    <TextView
        android:id="@+id/action"
        android:textSize="20dp"
        android:textColor="@color/black"
        app:layout_constraintTop_toBottomOf="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="100dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

GoodLuck Coding.

A: try this for double click:
int i = 0;
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
    i++;
    Handler handler = new Handler();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            i = 0;
        }
    };
    if (i == 1) {
        //Single click
        handler.postDelayed(r, 250);
    } else if (i == 2) {
        //Double click
        i = 0;
        ShowDailog();
    }

}
});

and for click listener:
btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

A: It is generally accepted to use long tap instead of double click in android apps. Try this:
yourView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                //do Your stuff here

                return true;
            }
        });


text:
Q: Belongs to two columns laravel I have tables:
attributes:
- id - id of attribute
- name - name of attribute
attributes_relations:
- id -id of relation
- attribute_id - current attribute id
- attribute_relation_id - relation of this current attribute id with other from table attributes
In model Attribute I have relation:
public function attributerelation()
{
    return $this->hasOne('App\AttributeRelation');
}

But in model AttributeRelation I have:
public function attribute_rel()
{
    return $this->belongsTo('App\Attribute', 'attribute_relation_id');
}

I need belongs this with two columns: attribute_id and attribute_relation_id.
Becuase if I call:
$attribute->attributerelation->attribute_rel->name

This was working only for related attribute.


text:
Q: java.net.SocketException: Permission denied: connect with eclipse I have small java program i wrote to send email.
I am running this program from eclipse.
public static void sendMail(){
    Properties prop = new Properties();
    prop.setProperty("mail.host", "****.com");
    prop.setProperty("mail.smtp.port", "25");
    prop.setProperty("mail.smtp.auth", "false");
    Session sess = Session.getDefaultInstance(prop);
    Message msg = new MimeMessage(sess);
        try {
            msg.setSubject("From me");
            msg.setText("Hello");
            msg.setFrom(new InternetAddress("****@***com","Me"));
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress("****@****.com"));
            Transport.send(msg);
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    System.out.println("mail Sent");
}

It throes following error
com.sun.mail.util.MailConnectException: Couldn't connect to host, port:      *****.com, 25; timeout -1;
 nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2054)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:697)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at javax.mail.Service.connect(Service.java:175)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at json.mail.sendMail(mail.java:33)

Following things i have tried so far but none of it worked.
   1. Disabled Firewall.
   2. added following line to eclipse.ini
   -Djava.net.preferIPv4Stack=true
None of it actually worked. Does anyone have any idea?


text:
Q: How to use an old Kingston DataTraveler Vault Privacy USB flash drive on Linux? My company provides me a DTVP with hardware AES encryption two years ago and the CDrom image does only contain tools for Windows and MacOS X. Kingston products now have support for Linux. Current version of documentation and FAQ for DTVP flash drive now refers to Linux binaries.
How can I use my "old" USB flash drive on Linux ?
I have the following ideas but no detail information how to achieve any of them:

*

*update the ISO image on the flash drive to have Linux binaries on the key

*get binaries alone and run them from my Linux desktops


text:
Q: Getting error while installing TensorFlow on Ubuntu 16.04? I'm getting error **PermissionError: [Errno 13]** Permission denied: '/usr/local/lib/python3.5/dist-packages/protobuf-3.1.0.post1-py2.7-nspkg.pth when I run pip install tensorflow-gpu.
pip install tensorflow-gpu
Collecting tensorflow-gpu
Using cached tensorflow_gpu-0.12.1-cp35-cp35m-manylinux1_x86_64.whl
Requirement already satisfied: numpy>=1.11.0 in ./.local/lib/python3.5/site-packages (from tensorflow-gpu)
Collecting protobuf>=3.1.0 (from tensorflow-gpu)
Using cached protobuf-3.1.0.post1-py2.py3-none-any.whl
Requirement already satisfied: six>=1.10.0 in /usr/lib/python3/dist-packages (from tensorflow-gpu)
Requirement already satisfied: wheel>=0.26 in /usr/lib/python3/dist-packages (from tensorflow-gpu)
Requirement already satisfied: setuptools in /usr/lib/python3/dist-packages (from protobuf>=3.1.0->tensorflow-gpu)
Installing collected packages: protobuf, tensorflow-gpu
Exception:
Traceback (most recent call last):
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install
    **kwargs
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
File "/home/amanckc/.local/lib/python3.5/site-packages/pip/wheel.py", line 323, in clobber
    shutil.copyfile(srcfile, destfile)
File "/usr/lib/python3.5/shutil.py", line 115, in copyfile
    with open(dst, 'wb') as fdst:
**PermissionError: [Errno 13]** Permission denied: '/usr/local/lib/python3.5/dist-packages/protobuf-3.1.0.post1-py2.7-nspkg.pth'

A: You should rely the command but with --user like:
pip install --user tensorflow-gpu

And please improve the design of your question!


text:
Q: Make a table match a specific design This is the table
I want to design the table like this in HTML and CSS
I am beginner in HTML.
I  tried making this table but am not getting exact table (especially
 a line after every row). I just need a code for two rows, the rest I can code on my own.

table#tbl {
 table-layout:fixed;
 word-wrap : break-word;
 text-align:right;

}

     Sr no.
     Item
  HSN
  Qty
  Rate/ Item
  Discount/ Item
  Taxable Value
  SGST
  CGST
  Total

      1
   Himalaya Herbal Cream
Neem Edition
   AFG41205
   10sc.
   150.00
   10.00
   150.00
   20.00
   20.00
   1500.00

      2
   Himalaya Herbal Cream
Neem Edition
   AFG41205
   10sc.
   150.00
   10.00
   150.00
   20.00
   20.00
   1500.00

      3
   Himalaya Herbal Cream
Neem Edition
   AFG41205
   10sc.
   150.00
   10.00
   150.00
   20.00
   20.00
   1500.00

   Total

A: You can set the border-bottom and border-top on each tr using this:
table#tbl tbody tr {
  border-top: 1px solid gray;
  border-bottom: 1px solid gray;
}

Note that I am not styling the tr elements under thead - which means that the border will not be created at the top of the table. If you need that, you can replace the selector with: table#tbl tr
However you will also need border-collapse: collapse on the table for this to work.
Apart from that I've also added a padding: 10px 0 on the td elements in the table. This applies a 10px padding at top and bottom of every cell in the table.
Finally, you can set the background on the thead and tfoot elements:
table#tbl thead,
table#tbl tfoot {
  background-color: #fffdf1;
}

Note that your structure of tbody element is slightly incorrect in the question. Specifically, you closed the
 tag with
 instead of
. So, I have fixed too, in snippet below.
You can see the snippet below:

table#tbl {
  table-layout: fixed;
  word-wrap: break-word;
  text-align: right;
  border-collapse: collapse;
}

table#tbl tbody tr {
  border-top: 1px solid gray;
  border-bottom: 1px solid gray;
}

table#tbl td {
  padding: 10px 0;
  vertical-align: top;
}

table#tbl thead,
table#tbl tfoot {
  background-color: #fffdf1;
}

      Sr no.
      Item
      HSN
      Qty
      Rate/ Item
      Discount/ Item
      Taxable Value
      SGST
      CGST
      Total

       1
       Himalaya Herbal Cream
Neem Edition
       AFG41205
       10sc.
       150.00
       10.00
       150.00
       20.00
       20.00
       1500.00

       2
       Himalaya Herbal Cream
Neem Edition
       AFG41205
       10sc.
       150.00
       10.00
       150.00
       20.00
       20.00
       1500.00

       3
       Himalaya Herbal Cream
Neem Edition
       AFG41205
       10sc.
       150.00
       10.00
       150.00
       20.00
       20.00
       1500.00

       Total

Finally, it looks like that table is using Open Sans font. I have not applied them in the snippet, but you can follow the instructions in the link to set it up in your application.


text:
Q: Сменить стандартную сортировку по имени mysql В стандартной сортировке идет сначала 0-9, A-Z, А-я, а нужно наооборот.
Делаю так:
ORDER BY `name` REGEXP '[^А-Яа-я]',
         `name` REGEXP '[^A-Za-z]',
         `name` REGEXP '[^0-9]',
         `name` collate utf8_unicode_ci

И ничего не происходит
Почему?

A:
сортировка по первой букве. Сначала кирилица, потом латиница, потом цифрьі

ORDER BY name REGEXP '^[А-я]' DESC,
         name REGEXP '^[A-z]' DESC,
         name REGEXP '^[0-9]' DESC,
         name

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=39e441389cb8f2ec9ac381f62d9feb55

A: В MySQL за сравнение двух строк отвечает collation. Это правила, которые позволяют базе решить больше ли 'a' чем 'b', равны ли 'a', 'A' и 'ä'. При сортировке по строке, база сравнивает строки с помощью этих правил.
Вы хотите задать свои правила. Это подразумевает, что вам надо создать собственный collation. Но это не такая простая задача как кажется на первый взгляд. Что вы будете делать со знаками препинания, иероглифами и символами эмодзи? Посмотрите сколько тонкостей в алгоритме для юникода. Кроме того, MySQL не предоставляет инструментов создания collation на уровне пользователя базы данных. Я никогда не пробовал провернуть подобное, но вероятно придётся писать на си и компилировать свою версию MySQL.
Однако вашу задачу можно решить проще. Вы можете изменить значения name так, чтобы они сортировались так как надо. Решение в лоб -- рассчитать вес (позицию) каждого имени заранее и сортировать по нему:

name
nameWeight

abc
1

123
2

абв
0

Это правильное решение, которое позволяет вам применить любые правила при расчёте. Но у него есть недостаток: вам надо пересчитывать все веса при любом изменении в столбце name. Такие пересчёты могут занимать очень много времени и памяти на большом объёме данных.
Можно схитрить. Напишем перед каждым символом коэффициент в зависимости от того, к какой группе этот символ относится. Для кириллицы -- 0, для букв английского алфавита -- 1, для остальных символов -- 2. Получится такая ерунда:

name
rankedName

abc
1a1b1c

123
212223

абв
0а0б0в

Теперь при изменении или добавлении имени в таблицу, достаточно рассчитать только один rankedName.


text:
Q: With Gtk3, how do I make a tree view accessible? I'm working on a Python+Gtk3 application with a fancy-looking GtkTreeView:

This is great for sighted users, but here's what Orca (the screen reader) says for a row in that tree view:
"Image, Devhelp, Collapsed, 9.2 MB"
A few problems, of course. First, it doesn't mention the checkbox for each row because I'm packing three cell renderers into a column. The three are available, but for some reason Orca doesn't mention the checkbox when it's buried that deep. Meanwhile, the image it mentions is the one on the far left, which is usually empty but sometimes a "restart required" indicator. Naturally, a blind user, much like a sighted user, couldn't care less that it is an image.
What I would like to do is to poke at the accessibility objects that describe this table in order to make them a little more helpful. Using Accerciser, I can see that these exist, but they all seem to be implemented with private, undocumented classes (like GtkTreeViewAccessible), and they don't look terribly extensible, but I'm hoping I'm wrong. Knowing that the treeview's accessible object is an AtkTable at some level, I did the following to set an accessible description for the image cell in the Backup row:
    access = self.treeview_update.get_accessible()
    cell_access = access.ref_at(0,0)
    cell_access.set_image_description("Requires system restart")

(Orca still says "Image" after speaking the description, but I'll assume it knows what it's doing).
However, that code isn't very nice. When I call access.ref_at, I'm making particular assumptions about how GTK is mapping cell positions to rows and columns in the ATK object. I'm also limited to calling that when I first populate the tree, and I'm not sure if that is particularly sane.
So there's my problem: I would like to add accessible descriptions for my tree view cells in a nice way that won't break unexpectedly. How can I do that?


text:
Q: ManagedBeanCreationException I have Users pojo and this pojo is not extend from T.It is like this
@Entity
@Table(name = "USERS")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "USERS.findAll", query = "SELECT s FROM USERS s")})
public class USERS implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected USERSPK usersPK;
    @Lob
    @Column(name = "Name")
    private Stirng name;
    @Size(max = 20)
    @Column(name = "Surname")
    private String surname;

And I wanted to select smth.from this table.Service and DAO classes are below:
public interface CommonService {

    public List<Object> hepsiniGetir2(Class persistenceClass, String property, Object searchCrit);

}

This is implementation of interface;
 @Service("commonService")
    public class CommonServiceImpl implements CommonService, Serializable {
    @Transactional
        public List<Object> hepsiniGetir2(Class persistenceClass, String property, Object searchCrit) {
            return commonDao.findAllByCrit2(persistenceClass, property, searchCrit);
        }
    }

And here dao interface:
public interface CommonDAO extends GenericDAO<TemelNesne, Long> {
   public List<Object> findAllByCrit2(Class persistenceClass, String property, Object searchCrit);

}

Here implementation of dao class:
@Repository
public class CommonDAOImpl extends GenericDAOImpl<TemelNesne, Long> implements CommonDAO {
  public List findAllByCrit2(Class persistenceClass, String property, Object searchCrit) {
        Criteria c = sessionFactory.getCurrentSession().
                createCriteria(persistenceClass).add(Restrictions.eq(property, searchCrit));
        List<Object> list = c.list();

        if (list.isEmpty()) {
            return null;
        } else {
            return list;
        }
    }

}

In view class I call this method like ;
@ManagedBean(name="userView", eager=true)
@ViewScoped
public class UserView extends BaseView implements Serializable {
@ManagedProperty("#{commonService}")
    private CommonService commonService;
    private List<USERS> list;

    @PostConstruct
    public void init() {
        list = (List) commonService.hepsiniGetir2(USERS.class, "name", "Deniz");
    }
}

Lastly, I had this exception:

Tem 04, 2014 5:38:10 PM
  com.sun.faces.application.view.FaceletViewHandlingStrategy
  handleRenderException SEVERE: Error Rendering View[/userList.xhtml]
  com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred
  performing resource injection on managed bean userView Caused by:
  org.hibernate.type.SerializationException: could not deserialize
  Caused by: java.io.StreamCorruptedException: invalid stream header:
  3C3F786D

A: Your problem is a concept problem. JSF beans cannot autowire Spring beans, nor the other way around. This is because they are managed in different containers. You should integrate Spring with JSF to allow injection, which basically boils down to Spring controlling everything. There are plenty tutorials in the net about doing this. One good tutorial is mkyong's: JSF 2 + Spring 3 Integration Example. Basically, these are the steps (taken from his tutorial):

*

*In faces-config.xml file, add Expression Language (EL) resolver:
<application>
    <el-resolver>
            org.springframework.web.jsf.el.SpringBeanFacesELResolver
    </el-resolver>
</application>

*Instead using JSF annotations, use Spring annotations for JSF managed beans. Example applied to your classes:
@Component("userView")
@Scope("view")
public class UserView extends BaseView implements Serializable {
    @Autowired
    private CommonService commonService;
    private List<USERS> list;

   @PostConstruct
   public void init() {
       list = (List) commonService.hepsiniGetir2(Sertifikalar.class, "name", "Deniz");
   }
}

Note that in this example, I'm using @Scope("view") but Spring doesn't have a view scope by default, the team is still working on it. You have to implement this scope manually. Fortunately, you can use Cagatay's implementation to solve this.
Apart of these problems, you have another conceptual problem: the only bean that supports eager=true is @ApplicationScoped since it will work as a @Singleton Spring bean, other managed beans will ignore this attribute at all.


text:
Q: Connecting two independent networks onto a switch I have two independent ISP connections connected to two separate routers. I am just curious what will happen If I connected the two routers to a single switch and then connected a computer to one of the switch's port. Will this setup even work, If so Which connection will my Computer use? Can I build a backup internet system out of this?
(Router : TP-LINK TL-WR840N )

A: It'll technically work, but it is not a good idea at all.

*

*When you connect two DHCP servers to the same subnet using a switch, a client will get offers from both and will usually choose the first offer that arrives, ignoring the rest. So depending on the routers themselves, either the "faster" router wins most of the time, or it'll be mostly random as to which one wins. There will be no automatic failover – once a client gets an address lease, it'll keep using it.

*When you connect two IPv6 SLAAC capable routers to the same subnet using a switch, a client will get advertisements from both and will usually accept all of them; it will have multiple IPv6 addresses (belonging to all subnets at once) and multiple default gateways. Current systems will treat all gateways as equivalent, only differing in priority, i.e. they will expect any gateway to handle packets for any prefix. Additionally, they will only fail over if the gateway itself is down, not if its uplink is down.

*If a router has DHCP and IPv6 SLAAC services disabled, then it's just a passive device and connecting it to a switch has no immediate effect – unless hosts are manually configured to use it, in which case of course there won't be any automatic failover. (Assuming it has an unique IP address of course.)

*Although... when you connect two routers with the same IP address to the same subnet using a switch, then a client will get ARP responses from both and (again) will usually choose the first one that arrives – AFAIK. However, unlike with DHCP above, it's quite possible that the client's ARP cache will keep switching between the two devices randomly – so if the routers don't provide completely identical uplink, then all connections will keep breaking randomly.
The usual method of implementing automatic failover is to put a single router in front of both connections and let it deal with the switching. (Many router firmwares have a "multi-WAN" or "failover" feature; check if yours does.) This will still cause connections to break during switchover, but at least it'll be predictable.


text:
Q: qgis refresh button for attributeactions QgsVectorLayer* vLyr=static_cast<QgsVectorLayer*>(aktLayer->qgsLayer);
vLyr->actions()->addAction(QgsAction::ActionType::OpenUrl, "Link im Webbrowser öffnen", "[% "+sAttribute+" %]" , ":/images/images/hotlink.png", false);
vLyr->actions()->setDefaultAction(vLyr->actions()->size()-1);

In my plugin after loading a layer to mapregistry i add with the code above an attribute-action to the layer. But i can't use it, because the button in attributes-toolbar is disabled. Looking at the layerproperties-dialog all seems to be ok and only after clicking 'OK' (not 'Apply') in the dialog the button in toolbar gets enabled and all works fine.
What function do I have to call to reload/refresh the attributes-toolbar in QGIS? Does anybody know this?
EDIT:
found the method "void QgisApp::refreshFeatureActions()" which maybe could solve my problem but how can i access this class from my cpp-plugin?
EDIT:
The final solution for me is the following:
QgsVectorLayer* vLyr=static_cast<QgsVectorLayer*>(aktLayer->qgsLayer);

QToolBar* attributeToolbar= mQGisIface->mainWindow()->findChild<QToolBar*>("mAttributesToolBar");

vLyr->actions()->addAction(QgsAction::ActionType::OpenUrl, "Link im Webbrowser öffnen", "[% "+sAttribute+" %]" , ":/images/images/hotlink.png", false);
vLyr->actions()->setDefaultAction(vLyr->actions()->size()-1);

QgsMapLayerAction * mapAction=new QgsMapLayerAction("Link im Webbrowser öffnen", attributeToolbar, aktLayer->qgsLayer, QgsMapLayerAction::Target::AllActions);//, new QIcon(":/images/images/hotlink.png"));
QgsMapLayerActionRegistry::instance()->addMapLayerAction(mapAction);
QgsMapLayerActionRegistry::instance()->removeMapLayerAction(mapAction);

I have to remove the QgsMapLayerAction because it doesn't know that it is an OpenURL an so it is empty. But only adding an entry to the QgsMapLayerActionRegistry emits a signal to check the toolbar availibility.
I don't know why I have no access to QgisApp-class, can't include qgisapp.h.

A: I am not sure if this help you since this is for python. Why not add the action to attributes toolBar.
attributeToolBar = self.iface.mainWindow().findChild(QToolBar,'mattributeToolBar')

action = QtGui.QAction(parent)

attributeToolBar.addAction(action)


text:
Q: Creating Threaded callbacks in XS EDIT: I have created a ticket for this which has data on an alternative to this way of doing things.
I have updated the code in an attempt to use MY_CXT's callback as gcxt was not storing across threads. However this segfaults at ENTER.
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#ifndef aTHX_
#define aTHX_
#endif

#ifdef USE_THREADS
#define HAVE_TLS_CONTEXT
#endif

/* For windows  */
#ifndef SDL_PERL_DEFINES_H
#define SDL_PERL_DEFINES_H

#ifdef HAVE_TLS_CONTEXT
PerlInterpreter *parent_perl = NULL;
extern PerlInterpreter *parent_perl;
#define GET_TLS_CONTEXT parent_perl =  PERL_GET_CONTEXT;
#define ENTER_TLS_CONTEXT \
        PerlInterpreter *current_perl = PERL_GET_CONTEXT; \
            PERL_SET_CONTEXT(parent_perl); { \
                                PerlInterpreter *my_perl = parent_perl;
#define LEAVE_TLS_CONTEXT \
                                        } PERL_SET_CONTEXT(current_perl);
#else
#define GET_TLS_CONTEXT         /* TLS context not enabled */
#define ENTER_TLS_CONTEXT       /* TLS context not enabled */
#define LEAVE_TLS_CONTEXT       /* TLS context not enabled */
#endif

#endif

#include <SDL.h>

#define MY_CXT_KEY "SDL::Time::_guts" XS_VERSION

 typedef struct {
 void* data;
 SV* callback;
 Uint32 retval;
 } my_cxt_t;

static my_cxt_t gcxt;

START_MY_CXT

static Uint32 add_timer_cb ( Uint32 interval, void* param )
{

        ENTER_TLS_CONTEXT
        dMY_CXT;
        dSP;
        int back;
        ENTER; //SEGFAULTS RIGHT HERE!
        SAVETMPS;
        PUSHMARK(SP);
        XPUSHs(sv_2mortal(newSViv(interval)));
        PUTBACK;

        if (0 != (back = call_sv(MY_CXT.callback,G_SCALAR))) {
        SPAGAIN;
        if (back != 1 ) Perl_croak (aTHX_ "Timer Callback failed!");
        MY_CXT.retval = POPi;
        } else {
        Perl_croak(aTHX_ "Timer Callback failed!");
        }

        FREETMPS;
        LEAVE;

        LEAVE_TLS_CONTEXT
        dMY_CXT;
        return MY_CXT.retval;

}

MODULE = SDL::Time  PACKAGE = SDL::Time    PREFIX = time_

BOOT:
{
  MY_CXT_INIT;
}

SDL_TimerID
time_add_timer ( interval, cmd )
    Uint32 interval
    void *cmd
    PREINIT:
        dMY_CXT;
    CODE:
        MY_CXT.callback=cmd;
        gcxt = MY_CXT;
        RETVAL = SDL_AddTimer(interval,add_timer_cb,(void *)cmd);
    OUTPUT:
        RETVAL

void
CLONE(...)
  CODE:
    MY_CXT_CLONE;

This segfaults as soon as I go into ENTER for the callback.
use SDL;
use SDL::Time;

SDL::init(SDL_INIT_TIMER);
my $time = 0;
SDL::Timer::add_timer(100, sub { $time++; return $_[0]} );
sleep(10);
print "Never Prints";

Output is
$

it should be
$ Never Prints

A: Quick comments:

*

*Do not use Perl structs (SV, AV, HV, ...) outside of the context of a Perl interpreter object. I.e. do not use it as C-level static data. It will blow up in a threading context. Trust me, I've been there.

*Check out the "Safely Storing Static Data in XS" section in the perlxs manpage.

*Some of that stuff you're doing looks rather non-public from the point of view of the perlapi. I'm not quite certain, though.

A: $time needs to be a shared variable - otherwise perl works with separate copies of the variable.

A: My preferred way of handling this is storing the data in the PL_modglobal hash. It's automatically tied to the current interpreter.

A: We have found a solution to this using Perl interpreter threads and threads::shared.  Please see these
Time.xs
Also here is an example of a script using this code.
TestTimer.pl


text:
Q: How to retrieve the position of a textarea in AFrame I was able to get the text value of my textarea by writing this line of code (thanks to Diego Marcos):
console.log("value="+els.components.textarea.textarea.value);

I now want to get the position of said textarea. The line of code:
console.log("value="+els.components.textarea.position); gives result=undefined.

console.log(getAttribute("position")) gives the result [object Object].

A: Posting Diego's answer:

That's expected. You're getting an object with an x,y and z properties. To print it do var position = el.getAttribute('position'); console.log('x: ' + position.x + ' y: ' + position.y + ' z: ' + position.z);


text:
Q: Fatal problem within my MySql queries I'm having a problem regarding these 3 queries:
select count(*) as rec_count from test_history inner join
  test_detail on test_history.history_id = test_detail.test_history_id
  where test_history.history_id in ({$_SESSION['history_ids']})
  and test_history.user_id = $userID

and
select count(*) as correct_answers from test_history inner join test_detail
  on test_history.history_id = test_detail.test_history_id
  where test_history.history_id in ({$_SESSION['history_ids']}) and
  test_history.user_id = $userID and is_correct = 1

and this one
select * from test_topics inner join
  test_topics_link on test_topics.`topic_id` = test_topics_link.`topic_id`
  where test_topics_link.test_id in ({$_SESSION['ids_tests']}) and percentage > 0

I'm always getting this error:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ') and
test_history.user_id = 82' at line 3

You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ') and
test_history.user_id = 82 and is_correct = 1' at line 2

You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ')' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ') and percentage > 0' at
line 3

A: Since $_SESSION['ids_tests'], I suppose, is an array, you should write implode(',',$_SESSION['ids_test']), e.g. in PHP it should be:
$query = "select * from test_topics inner join
        test_topics_link on test_topics.`topic_id` = test_topics_link.`topic_id`
        where test_topics_link.test_id in (".
        implode(',',$_SESSION['ids_tests']).") and percentage > 0";


text:
Q: How to commit an uncommitted mysql query I am using MySQL DB, and use python's MySQL-connector to connect with it. I try to insert a record to MySQL using
def insert_users(first_name, last_name, country):
  conn, cursor=connection()
    cursor.execute(
      """
      INSERT INTO users (first_name, last_name, country_code)
      SELECT %s,%s, code
      FROM countries
      WHERE countries.name=%s
      """, (first_name, last_name, country)
    )

but I forget to commit after execute, and then I use the same function to insert the same data with a commit but when I check the table, I find the primary_key starts from 2 instead of 1, which means the data is somehow existing (but uncommitted?) but what should I do to make it recover to a normal state, i.e commit the data I want to insert?
my isolation level is repeatable-read.
and i try to kill the connection through process id but i got the error "Query execution was interrupted", this is the result of show processlist
| Id | User | Host            | db    | Command | Time | State    | Info             |
 82 | root | localhost       | test2 | Query   |    0 | starting | show processlist |

what should i do, i want to either commit the query or get rid of it. anyone can help? thanks in advance, Emergent...


text:
Q: Can not feed when using Dataset with MonitoredTrainingSession in tensorflow I have below code with tensorflow 1.3.0. You can run it without any error.
But if uncomment tf.summary.scalar('test', next_batch) and checkpoint_dir='/temp',
I got
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder' with dtype string
     [[Node: Placeholder = Placeholder[dtype=DT_STRING, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]].
What's wrong?
import tensorflow as tf

with tf.Graph().as_default():
    global_step = tf.contrib.framework.get_or_create_global_step()
    dataset_train = tf.contrib.data.Dataset.range(10)
    dataset_val = tf.contrib.data.Dataset.range(90, 100)

    iter_train_handle = dataset_train.make_one_shot_iterator().string_handle()
    iter_val_handle = dataset_val.make_one_shot_iterator().string_handle()

    handle = tf.placeholder(tf.string, shape=[])
    iterator = tf.contrib.data.Iterator.from_string_handle(
        handle, dataset_train.output_types, dataset_train.output_shapes)
    next_batch = iterator.get_next()
    # tf.summary.scalar('test', next_batch)

    with tf.train.MonitoredTrainingSession(
            # checkpoint_dir='/temp',
    ) as sess:
        handle_train, handle_val = sess.run([iter_train_handle, iter_val_handle])

        for step in range(10):
            print('train', sess.run(next_batch, feed_dict={handle: handle_train}))

            if step % 3 == 0:
                print('val', sess.run(next_batch, feed_dict={handle: handle_val}))

A: If you still want to use MonitoredTrainingSession then a workaround for this issue is to use tf.placeholder_with_default. Use a sensible initial default value and then update it as required.

A: Get the answer from github. by @asimshankar.

That said, MonitoredTrainingSession runs the summary operations and
  since your summary operation is connected to the placeholder, it is
  complaining about the missing feed.
If you do not want the features of the MonitoredTrainingSession,
  might I suggest using MonitoredSession or Session directly.
Closing this out since it is not a bug or feature request
  (MonitoredTrainingSession intentionally tries to run summary
  operations at periodic intervals).


text:
Q: Xcode "-[UIViewController _loadViewFromNibNamed:bundle:] loaded the nib but the view outlet was not set." error I'm using Xcode 4 and when I run my app, the first screen doesn't load. It fails in the simulators and on a device. I've searched for answers and they all say to make sure I've dragged the circles in Files Owner to the correct views. Sorry I don't remember the names of the things, I'm new to Xcode. I've dragged the circles to the correct view and tried many things but none of them worked. What could I be doing wrong?
Here is the full error:
2012-02-19 12:59:54.655 Ponyboard[271:207]
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "PonyboardViewController" nib but the view outlet was not set.'

*** Call stack at first throw:
(
    0   CoreFoundation                      0x00f095a9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x0105d313 objc_exception_throw + 44
    2   CoreFoundation                      0x00ec1ef8 +[NSException raise:format:arguments:] + 136
    3   CoreFoundation                      0x00ec1e6a +[NSException raise:format:] + 58
    4   UIKit                               0x0020d709 -[UIViewController _loadViewFromNibNamed:bundle:] + 295
    5   UIKit                               0x0020b134 -[UIViewController loadView] + 120
    6   UIKit                               0x0020b00e -[UIViewController view] + 56
    7   UIKit                               0x0017ed42 -[UIWindow addRootViewControllerViewIfPossible] + 51
    8   Ponyboard                           0x00002a87 -[PonyboardAppDelegate application:didFinishLaunchingWithOptions:] + 135
    9   UIKit                               0x0015bc89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163
    10  UIKit                               0x0015dd88 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 439
    11  UIKit                               0x00168617 -[UIApplication handleEvent:withNewEvent:] + 1533
    12  UIKit                               0x00160abf -[UIApplication sendEvent:] + 71
    13  UIKit                               0x00165f2e _UIApplicationHandleEvent + 7576
    14  GraphicsServices                    0x031fd992 PurpleEventCallback + 1550
    15  CoreFoundation                      0x00eea944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    16  CoreFoundation                      0x00e4acf7 __CFRunLoopDoSource1 + 215
    17  CoreFoundation                      0x00e47f83 __CFRunLoopRun + 979
    18  CoreFoundation                      0x00e47840 CFRunLoopRunSpecific + 208
    19  CoreFoundation                      0x00e47761 CFRunLoopRunInMode + 97
    20  UIKit                               0x0015d7d2 -[UIApplication _run] + 623
    21  UIKit                               0x00169c93 UIApplicationMain + 1160
    22  Ponyboard                           0x000029c9 main + 121
    23  Ponyboard                           0x00002945 start + 53
)
terminate called after throwing an instance of 'NSException'

A: Are you sure you have a UIView (or subclass) assigned to the "view" property of PonyboardViewController? Right click on "File Owner" in the left pane of the xib for PonyboardViewController and verify that the "view" outlet is set.
If not, set it to a view!

A: I just have the same problem as you, so I fixed it like that:
this is my code block:
self.chatsView = [[ChatsView alloc] initWithNibName:@"ChatsView" bundle:nil];

I click ChatsView.xib to find the "File's owner", then hover my mouse over the "File's owner", and right click, that will prompt something like this:
The unconnected 'view' outlet
you must drag the "view" Outlet to connect to the View which have two subViews: Search Bar&Table View in my xib file.
The connected 'view' outlet

A: Your problem probably lies with the XIB or Stroyborad scene. Check whether the View is connected properly to the class.
I've tried, and it works fine for me after doing it.


text:
Q: Как предатвратить пересоздание фаргментов при использовании BottomNavigationView с Navigation component? У меня есть приложение, одно активити, с BottomNavigationView и Fragment:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment_activity_main"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

И четыре фрагмента, навигацию осуществляю так:
MainActivity
        val navController = findNavController(R.id.nav_host_fragment_activity_main)
        binding.navView.setupWithNavController(navController)

        binding.navView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_fra1 -> {
                    findNavController(R.id.nav_host_fragment_activity_main).navigate(R.id.Fragment)
                }
                R.id.navigation_fra2 -> {
                    findNavController(R.id.nav_host_fragment_activity_main).navigate(R.id.Fragment2)
                }
                R.id.navigation_fra3 -> {
                    findNavController(R.id.nav_host_fragment_activity_main).navigate(R.id.Fragment3)
                }
                R.id.navigation_fra4 -> {
                    findNavController(R.id.nav_host_fragment_activity_main).navigate(R.id.Fragment4)
                }
            }
            true
        }

Фрагменты все одинаковые но тянут разные данные из Firebase Database:
class Fragment : Fragment() {
    private var _binding: FragmentBinding? = null
    private val binding get() = _binding!!
    private lateinit var arrayList: ArrayList<FireItems>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentBinding.inflate(inflater, container, false)
        val view = binding.root

        arrayList = ArrayList()

        val database = Firebase.database
        val myRef = database.getReference("items")
        myRef.addValueEventListener(object : ValueEventListener {
            @SuppressLint("NotifyDataSetChanged")
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val value = dataSnapshot.value
                arrayList.clear()
                Log.d("mDatabase", "Value is: $value")
                for (postSnapshot in dataSnapshot.children) {

                    arrayList.add(FireItems(postSnapshot.child("image").value.toString(), postSnapshot.child("name").value.toString(), postSnapshot.child("description").value.toString()))
                    if (!arrayList.isNullOrEmpty()) {
                        binding.apply {
                            progressCircular.visibility = View.GONE
                            recyclerView.setHasFixedSize(true)
                            val adapter = FireRecyclerViewAdapter(requireActivity(), arrayList)
                            recyclerView.layoutManager = GridLayoutManager(requireActivity(), 2)
                            recyclerView.adapter = adapter
                        }
                    }
                }

            }

            override fun onCancelled(error: DatabaseError) {
                Log.w("mDatabase", "Failed to read value.", error.toException())
            }
        })

        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {}
        })

        return view
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}

Мне нужно сделать так чтобы по переходу из одного фрагмента на другой через BottomNavigationView, не пере создавались каждый раз фрагменты. Потому что во-первых если элементов в списке много, я не хочу чтобы приходилось каждый раз снова прокручивать весь recycler, а во-вторых каждый раз дергать базу данных не правильно, на сколько я знаю.
Подскажите пожалуйста, как это лучше сделать?


text:
Q: Should repeated capital letters remain capitalised? When one wants to emphasise stress on a particular part of a word by repeating letters, if one of those letters is a capital, should it remain capitalised?
For example, would someone calling out the name Allen be AAAAAlllllen or Aaaaalllllen?
Or another example: David Bowie's "Changes" - Ch-ch-ch-ch-changes or Ch-Ch-Ch-Ch-Changes?
Are there any style manuals that address this?

A: Sorry if this is a bad answer since I'm new here, I personally think that it's how much emphasis you put onto it, if it's like shouting like in AAAAAAAAAAAlllen! it would be like that, but if it's something like Ch-ch-ch-ch-ch , it would have lowercase letters. I don't really have any references though, just my opinion.

Here's the difference between one capital and multiple capitals.

Ahhhhhhhhhhhhh!

AHHHHHHHHHHHHHHH!

Doesn't it give a effect? Also, doesn't it seem like the one capital one seem like a person sighing because they understand something, and the multiple capital one sounds like someone screaming.

So, in my opinion, my answer is that it varies on what you want the reader to understand. I always thought that it was such a simple question. Maybe you think something else though, but however it is your choice on what YOU want the reader to believe. Just don't use all capital letters in a whole sentence, as it really gives a headache.
References:

1. capital letters for emphasis, BtB

2.All caps hard for users to read *note: first paragraph


text:
Q: Eureka Server dashboard is not coming up with JDK 11 After migrating to java 11, Eureka Server dashboard is not coming up.
The same is running with jdk 1.8.
When the server is started as spring boot application, the server is started successfully but when tried to launch it from browser it is throwing 404 error.
This is the error I am getting :
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 404


text:
Q: Try to use reflection to open url in a webview, I'm trying to use reflection for loadUrl in a webview, but it doesn't works.
I use this code :
Class primary
{..............
public void start(InputStream is)
{

    prova = new _JsonRead();
    try {
        Class<?> test=Class.forName("xxx.test.learning.Webview1");
        Field f=test.getDeclaredField("myWebView");

        Class<?> web=WebView.class;
        Method metodo=web.getMethod("loadUrl",String.class); //restituisce il metodo loadUrl con parametro tipo stringa
         ;
        metodo.invoke(f, "www.google.com");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.i("ecc", "error "+e);
        e.printStackTrace();
    }
.......
}
public class Webview1 extends Activity
{
public WebView myWebView = null;
public WebSettings webSettings = null;

@Override
public void onCreate(Bundle SavedInstance)
{
    super.onCreate(SavedInstance);
    setContentView(R.layout.activity_webview);

    myWebView = (WebView) findViewById(R.id.webview);
    webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    Primary prova = new Primary();
    prova.start(getResources().openRawResource(R.raw.config));
    //myWebView.loadUrl(prova.indirizzo);

    /*
     * I move this function
     * myWebView.loadUrl("file:///android_asset/test.html");
     * in the Learning_lib2
     */

}

}

But there is this error :
"03-01 15:58:07.200: I/ecc(19919): error java.lang.IllegalArgumentException: expected receiver of type android.webkit.WebView, but got java.lang.reflect.Field
"
I'm new in reflection, and this is my first test. I have thought that Field was a generic Object , but securely I'm wronging..but where ? :/

A: Should be something akin to
  Class<?> test = Class.forName("xxx.test.learning.Webview1"); //could be just Webview1.class;
  Field f=test.getDeclaredField("myWebView"); //get field of particular class

  Class<?> web=WebView.class; //get the class for WebView
  Method metodo=web.getMethod("loadUrl",String.class); //get the Method of WebView class by name loadUrl and parameter String
  WebView1 webView1 = test.newInstance(); //create instance of WebView1
  WebView webView = (WebView) f.get(webView1); //get the field of webView1, cast to WebView
  metodo.invoke(webView, "www.google.com");

But I don't think this will work because your WebView1 is an Activity, and so the onCreate() method wouldn't run that creates the WebView field.


text:
Q: Discord Unable To Remove App In Discord Developer Portal I created an application. I use it and now I want to delete it but I can't. I reloaded the site but it still doesn't work.
Here is the picture:

A: Basically, the reason is that there is an extra space in the name.


text:
Q: pgfgantt: Is it possible to create bars with "double" labels? here's a problem I have: I want my gantt bars to have two types of labels --  one on the side of the chart, and one inline -- and I'm having a hard time making it work. The code I use to generate the chart is listed below:
\begin{ganttchart}[
vgrid,
x unit=1cm,
title height=1]{12}{12}
  \gantttitle{Quarters}{12} \\
  \gantttitlelist{1,...,12}{1} \\
  \gantttitle{Year 1}{4}
  \gantttitle{Year 2}{4}
  \gantttitle{Year 3}{4}\\
\ganttbar{WP1 Theoretical part}{1}{5} \\
\ganttbar{WP1 Experimental part}{2}{6} \\
\ganttbar{WP2 Theoretical part}{7}{11}\\
\ganttbar{WP2 Experimental part}{8}{12}\\
\ganttbar[bar/.append style={fill=gray,pattern=north east lines}]{WP3 Theoretical part}{6}{12}\\
\ganttbar[bar/.append style={fill=gray,pattern=north east lines}]{WP3 Experimental part}{7}{12}
\end{ganttchart}

And the idea is to have WPx labels on the left of the chart, but "Theoretical/experimental part" labels inside the bars. Is it possible to make this with pgfgantt?

A: You could use two \ganttbars; the second one using the inline option. Below, this approach, thorough a command:
\Dganttbar{<side text>}{<inline text>}{<start>}{<end>}

The code:
\documentclass{article}
\usepackage{pgfgantt}

\newcommand\Dganttbar[4]{%
  \ganttbar{#1}{#3}{#4}\ganttbar[inline,bar label font=\footnotesize]{#2}{#3}{#4}
}

\begin{document}

\begin{ganttchart}{1}{12}
\gantttitle{2011}{12} \\
\gantttitlelist{1,...,12}{1} \\
\Dganttbar{WP1}{Theoretical part}{1}{5} \\
\Dganttbar{WP1}{Experimental part}{2}{6} \\
\Dganttbar{WP2}{Theoretical part}{7}{11}\\
\Dganttbar{WP2}{Experimental part}{8}{12}\\
\end{ganttchart}

\end{document}


text:
Q: A villager asked me to take a picture and send it to them. How do I do that? A villager walked up to me and asked me to take a picture of them, so I did. Then they asked me to send it to them. I assume that means attaching it to a letter. However, I can't figure out how to do that, since I can't drag it like other items. How do I go about sending that picture?

A: When you have a G-Mail,and the villager too,you can attach a file on it,when you're writing an E-Mail to him,somewhere.


text:
Q: Can't see predefined values section on object-specific quick action I've created quick action with Lightning Component content source and I wanted to add predefined values for the action. However, I can't see "Predefined Values" section. Do somebody know why?

A: You can set predefined value only for Creating Object-Specific Quick Actions in salesforce. It means you should select an action type as "create a record",  While you are going for action having the source as Lightning Component you can not do it.
If you are creating a record or editing it, You can modify your lightning component accordingly to set the predefined values.


text:
Q: Runtimes supported by containerd apart from runC? Does containerd support any other runtimes apart from runC?
Further, the containerd site says, "An industry-standard container runtime with an emphasis on simplicity, robustness and portability". Does this refer to any specific standard like the OCI or CRI.

A: From: github.com/containerd/containerd

Runtime Requirements
Runtime requirements for containerd are very minimal. Most interactions with the Linux and Windows container feature sets are handled via runc and/or OS-specific libraries (e.g. hcsshim for Microsoft).

From: github.com/Microsoft/hcsshim

hcsshim
This package contains the Golang interface for using the Windows Host Compute Service (HCS) to launch and manage Windows Containers. It also contains other helpers and functions for managing Windows Containers such as the Golang interface for the Host Network Service (HNS).

Regarding the OCI part of your question:

OCI Runtime Specification
containerd fully supports the OCI runtime specification for running containers. We have built in functions to help you generate runtime specifications based on images as well as custom parameters.
You can specify options when creating a container about how to modify the specification.
redis, err := client.NewContainer(context, "redis-master", containerd.WithNewSpec(oci.WithImageConfig(image)))


text:
Q: How to wait until all cell content is show after conversion of a pivottable to formulas? I want to "flatten" a pivot table via the ConvertToFormulas function and copy the result into the clipboard.
My code looks something like this:
ActiveSheet.PivotTables(1).ConvertToFormulas True
Range("A1").Select
ActiveCell.CurrentRegion.Select
Application.CutCopyMode = False
Selection.Copy

My problem is that not all cells are fully loaded from the datasource (they show #GETTING_DATA) when my Selection.Copy executes and I am left with cells in the clipboard that contain the text "#GETTING_DATA".
I would like to find a way to wait until all the cells are loaded or at least to wait 10s until (hopefully) all cells are loaded.
I have tried to add
Application.Wait(Now + TimeValue("0:00:10"))

or
Sleep(10000)

before Copy but this seams to block the thread on which the loading of the cells is done and I am left with with the same result after 10s.

A: Didn't build pivot table to test the result but see if below code will helps.  The idea is to keep looping through the selected cells, until all cells are integer then we copy it:
Sub test()
Dim pcced As Boolean
pcced = False
ActiveCell.CurrentRegion.Select

Do While pcced = False
pcced = chkv(Selection)
Loop

Application.CutCopyMode = False
Selection.Copy
End Sub

Function chkv(s As Variant) As Boolean
Dim rslt As Boolean
For Each cell In s
If IsNumeric(cell) Then
    rslt = True
Else:
    rslt = False
    Exit For
End If
Next
chkv = rslt
End Function


text:
Q: Error in writing own system call: incompatible type for argument 2 of `copyout' I am writing my own system call in openBSD. I am trying to use the copyout function which has the signature :
 int
     copyout(void *kaddr, void *uaddr, size_t len);

I have an array
char word[MAX_STR_LENGTH+1];

I also have a struct
 struct sys_<name of the function>_args *uap

The struct is declared as the following:
struct sys_<name of function >_args {
    syscallarg(char *) text;
};

I am getting an incompatible type for argument 2 of copyout when I try to use the copyout function like this:
copyout(word, uap->text, sizeof (word));

Here is the error message:
 In function <name of function>
 incompatible type for argument 2 of `copyout'
*** Error code 1

What am I doing wrong?


text:
Q: Is it possible to forward all traffic from one Ethernet interface to another without NAT? Set up:
Cable modem --> HW Ethernet port on Ubuntu 16 box (eth0).
OpenVPN client connection (tun0) over eth0.
2nd HW Ethernet port on Ubuntu 16 box (eth1) to hardware router.
I can set up internet sharing over eth1 and run that as a DHCP server with typical 10.42.0.0.
Assume for iptables that eth0 has 192.168.1.1, tun0 has 60.60.1.1, and eth1 has 10.42.0.1.
Is it possible to simply have all the data coming in and out of eth0 be sent to eth1, without this masquerade? That way, all data from the cable modem WAN is flowing through the Ubuntu box to the hardware router, but the hardware router can still do its NAT job without the Ubuntu box doing it in between. Is this possible?
Thank you!

A: If eth0 has 192.168.1.1 then you've already got NAT somewhere in the equation, either as CGNAT (in which case maybe consider changing ISP) or inside the cable modem. If tun0 has 60.* then it's using a public IP address.
You can definitely forward traffic between interfaces without NAT. It's called forwarding.
sysctl -w net.ipv4.ip_forward = 1

You also need to set up the routing so that your cable modem knows not only about its directly connected subnet 192.168.1.1/24 but also the other subnets in your network, principally 10.42.0.0/??.


text:
Q: is it possible to change the Class of a Doctrine Object? Im using Doctrine and I need to clone an object.
Two tables in the database have the same columns, but one exists for backlog orders whilst one is confirmed orders. Probably not the best way to do it, but they must be seperate as certain foreign keys cannot be satisfied on backlog objects.
So, I need to clone one object from the backlog and insert it into the current orders table. But if I clone the backlog order object, it will set the class to backlog order.
$backlog_orders = $this->Subscription_model->getBacklogOrders();
foreach($backlog_orders as $backlog_order){
    $new_order = new Entities\NewOrder;
    $new_order = clone $backlog_order;
    //Do other stuff to new order
    //At this point, I need to change the class of the object to NewOrder so that it will insert it into the correct table
    echo get_class($order); // Outputs BacklogOrder
    $this->Subscription_model->updateOrder($order); // Saves to DB
}

A: I can't give you a specific answer but if you clone the object, you also clone its entity's primary key (order_id?), and I doubt Doctrine can handle this well.
I suggest you the to instance and persist a new object and use get/set like this:
$new_order = new Entities\NewOrder;
$new_order->setCustomer($backlog_order->getCutomer());

A: First I'd like to point out a mistake in your question, which kind of explains why you run into this.

"But if I clone the backlog order object, it will set the class to backlog order."

Nothing gets set, in this point in your code..
$new_order = new Entities\NewOrder;
$new_order = clone $backlog_order;

..you first make a $new_order object and then make a new $new_order object which is a clone of $backlog_order. In other words, the first line with new Entities\NewOrder means absolutely nothing.
You also should know that the clone keyword in PHP makes a shallow copy. So all the references in $new_order are still to the old order. Even if you would manage to change the class in the way you are trying it right now doctrine would not do an insert but rather an update.
What you basically want is to make a true copy, which is not provided by PHP because it would violate the type system. In order to do this you should just fill $new_order with all the data from $backlog_order.
You should however also consider that you probably have an auto incrementing primary key right now. I don't know if doctrine will let you override this.


text:
Q: Constraints reactivate when contextMenu appears I am using UIContextMenuConfiguration for actions on a collection view cell. Everything works exactly as expected, however if my cell has (de)activated constraints from nib, it refreshes upon long press.
To demonstrate the problem, I have created a new project, with a collectionView in the storyboard. A custom cell in the collection view has a label with two constraints, a constraint pinning it to the bottom of the cell (initially active), and the other aligns it in the center (initially disabled).
Here's my code,
import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
        cell.configure()
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration.init(identifier: nil, previewProvider: nil) { (array) -> UIMenu? in
            return UIMenu(title: "Hello", image: nil, identifier: nil, options: .destructive, children: [UIAction(title: "Share", image: UIImage(systemName: "tray.and.arrow.up"), identifier: nil) { _ in
                print("HelloWorld!")
              }])
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 265, height: 128)
    }
}

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    @IBOutlet weak var centerConstraint: NSLayoutConstraint!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func configure() {
        bottomConstraint.isActive = false
        centerConstraint.isActive = true
    }
}

A: The issue appears to be directly related to:

*

*two constraints created in Storyboard which would conflict with each other

*setting one constraint to Not Installed

*de-activating the installed constraint and activating the not-installed constraint

When initializing UIContextMenuConfiguration with previewProvider: nil - which tells UIKit to auto-generate a preview view - the "installed" states of the constraints are reset.
One way to get around it:
Instead of marking the Center constraint "not installed" give it a Priority of 998, and give the Bottom constraint a Priority of 999 (that will prevent IB from complaining).
You can then keep your configure() func as:
func configure() {
    bottomConstraint.isActive = false
    centerConstraint.isActive = true
}

and the label's centerY constraint will remain active in both the cell and in the context menu's preview.
However, if you WANT the previewView to look different than the cell, your best bet (and probably a better approach to begin with) is to use a custom previewProvider.


text:
Q: Imprimir el máximo entre un conjunto de variables utilizando if y strings en Python Supongamos que tengo 3 números cualquiera alojados en tres variables distintas:
x= 5
y= 11
z= 37

La prueba que realiza el if es determinar que las 3 variables sean impares. Si es así, da los mensajes "Los tres números son impares" y "El mayor es" seguido del número correspondiente.
if x %2!=0 and y %2!=0 and z %2!=0:
    print("Los tres números son impares")
    print("El mayor es",  max(x,y,z))
elif x %2!=0 or y %2!=0 or z %2!=0:
    print("Al menos uno es par")
else:
    print("Todos son pares")

Lo que deseo es que el segundo print para el if regrese un mensaje como el siguiente, tomando en cuenta los valores que asigné en un principio:
"El mayor es 37 y corresponde a la variable z"

Por supuesto, la idea es que el print devuelva, para cualquier caso, el mayor número y su correspondiente variable. Entiendo que esto podría hacerse utilizando diccionarios, pero deseo que la solución se ciña a los requerimientos que he comentado.
De antemano agradezco cualquier ayuda.

A: Si solo tienes esas tres variables una aproximación simple es usar condicionales, dentro o fuera de la propia llamada a print:
x= 5
y= 11
z= 37

if x %2!=0 and y %2!=0 and z %2!=0:
    print("Los tres números son impares")
    m = max((x,  y,  z))
    print("El mayor es {1}  y corresponde a la variable {0}".format("x" if m == x
                                                                    else "y" if m == y
                                                                    else "z",  m))
elif x %2!=0 or y %2!=0 or z %2!=0:
    print("Al menos uno es par")
else:
    print("Todos son pares")

Se usa el operador ternario dentro de str.format pero podrías implementarlo en un bloque if-elif-else antes de imprimir.
Si lo quieres todo metido en el print puedes hacer esto:
print("El mayor es {}  y corresponde a la variable {}".format(*((x, "x") if x == max(x,  y,  z)
                                                                  else (y, "y") if y == max(x,  y,  z)
                                                                  else (z, "z"))))

o bién:
print("El mayor es {}  y corresponde a la variable {}".format(*((x, "x") if x >= z and x >= y
                                                                else (y, "y") if y > z
                                                                else (z, "z"))))

Muy poco legible pero funciona...

Aunque no quieras usar diccionarios, es posiblemente una solución más escalable, para ello usa un diccionario y el argumento key de max:
>>> from operator import itemgetter

>>> x= 5
>>> y= 11
>>> z= 37

>>> d=dict(x=x, y=y, z=z)
>>> max(d.items(), key=itemgetter(1)))
('z', 37)

Esto retorna la tupla con la pareja (key, value) que se corresponde con el máximo valor.
Implementado en tu código:
from operator import itemgetter

x= 5
y= 11
z= 37

d=dict(x=x, y=y, z=z)

if x %2!=0 and y %2!=0 and z %2!=0:
    print("Los tres números son impares")
    print("El mayor es {1}  y corresponde a la variable {0}".format(*max(d.items(), key=itemgetter(1))))
elif x %2!=0 or y %2!=0 or z %2!=0:
    print("Al menos uno es par")
else:
    print("Todos son pares")

Salida:

Los tres números son impares
  El mayor es 37  y corresponde a la variable z

Edición:

*

*Puedes mirarte el funcionamiento str.format y del Format Specification Mini-Language en la documentación oficial, junto a múltiples ejemplos (en inglés):
6.1.3. Format String Syntax
Básicamente este método lo que hace es realizar una operación de formato en la cadena. La cadena en la que se llama este método puede contener texto literal o campos de reemplazo delimitados por llaves {}. Devuelve una copia de la cadena donde cada campo de reemplazo se reemplaza con el valor o valores que se le pasan como argumentos.
Cada campo de reemplazo puede contener un índice numérico para determinar en que lugar va cada argumento:
>>> cad = "¡Hola {}!".format("Python")
>>> cad
'¡Hola Python!'

Permite realizar formateos mucho más complejos, número de decimales, impresión o no de signos de números, tabulación de datos, alineación, cambios de bases numéricas al imprimir, etc.

*El operador *  se limita a desempaquetar argumentos de una tupla/lista. mifunción(4, "hola") es "equivalente" a mifunción(*(4, "hola")) o a mifunción(*[4, "hola"]).

*La sintaxis A if x else B if y else C es la sintaxis propia del operador ternario. Retorna A si se cumple x, sino retorna B si y es cierta o si nada se cumple retorna C. Otro ejemplo real:
>>> a = 3
>>> b = 4
>>> "Mayor" if a > b else "Menor" if a < b else "Iguales"
"Menor"

A: La respuesta de JSevilla en particular usando un diccionario creo que es la óptima. De todas formas quiero agregar algo más. Lo que quieres hacer es básicamente identificar una variable por medio de su valor, esto si bien es posible, es absolutamente ambiguo, supongamos el siguiente ejemplo:
a = 3
b = 3

Si pudiéramos identificar la variable a la que "apunta" el valor 3. ¿Cuál sería? ¿La variable a o la variable b?. Es decir, se puede relacionar una variable a un valor de manera unívoca pero no al revés. Teniendo en cuenta este problema y solo a titulo informativo hay una forma de obtener el nombre de una variable a partir de un valor no recomendable para usarlo si no tenemos bien claro las limitaciones relacionadas.
x= 5
y= 11
z= 3
maximo, variable = [v for v in list(locals().items()) if v[1] == max(x, y, z)][0]
print("El valor máximo es {1} y corresponde a la variable '{0}'".format(maximo, variable))
> El valor máximo es 11 y corresponde a la variable 'y'

Haciendo uso de locals() accedemos a un diccionario con la tabla de símbolos del ámbito local, el cual dependerá desde dónde invoquemos la función.
Esto tiene su limitación que es muy clara cuando ocurre esto:
otra_variable = 11

x= 5
y= 11
z= 3

maximo, variable = [v for v in list(locals().items()) if v[1] == max(x, y, z)][0]

print("El valor máximo es {1} y corresponde a la variable '{0}'".format(maximo, variable))
> El valor máximo es 11 y corresponde a la variable 'otra_variable'


text:
Q: AttributeError: 'Intents' object has no attribute 'message_content' в дискорд боте Хотел повторить обычный код музыкального бота из официального GitHub discord.py. Вписал туда свой токен, но при запуске получаю ошибку:
Traceback (most recent call last):
  File "d:\Python\DiscordMusic\bot.py", line 130, in <module>
    intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'

Мои настройки дискорд бота:


text:
Q: Quickblox 50 messages from room history My question is base on This
I have also read this
Where this is written
"By default, maximum number of history messages returned by room is 50. There is no way to change this value now."

now my question is that .Is this limit apply for every single user or 50 messages combining all users of room.

A: You get last 50 messages of all users in current chatroom. In near future, Quickblox iOS SDK will provide API for control this feature. Please check last updates of framework at http://quickblox.com/developers/IOS#Framework_changelog:
Good luck!


text:
Q: How to eliminate references when switching activities? [Android] I have been really trying to figure out how to use memory management in my program. Another post said System.gc() is a bad practice, and it also doesn't seem to really do too much for me anyway.
Main question: after reading tons on memory management, I am constantly stumbling across "eliminate references" (because they cause memory leaks). What does that mean? How do I eliminate references to things? Also I use SharedPreferences to store variables between activities so would that contribute to memory leaks?

A: I usually create a method reset where I empty all the values created, this way you clean all the data that has been stored!Inside this method you just call to every variable you think occupies space and empty them.


text:
Q: Quais as diferenças entre TreeSet, HashSet e LinkedHashSet? A ideia do Set é não permitir elementos repetidos, no java existem três implementações TreeSet, HashSet e LinkedHashSet encontrei algumas diferenças nessa resposta, gostaria de saber detalhamente se existem outras e em qual caso/cenário cada coleção se destaca.

A: O que muda são as estruturas internas. Algumas dão mais garantias que outras.
Não vou entrar em detalhes do que é um Set, não parece ser o propósito da questão.
TreeSet
Só se aplica a elementos com ordenação absoluta. Se eles não forem comparáveis (Comparable), você pode ensinar com um comparador (Comparator).
Por baixo dos panos, usa uma árvore de busca balanceada (acho que árvore binária, a rubro-negra, mas não lembro da fonte dessa informação nem se os detalhes internos já mudaram).
Como é uma árvore balanceada, todas as operações são feitas em O(lg(n)). Tem garantias de que você vai iterar diferente da ordem em que os elementos foram inseridos.
HashSet
Por baixo, usa uma tabela de espalhamento que aponta para uma lista ligada de nós. Quando há colisão, insere-se no início da lista ligada.
Só aplicável para objetos que tenham função de hash. Em Java, todos os objetos tem essa função (Object.hashCode()), então todos são candidatos para essa coleção =D

Se você desejar usar um número de espalhamento próprio, como se fosse fornecido um IntFunction<T> para gerar o número, então você precisa criar sua própria coleção ou fazer um HashSet<MyHashWrapper<T>>, onde MyHashWrapper<T> seria um envólucro que contenha um objeto T e uma função de hash própria.

No mundo ideal, operações em O(1), mas pode degradar para O(n).
Não há garantia de ordem de iteração.
LinkedHashSet
Idem ao HashSet, porém os nós da lista ligada da colisão tem uma ligação extra. Essa ligação garante que seja possível iterar na ordem de inserção. Daí, você tem a garantia que itera na mesma ordem da inserção.
Quando usar cada um?
De maneira geral, o HashSet você usaria por preguiça. Performance razoavelmente boa na maioria dos casos. Dificilmente necessita-se acessar na mesma ordem da inserção.
O LinkedHashSet custo dois centavos de memória extra e um de processamento, deve ser usado para extrair em ordem de inserção.
Já o TreeMap teria duas possíveis utilizações:

*

*evitar a degradação do hash

*iterar sempre na ordem crescente

Caso a sua aplicação precise percorrer muitas e muitas vezes esses valores na ordem crescente, então pode fazer sentido usar o TreeMap para este fim. Caso não precise fazer essa iteração constantemente, mas apenas de vez em quando, transformar do Set para uma List e ordenar não será um grande overhead. Daí a preguiça fala mais alto e eu usaria HashSet =)


text:
Q: Grails Json Views "model" key conflicts with model keyword I am using the rest-api profile for a Grails app and have the following in one of my json views (_event.gson):
model {
    Event event
}

json g.render(event, [excludes: ['product']]) {
    product {
        id event.product.id
        name event.product.name
        model event.product.model
    }
}

In short, a Product belongs to an Event. By default, I would get the product key with an id inside it as json. I wanted to add more fields to that.
So I used excludes so I could define the fields that would appear under the embedded json document detailing the product. My goal is to have the following as json:
{
  "id": 123,
  ...,
  "product": {
    "id": 545434,
    "name": "Something Cool",
    "model": "MZX 1234"
  }
}

The last fields -- model -- is not appearing. It seems it is being confused with the model keyword that is used in the very first line of my _event.gson file. Is there any way around this? I tried adding quotes to "model" but it still does not work.

A: The issue has been reported as a bug: http://github.com/grails/grails-views/issues/45


text:
Q: E - Commerce open source review Do you know a good review of the existing e-commerce open source platforms? I'll like it to be written in PHP in order to understand them faster and to contribute back.
many thanks

A: Magento Shopping Cart- they are using Zend Framework.
Magento is replacing other open source cart, and becoming the best, in terms of functionality and interface.

A: Have a look at Zen Cart or osCommerce. Both are widley supported and have a large community base.


text:
Q: java grouping regex fail to match string+text I wrote this test
@Test
public void removeRequestTextFromRouteError() throws Exception {
    String input = "Failed to handle request regression_4828 HISTORIC_TIME from=s:33901510 tn:27825741 bd:false st:Winifred~Dr to=s:-1 d:false f:-1.0 x:-73.92752 y:40.696857 r:-1.0 cd:-1.0 fn:-1 tn:-1 bd:true 1 null false null on subject RoutingRequest";
    final String answer = stringUtils.removeRequestTextFromError(input);
    String expected = "Failed to handle request _ on subject RoutingRequest";
    assertThat(answer, equalTo(expected));
}

which runs this method, but fails
public String removeRequestTextFromError(String answer) {
    answer = answer.replaceAll("regression_\\d\\[.*?\\] on subject", "_ on subject");
    return answer;

}

The input text stays the same and not replaced with "_"
how can I change the pattern matching to fix this?

A: You are using the a wrong regex. You are escaping [ and ] (not necessary at all) and using \\d instead of \\d+. Also, you should use a positive look-ahead instead of actually selecting and replacing the String "on subject"
Use :
public static void main(String[] args) {
    String input = "Failed to handle request regression_4828 HISTORIC_TIME from=s:33901510 tn:27825741 bd:false st:Winifred~Dr to=s:-1 d:false f:-1.0 x:-73.92752 y:40.696857 r:-1.0 cd:-1.0 fn:-1 tn:-1 bd:true 1 null false null on subject RoutingRequest";
    final String answer = input.replaceAll("regression_.* (?=on subject)", "_ ");
    System.out.println(answer);
    String expected = "Failed to handle request _ on subject RoutingRequest";
    System.out.println(answer.equals(expected));
}

O/P :
Failed to handle request _ on subject RoutingRequest
true

A: As an alternative to the answer given by @TheLostMind, you can try breaking your input into 3 pieces, the second piece being what you want to match and then remove.
Each quantity in parentheses, if matched, will be available as a capture group.  Here is the regex with the capture groups labelled:
(.*)(regression_\\d+.* on subject)(.*)
 $1             $2                 $3

You want to retain $1 and $3:
public String removeRequestTextFromError(String answer) {
    answer = answer.replaceAll("(.*)(regression_\\d+.* on subject)(.*)", "$1$3");
}


text:
Q: Need help with the position of a particle in a velocity-versus-time graph I am having trouble with a velocity-versus-time graph. I recently took a Physics test that asked this question: The graph shows the velocity versus time for a particle moving along the $x$ axis. The $x$ position of the particle at $t$=0 seconds was 8 meters. What was the $x$ position of the particle at $t$=2 seconds What was the $x$ position of the particle at $t$=4 seconds?

So, in order to solve this problem, I used the position equation: $x(t)=x_o + v_ot + \frac{1}{2}at^2$. Starting with the first position, I plugged 2 seconds into $t$, the time; 8 meters into $x_o$, the initial position; 20 meters per second into $v_o$, the initial velocity; and -10 meters per second squared into $a$, the acceleration. I derived the acceleration from the graph using $\frac{\Delta v}{\Delta t}$.
$a = \frac{\Delta v}{\Delta t} = \frac{-20}{2} = -10$
The position equation, with everything in place, reads:
$x(2)=8 + 20(2) + \frac{1}{2}(-10)(2^2)$
This math works out to 28 meters, which is the answer I gave on the test. I did the same thing for the second part of the question--the position of the particle at 4 seconds, as well as the acceleration based on the change in velocity and the change in time.
$a = \frac{\Delta v}{\Delta t} = \frac{-35}{4} = -8.75$
The equation comes out to this:
$x(4)=8+20(4)+\frac{1}{2}(-8.75)(4^2)$
The math comes out to 18 meters. However, according to the curriculum I used, the answer to the first part is 38 meters and the answer to the second part is 16 meters. How can this be the case? Did I fail to apply the position equation correctly? Did I make a mistake when computing the acceleration of the particle? I can't figure out what I did wrong. Is it possible that I used the wrong equation?
I really have no idea. I would appreciate any insight you might have to offer. Thank you in advance for you consideration.

A: I'm not sure why you are using the displacement-time formula if you have the shape of the graph.
The distance covered by the particle is given by the area under the graph from point 0.
After t = 2s, the distance the particle would have covered is the area under the trapezium, that is: $$\dfrac12 (1+2)(20) = 30$$
The position of the particle becomes $8 m + 30m = 38m$.
Maybe you can work out the second part now.
Explanation:
Your formula assumes constant acceleration, which is not the case! For the first 1 s, the acceleration is $0ms^{-2}$, the next 1s, the acceleration is $-20 ms^{-2}$! If you used your formula for $0<t<1$ and then $1<t<2$, then you would have obtained the desired answer. But it's just making the problem more complicated than it actually is at that point :)


text:
Q: Рефлексия получение заранее заданных методов Господа, подскажите, пожалуйста, по коду.
using System;
using System.Reflection;
class a
{
    public void K(int x)
    {
        Console.WriteLine(x);
    }
    public int K(int x, int y)
    {
        return x + y;
    }
    public void V(string s)
    {
        Console.WriteLine(s);
    }
}
class b
{
    static void Main()
    {
        MethodInfo[] Mi = typeof(a).GetMethods(BindingFlags.DeclaredOnly);
        foreach (MethodInfo m in Mi)
        {
            ParameterInfo[] Pi = m.GetParameters();
            if (Pi.Length == 1 && Pi[0].ParameterType.Name == typeof(int).Name)
            {
                object[] o = new object[1] { 4 };
                m.Invoke(new a(), o);
            }
            if (Pi.Length == 2 && Pi[1].ParameterType.Name == typeof(int).Name)
            {
                object[] o = new object[2] { 7, 19 };
                m.Invoke(new a(), o);
            }
            if (Pi[0].ParameterType.Name == typeof(string).Name)
            {
                object[] o = new object[1] { "Colbasa" };
                m.Invoke(new a(), o);
            }
        }
    }
}

Почему typeof(a).GetMethods(BindingFlags.DeclaredOnly); возвращает пустое значение?
Но при этом если typeof(a).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);, тогда все ок. Ведь, как мне кажется, наоборот, первый вариант более общий.
Спасибо.
A: Чтобы получить просто все методы класса, нужно использовать GetMethods() (без параметров).
В случае с методом GetMethods(BindingFlags) нужно указывать также и флаги, определяющие дополнительные параметры методов. В частности, хотите ли вы получить методы экземпляра (BindingFlags.Instance) или статические (BindingFlags.Static)


text:
Q: q-exponential functions We know that
$$e_q(z)=\sum_{j\geq 0} \frac{z^j}{(q;q)_j}=\frac{1}{(z;q)_{\infty}}$$
where $(a;q)_{\infty}=\prod_{i=0}^{\infty}(1−aq^i)$ denotes the q-shifted factorial.
The limit between the $q$-exponential and the ordinary exponential is
$$\lim_{q\rightarrow1}e_q((1-q)z)=\lim_{q\rightarrow1}\frac{1}{((1-q)z;q)_{\infty}}=e^z.$$
My question is how to prove
$$\lim_{q\rightarrow1}\frac{1}{((1-q)\sqrt{1-q^2}x;q)_{\infty}}=e^{\sqrt{2}x}?$$
I'm glad for your help.

A: We know that $(q;q)_n=(1-q)^n[n]_q!\;$ and $\lim_{q\to1} [n]_q!=n!.\quad$ Therefore $$e_q((1-q)(1+q)x) = \sum_{n=0}^\infty \frac{(1-q)^n(1+q)^nx^n}{(q;q)_n}=\sum_{n=0}^\infty \frac{(1+q)^n x^n}{[n]_q!}.$$
The limit as $q\to1$ gives $e^{2x}$ which is justified because of absolute convergence.


text:
Q: Interpretation of Feynman propagator for massive scalar field in position space I've always treated propagator in the momentum representation so when it diverges, we are on-shell. But what is the interpretation of light-cone divergences in position space? If it is something we have to renormalize, how can I do it? More precisely, if I have to renormalize light-cone divergences of the following Feynman propagator:
\begin{equation*}
G(s)=\frac{m}{8\pi s} H^{(1)}_1(m s)\,\,,\,\,s^2=(x^0-y^0)^2-|\vec{x}-\vec{y}|^2
\end{equation*}
(where $H^{(1)}_1$ is a Hankel function of the first type) how should I proceed? Is there a method like dimensional regularization for this problem?

A: There is no need to renormalize here.
The interpretation is that a quantum field is not an operator-valued function $\hat{\phi}(x)$, but an operator-valued distribution, aka generalized function. That means that $\hat{\phi}$ is a linear functional from test functions on space-time (e.g. you can choose functions with compact support to get temporal distributions).
Intuitively,
$$
\hat{\phi}(f) = \int d^4 x f(x) \hat{\phi}(x).
$$
But this formula is only formal, because $\hat{\phi}(x)$ doesn't mathematically exist.
For any two test functions $f_{1,2}$, the quantity
$$
\left< \hat{\phi}(f_1) \hat{\phi}(f_2) \right> = \int d^4 x f_1(x) \int d^4 y f_2(y) \cdot G(x - y)
$$
is finite and well defined, even when $G$ has a divergence on the light cone.