text:
Q: Rails & Postgres - Are queries with count columns really this complex? I have the following models in my app (only showing the related scopes):
class Audition < ActiveRecord::Base
  def self.with_new_applications
    columns = self.column_names.map{|c| "auditions.#{c}" }.join(', ')

    select(columns).joins(:applications).merge(Application.unreplied).group(columns)
  end
end

class Application < ActiveRecord::Base
  def self.unreplied
    columns = Application.column_names.map{|c| "applications.#{c}" }.join(', ')

    select("#{columns}, count(messages.id) as message_count").
      joins('left outer join messages on messages.application_id = applications.id').
      group(columns).
      having('count(messages.id) = 0')
  end
end

Due to using postgreSQL it seems like the queries have been made unnecessarily complex when compared to MySQL due to the need to include all the columns for the count columns/grouping.
Am I missing something? It doesn't seem very "Rails-like" to me.
Could these queries be executed in a simpler manner?
Thanks

A: Maybe you could approach the problem from a completely different angle by using the ActiveRecord :counter_cache ? e.g.
belongs_to :application, :counter_cache => true

You could maybe have a short, simple and performant query this way.


text:
Q: Is there a way to rewrite these URLs? Is there a way to get accessible all images in the folder:
www.example.com/image/

through URL like this:
static.example.com/image/

For instance, the image
www.example.com/image/hello.jpg

is accessible only through:
static.example.com/image/hello.jpg

A: Set up a virtual name host for static.example.com and Alias /image/ to the directory you want.
Then set up a <Location> section in the virtual host for www.example.com and Deny access to it.

A: Assuming you've already created the subdomain: static.example.com.
On www.example.com host, enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?\.example\.com$ [NC]
RewriteRule ^(image(?:/.*|))$ http://static.example.com/$1 [L,R=301,NC]

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can show 5 millons of data datatable in codeigniter I am new in php. I want to show 5 Millions of record from my database in php in codeignter. I am using select star sql query to select table. It's working good but takes long time in loading data into datatable.
Any help would be appreciated.
Thanks in Advance.
<?php
   include('layout/header.php');
   include('layout/sidebar.php');

   ?>

Data Tables

               <form action="<?= base_url(); ?>signin/sendemailstudent" method="post">

                           S.No
                           School
                           Date Of Admission
                           Register Serial
                           Student Name
                           Date Of Birth
                           Father Name
                           Phone
                           Email

                           Pincode
                           Class To Which Admitted
                           Class From Which Withdrawn
                           Date Of Withdrawl
                           Upload By
                           Notify<input type="checkbox" onclick="check();" id="select_all" name="select_all" />

                        <?php
                           $i = 1;
                           foreach ($data as  $value) {

                            ?>

                           <?php echo $i; ?>
                           <?php echo $value['school_name']; ?>
                           <?php echo $value['doa']; ?>
                           <?php echo $value['register_serial']; ?>
                           <a href='<?php echo base_url('signin/editstudent').'/'.$value['id']; ?>'><?php echo $value['name']; ?>
                           <?php echo $value['dob']; ?>
                           <?php echo $value['father_name']; ?>
                           <?php echo $value['phone']; ?>
                           <?php echo $value['email_address']; ?>

                        <?php
                           $i++;
                            } ?>

               </form>

<?php include('layout/footer.php'); ?>

A: As someone already mentioned:

*

*paginate

*filter

*'using select star', dont use the star selector if you wont use all the fields.

*codeignitter is using Active Record, something that uses DataMapper could be faster, not sure if you can change that though, most probably you can (havent use codeignitter). or using pure php pdo to deal with db.

*have a look on how to use generators, they're much faster for processing big sets as they dont load everything in memory at once (that's what foreach would do)

*not sure which version of php you're running, but if you're working on php <5.6 then you should definitely upgrade as new versions use much less memory/cpu for dealing with db.

*install sql profiler to check if your queries are optimal.


text:
Q: kubernetes: a service is not accessible outside host I am following the guide at http://kubernetes.io/docs/getting-started-guides/ubuntu/ to create a kubernetes cluster. Once the cluster is up, i can create pods and services using kubectl. Basically, do the following
kubectl run nginx --image=nginx --port=80
kubectl expose deployment/nginx

I see a pod and service running
# kubectl get services
NAME         CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
kubernetes   192.168.3.1     <none>        443/TCP   2d
nginx        192.168.3.208   <none>        80/TCP    2d

When I try to access the service from the machine where the pod is running, I get back the nginx helloworld page. But if i try it another machine in the kubernetes cluster, i get a timeout.
I thought all the services are accessible anywhere in the cluster. Why could it not be working that way?
Thanks

A: Yes, services should be accessible anywhere in the cluster. Is your "another machine" listed in the output of kubectl get nodes? Is the node Ready? Maybe the machine wasn't configured correctly.

A: If you want to get the servicer anywherer in the cluster, You must use the network plug-in,such as Flannel,OpenVSwitch.
http://kubernetes.io/docs/admin/networking/#flannel
https://github.com/coreos/flannel#flannel

A: found out my error by comparing it with another installation where it worked. This installation was missing an iptables rule that forced everything going to the containers onto the flannel interface. So the traffic was reaching the target host on eth0 making it discard the packet. I donot know why the proxy didnt add that rule. Once i manually added it, it worked.


text:
Q: flutter - how to showDateRangePicker widget row view? [widget - showDateRangePicker]
https://api.flutter.dev/flutter/material/showDateRangePicker.html
calender view = column
i want dateRangePicker - calender row View
https://pub.dev/packages/syncfusion_flutter_datepicker
ㄴ do not use package

ex)


text:
Q: How to read command line argument while running py.test -sv B/ I have a file conftest.py in directory A. I have some test files in directory B which is in A. I run all of them using py.test -sv B/. However sometime I want to pass argument -val="Hello" and store in a file.
I am trying to do it as following:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("val",help="value")
args=parser.parse_args()
print(args.val)
a_file=open("file_val","w")
a_file.write(args.val)
a.file.close()
def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")

However it doesn't write anything and gives error: unrecognized arguments: -sv —val=hello, when I run  py.test -sv B/ —val=Hello
so I tried following :
import argparse

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")
    parser.add_argument("val",help="value")
    args=parser.parse_args()
    print(args.val)
    a_file=open("file_val","w")
    a_file.write(args.val)
    a.file.close()

But it gives error : No method add_argument when I run py.test -sv B/ —val=Hello

A: read command line argument while running pytest -sv B/
It should work for you:
First of all you need to pass the argument using addoption and fixture that will read the option.
For that you should create a separate file and name it conftest.py in your test folder.
The content of the  conftest.py file:
import pytest

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")

@pytest.fixture
def name(request):
    return request.config.getoption("--name")

Then you need to create a test function with an argument which named after the fixture in the separate file, or like in your case, even in a separate folder.
Content of B/test_write_file.py:
def test_write_file(name):
    print(name)
    a_file = open("file_val.txt", "w")
    a_file.write(name)
    a_file.close()
    assert 0 # or whatever you want

After that you can freely run your test from the test root folder:
pytest -sv B/ --name=Hello
Output:
________________ test_write_file _________________
name = 'Hello'

    def test_write_file(name):
        print(name)
        a_file = open("file_val.txt", "w")
        a_file.write(name)
        a_file.close()
>       assert 0
E       assert 0

B\test_write_file.py:8: AssertionError

You don't need to use argparse, pytest does everything for you.
The structure of the test folder:

Just like in this example:
https://docs.pytest.org/en/6.2.x/example/simple.html
Cheers!


text:
Q: Unable to restrict the Ti.App.fireEvent execute multiple time In my app Ti.App.addEventListener executed multiple times even fireEvent calls one time.
I was unable to remove the fireEvent.
How to remove the created fireEvent.
Here is my sample files:
selectUser.xml
Alloy>
    <NavigationWindow id="selectUserNav" platform="ios">
        <Window id="selectUserWin">
             <Label id="selectUserLabel"/>
             <Label id="userName"/>
        </Window>
    </NavigationWindow>
</Alloy>

selectUser.js
var selectedUser = '';
function  displaySelectedUser(){
    $.selectUserLabel.setText('Select the user');
    $.userName.setText(selectedUser);
}
displaySelectedUser();

$.selectUserWin.addEventListener('open', function() {
    var titleLabel = Ti.UI.createLabel({
        text : 'Select User',

    });
    $.selectUserWin.setTitleControl(titleLabel);
    var leftView = Ti.UI.createView({
    });
    var leftButton = Titanium.UI.createButton({
        backgroundImage : '/left_arrow.png'
    });
    leftView.add(leftButton);
    $.selectUserWin.setLeftNavButton(leftView);
    var rightView = Ti.UI.createView({
    });
    var rightButton = Titanium.UI.createButton({
        backgroundImage : '/right_arrow.png'
    });
    rightView.add(rightButton);
    $.selectUserWin.setRightNavButton(rightView);

    leftButton.addEventListener('click', function(e) {
        $.selectUserNav.close();
    });
    rightButton.addEventListener('click', function(e) {

            Alloy.createController('usersList').getView().open();
    });
});

Ti.App.addEventListener('username', function(data) {

    Ti.API.info('### selectedUser: '+ data.selectedUserName);
    selectedUser = data.selectedUserName;
    displaySelectedUser();

});

usersList.xml
Alloy>
    <NavigationWindow id="usersListNav" platform="ios">
        <Window id="usersListWin">
            <TableView id="usersDispTable"></TableView>
        </Window>
    </NavigationWindow>
</Alloy>

usersList.js
 var usersTableData = [];
    function userList(){
        for ( i = 0; i < 5; i++) {

                var titleLabel1 = Titanium.UI.createLabel({
                    text :  'srinivas',
                });
                var userListRow = Ti.UI.createTableViewRow({
                        userName : 'srinivas',
                        height : '40',
                });
                userListRow.add(titleLabel1);
                usersTableData.push(userListRow);

                userListRow.addEventListener('click', function(e) {
                    var selectedArgs = {
                        selectedUserName : e.rowData.userName
                    };
                     Ti.App.fireEvent('username', selectedArgs);
                     $.usersListNav.close();
                });

        }
$.usersDispTable.setData(usersTableData);

    }
    userList();
    $.usersListWin.addEventListener('open', function() {
        var titleLabel = Ti.UI.createLabel({
            text : 'Users List',

        });
        $.usersListWin.setTitleControl(titleLabel);
        var leftView = Ti.UI.createView({
        });
        var leftButton = Titanium.UI.createButton({
            backgroundImage : '/left_arrow.png'
        });
        leftView.add(leftButton);
        $.usersListWin.setLeftNavButton(leftView);

        leftButton.addEventListener('click', function(e) {
            $.usersListNav.close();
        });

    });

A: sorry but I will answer your question indirectly, because what you are trying to do isn't efficient.
What you need to do is to listen your TableView not your TableViewRow like example below:
$.usersDispTable.addEventListener('click',function(e){
    Ti.App.fireEvent('username', e.rowData.username);
}

By the way, if you need to remove an EventLister you can do like this:
window.addEventListener('click', function foo(e) {
    window.removeEventListener('click', foo);
    [...]
}

--Edited (Answer comment)
That is because you are creating a Global EventListener Ti.App.addEventListener every time selectUser is called.
One possible option is to bind the event listener to userList creation like:
[...]
var userList = Alloy.createController('usersList').getView();
userList.addEventListener('username',function setUsername(username){
    userList.removeEventListener('username',setUsername);
    Ti.API.info('### selectedUser: '+ data.selectedUserName);
    selectedUser = data.selectedUserName;
    displaySelectedUser();
});
userList.open();
[...]


text:
Q: Vanishing partial derivatives implies that map is constant Let $m,n \in \mathbb{N}$, $r>0$, and $a \in \mathbb R^n$. Suppose $f: B_r(a)\rightarrow \mathbb{R}^m$ is $C^1$ on $B_r(a)$ with $f_{x_j}(x)=0$ for every $j=1,\ldots, n$ and every $x \in B_r(a)$.
I want to show that $f(x)=f(a)$ for every $x \in B_r(a)$.
When $m=1$, I am able to prove this by using the mean value theorem for partial derivatives.
But I don't know how to generalize to $\mathbb R^m$. Can I use the fact that it holds for $m=1$? If so, how? If not, what argument would work?

A: Let $f=(f_1,...,f_m)$. Thus each $f_j$ is real-valued !
You have shown that $f_j(x)=f_j(a)$ for every $x \in B_r(a)$ and $j=1,...,m$
It follws that  $f(x)=f(a)$ for every $x \in B_r(a)$.


text:
Q: Create partition is using timestamp with local time zone [Oracle 11g] I try to find one solution for my problem when create a partition in oracle database 11g. I think partition can't be created on datatype "TIMESTAMP WITH LOCAL TIME ZONE", Is it true?
I find the tread below that talk about this subject:
https://community.oracle.com/message/9515330
Anyone know the solution for this problem?
Code Example:
CREATE TABLE "XPTO"
(
  "XPTO_DATE" TIMESTAMP (6) WITH LOCAL TIME ZONE
)
STORAGE(BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "TABLES"
PARTITION BY RANGE ("XPTO_DATE") INTERVAL (NUMTOYMINTERVAL(1,'MONTH'))
(
  PARTITION "P1" VALUES LESS THAN (TIMESTAMP' 2013-01-01 00:00:00')
  SEGMENT CREATION DEFERRED
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
  NOCOMPRESS LOGGING
  TABLESPACE "TABLES"
 )

SQL Error: ORA-14020 - "this physical attribute may not be specified for a table partition"...

A: You can't interval partition on a column of that type. You could potentially add a virtual column that has the UTC equivalent of you local time zone timestamp, and partition on that instead:
CREATE TABLE "XPTO"
(
  "XPTO_DATE" TIMESTAMP (6) WITH LOCAL TIME ZONE,
  "XPTO_GMT" TIMESTAMP (6) GENERATED ALWAYS AS (SYS_EXTRACT_UTC("XPTO_DATE"))
)
STORAGE(BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "TABLES"
PARTITION BY RANGE ("XPTO_GMT") INTERVAL (NUMTOYMINTERVAL(1,'MONTH'))
(
  PARTITION "P1" VALUES LESS THAN (TIMESTAMP '2013-01-01 00:00:00 UTC')
  SEGMENT CREATION DEFERRED
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
  NOCOMPRESS LOGGING
  TABLESPACE "TABLES"
 );

table "XPTO" created.

The partitions will be roughly the same size but the boundaries will be a bit different, but that may or not matter - I guess it would be a problem for partition swaps but not sure if it would have any other noticeable effect for you.


text:
Q: Replacing second column using shell script I want to change the second column to upper case and I want to do it in shell script only. (no one liners!)
#!/bin/sh
# read file line by line
file="/pdump/country.000000.txt"
while read line
do
mycol=`echo $line | awk -F"," '{print $2}'`
mycol_new=`echo $mycol | tr "[:lower:]" [:upper:]`
echo $line | awk -F"," '{print $1 "," $mycol_new "," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'
done < $file

I am not able to replace the $2 with $mycol_new.
Any suggestion?

A: awk cannot see $mycol_new because it is a shell variable. Here is one way of passing a shell variable into awk using the -v flag:
echo $line | awk -v var="$mycol_new" -F"," '{print $1 "," var "," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'

Here is an alternative method which lets the shell expand $mycol_new:
echo $line | awk -F"," '{print $1 ",'"$mycol_new"'," $3 "," $4 "," $5 "," $6 "," $7 "," $8}'

A: why no one liners? Doing homework?
$ cat file
one two three four
five six seven eight

$ awk '{$2=toupper($2)}1' file
one TWO three four
five SIX seven eight

A: If you want to do this all in the shell, then you don't need awk:
IFS=,
while read line; do
  set -- $line
  a="$1"
  b="${2^^}"  # assumes bash, use "tr" otherwise
  shift 2
  set -- "$a" "$b" "$@"
  echo "$*"
done < "$file" > "$file.new"


text:
Q: Is there a way to block ALL inbound/outbound traffic going outside of a LAN with iptables? As the title says, I'm just looking for a way to disallow any traffic on ANY port unless it's going to a local IP address (192.168.1.*).

A: Yes with this :
iptables -P INPUT  DROP
iptables -P OUTPUT DROP
iptables -A INPUT  -s 192.168.1.0/24 -j ACCEPT
iptables -A OUTPUT -d 192.168.1.0/24 -j ACCEPT

A: you can use something like this:
iptables -A INPUT -i eth0 -p tcp ! -s 192.168.1.0/24 -d 192.168.1.0/24 -j DROP

and
iptables -A OUTPUT -o eth0 -p tcp ! -d 192.168.1.0/24 -j DROP

the first rule block the ip address with coming from other sources and the second rules block the access to destination outside 192.168.1.0/24


text:
Q: Untranslated address in PCIe I was going through the ATS feature which has been added in PCIe. I came across terms like Untranslated address and Physical address. Essentially the Translation agent on the host will convert Untranslated address received from the device to the Host's Physical address.
But my query is that the host-driver always gives the Physical address to the device, so who really provides this Untranslated address(Virtual address) to the device?
Eg: In case of "nvme", the nvme driver while preparing the PRP for a command, takes the physical address(and not Virtual address) from the host memory and submits the command in the Submission Queue.
So who really sends Virtual address to the device?

A: ATS can be used for direct device assignment, assigning a hardware device to a virtual machine. In that case, the VM drivers can use guest-physical addresses as untranslated addresses, and the platform IOMMU translates them into host physical addresses, selecting the translation table based on the device's requestor ID.
With the PCIe PASID extension, untranslated addresses can also include a process address space ID (PASID). The IOMMU can take this ID into account when selecting the translation table. For example, this can be used to assign a device to process and have the process use IO virtual addresses with the device.


text:
Q: Sending email and Attachmement with adobe flash and action script 3.0 i try to use some source code for sending email with adobe flash and action script 3.0 that i got from internet.. here i want to send email with an attachment..but it still using adobe air as player.. and now i want to use it flash player 10.. so i can't use flash.filesystem that provided by air library.. and know how to change it if i use flashplayer 10 as player...and how my code become??? any body could help????
import org.bytearray.smtp.mailer.SMTPMailer;
import org.bytearray.smtp.encoding.JPEGEncoder;
import org.bytearray.smtp.encoding.PNGEnc;
import org.bytearray.smtp.events.SMTPEvent;
import flash.utils.ByteArray;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.*;

/* For air library*/
import flash.filesystem.FileStream;
import flash.filesystem.File;

// create the socket connection to any SMTP socket
// use your ISP SMTP

var myMailer:SMTPMailer = new SMTPMailer ("smtp.mail.yahoo.com", 25);
var fileRef:FileReference;

// register events
// event dispatched when mail is successfully sent
myMailer.addEventListener(SMTPEvent.MAIL_SENT, onMailSent);
// event dispatched when mail could not be sent
myMailer.addEventListener(SMTPEvent.MAIL_ERROR, onMailError);
// event dispatched when SMTPMailer successfully connected to the SMTP server
myMailer.addEventListener(SMTPEvent.CONNECTED, onConnected);
// event dispatched when SMTP server disconnected the client for different reasons
myMailer.addEventListener(SMTPEvent.DISCONNECTED, onDisconnected);
// event dispatched when the client has authenticated successfully
myMailer.addEventListener(SMTPEvent.AUTHENTICATED, onAuthSuccess);
// event dispatched when the client could not authenticate
myMailer.addEventListener(SMTPEvent.BAD_SEQUENCE, onAuthFailed);

// take the snapshot
send_btn.addEventListener (MouseEvent.CLICK, onClick);

function onClick ( pEvt:MouseEvent )

{
/*How to change this attachment by using adobe flash player library code and action script 3.0, not adobe air player library ?????? */

/* change from here........... ..........*/
 var attachmentFile:File=File.documentsDirectory;
 attachmentFile = attachmentFile.resolvePath("file/Questions.xml");
 var stream:FileStream = new FileStream();*/
 var myCapStream:ByteArray = myEncoder.encode ( fileRef );
 stream.open(attachmentFile,FileMode.READ);
 stream.readBytes(myCapStream,0,stream.bytesAvailable);
 stream.close();

/* until here.......................... */
myMailer.authenticate("x@yahoo.com","xxxx");
     myMailer.sendAttachedMail ( "x@yahoo.com", "y@gmail.com", "test", "test body", myCapStream, );
}

function onAuthFailed ( pEvt:SMTPEvent ):void

{

 status_txt.htmlText = "Authentication Error";

}

function onAuthSuccess ( pEvt:SMTPEvent ):void

{

 status_txt.htmlText = "Authentication OK !";

}

function onConnected ( pEvt:SMTPEvent ):void

{

 status_txt.htmlText = "Connected : \n\n" + pEvt.result.message;
 status_txt.htmlText += "Code : \n\n" + pEvt.result.code;

}

function onMailSent ( pEvt:SMTPEvent )

{

 // when data available, read it
 status_txt.htmlText = "Mail sent :\n\n" + pEvt.result.message;
 status_txt.htmlText += "Code : \n\n" + pEvt.result.code;

}

function onMailError ( pEvt:SMTPEvent ):void

{

 status_txt.htmlText = "Notification :\n\n" + pEvt.result.message;
 status_txt.htmlText += "Code : \n\n" + pEvt.result.code;

}

function onDisconnected ( pEvt:SMTPEvent ):void

{

 status_txt.htmlText = "User disconnected :\n\n" + pEvt.result.message;
 status_txt.htmlText += "Code : \n\n" + pEvt.result.code;

}

A: Browser flash application cannot read file from disk (silently) and use network to send email. You have to load file with FileReference, get ByteArray from it (not entirely sure if that is possible, try to experiment) and feed into myCapStream.


text:
Q: How to augment methods during ByteBuddy transformation? Context
I am implementing byte code transformations with ByteBuddy and the process of manipulation is a multi step process.
Because of that, the manipulation has to be able to:

*

*augment originally existing methods

*create new methods entirely

*augment a method that was introduced via 2.

For 1. I used an @OnMethodExit advice applied via:
Builder<?> builder = builder.visit(Advice.to(Helper.class)
  .on(ElementMatchers.hasMethodNamed(name));

with Helper the augmentation code for the method (effectively setting a field's value).
When creating new methods, I build them as follows:
Builder<?> builder = builder.defineMethod(…)
  .intercept(MethodDelegation.to(OtherHelper.class));
  .…;

OtherHelper consumes the runtime instance via a static method taking @This Object object as argument.
The problem
In short: I don't see the former transformation applied if it follows the latter.
The actual execution order is as follows:

*

*My type gets processed and a method added via MethodDelegation.….

*In a subsequent step I find that newly introduced method and try to augment the implementation generation through Advice.to(…) using an @OnMethodExit advice.

*The resulting code has the behavior of step 1 but is lacking the behavior of step 2.

I am assuming I invalidly combine the two parts of the implementation. Any ideas? A hunch: does the ElementMatcher matching the augmentation by name not see the method introduced using ….defineMethod(…) yet? The name is coming from some method inspection I start from builder.toTypeDescription() which actually makes me assume that the to-be-created method is already visible to the builder as otherwise it wouldn't be found in that step in the first place.

A: Can you share a reconstruction of your example? In a simple example, I observe the expected behavior:
public class Bar {
  public static void main(String[] args) throws Exception {
    Class<?> type = new ByteBuddy().subclass(Object.class)
      .visit(Advice.to(Bar.class).on(named("m")))
      .defineMethod("m", void.class, Visibility.PUBLIC)
      .intercept(MethodDelegation.to(Bar.class))
      .make()
      .load(Bar.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
      .getLoaded();

    type.getMethod("m").invoke(type.getConstructor().newInstance());
  }

  @BindingPriority(2)
  public static void delegation() {
    System.out.println("Delegation!");
  }

  @Advice.OnMethodEnter
  public static void enter() {
    System.out.println("Advice!");
  }
}

This example prints both Advice! and Delegation!.


text:
Q: Salesforce Document Unique Name Issue We are facing an issue with "Salesforce Document" while uploading a document in "My Personal Document".
After uploading a "Test Document" if we delete it, we are not able to upload a "Test Document" with the same name as deleted file. It shows below error message :
"This Document Unique Name already exists or has been previously used. Please choose a different name."
We deleted that document from recycle bin as well.
Is it the behavior of Salesforce Document or a bug?
Thanks and Regards,
Ashish Shukla

A: Yes, it's standard behavior. Records in recycle bin are a result of a soft delete, thus they tend to keep intact the api names or unique names with them until they are hard deleted or deleted from recycle bin.
Also, you may want to vote this Idea up:
Allow re-use of Report Unique Name


text:
Q: How to enforce Xticks order not changed I am drawing a graph on realestate builder data. There are couple of builders who is selling different types of apartment for different price. I wanted to plot the data as apartment type is X-axis, apartment price is y-axis. There is no guaranty that every builder builds same kind of apartments, you can see the data below. When i plot below data, it's not coming the order by ApartmentType, because all builders are not offering all kinds of apartments. The expected output i am looking for is, X-axis should be intact even the Builder is not building all apartments.
Below is the sample data.
Builder,UnitType,Area,Price,AvgPriceInLakhs,UnitSizeInBhk
SJR Palazza City,Apartment,702 sq.ft,47 L,4700000.0,0.5
SJR Palazza City,Apartment,702 sq.ft,35 L -48.50 L,4175000.0,1
SJR Palazza City,Apartment,1242-1308 sq.ft,62.10 L -87.50 L,7480000.0,2
SJR Palazza City,Apartment,1550-1813 sq.ft,66.71 L -1.17 Cr,9185500.0,3
SJR Palazza City,Apartment,1657 sq.ft,84.50 L,8450000.0,3.5
SJR Palazza City,Apartment,1813 sq.ft,1.70 Cr,17000000.0,4
Century Ethos,Apartment,510 sq.ft,25.44 L,2544000.0,0.5
Century Ethos,Apartment,693 sq.ft,30 L -61.06 L,4553000.0,1
Century Ethos,Apartment,895 sq.ft,61.06 L,6106000.0,1.5
Century Ethos,Apartment,1040-1245 sq.ft,40 L -83.60 L,6180000.0,2
Century Ethos,Apartment,1437 sq.ft,76.03 L,7603000.0,2.5
Century Ethos,Apartment,1732-2157 sq.ft,66.86 L -1.25 Cr,9593000.0,3
Century Ethos,Apartment,2200 sq.ft,1.10 Cr,11000000.0,4
Prestige Lake Ridge,Apartment,661 sq.ft,36 L,3600000.0,0.5
Prestige Lake Ridge,Apartment,661 sq.ft,38 L -38.90 L,3845000.0,1
Prestige Lake Ridge,Apartment,1137-1159 sq.ft,56.85 L -73 L,6492500.0,2
Prestige Lake Ridge,Apartment,1345-1367 sq.ft,75 L -76.22 L,7561000.0,2.5
Prestige Lake Ridge,Apartment,1571 sq.ft,63.70 L -1.09 Cr,8635000.0,3
Prestige Lake Ridge,Apartment,1745-1750 sq.ft,96.07 L -96.35 L,9621000.0,3.5
Salarpuria Sattva Aspire,Apartment,613 sq.ft,60 L,6000000.0,1
Salarpuria Sattva Aspire,Apartment,1388-1799 sq.ft,84.28 L -1.20 Cr,10214000.0,2
Salarpuria Sattva Aspire,Apartment,1459-1622 sq.ft,98 L -1.10 Cr,10400000.0,2.5
Salarpuria Sattva Aspire,Apartment,1933-2762 sq.ft,98 L -1.93 Cr,14550000.0,3
Salarpuria Sattva Aspire,Apartment,2949-2956 sq.ft,2 Cr -2.20 Cr,21000000.0,4
Salarpuria Sattva Aspire,Apartment,6290 sq.ft,4.08 Cr -4.35 Cr,42150000.0,4+
Salarpuria Sattva Aspire,Apartment,6290-6314 sq.ft,4.08 Cr -4.35 Cr,42150000.0,5
Global Golden Pearl,Apartment,250 sq.ft,25.44 L,2544000.0,0.5
Global Golden Pearl,Apartment,620-636 sq.ft,30.42 L -48 L,3921000.0,1
Global Golden Pearl,Apartment,895 sq.ft,40 L -85 L,6250000.0,2
Global Golden Pearl,Apartment,1180-1257 sq.ft,59 L -62.85 L,6092500.0,2.5
Global Golden Pearl,Apartment,1509-1629 sq.ft,72.35 L -1.75 Cr,12367500.0,3
Global Golden Pearl,Apartment,1655 sq.ft,82.75 L,8275000.0,3.5
Global Golden Pearl,Apartment,1917 sq.ft,1.27 Cr -2.60 Cr,19350000.0,4

plt.subplots(figsize=(20,8))
g = sns.lineplot(x='UnitSizeInBhk',y='AvgPriceInLakhs',data=top5buildersdatadf,hue='Builder')
g.set_title('Top 5 Builders Data')
g.set(xlabel='Car Model Year',ylabel='Average MPG')
plt.show()

FYI this is the original graph

A: When there is always just one datapoint per builder and apartment size all you need to do is sort according to the apartment size.
import numpy as np
import matplotlib.pyplot as plt

# Unsorted dummy data
n = 10
x1 = np.arange(n)
np.random.shuffle(x1)
y1 = np.random.random(n)

# Sort the x values from small to large
i = np.argsort(x1)
x2 = x1[i]
y2 = y1[i]

fig, ax = plt.subplots(1, 2)
ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

#                Unsorted                                     Sorted

I would remove the data points where the size is 4+ (in your example the value is the same as for 5) as this prevents you from using numerical values. With numerical values the ordering is clear and should give the expected result:
# df = top5buildersdatadf
df.drop(df[df['UnitSizeInBhk'] == '4+'].index, axis=0, inplace=True)
df['UnitSizeInBhk'] = pd.to_numeric(df['UnitSizeInBhk'])

# do plotting


text:
Q: mv : get info from files to be overwritten Is there any "super" mv command out there which displays files info (size, date, etc.) when a destination file is to be overwritten with a source one ? This is, when  moving files around and two files happen to have the same name.
When this happens I need first to cancel the 'mv' command, 'ls' the destination folder, have a look at the file size, timestamp, etc., then compare it to the source one to see which one I want to keep, then resume the mv operation if I want to overwrite, otherwise just 'rm' the source one.
It would be great to get a similar behaviour as when this happens under a X session or Windows, so a decision can be taken without canceling the ongoing command.

A: Use a very simple script wrapper, called for instance smv (for "super-move").
The script accepts exactly 2 arguments, the way the cmd mv would.  Make sure that it is executable, e.g. with chmod 751 smv, and ensure that the path corresponding to its location is in yr PATH variable.
#!/usr/bin/bash

if ! [ $# -eq 2 ]; then
    printf "%s\n" "Usage: Include exactly 2 fully qualified file names as arguments, as in:" \
    "   $ smv /path/to/source /path/to/destination" "Abort."
elif [ -e "$2" ]; then
    (printf "\n%s\n\n" "Destination file exists."  && /usr/bin/stat "$2" ) 2>&1
    printf "\n"
    read -p "Clobber it ? (Y/n):  " answer
    case "$answer" in
        N|n) echo "$1 not moved; $2 preserved. Abort.";  exit(11) ;;
        Y|y) \mv -f "$1" "$2" ;;
    esac
else
    printf "\n%s\n" "Destination file does not exist."
    \mv -i "$1" "$2"
    printf "%s\n"  "$1 was moved to $2."
fi

HTH

A: The -i or --interactive option to mv makes it prompt before overwriting. You can then easily copy the filename to another terminal and look at its metadata there.


text:
Q: How to check if a message contains an emoji in Discord.py? I've created a bot that allows to create only-emojis text channels.
Now, I have the code, but how can I check if the message sent by the user contains any type of emoji (not customs)?
Thanks in advance


text:
Q: Envoy extension with Lua VS with WASM We are expecting to develop api gateway on base of Istio envoy extension feature.
Per the community information, there are 3 options, as below:

ExtensionOption
Step
configurableplug-in
Dynamicextension
Performance
Language
DevelopComplexity

native C++ filters
Recompile envoy
Y
Y
Optimal
C++
Complex

Lua script filters
Inline with config
N
N
Normal-
Lua
Simple

WASM filters
Filter in a separate module
Y
N
Poor
C++/Rust/Go
Medium

We would like to learn from Community professor below concerns:

*

*Whether upper comparison is exactly?

*Any best practice on the envoy extension?

*which one is preferred?

The questions are also raised here.
https://discuss.istio.io/t/envoy-extension-with-lua-vs-with-wasm/13789


text:
Q: Array Formula return by Excel Custom Function I want to return multiple values or array formula without making range selection in excel through the function.
# excel custom function
async function add(first, second) {
    try {

        Excel.run(async context => {
            # selecting active worksheet
            const worksheet = context.workbook.worksheets.getActiveWorksheet();

            # selecting range
            const range = worksheet.getRangeByIndexes(0, 0, 1, 4);

            # set values for selected range
            range.values = [[1, 2, 3, 4]];

            return context.sync();
        });
    }
    catch(err) {
        return err.message;
    }
}

# mapping function with key
CustomFunctions.associate("ADD", add);

A: Thanks for posting this question. Currently to enable what you're asking for requires Excel Dynamic Arrays to be enabled. This feature is still in preview, and you can start testing against that by joining the Insiders Channel (on Windows and Mac).

*

*Join the Office 365 Developer program if you need a tenant: https://aka.ms/O365DevProgram.

*Get a tenant and once setup, click Install Software to download Office (if needed)

*Look at insiders.office.com to follow instructions on how to switch channels.

*Launch Excel and try this formula "=MUNIT(10)"

*If it returns a 10x10 array, you are on insiders channel.

*Once on the insiders channel, you can just return that array from your function, i..e return [[1, 2, 3, 4]]; and Excel would dynamically spill or return an #SPILL! error if it was about to overlap certain values.


text:
Q: Flex-Basis: Force Children to have fixed size I'm sorry, I checked out multiple answers but nothing seems to work. If somebody could point me into the right direction, that would be helpful!
I have a Wrapper and 8 Boxes:
<Wrapper>
  <Box></Box>
  <Box></Box>
  <Box></Box>
  <Box></Box>

  <Box></Box>
  <Box></Box>
  <Box></Box>
  <Box></Box>
</Wrapper>

I want my Flex Wrapper to break after 4 Boxes, so I want to have 4 Boxes in a row. I have solved this in the following way:
Wrapper:
const Wrapper = styled.div`
  display: flex;
  flex-wrap: wrap;`;

Box:
const Box = styled.div`
  background-color: gray;
  width: 150px;
  height: 150px;
  margin: 5px;`;
  flex: 1 0 21%;`;

However, I'd like my Boxes to not stretch, I'd like them to always be 150x150px. Right now they're stretching and they're not 150x150 - I don't know what to do though?


text:
Q: Referencing Non-Scalar Variables Not Supported hat is wrong with my query below?  I'm getting a NotSupportedException ""Unable to create a constant value of type JobLanguage. Only primitive types ('such as Int32, String, and Guid') are supported in this context."
public IQueryable<Candidate> GetMatchingCandidates(Job job)
{
   return from candidate in _db.Candidates
   where candidate.CandidateLanguages.Any(c => job.JobLanguages.Select(jl =>      jl.LanguageId.Value).Contains(c.LanguageId))
   orderby candidate.Name descending
   select candidate;
}

//caller
List<Candidate> matchingCandidates = _repository.GetMatchingCandidates(job).ToList();

Apparently, this is a known issue (http://msdn.microsoft.com/en-us/library/bb896317.aspx#RefNonScalarClosures) but I'm wondering how I can get around it.  Basically, what I'm trying to do is this: Comparing two lists using linq to sql

A: Well, one thing you could try is extracting the set of desired language IDs to start with:
(I'm assuming language IDs are strings. If they're not, please give more information.)
public IQueryable<Candidate> GetMatchingCandidates(Job job)
{
    List<string> languageIds = job.JobLanguages
                                  .Select(jl => jl.LanguageId.Value)
                                  .ToList();
   return from candidate in _db.Candidates
          where candidate.CandidateLanguages
                         .Any(languageIds.Contains(c.LanguageId))
          orderby candidate.Name descending
          select candidate;
}

If the job is already in the database, you could try performing an inner query using the job ID to refer to the database copy of the data rather than the local one.


text:
Q: encrypt the Password in jQuery and decrypt in Apex class I'm creating the custom login page for customer community. Login page has functionality like, Save Username Password, Remember me.
When I check the Save Username Password while login, then  at the time of next login, Username and password field are auto-populate. This implemented by using jQuery and cookies.
When I click remember me then it will skip the login page while next login. this implemented by calling action in <apex:page> which called the controller method while VF page load. controller method check cookies available and login.
I'm storing cookies in jQuery and for remember me functionality login, I'm getting that cookies(Username, Password) in apex class.
Presently In cookies, password is not in encrypt form. Now I've store the password in encrypt form.
How to encrypt the password in jQuery and decrypt the password in apex class.
Calling action in page like :
<apex:page sidebar="false" controller="demo2Controller" action="{!directlogin}" showheader="false" standardStylesheets="false">

script of Vf Page:
function submitbtn(){
      var username = $("[id$='username']").val();
      var password = $("[id$='password']").val();
      if($("[id$='UserPass']").is(":checked")){
            $.cookie('apex__username', username, { expires: 14 });
            $.cookie('apex__password', password, { expires: 14 });
            $.cookie('apex__remember', true, { expires: 14 });
        }
        else  if($("[id$='directlogin']").is(":checked"))
        {

            $.cookie('apex__username', username, { expires: 14 });
            $.cookie('apex__password', password, { expires: 14 });
            $.cookie('apex__directlogin', true, { expires: 14 });
        }
      console.log($.cookie("apex__password"));
      console.log(CryptoJS.MD5(password));
     //here we have to encrypt the password.
      $.cookie('apex__encryptpassword', CryptoJS.MD5(password), { expires: 14 });

     controllerMethod();
}

controller part:
public PageReference directlogin(){
Cookie getPass = ApexPages.currentPage().getCookies().get('encryptpassword');
          password =  getPass.getValue();
//here we have to decrypt the password.
}

A: It's probably not the answer you want to hear but this approach sounds everything but safe to be honest. In order to encrypt it you will need a secret. You would need to store this key in sf and then expose it to jquery (NOT SAFE). I would recommend using a password browser extension like LastPass if needed but would never store the password on the client side.
Also, I have never seen the option on any portal/website that allows me to store the password.

A: As you are using crypto-js to encrypt your data . And the MD5 enccryption format so when I google it I found

MD5 means a 128-bit encryption algorithm, generating a 32-character
  hexadecimal hash, whatever the captcha. This algorithm is not
  reversible, ie it is normally impossible to find the original word
  from the md5 hash.

So its not possible to decrypt it using this way. So you have one alternative solution here. Pass the username, password in apex using apex:param or any other approach then in apex you can encrypt decrypt them easily.
// Generate an AES key for the purpose of this sample.
// Normally this key should be stored in a protected custom setting
// or an encrypted field on a custom object
Blob cryptoKey = Crypto.generateAesKey(256);

// Generate the data to be encrypted.
Blob data = Blob.valueOf('Test data to encrypted');
// Encrypt the data and have Salesforce.com generate the initialization vector
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
// Decrypt the data - the first 16 bytes contain the initialization vector
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);

// Decode the decrypted data for subsequent use
String decryptedDataString = decryptedData.toString();

Using the Apex Crypto Class


text:
Q: IntelliJ IDEA and Maven in Windows There is a project that definitely uses Maven.
In IntelliJ IDEA in Windows, when the project is opened, there are such errors in the Maven Projects area as
Unresolved plugin: org.apache.maven.plugins:maven-war-plugin:2.1.1
Unresolved plugin: org.apache.maven.plugins:maven-clean-plugin:2.4.1

and many other similar unresolved plugins.
Also, all of Maven projects in the Maven Projects area are underlined with red.
So, something definitely needs to be done with Maven. However, I'm not sure what exactly.
As http://www.jetbrains.com/idea/webhelp/maven.html#d661509e173 says, IntelliJ IDEA fully integrates with Maven version 2.2 and later versions. However, I'm not sure:

*

*if it comes with IntelliJ IDEA program, or

*I have to install the Maven plugin in IDEA, or

*I have to follow Installation instructions for Windows from http://maven.apache.org/download.cgi#Installation
P.S. Java is installed, java -version says it is 1.7.0_60


text:
Q: Linq To Entity :: What the following code is doing? I am running this query but i am unsure of what is it fetching ?
var sm = pe.Categories.Include("ParentCategory").Where(c => c.ParentCategory.CategoryName == "Electronics");

What will the variable sm have ??

A: Edit - You need to remove the Include statement. Linq-to-Entities will allow you to access the properties of the entity without having to include them
var sm = pe.Categories
           .Where(c => c.ParentCategory.CategoryName == "Electronics");

*

*sm will be an IQueryable of type Category

*It will contain Categories where its ParentCategory CategoryName is "Electronics"

*Each cateogry will have its ParentCategory preloaded for you

A: var sm = pe.Categories
           .Where(c => c.ParentCategory.CategoryName == "Electronics");

This should work as you expect. Adding Include preloads the specified entity.


text:
Q: Two-sum problem with $n$ iterations Preamble:
The famous two-sum problem asks for an algorithm to determine if a given integer $s$ is the sum of two integers in a given ordered list $L$. If $n$ is the size of $L$, this can be solved in $O(n)$ with a clever use of pointers as follows:
i = 0
j = n-1
found = false

while (!found and i<=n-1 and j >= 0):
   S = L[i] + L[j]
   if s > S:
      i += 1
   elif s < S:
      j -= 1
   else
      found = true

if found:
   print(L[i],L[j])

A trivial variation of this problem asks to find if a given integer $s$ is the sum of two integers, one from an ordered list $L$ and another from an ordered list $M$. If both lists have the same size, $n$, it is also solved in $O(n)$ by changing all instances of L[j] by M[j] in the code.
Note that since the size of the input is $n+1$ in the first case, and $2n+1$ in the variation, no algorithm can do any better than $O(n)$.
New variation:
Assume now that three ordered lists of size $n$ are given, $L, M, N$ and we are told that every element in $N$ is the sum of an element in $L$ and an element in $M$ in a one-to-one way. That is, if $n_1 = l_1 + m_1$ and $n_2 = l_2 + m_2$ then $l_1 \neq l_2$ and $m_1 \neq m_2$. Since the size of all lists is $n$, that means that each element in $L$ and in $M$ participates exactly once in a sum to produce an element in $N$. We are asked to find all $n$ triplets $(l_i,m_j,n_k)\in L\times M\times N$ such that $l_i + m_j = n_k$.
We could, of course, use the variation problem in the preamble to treat each element of $N$, and thus, solve this new variation in $O(n^2)$. We could delete each $l_i$ and $m_j$ from $L$ and $M$ as we find them to improve marginally our run time (though still in $O(n)$, of course).
Question:
Could we do any better than $O(n^2)$? Does the extra one-to-one property allows for some clever way to discard possibilities and thus achieve something like $O(n\log n)$?


text:
Q: Duplicating Data looking at duplicating data to include a type A and type B
select *
    from [dbo].[dayStats]
    where status in ('IDmon', 'IDtue', 'IDwed', 'IDthu', 'IDfri')
    order by status

currently have around 3000 records.
i need to duplicate each of these records so they include a A and B
for example:
IDmon
IDtue ...

becomes
IDmonA, IDmonB
IDtueA, IDtueB
...

no IDmon / IDtue records to remain
all the other fields are to be duplicated as normal
really struggling to think how i would create such a query / stored procedure

A: Not really sure if you're after this?
select
  status & 'A',
  status & 'B',
  other_col_1,
  other_col_2
from
  [dbo].[dayStats]
where status in ('IDmon', 'IDtue', 'IDwed', 'IDthu', 'IDfri')


text:
Q: If $D$ is a derivation of a Lie Algebra, and $D X = \lambda X$ $\Rightarrow$ $\text{ad}(X)$ is nilpotent I'm very stuck in this exercise, can anyone help me or give me some hints?

Exercise: Let $\mathfrak{g}$ be a finite dimensional Lie Algebra (over a zero characteristic field), $D:
 \mathfrak{g}\to \mathfrak{g}$ a derivation and $X \in \mathfrak{g}$,
  such that $D(X) = \lambda X$ (with $\lambda \neq 0$). Then $\text{ad}(X)$ is nilpotent.

I could only conclude that $\text{tr}(\text{ad}(X)^2) =0$. In fact, if $\langle \cdot,\cdot \rangle$ is the Killing form, then
$$ \langle X,X \rangle= \frac{1}{\lambda} \langle D X, X \rangle=\frac{-1}{\lambda} \langle  X, DX \rangle = - \langle X, X \rangle,$$
follows that $ \langle X,X \rangle = 0$, and therefore $\text{tr}(\text{ad}(X)^2) = 0.$ However, this result does not give me a useful conclusion.

A: Keeping in mind that $\text{ad}(DX)=[D,\text{ad}(X)]$, since
$$\text{ad}(DX)(Y) = [DX,Y] = D[X,Y] - [X,DY] = [D,\text{ad}(X)](Y).$$
Then
$$\lambda \text{ad}(X) = \text{ad}(D X) = [D,\text{ad}(X)] \Rightarrow \text{tr}(\text{ad} (X)) = 0. $$
Moreover,
\begin{align*}
\lambda\text{ad}(X)^{n+1} &= \left(\lambda \text{ad}(X)\right) \cdot \text{ad}(X)^{n} \\
&=  [D, \text{ad}(X)] \cdot \text{ad}(X)^n\\
&=  D \text{ad}(X)^{n+1} - \text{ad}(X) D \ \text{ad}(X)^n,
\end{align*}
so  $\text{tr}(\text{ad}(X)^{n+1}) =0 $, $\forall$ $n $ $\in$ $\mathbb{N}$, and consequently $\text{ad}(X)$ is nilpotent, because if $\text{tr}(A^n)=0$ for all positive integers $n$, then $A$ is nilpotent.

Bonus Information
Another interesting approach is that we can, by primary decomposition theorem, write $\mathfrak{g}$ as
$$\mathfrak{g} = \mathfrak{g}_{\lambda_1}\oplus \mathfrak{g}_{\lambda_2}\oplus ...\oplus \  \mathfrak{g}_{\lambda_n},  $$
where $ \mathfrak{g}_{\lambda_i} = \{X \in \mathfrak{g};$ there exists $n\in \mathbb{N}$, such that $(D-\lambda_i I)^n X = 0 \}. $ Since $D$ is a derivation it is possible to demonstrate that
$$[\mathfrak{g}_{\lambda_i}, \mathfrak{g}_{\lambda_j}]\subset \mathfrak{g}_{\lambda_i +\lambda_j},$$
where $\mathfrak{g}_{\lambda_i +\lambda_j}=\{0\}$ if $\lambda_i +\lambda_j$ is not an eigenvalue of $D$. Therefore, for any $Y$ $\in$ $\mathfrak{g}_{\lambda_Y}$
$$\text{ad}(X)^k (Y) = [X, [X,...,[X,Y] ...] \in \mathfrak{g}_{k \lambda + \lambda_Y},$$
since, there are only a finite number of eigenvalues of $D$ and $\lambda \neq 0$, there exists some $k \in \mathbb{N}$, large enough, such that $\text{ad}(X)^k Y=0$, $\forall\  Y \in \mathfrak{g}_Y$, showing that $\text{ad}(X)$ is a nilpotent linear operator.
With a similar argumentation, we can show that if $D$ an invertible derivation, then $\text{ad}(X)$ is nilpotent for all $X\in \mathfrak{g}$ (because all eigenvalues are different from $0$, then, if $X$ $\in$ $\mathfrak{g}_{\lambda_i}$ $\Rightarrow$ $\text{ad}(X)^{k} Y$ $\in$ $\mathfrak{g}_{ k \lambda_i + \lambda_Y}$ ), and consequently, $\mathfrak{g}$ is nilpotent (Engel theorem).


text:
Q: Non-parametric test for separating samples from two populations I have samples $\mathcal{Z} = \{Z_1,\ldots,Z_n\}$. These samples either come from the unknown distribution $\mathcal{D}_1$ or $\mathcal{D}_2$. (Note: I can't make any assumptions about these distributions). I wish to devise a non-parametric test for identifying and picking a maximal subset, $\mathcal{S} \subset \mathcal{Z}$ of samples all of which come from $\mathcal{D}_1$ (or alternatively $\mathcal{D}_2$).
If I am to do this naively by checking for all possible subsets, it's going to be computationally expensive. Is there a clever way to do this?
Is there any literature that has looked into such subset selection problems? Or are there any suggestions to formulate the problem differently?
Clarification: I am not looking for a numerical solution. I am looking for ways to formally state and prove such statements.


text:
Q: Remove everithing that it outside the brackets I need your help.
I working with Oracle SQL and I need to remove everything that it outside the brackets.
For example:
 - Stabilization loans, mortgage lending (StabL ML) => StabL ML
 - Refinanced loans and restructured loans (RefL RL) => RefL RL
 - Individual reserve (IR) => IR

I'm trying to use something like this but it doen't work
select regexp_replace(example, '\([A-Za-z ]\)', '') from dual;

I will be grateful for any help!

A: Although you might consider using a pattern like .*\(|\).* with REGEXP_REPLACE, I'd rather you use
REGEXP_SUBSTR(example, '\(([^()]*)\)', 1, 1, 'i', 1)

See the DBfiddle.
Details:

*

*\( - a ( char

*([^()]*) - Group 1: any zero or more chars other  than parentheses

*\) - a ) char.

1, 1, 'i', 1 make the regex engine search from the first char in the string only once (in a case insensitive way, though it is not quite important here) and the last 1 extracts Group 1 value.

A: Your algorithm is partially correct. But you have to add the expression is "+"
'\([A-Za-z ]+\)'
Regex101
or
Regex101
'([A-Za-z].+)([(])([A-Za-z].+)([)])'
You can use the code as above with substitution "$3". But I think this code maybe more useful for you.

A: You can use this:
SELECT  REGEXP_SUBSTR ( 'Stabilization loans, mortgage lending (StabL ML)', '\( *([^)]*) *\)', 1, 1, NULL, 1) FROM    dual;


text:
Q: can we store multiple records with same key in memcache? I have two database tables, 1. Cities, 2. Details.
'Details' table references 'cities' as foreign key. Now can I store data in memcache according to city (one key storing multiple records of details)? If yes, how should I make my key? If not, what's the best way to do it using memcache?

A: DeNormalize - against the city ket store details from the city table AND the details table. That denormalization is common; though it comes with associated disadvantages of denormalization; primarily memory/space related.
If not, introduce a synthetic key; maintain city table as is with it's own key BUT store an additional key within city record. Store the data from details against this other key.  This comes with associated disadvantage of having to make two queries against memcache.

A: memcached is a plain key-value store, so there is no multi-associativity.
One possible solution is to store details by city through separator
<city>=<detail1>;<detail2>;

The downside of this approach - there is no way to check if <city> key already contains specific detail data on a server side.
The usual way is to create combined keys
<city>:<detail_id>=<detail>

But then, there is no way to get all details by the city.


text:
Q: App uses https - what is the correct value of ITSAppUsesNonExemptEncryption The ONLY encryption my App uses is calls over HTTPS. Currently (7 June 2017) iTunes Connect requires an Export Compliance according to this information in iTunes Connect.

I've entered the iTunesConnect -> My Apps -> Features -> Encryption page, clicked the plus symbol besides "iOS Documentation" and in the Export Compliance form answered YES.

The following two screen shots show more details of the export compliance box as I scroll down.

The last 2 screen shots suggest using HTTPS is an EXEMPT use of encryption and I should therefore in info.plist set ITSAppUsesNonExemptEncryption=false. But this is not clear, and is contradicted in my 1st screen shot that says if you are making a call to HTTPS ... required to submit a year-end classification report to the US government.
So my questions:

*

*is it correct to set ITSAppUsesNonExemptEncryption=false if the only encryption I use is via HTTPS calls?

*if I must set ITSAppUsesNonExemptEncryption=true, where do I go to submit a report to the US government and how does this report get passed to Apple? I cannot find any clear information on the process. I don't want to screw this up as the consequences can be major as threatened in the last screen shot.

*regardless of how I set ITSAppUsesNonExemptEncryption, according to my 1st screen shot if I use HTTPS I must submit a year-end self classification to the US government. Is that true, and what is the process? (clicking the "learn more" link doesn't help)

A: I was searching the web for this for some hours. Actually it is pretty easy and you can verify this in itunes connect:
1. All you have to do
If your app uses only HTTPS or uses encryption only for authentication, tokens, etc., there is nothing you have to do, just include
<key>ITSAppUsesNonExemptEncryption</key><false/>

in your Info.plist and you are done.
2. Verification
You can verify this in itunes connect.

*

*select your app

*chose features

*chose encryption

*click "+"

*follow the dialog

*for https or authentication the answer is yes and yes
3. Year-end self classification report
As is written in the dialog in 2., you still need to submit a year-end self classification report:

If you are making use of ATS or making a call to HTTPS please note
  that you are required to submit a year-end self classification report
  to the US government. Learn more

You can check How do I submit a Self Classification Report for Encryption Items and this SO question https://stackoverflow.com/a/48462458/276648 .

In any case you should of course read yourself carefully through the dialog.
A very helpful article can be found here:
https://www.cocoanetics.com/2017/02/itunes-connect-encryption-info/

A: I unfortunately do not have enough rep to comment but at the minute I am looking into the exact same issue and I believe that you are correct when you say that you can set the ITSAppUsesNonExemptEncryption key to false, at least this was the conclusion I came to from my research.
For the self classification report it does look like you have to submit one by February of next year, I found this link helpful in explaining the report and what to do
https://www.bis.doc.gov/index.php/policy-guidance/encryption/reports-and-reviews/annual-self-classification
Like I said this is all from my own investigation like you and I think this is correct but if anyone does have any more information would be greatly appreciated.


text:
Q: Output an array of terms names for WooCommerce product attributes This is my code and I need to display names of my each array:
Black
Blue
Green
foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ){
// To get the taxonomy object
$taxonomy_obj = get_taxonomy( $taxonomy );

$taxonomy_name = $taxonomy_obj->name; // Name (we already got it)
$taxonomy_label = $taxonomy_obj->label; // Label

// Setting some data in an array
$variations_attributes_and_values[$taxonomy] = array('label' => $taxonomy_obj->label);

foreach($terms_slug as $term){

    // Getting the term object from the slug
    $term_obj  = get_term_by('slug', $term, $taxonomy);

    $term_id   = $term_obj->term_id; // The ID  <==  <==  <==  <==  <==  <==  HERE
    $term_name = $term_obj->name; // The Name
    $term_slug = $term_obj->slug; // The Slug
    $term_name = $term_obj->description; // The Description

    // Setting the terms ID and values in the array
    $variations_attributes_and_values[$taxonomy]['terms'][$term_obj->term_id] = array(
        'name'        => $term_obj->name,
        'slug'        => $term_obj->slug
    );
}}

And this is my arrays:
Array(
[pa_color] => Array(
    [label] => Color
    [terms] => Array(
        [8] => Array(
            [name] => Black
            [slug] => black'
        )
        [9] => Array(
            [name] => Blue
            [slug] => blue
        )
        [11] => Array(
            [name] => Green
            [slug] => green
        )
    )
))

How can I do it?
/////NEW EDIT
echo '
'; print_r($term_obj->name);echo '
';

I used this code for showing names but just display last name!

A: This is one of my aswer's code: Get the product variations attributes values term ID and name
It has been done before Woocommerce 3 release.
Since woocommerce 3+ things have changed a little bit. You don't need all this code in the function. So here is an arranged version to feet your needs.

Remember that you can have many attributes for a variable product, so you will need to use foreach loops to output separated values for each product attribute…

Here is the code:
foreach( $product->get_variation_attributes() as $taxonomy => $terms_slug ){

    // To get the attribute label (in WooCommerce 3+)
    $taxonomy_label = wc_attribute_label( $taxonomy, $product );

    foreach($terms_slug as $term){

        // Getting the term object from the slug
        $term_name  = get_term_by('slug', $term, $taxonomy)->name;

        // Setting the terms ID and values in the array
        $attributes_and_terms_names[$taxonomy_label][$term] = $term_name;
    }
}
echo '
'; print_r($attributes_and_terms_names); echo '
';

Then you will get:
Array
(
    [Color] => Array
        (
            [0] => Black
            [1] => Green
            [2] => Red
        )
)

Usage example output:
foreach ( $attributes_and_terms_names as $attribute_name => $terms_name ){
    // get the related attribute term names in a coma separated string
    $terms_string = implode( ', ', $terms_name );
    echo '
' . $attribute_name . ': ' . $terms_string . '
';
}

You will get:

Color: Black, Green, Red


text:
Q: Concatenate or merge many columns values with a separator between and ignoring nulls - SQL Server 2016 or older I want to simulate the CONCAT_WS SQL Server 2017+ function with SQL Server 2016 version or older in order to concatenate many columns which values are strings like that:
Input:
| COLUMN1 | COLUMN2 | COLUMN3 | COLUMN4 |
   'A'        'B'       NULL     'D'
   NULL       'E'       'F'      'G'
   NULL       NULL      NULL     NULL

Output:
| MERGE |
 'A|B|D'
 'E|F|G'
  NULL

Notice that the output result is a new column that concatenate all values separated by '|'. The default value should be NULL if there are no values in the columns.
I tried with CONCAT and a CASE statement with many WHEN conditions but is really dirty and I am not allowed to use this solution. Thanks in advance.

A: One convenient way is:
select stuff( coalesce(',' + column1, '') +
              coalesce(',' + column2, '') +
              coalesce(',' + column3, '') +
              coalesce(',' + column4, ''), 1, 1, ''
            )

A: Here is another method by using XML and XQuery.
The number of columns is not hard-coded, it could be dynamic.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, col1 CHAR(1), col2 CHAR(1), col3 CHAR(1), col4 CHAR(1));
INSERT INTO @tbl (col1, col2, col3, col4) VALUES
( 'A',  'B',  NULL, 'D'),
(NULL, 'E' , 'F'  , 'G'),
(NULL, NULL, NULL , NULL);
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = '|';

SELECT id, REPLACE((
    SELECT *
    FROM @tbl AS c
    WHERE c.id = p.id
    FOR XML PATH('r'), TYPE, ROOT('root')
).query('data(/root/r/*[local-name() ne "id"])').value('.', 'VARCHAR(100)') , SPACE(1), @separator) AS concatColumns
FROM @tbl AS p;

Output
+----+---------------+
| id | concatColumns |
+----+---------------+
|  1 | A|B|D         |
|  2 | E|F|G         |
|  3 |               |
+----+---------------+


text:
Q: Como criar colunas dinamicas com Bootstrap e PHP? Eu tenho 30 itens que vão vir em ordem alfabética.
Eu preciso distribuir estes itens em 3 colunas por ordem alfabética VERTICAL.
O problema é que no Bootstrap, os blocos vão casando um ao lado do outro fazendo com que os itens fiquem em ordem alfabética horizontal e não VERTICAL.
Vou mostar o que preciso:

        aa
        ab
        ac
        ad
        ae

        af
        ag
        ah
        ai
        aj

        ak
        al
        am
        an
        ao

Os meus itens vêm daqui:
<?php
     foreach ($qartie as $bairros => $bairro) {

     }
?>

A: Um exemplo simples:
<!DOCTYPE html>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

            <?php
            $array = array( "b","a","j","k","l",
                            "x","q","j","t","c",
                            "q","e","z","u","o",
                            "e","t","h","e","p",
                            "r","d","u","z","m",
                            "t","y","u","n","y"); //array com 30 posições

            sort($array); // ordem alfabetica

            for($i = 0; $i < count($array); $i ++) { // vai percorrer todo o meu array
                echo "\t{$array[$i]}
\n"; //printa meu elemento (\n e \t apenas para formatação do html)

                if((($i + 1) % 10 == 0) and ($i < count($array)-1)) { // como é separado de 10 em 10, quando o resto da divisão do meu contador atual por 10 for 0, quer dizer que ele fezou no item 10 daquela coluna
                    echo "\n\t
\n\t
\n"; // assim ele termina a coluna anterior e incia outra
                }
            }

            ?>

A: Se quiser que tudo fique dentro de uma coluna do tamanho 4 do bootstrap pode fazer assim também ..

                    aa
                    ab
                    ac
                    ad
                    ae

Espero ter ajudado, pelo meu entendimento da parte do seu código, desta forma resolveria.


text:
Q: Listen to pin/unpin tab events in Firefox Add-on SDK I am writing a Firefox Add-on SDK extension. I want to be notified when any tab is pinned or unpinned. Unfortunately, the sdk/tabs module doesn't provide such events. Is there some low-level API which provides events for pinning/unpinning tabs?

A: There is no Firefox Add-on SDK Low-Level API which provides a way to listen for tabs being pinned, or unpinned. The "Add-on SDK Low-Level APIs" are a very specific list of APIs which are defined only within the Add-on SDK. You did not limit your request to just the Add-on SDK specific APIs, but to all Firefox APIs which function within the Add-on SDK, which is almost all Firefox APIs, except WebExtensions.
You can get such events by listening for the TabPinned and TabUnpinned events on the XUL <tabs> element for the window in which you are interested.  You can get the XUL <tabs> element by using getTabContainer(window).  If you want to get all such events within all browser windows, you will need to add the events to the tabContainer, the XUL <tabs> element, for each browser window. You can see a list of the tab specific events in the MDN Event Reference page.
The following is a Firefox Add-on SDK based extension which will listen for TabPinned and TabUnpinned events in all windows.
index.js:
var sdkWinUtils = require('sdk/window/utils');
var sdkTabsUtils = require('sdk/tabs/utils');
var sdkWindows = require("sdk/windows");

//For testing, open the Browser Console
sdkWinUtils.getMostRecentBrowserWindow()
           .document.getElementById('menu_browserConsole').doCommand();

function tabPinned(event) {
  let tabId = sdkTabsUtils.getTabId(event.target);
  console.log('Pinned Tab ID:',tabId);
}

function tabUnpinned(event) {
  let tabId = sdkTabsUtils.getTabId(event.target);
  console.log('Unpinned Tab ID:',tabId);
}

function addTabPinUnpinListenersInWindow(win){
    //win can be either a browserWindow provided by the
    //    sdkWindows.browserWindows.on('open',);
    //  event, or nsIDOMWindow instances provided in the array from
    //    sdkWinUtils.windows()
    //  We can distinguish between the two by using
    //    sdkWinUtils.isBrowser(win)
    let container;
    if(sdkWinUtils.isBrowser(win)){
        container = sdkTabsUtils.getTabContainer(win);
    }else{
        let { viewFor } = require("sdk/view/core");
        container = sdkTabsUtils.getTabContainer(viewFor(win));
    }
    container.addEventListener("TabPinned", tabPinned, false);
    container.addEventListener("TabUnpinned", tabUnpinned, false);
}

function removeTabPinUnpinListenersInWindow(win){
    let container = sdkTabsUtils.getTabContainer(win);
    container.removeEventListener("TabPinned", tabPinned, false);
    container.removeEventListener("TabUnpinned", tabUnpinned, false);
}

function forEachOpenWindow(func){
    let allWindows = sdkWinUtils.windows('navigator:browser', {includePrivate:true});
    for(let win of allWindows){
        func(win);
    }
}

function forEachOpenWindowAndAllNewWindows(func){
    forEachOpenWindow(func);
    //Listen for new windows opening and add tab pin/unpin listeners:
    sdkWindows.browserWindows.on('open',func);
}

function removeAllListeners(){
    //To be called upon shutdown for add-on upgrade/disable/removal
    //Remove new window open listener
    sdkWindows.browserWindows.off('open',addTabPinUnpinListenersInWindow);
    //Remove tab pin/unpin listeners
    forEachOpenWindow(removeTabPinUnpinListenersInWindow);
}

//Add listeners to all open windows and all which open
forEachOpenWindowAndAllNewWindows(addTabPinUnpinListenersInWindow);

//Clean up if Firefox is not shutting down (e.g. the add-on is disabled by user).
exports.onUnload = reason => {
    if(reason !== 'shutdown'){
        //The add-on is being unloaded and it is not because Firefox is sutting down.
        removeAllListeners();
    }
};

package.json:
{
    "title": "Listen to tab pin/unpin",
    "name": "listen-to-tab-pin-unpin",
    "version": "0.0.1",
    "description": "Output to console when a tab is pinned or unpinned.",
    "main": "index.js",
    "author": "Makyen",
    "permissions": {"private-browsing": true},
    "engines": {
        "firefox": ">=38.0a1",
        "fennec": ">=38.0a1"
    },
    "license": "MIT",
    "keywords": [
        "jetpack"
    ]
}


text:
Q: Deploy large size OVF to ESXI with Ansible I want to deploy a large size OVF to an ESXI with Ansible.
This is the playbook:
- hosts: localhost
  tasks:
   - community.vmware.vmware_deploy_ovf:
      hostname: "192.168.15.1"
      username: "root"
      password: "P@55w0rd"
      datastore: "datastore1"
      name: "NewVM"
      power_on: no
      ovf: /home/user/ubuntu-16.04-amd64.ovf
    delegate_to: localhost

The process is interrupted during deploying OVF with:

"msg": "<urlopen error The write operation timed out>"

I think this is because the OVF file is big. (2.3 GB). How do I automate this task?


text:
Q: Erro ao pegar valor do input Estou tentando capturar o valor do input e mandar para o script do js, onde se a nota do aluno for >= 7 exibe na tag p "Aprovado" e caso contrario exibe "Reprovado", mas estou travado na lógica do js, não consigo exibir o resultado.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>College FX</title>

    <link rel="stylesheet" href="style.css">

COLLEGE FX

Welcome student, this is your grading portal, together we will check if you pass or fail

            <form class="form" action="">
                <input type="text" name="name" id="name" placeholder="enter you name">
                <input type="number" name="note1" id="note1" placeholder="enter test grade 1">
                <input type="number" name="note2" id="note2" placeholder="enter test grade 2">

                <select class="city" value="college">
                    <option value="sp">São paulo</option>
                    <option value="sp">Toronto</option>
                    <option value="sp">New york</option>
                    <option value="sp">Sydney</option>
                </select>

                <input  onclick="" type="submit" value="Calcular" class="Calcular" id="btn">

            </form>

let btn = document.querySelector("#btn")

btn.addEventListener("click",function(e){

    e.preventDefault()

    const n1 = document.querySelector("#note1").value
    const value1 = n1.value
    const n2 = document.querySelector("#note2").value
    const value2 = n2.value

    const media = parseInt((value1)) + parseInt((value2)) /2
            if (media >=7){
                    document.getElementById("#result").innerHTML = "Aprovado"
            } else{
                    document.getElementById("#result").innerHTML = "reprovado"
            }

})

A: Isso está acontecendo porque você está tentando
document.getElementById("#result").innerHTML

Mas o id do seu elemento é id="result", portanto basta substituir por
document.getElementById("result").innerHTML

A # só é utilizada no querySelector para especificar que se trata de um id, assim como o . no querySelector indica se tratar de uma classe. Como você está fazendo o uso do getElementById para selecionar o elemento no qual deseja exibir o resultado, o uso da # torna-se errôneo, a menos que seu id seja id="#result".
Além disso, quando você escreve
const n1 = document.querySelector("#note1").value

você já está pegando o valor do input, assim quando você escreve novamente
const value1 = n1.value

sua variável value1 possuirá valor undefined, pois n1 já é o valor que estava armazenado no input, e esse valor não possui um atributo value.
Ainda, ao parsear os valores, não é necessário
parseInt((value1))

apenas
parseInt(value1)


text:
Q: I want to upload files only from particular user and allow anyone (public) to view it on Amazon S3 Trying deny write permission from all and allow only single user to write to an Amazon S3 bucket, but I want all users to view it. Therefore, I have set public access on the bucket.
IAM user Joe has AmazonS3FullAccess.
Here is the Bucket policy:
{
    "Id": "Policy98745183475249",
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt15681834712546",
            "Action": [
                "s3:PutObject"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::buketname/*",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::98754131531:user/Joe"
                ]
            }
        },{
            "Sid": "Stmt15681834478323",
            "Action": [
                "s3:PutObject"
            ],
            "Effect": "Deny",
            "Resource": "arn:aws:s3:::buketname/*",
            "Principal": "*"
        },

    ]
}

However, it does not appear to be working correctly.

A: Deny always beats Allow. Therefore, the policy is actually denying everybody the ability to write to the bucket.
Users have no permission by default, so it is typically only necessary to specify Allow policies.
If you wish to assign permissions to a specific IAM User, it is better to put the permissions on the IAM User themselves, rather than in a Bucket Policy. This makes it easier to manage permissions as more are added in future.
So, you would put a policy like this onto Joe in IAM:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowWrite",
            "Effect": "Allow",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::my-bucket/*"
        }
    ]
}

To allow everyone in the entire world to read the contents of the bucket (Note: Not good from a security standpoint!), use a Bucket Policy like this:
{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AnyoneRead",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::my-bucket/*"]
    }
  ]
}


text:
Q: CastCastException when casting to class loaded from a different class loader I write a library and one of its API methods takes Class as a parameter, then in the body of this method I create an instance of this class:
void foo(Class scriptClass) {
  Script script = scriptClass.newInstance();
  // do stuff with the script object
}

The problem is that while scriptClass is a child of Script class I get ClassCastException as scriptClass was loaded by different class loader than Script. What is the usual way to resolve such collisions?

A: You cannot cast unless the class it the same, it is, its the same instance of Class, thus, loaded by the same class-loader.
Common class loader
Use a classloader that already has groovy.Script so when any child class loader use this class it's the common class.
When you use URLClassLoader, then use this constructor: URLClassLoader(URL[] urls, ClassLoader parent) to make the script use the existing classes.
Other class loader
If the above is not posible, you could use reflection (as JRE classes ARE common). But have in mind that this is a lot of boilerplate code and should be kept to a minimum.
So the bottom-line is review your classloader structure and try to put common things in common places.

A: It's unclear whether your "scriptClass" is precisely "Script" or a subclass of it.  If the latter, then you basically just need to make sure that "Script" is loaded by the JVM before you load your "scriptClass".  If "Script" hasn't been loaded yet, your "odd" class loader will load it itself, creating your problem.  If it has already been loaded, the already-loaded (by the system class loader) version will be used in both cases.


text:
Q: building a select query to scan specified columns by the user I am trying to create create an API which allow users to query the database based on whatever columns they wish to use, by passing the column name as parameter.
@app.route('/api/restaurants/search1/',methods=['GET'])
def search():
    col = request.args['col']
    key = request.args['key']
    restaurant = Restaurant.query.filter(Restaurant.menu_type.like("%"+key+"%")).all()
    return jsonify(json_list=[i.serialize for i in restaurant])

I am trying to replace "Menu_type" which is the current column by whatever the user enters for the variable "col" any help would be appreciated.

A: You can just use getattr function. To avoid cases when object has requested attribute but it is not a table column (a method for example) check Restaurant.__table__.c — collection of table columns:
@app.route('/api/restaurants/search1/',methods=['GET'])
def search():
    col = request.args['col']
    key = request.args['key']
    if col in Restaurant.__table__.c:
        restaurant = Restaurant.query.filter(getattr(Restaurant, col).like("%"+key+"%")).all()
    else:
        raise RuntimeError('Restaurant table doesn`t have column %s' % col)
    return jsonify(json_list=[i.serialize for i in restaurant])


text:
Q: Populate drop down list from SQL Server database I have an ASPX page that has a drop down on it.

Pick a customer to show their order(s)

    <asp:DropDownList ID="customerSelect" AutoPostBack="true" runat="server" OnSelectedIndexChanged="customerSelect_SelectedIndexChanged"></asp:DropDownList>

I want the options in the drop down to be populated from a database of customer names.
Here is what my database looks like

Here is my code behind
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        populateDropDown();
        customerSelect_SelectedIndexChanged(null, null);
    }
}

public void populateDropDown()
{
    SqlCommand cmd = new SqlCommand("SELECT * FROM [Orders]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
    cmd.Connection.Open();

    SqlDataReader ddlValues;
    ddlValues = cmd.ExecuteReader();

    customerSelect.DataSource = ddlValues;
    customerSelect.DataValueField = "OrderID";
    customerSelect.DataTextField = "CustomerName";

    cmd.Connection.Close();
    cmd.Connection.Dispose();

}

I've used this code before. So I must be missing something simple but I'm not sure what it is.
EDIT
I am getting no errors. The code compiles. But the drop down list remains blank.

A: Well, I think you forget to bind your dropdownlist like;
customerSelect.DataBind();

And use using statement to dispose your SqlCommand, SqlConnection and SqlDataReader instead of calling .Dispose() method manually.
using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = con.CreateCommand())
{
    ...
    ...
    using(SqlDataReader ddlValues = cmd.ExecuteReader())
    {
       ...
    }
}


text:
Q: difference between "bell ringing" & "ringing bell" and " car parked" & "parked car" what's the difference between "ringing bell" & "bell ringing " here:
1- I was awaken by a bell ringing.
2- I was awaken by a ringing bell.
and "car parked" & "parked car" here:
1-there was a car parked outside
2-there was a parked car outside

A:
1- I was awakened by a bell ringing.
2- I was awakened by a ringing bell.

The difference is subtle and contextual. "A bell ringing" is really talking about the bell. You woke up and heard a bell, which you realized was ringing, as opposed to gonging or chiming, I suppose. Or you woke up and heard a ringing, which you realized was coming from a bell, rather than a phone or something else. There isn't really much difference between the two without knowing what comes after this scene, or what has come before. If this is part of a larger story, for example, either the bell or the ringing could be important to the characters, and making the distinction is important.
The same is true with "car parked" and "parked car." Their order tells us which part is more important. Do we need to know that it's a car that's parked outside, or do we need to know that the vehicle outside is parked, in which case the fact that it's a car is secondary.
Maybe there's more to this on a grammatical level, and someone else could explain the mechanics of this more precisely, but as a fiction writer, this is how I see and use the difference.

A: There is another difference in meaning that the other answer didn't provide.

a bell ringing

This could be interpreted as an event: "We're going to have a real bell ringing." In other words, one or more people are actually involved in the act of ringing a bell.

a ringing bell

This simply means that there is a bell that is ringing. It may or may not be the case that somebody is ringing it. Potentially, there could be a device inside the bell that is causing it to ring—or it could be that it's designed in such a way that it's already been rung but the sound is continuing for some time afterwards.
A similar analysis could be given for a car parked (verb) and a parked car (noun).

A: *

*I was awakened by a bell ringing. = I was awakened by a ringing sound (which was made by a bell).

*I was awakened by a ringing bell. = I was awakened by a bell (which was ringing).

These sentences have very similar meanings. The first sentence is saying that the ringing sound woke you up, and the second sentence is saying that the bell woke you up. Usually, these have the same meaning.
However, suppose that a bell is ringing quietly, so that it doesn't wake you up, but then the bell falls on your head while it is still ringing, and the blow to your head wakes you up. Then it would be accurate (but strange) to say "I was awakened by a ringing bell", but it would not be accurate to say "I was awakened by a bell ringing."

*

*There was a car parked outside. = There was a car, and the car was parked outside.

*There was a parked car outside. = There was a parked car, and the car was outside.

The first sentence is saying one thing about the car: it's saying that the car is parked outside.
The second sentence is saying two things about the car: it's saying that the car is parked, and that it is outside.
In practice, these two sentences mean exactly the same thing. However, the first sentence is the common way to say this; the second sentence sounds a little strange.


text:
Q: Good way to handle ability usage within a multiplayer game? I have written a client<>server based multiplayer game and have finished the basics (it's a flash client written in actionscript 3). The next step will be implementing a system which will allow me to easily add abilities to the game.
The problem here is that an ability can do so many things. Eg. player A uses ability "repair" on player B, the following will have to happen:

*

*Player A sends message to server informing about the action

*Player A is now showing a "repair casted" animation on its own ship

*The server has to inform all players near that ship A now has the "repair casted" animation

*The server has to increase the "health" of player B because it has been repaired by player A

*The server has to inform all nearby players that player B now has a different health value

*The server has to inform all nearby players that player B should show the "being repaired" animation

That's just an example, a lot of things have to happen for 1 simple ability. I could go into every object and add lines of code just for this spell. However, that would become a mess when I need to add a lot (~50) abilities. Also notice that some abilities do whole other things than others, some will have to show animations, some won't. Some will have to damage, some will have to increase statistics, etc.
So, how is such "ability system" usually handled both client and server side?

A: On client side never do a thing without the consent of the server. So client should only send the request of an ability and an optional target or some value. Also client should have to listen server for any commands. On the other hand, server should implement a function or classes (whatever you feel comfortable) to control ability actions. Whenever a client requests an ability to cast ability function should be called. As first task, function should check prerequisites. If they fail, client should be notified. Otherwise, a use repair ability ok signal should be passed to client. Then the function finds and send required commands to any nearby ships while updating their statuses. This method will guarantee that abilities cannot be abused by clients.
To understand it check the following, this is for illustration of the method, so dont tell me its not good to use so many ifs.
Client
function massRepair() {
    server.send("USE mass_repair;"); //no decisions in here
}

function recive(command, target) {
    if(command=="USE mass_repair OK")
        massRepairAnim.gotoAndPlay(0);

    if(command=="ANIM mass_repair") {
        massRepairAnim.setTarget(target);
        massRepairAnim.gotoAndPlay(0);
    }

    if(command==/SET ENERGY [0-9]/) {
         value=getValue(command);
         setEnergy(value);
    }

    if(command==/SET HEALTH [0-9]/) {
         value=getValue(command);
         setHealth(value);
    }

    if(command=="ANIM self_repair") {
        selfRepairAnim.gotoAndPlay(0);
    }

    if(command=="USE mass_repair FAIL NOENERGY") {
        display("Not enough energy to use the skill");
    }
}

somebutton.click=function() { massRepair(); }

Server
function userMassRepair(Ship owner) {
    if(owner.energy<30) {
        send(owner, "USE mass_repair FAIL NOENERGY");
        return false;
    }

    owner.energy-=30;
    send(owner, "SET ENERGY "+owner.energy); //every data sent is absolute
    send(owner, "USE mass_repair OK");

   foreach(ship in owner.shipsInRange(100)) {
        if(owner.ally(ship)) {
             ship.health+=10;
             ship.send("SET HEALTH " + ship.health);
             ship.send("ANIM mass_repair "+owner.position);
             ship.send("ANIM self_repair");
        }
   }
}

A: It looks like a lot of things, but it's really just a permutation of several standard components. Most actions will consist of changes to intrinsic properties and some cosmetics to be shown on the client, and there are only a handful of different ways to do those.
You need something like the following:

*

*a standard way of sending actions to the server, which allows for convenient extraction of arbitrary parameters (as each action may have some very specific arguments)

*a message type from server to clients to start playing a specified animation on a specified ship

*a message type from server to clients increasing the health value on a ship

Then your server code for the action you mention looks like this pseudocode:
if (message.type == REPAIR)
{
    repairer = message.actor;
    repaired = message.target;

    // Insert verification code here to check that the 2 ships are close enough,
    // that the repairer is entitled to perform this action, etc

    // Verification has passed: do the work
    broadcastToAllClients(new Message(type=PLAY_ANIM, target=repairer, value=REPAIR_CASTED));
    broadcastToAllClients(new Message(type=CHANGE_PROPERTY, target=repaired, proerty=HEALTH, value=5)); // 5 is the amount
    broadcastToAllClients(new Message(type=PLAY_ANIM, target=repaired, value=BEING_REPAIRED));
}

That is very easy to extend to any number of actions, and will just require a few extra message types to accommodate the different things that can change or can be displayed.


text:
Q: CSS3 Border Radius e Background no IE 11 Olá, estou enfrentando um problema com border-radius e background no Internet Explorer 11, ele coloca uma leve borda branca, neste caso, ela fica em cima do border-shadow, porém, se eu tirar os efeitos do box-shadow, continua uma sombra azul quase branca em baixo do botão.

Alguém já passou por isso e tenha idéia de como resolver?


text:
Q: ProtoBuff.NET WCF - Incorrect wire-type error on client We are using ProtoBuff.NET with our WCF service. ProtoBehavour has been applied to the interface, ProtoContract has been applied to the class & ProtoMember has been applied to the properties.
On the client side we have added the protobuff behavior to the app.config as below however when the client requests a object via the WCF service we receive a incorrect wire type error.
Removing the ProtoBuff behavior on the service results in the service working fine.
Can anybody please shed some light on what is happening or point us in the right direction.
We are using the NET TCP binding.
Client Configuration
<behaviors>
        <endpointBehaviors>
            <behavior name="ProtoBufBehaviorConfig">
                <ProtoBufSerialization/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <extensions>
        <behaviorExtensions>
            <add name="ProtoBufSerialization" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.480, Culture=neutral, PublicKeyToken=257b51d87d2e4d67"/>
        </behaviorExtensions>
    </extensions>

Example Class
<DataContract()> <ProtoBuf.ProtoContract()> _
Public Class Product
    Private _ID As String
    <DataMember(Order:=1)> <ProtoBuf.ProtoMember(1)> _
    Public Property ID As String
        Get
            Return _ID
        End Get
        Set(value As String)
            _ID = value
        End Set
    End Property

    Private _Name As String
    <DataMember(Order:=2)> <ProtoBuf.ProtoMember(2)> _
    Public Property Name As String
        Get
            Return _Name
        End Get
        Set(value As String)
            _Name = value
        End Set
    End Property

    Private _Supplier As Supplier
    <DataMember(Order:=3)> <ProtoBuf.ProtoMember(3)> _
    Public Property Supplier As Supplier
        Get
            Return _Supplier
        End Get
        Set(value As Supplier)
            _Supplier = value
        End Set
    End Property

    Private _Income_Group As Primary_Income_Group
    <DataMember(Order:=4)> <ProtoBuf.ProtoMember(4)> _
    Public Property Primary_Income_Group As Primary_Income_Group
        Get
            Return _Income_Group
        End Get
        Set(value As Primary_Income_Group)
            _Income_Group = value
        End Set
    End Property

    Private _Margin_Percentage As Decimal
    <DataMember(Order:=5)> <ProtoBuf.ProtoMember(5)> _
    Public Property Margin_Percentage As Decimal
        Get
            Return _Margin_Percentage
        End Get
        Set(value As Decimal)
            _Margin_Percentage = value
        End Set
    End Property

    Private _Cost_Price_exGST As Decimal
    <DataMember(Order:=6)> <ProtoBuf.ProtoMember(6)> _
    Public Property Cost_Price_exGST As Decimal
        Get
            Return _Cost_Price_exGST
        End Get
        Set(value As Decimal)
            _Cost_Price_exGST = value
        End Set
    End Property

    Private _Retail_Price_incGST As Decimal
    <DataMember(Order:=7)> <ProtoBuf.ProtoMember(7)> _
    Public Property Retail_Price_incGST As Decimal
        Get
            Return _Retail_Price_incGST
        End Get
        Set(value As Decimal)
            _Retail_Price_incGST = value
        End Set
    End Property

    Private _Active As Boolean
    <DataMember(Order:=8)> <ProtoBuf.ProtoMember(8)> _
    Public Property Active As Boolean
        Get
            Return _Active
        End Get
        Set(value As Boolean)
            _Active = value
        End Set
    End Property

    Private _Image As String
    <DataMember(Order:=9)> <ProtoBuf.ProtoMember(9)> _
    Public Property Image As String
        Get
            Return _Image
        End Get
        Set(value As String)
            _Image = value
        End Set
    End Property

    Private _Secondary_Income_Group As Secondary_Income_Group
    <DataMember(Order:=10)> <ProtoBuf.ProtoMember(10)> _
    Public Property Secondary_Income_Group As Secondary_Income_Group
        Get
            Return _Secondary_Income_Group
        End Get
        Set(value As Secondary_Income_Group)
            _Secondary_Income_Group = value
        End Set
    End Property
End Class

Server Config Excerpts
Dim TCPBinding As NetTcpBinding = New NetTcpBinding With { _
              .PortSharingEnabled = True, _
              .ListenBacklog = 5000, _
              .ReaderQuotas = New System.Xml.XmlDictionaryReaderQuotas With {.MaxArrayLength = Integer.MaxValue, .MaxBytesPerRead = Integer.MaxValue, .MaxDepth = Integer.MaxValue, .MaxNameTableCharCount = Integer.MaxValue, .MaxStringContentLength = Integer.MaxValue}, _
              .MaxConnections = 10000, _
              .TransferMode = TransferMode.Buffered, _
              .MaxBufferSize = Integer.MaxValue, _
              .MaxReceivedMessageSize = Integer.MaxValue, _
              .ReliableSession = New System.ServiceModel.OptionalReliableSession With {.Enabled = False}, _
              .Security = New System.ServiceModel.NetTcpSecurity With { _
                                                       .Mode = SecurityMode.Transport, _
                                                       .Transport = New System.ServiceModel.TcpTransportSecurity With {.ProtectionLevel = Net.Security.ProtectionLevel.Sign, .ClientCredentialType = TcpClientCredentialType.Windows} _
                                                   } _
          }
.....
Dim endpoint As ServiceEndpoint = ServiceHostObject.AddServiceEndpoint(Contract, TCPBinding, "")
endpoint(New ProtoBuf.ServiceModel.ProtoEndpointBehavior)

A: If you are not sharing the service contract assemblies as suggested in marc's answer then you need a way to make WCF use the ProtoBuf serializer instead of the WCF default serializer in your client code. The problem is the ProtoBuf attribute markings in the service contract will not be in the WSDL document that is normally used to generate the service proxy in the client code.

A: In regard to Marc's comment where he stated that there were ways to make protobuf-net work along with SvcUtil or "Add Service Reference" VS command, I found this post, where he says:

Re Order=..., it would be worth checking the contents; if they are coming up with different numbers, there are ways to fix this via a partial class - an ugly hack, but IIRC there is ProtoPartialMember (or similar) that can be applied to the class, but which talks about an individual member (property/field).

Then there is this post, where he says:

There are 2 options for fixing this; the first (and easiest) is to use WCF's ability to share a contract assembly between client and server. If you can share the DTO layer, that'll keep things simple.
The second is to add additional markers at the client to give it a clue. You can do this via a partial class, for example in a separate code file (don't edit the generated file):

namespace YourNamespace {
    [ProtoContract(DataMemberOffset = 1)] /* shift all DataMember orders */
    public partial class tbEmployee {}
}

a more explicit alternative is:

namespace YourNamespace {
    [ProtoPartialMember(1, "EmployeeID")]
    [ProtoPartialMember(2, "EmployeeName")]
    public partial class tbEmployee {}
}


text:
Q: Отзывы и База данных Ребят проблема такая, все работает, но я не знаю как сделать так, чтобы если скопилось много отзывов перекидывало на другую страницу, точнее оставалось на той же странице, но уже например на 2 нумерации и тд, например 1 2 3 4 5 6 7 и тд, когда будет достигнут лимит отзывов должно следующий отзыв перекидывать на 2 страницу и тд, как это осуществить с этим кодом, нужен алгоритм на php или что, НАДЕЮСЬ НА ВАШУ ПОМОЩЬ БРАТЦЫ!)) Заранее спасибо.
index.php.

    <?php

     require "shout.php";

    ?>
    <DOCTYPE html>

        <title></title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <form method="post" action="add_comment.php">

        Name
        <input  type="name" name="name" class="form-control" id="exampleFormControlInput1" style="margin-left:15px; width:50%"  placeholder="name">

        Example textarea
        <textarea style="width:50%; margin-left:15px;" class="form-control" id="exampleFormControlTextarea1" rows="7" name="content"></textarea>

        <button class="btn btn-dark" style="margin-left:15px; ">Send</button>
    </form>

          <?php
        $comments = getAllComments();
        if($comments!=null){
        foreach($comments as $n){
        ?>

        <?php echo $n['name']; ?> at <?php echo $n['post_date']; ?>

         <?php
        echo htmlspecialchars($n['content']);
        }
        }
        ?>

/////////////////////////////////////////////

shout.php

 <?php

  $connection = new PDO('mysql:host=localhost;dbname=Ors','root','');

        function addComents( $name, $content){
           global  $connection;
        $query = $connection->prepare("
            INSERT INTO comments (id, name, content, post_date)
            VALUES (NULL, :name, :content, NOW())
        ");

        $query->execute(
            array(
                "name"=>$name,
                "content"=>$content
            )
        );
        }

function getAllComments(){

    global $connection;

       $query = $connection->prepare("
                    SELECT * FROM comments
                ");

                $query->execute();

                $result = $query->fetchAll();

    return $result;

    }

?>

////////////////////////////////////////////

add_comment.php

     <?php
if($_SERVER['REQUEST_METHOD']=='POST'){

require "shout.php";

    if(isset($_POST['content'])&&isset($_POST['name'])){

        addComents( $_POST['name'], $_POST['content']);

    }
}

header("Location:index.php")

?>


text:
Q: DateTime.Ticks property value Shouldn't the value of DateTime.Now.Ticks be the same as DateTime.UtcNow.Ticks? I checked their values and found that the difference represents my current time zone offset from UTC. What am I missing here?

A: This is part of how the objects were designed.
In other libraries and languages (for example, JavaScript's Date type), the value is bound to UTC, and usually uses an epoch of 1970-01-01.
But in .NET, the Ticks value is related to the same frame of reference that the Years, Months, Days, and other properties are based on.  It uses an epoch of 0001-01-01.
In DateTime, there's a property called Kind:

*

*If the kind is DateTimeKind.Utc, then you know the value is related to UTC.

*If the kind is DateTimeKind.Local, then you know the value is related to the local time zone.

*If the kind is DateTimeKind.Unspecified, then you have no idea what time zone reference you have.  You simply have a date and time.

You see the difference between DateTime.UtcNow.Ticks and DateTime.Now.Ticks as your current time zone offset, because DateTime.Now has Local kind, while DateTime.UtcNow has Utc kind.  So the ticks of DateTime.Now are based on your local time zone, while ticks from DateTime.UtcNow are based on UTC.
The DateTimeOffset type can be used to counteract this problem.  The Ticks are still relative to the value shown, but the Offset can be used to always adjust these ticks back to a UTC frame of reference.
If you don't like this, as many do not, an alternative is to use types from the Noda Time library.
By the way, I cover this information in even greater detail, and compare it to other programming languages in my Pluralsight course, Date and Time Fundamentals.

A: It's different because the time zones are different.