text:
Q: Characterizing polyhedron from Brownian particle collisions with a boundary Please imagine that we have an ordinary 2-sphere, of radius $r_{sphere}$, and some three-dimensional polygon that has all of its points fixed at positions strictly internal to the sphere's surface.  Also confined in the sphere is point-like particle (with diffusion constant, $D_{particle}$) undergoing Brownian motion.  The surface of the 2-sphere, as well as the surface of the polygon internal to the 2-sphere, are perfect reflecting boundaries for the particle.
Working in discrete time, we track the point-like particle for $N$ finite time units (we'll call them seconds), $(t_1, t_2, ..., t_k, ..., t_N) \in T$.  However, during this time the only information we are allowed to record is:

*

*If a collision between the probe and the surface of the 2-sphere occurs at a given time point, $t_k$.

And if there is at least one such collision during $t_k$...

*

*The coordinates of a collision event on the surface of sphere, randomly selected from all collisions that occur during $t_k$.

Beyond, perhaps, the volume of the polygon in the sphere (and I'm not entirely sure this is learnable), how (if at all possible) can we use the information specified above to characterize the polygon in some additional manner?
Update - If we apply a further restriction that the polyhedron is convex, at the limit of large $N$ will there be enough information from the collisions to reconstruct the convex polyhedra?


text:
Q: Caffe docs:"Use multiple classification threads to ensure the GPU is always fully utilized". How? In the end of the "Classifying ImageNet: using the C++ API" tutorial (http://caffe.berkeleyvision.org/gathered/examples/cpp_classification.html) I found such phrase:

Use multiple classification threads to ensure the GPU is always fully
  utilized and not waiting for an I/O blocked CPU thread.

What do they mean by that?
I understand right, that there is a way to use multiple threads for CPU layers while running on the one GPU?
Thanks

A: You can use multiple threads on one GPU using CUDA and CUDNN.
As example, of the CUDA programming guide:
The following code adds two matrices A and B of size NxN and stores the result into matrix C:
// Kernel definition
__global__ void MatAdd(float A[N][N], float B[N][N],
                       float C[N][N])
{
    int i = threadIdx.x;
    int j = threadIdx.y;
    C[i][j] = A[i][j] + B[i][j];
}

int main()
{
    ...
    // Kernel invocation with one block of N * N * 1 threads
    int numBlocks = 1;
    dim3 threadsPerBlock(N, N);
    MatAdd<<<numBlocks, threadsPerBlock>>>(A, B, C);
    ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add text to label(not changing) in Xcode Is it possible to add on to the text of a label without changing existing text? I'm new to mac development in Xcode so any help is appreciated.

A: Yes and no. Basically, you replace the text with a new string that includes the old text
self.myLabel.text = [self.myLabel.text stringByAppendingString:@"more stuff"];


text:
Q: Procedure not working create table Train_Types
(
id int not null primary key,
name varchar(50) not null
)

create table Trains
(
id int not null primary key,
name varchar(50) not null,
trainTypeId int not null foreign key references Train_Types(id)
)

create table Stations
(
id int not null primary key,
name varchar(50) not null
)

create table Routs
(
id int not null primary key,
name varchar(50) not null,
trainId int not null foreign key references Trains(id)
)

create table Routes_Stations
(
stationId int not null foreign key references Stations(id),
routeId int not null foreign key references Routs(id),
arrivalDate datetime not null,
departureDate datetime not null
)

create procedure addStation @stationId int, @routeId int, @arrivalTime datetime,
                            @departureTime datetime
as
begin
insert into Routes_Stations (stationId,routeId,arrivalDate,departureDate)
values (@stationId, @routeId, @arrivalTime, @departureTime)
end
go

So here I basically have a train-schedule database . I tried to make a procedure that receives a station, a route , an arrival and a departure time and adds this new station to the route. My problem is that when I write this
exec addStation 1,4,'18:00','18:05'

I get this error :

Msg 547, Level 16, State 0, Procedure addStation, Line 5
  The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Routes_St_stati_1DE57479". The conflict occurred in database "Train Schedule", table "dbo.Stations", column 'id'.

I don't understand what it says. Can someone help me fix it please I'm new to databases
Now that I fixed my problem I try to modify this procedure so that if the station that I want to insert already exists I just update the arrival and departure time . So far I wrote this but I'm stuck , I don't know how to assign the total nr. of stations to a variable.
create procedure addStation @stationId int, @routeId int, @arrivalTime datetime,
                            @departureTime datetime
as
begin
declare @isStation_inRoute int
set @isStation_inRoute = 0

select *from Routes_Stations where stationId = @stationId
and routeId = @routeId
@isStation_inRoute = count(*)
insert into Routes_Stations (stationId,routeId,arrivalDate,departureDate)
values (@stationId, @routeId, @arrivalTime, @departureTime)
end
go

A: The error says: you're trying to insert a row into dbo.Routes_Stations with a value for StationId that doesn't exist in the referenced  dbo.Stations parent table.
It seems you're trying to insert a stationId = 1 value - and judging from the error, that Station with that Id value doesn't exist.
This behavior is the whole point of foreign key constraints: you cannot insert data that doesn't match the FK relationships. Those would be "ghost records", routes pointing to a station that doesn't exist. You need to make sure to insert only valid values into your foreign key column!


text:
Q: Cannot post the var to another php file successfully I have a php file A.php contained a form called formA .
The formA get the result and then post and store into the MYSQL through php & SQL & traditional HTML form posting method .
In one of the field in formA ,I want to post this value $amountto another php file B.php .It is because there is a hidden form in B.php .I tried to post this with php-curl method for further action .
In the B.php , I tried to test whether I can get the $amount successfully.

Both print_r($_POST); print_r($_GET); show   Array ( ) Array ( ) ,which means that fail to get the amount

Here is my code :
A.php:
if ($_SERVER["REQUEST_METHOD"] == "POST") {

  // Validate amount
    $input_amount = trim($_POST["amount"]);
    if (empty($input_amount)) {
        $amount_err = "Please enter the amount.";
    } elseif (!ctype_digit($input_amount)) {
        $amount_err = 'Please enter a positive integer value.';
    } else {
        $amount = $input_amount;
    }
//storing to db
 if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
        // Prepare an insert statement
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";

        $q = $pdo->prepare($sql);
        $q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
        Database::disconnect();

        //curl part start:  post the `amount`
        $ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"B.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "amount=amount,input_amount=input_amount");

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

    header("Location: B.php");
}

}
?>

//Form A -the field that get the `amount` value

    <div class="form-group <?php echo (!empty($amount_err)) ? 'has-error' : ''; ?>">
                                 * Donation amount
               <input list="amount" name="amount"  multiple class="form-control">
   <datalist id="amount" >
    <option value="100">
    <option value="300">
    <option value="500">
    <option value="1000">
  </datalist>
                     <?php echo $amount_err; ?>

....other fields. ....

B.php:
<?php
print_r($_POST);
print_r($_GET);
    $amount = null;
    if ( !empty($_GET['amount'])) {
        $amount = $_REQUEST['amount'];
    }
     ...later  action....

?>

How to tackle this problem ?

A: Your CURLOPT_POSTFIELDS value is incorrectly formatted, and does not contain the values you're expecting. The encoding of your values needs to be in what's known as application/x-www-form-urlencoded. Essentially, variables separated by &.
David Walsh has a terrific example here.
Your string should look something like this. "amount=".$amount."&input_amount=".$input_amount


text:
Q: Only allowing certain characters I am in the process of creating a form and I wish to validate the input fields onKeyPress. I have managed to find JavaScript to restrict a field to only allowing numbers to be entered. Now I am trying to adapt that code to only allow letters and a hyphens to be allowed.
The code I have to only allow numbers is as follows...
     function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
   }

How would I adapt and change this to only allow letters and hyphens instead.
Sorry if this question has been asked  before but all I can find is doing it using Jquery etc. and I would like to try and avoid that if I can.
Thanks in advance

A: var myRegex = /^[A-Za-z\-]+$/;

myRegex.test('hello'); //true
myRegex.test('asdasd-adasd'); //true
myRegex.test('123as'); //false


text:
Q: Delphi 7 and Indy 9 writing data from TCPServer I have a Delphi program which sits as a server receiving data and sending back small  acknowledgement packets.  I previously used this code (edited for brevity)
procedure TdmServer.OnExecuteTCPServer(AThread: TIdPeerThread);
var
  IncomingPacket : string;
  ResponsePacket : string;
begin
  IncomingPacket := AThread.Connection.Readln(#$03);

  if IncomingPacket <> '' then
  begin
    ResponsePacket := ProcessTelegram(IncomingPacket);

    AThread.Connection.writeln(ResponsePacket);
  end;

  AThread.Connection.Disconnect;
end;

This almost works fine, apart from appending an end of line CRLF as it sends, which the client (not under my control) doesn't like.
So I changed it to:
AThread.Connection.Write(ResponsePacket);

and nothing is received on the client.
Then I tried
AThread.Connection.WriteBuffer(ResponsePacket, length(ResponsePacket), true);

to try and get it to write immediately,  but it still doesn't send at all.
I have put in delays, tried opening the buffer, flushing and closing it again (like the help file), but still no joy and any time FlushWriteBuffer is called I get an AV.
I'm stuck. Please could anyone offer any words of wisdom?

A: ReadLn() strips off the terminator from its Result. Is your ProcessTelegram() accounting for that?  If it needs the terminator, you will have to add it back in manually, eg:
ProcessTelegram(IncomingPacket + #03)

Is ResponsePacket being formatted correctly for what the client is expecting? If the client is not expecting a terminating CRLF, then using Write() instead of WriteLn() is the correct thing to do.
If you use WriteBuffer(), you must dereference a String in order to pass the correct data address to WriteBuffer(), eg:
WriteBuffer(ResponsePacket[1], Length(ResponsePacket), True)

Or:
WriteBuffer(PChar(ResponsePacket)^, Length(ResponsePacket), True)

If the client is still not receiving the response correctly, then either you are not sending anything at all, or you are not sending the terminator that the client is expecting.  Use a packet sniffer, such as Wireshark, to see what the client is actually receiving, if anything.


text:
Q: OSX cmd+tab behavior with multiple windows of same application and monitors First of all, my question is not answered in any of the questions with the similar titles. My context is a little different.
I have 2 monitors connected to my MacBook Pro. I opened 2 windows of Safari, one for each monitor.

*

*On 1st monitor, there's a Safari window and Application A.

*On 2nd monitor, there's the 2nd Safari window and Application B.

*2nd monitor is focused on Application B.

*1st monitor is focused on Application A.

*On the 1st monitor, I switch from Application A to Safari using cmd+tab and 1st monitor successfully focuses on it's own Safari window.

*But 2nd monitor also switches to it's own Safari windows instead of keeping the Application B on the screen.
How can I prevent this from happening so 2nd monitor doesn't switch to Safari as well and instead keep it's application on its screen?
I already tried all the combinations from Mission Control page but none of them helped me achieve this. Or maybe they didn't work as they intended to be, I'm not sure if that's the case.

A: You're trying to fight the basic paradigm. Bringing an app to the front… brings it all to the front, no matter which screen it's on.
The simplest workaround I could think of would be to use a different browser app on each screen.

A: A way to ignore the Apple paradigm is to use one of the suggestions in Best app to switch between all open windows
These basically make ⌥TAB behave as  CmdTAB does in Microsoft Windows, that is the keypress switches between windows independent of which app they are from only bringing one window to the front.


text:
Q: "Fixed" Strange "unrecognized selector sent to instance" crash happens on iOS8 beta5 My app works fine on iOS7,but crashes on iOS8.
I've seen various question on this topic but never found a good solution for it.
I have an App that's using UITableViewController and UITableViewController has an SearchDisplayController instance call m_searchDisplayController.
When firstly I click on the search bar to search something, the table-view then show the result, and the search bar resignFirstResponder.But again I click on the search bar,the app crashes:
-[MyFavoritesViewController _searchController]: unrecognized selector sent to instance

Here is the stack:

Then I try to add _searchController method to MyFavoritesViewController class,like this:
 - (UISearchDisplayController *)_searchController
 {
      return nil;
 }

Then app works OK except search bar's textField cannot be inputing.So I try this:
 - (UISearchDisplayController *)_searchController
 {
      return m_searchDisplayController;
 }

And another crash message shows:
-[UISearchDisplayController _searchBarShouldFinalizeBecomingFirstResponder]: unrecognized selector sent to instance

I don't know how to locate the error code, and anyone has solution about this? Thanks in advance.
My situation:
I do some hack in UISearchBar and I change the delegate of searchBar's textField to some object.Originally, the "_searchController" method of system will call to delegate of searchBar's textField, but now, it will call to my object and then crash. I hope it helps.

A: If you're trying to respond to the clear button being tapped by assigning a delegate to the UISearchBar textField this breaks in iOS8. Try another technique.
Maybe the UISearchBarDelegate's method
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    // fired whenever the text is changed, or clear tapped
    if (searchText.length == 0) {
       // Do something
    }
}

Now if you need to respond differently to a last backspaced key then you will have to figure some work around, like responding to a backspace key, or adding an invisible character that the backspace can't remove, but the clear does remove. These are just 2 suggestions.

A: I've got the same problem.
Compile your project with SDK 8.0+ and the problem will disappear.
No code changes required.
Another solution, do not assign UITextField that is in UISearchBar delegate and that additional functional (if you have) move to other places.


text:
Q: How to collapse adjacent rows, grouping by some column? I want to get statistics from some chat by messages per user. But I want to group adjacent messages. If user writes 3 messages one by one it counts as one.
For example, I have these records:
id  user   message
 1   1      text1
 2   1      text2
 3   2      text3
 4   3      text4
 5   1      text5
 6   2      text6
 7   2      text7
 8   3      text8
 9   1      text9
10   1      text10
11   1      text11
12   3      text12

I need to get this result:
user
  1
  2
  3
  1
  2
  3
  1
  3

I expect to get subquery results with collapsed messages and then run query with "group by" for getting all stats.
I tried to run
SELECT * FROM messages GROUP BY user ORDER BY id

but it groups all messages by one user:
id   user
 1    1
 3    2
 4    3

A: E.g. (although in practice I'd be tempted to solve this kind of problem in application code):
SELECT MAX(user) user
     , i
  FROM
     ( SELECT user
            , CASE WHEN @prev = user THEN @i:=@i ELSE @i:=@i+1 END i
            , @prev:=user
         FROM my_table
            , (SELECT @prev:=null, @i:=0) vars
        ORDER
           BY id
     ) x
 GROUP
    BY i;

or...
SELECT DISTINCT user, i
  FROM
     ( SELECT user
            , CASE WHEN @prev = user THEN @i:=@i ELSE @i:=@i+1 END i
            , @prev:=user
         FROM my_table
            , (SELECT @prev:=null, @i:=0) vars
        ORDER
           BY id
     ) x
 ORDER
    BY i;


text:
Q: vector / matrix library for OpenGL ES 2.x app I'm looking for a free 3D vector / matrix library that handles canonical operations ala the OpenGL specification and GLU (dot, cross, rotations, translations, inversions, look at, etc).  This will be used with ES 2.x+ apps.  GLU and GLUT are not available.
Platform is iphone OS 4.1 sdk.
Seems like a waste of time to write one of these from scratch but will if necessary.
Thanks.

A: you can get the source to GLU and port it yourself. it's really just a matter of changing double to float and including it in your project.


text:
Q: SSIS 2005 running in SQL Server Agent on local PC connecting to database on remote server produces error I'm trying to run an SSIS 2005 package from a SQL Server Agent job on my local PC. This package is attempting to connect to a SQL Server 2005 database on a remote server, but it gets the error message, Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.  What is the problem and how can I solve it?

A: you can create a SQL job to run the start_execution command and then the process will run under the user running the job.
the approach is explained here.

A: The problem is that the SSIS package is being executed under the NT credentials of the account running the SQL Server Agent service (likely to be either your local PC's "local system" or "network service" account), and is attempting to connect to the remote SQL instance with windows integrated security. This fails because the remote SQL server cannot authenticate the service account as permitted to connect.
When you developed it, the package was connecting to the remote SQL server using your NT credentials (a domain account which the remote SQL server could authenticate).
The quickest fix will be to change the service account under which your SQL Server Agent service runs to a domain account with rights to connect to the remote SQL server. To prove that this is the issue you could use your own domain account for this, although this isn't really a long term solution.

A: Another thing to consider if above fails is "hop count". If I try to run a SP from a local machine that is connected to remote DB that is trying to connect to another remote DB. I will get the error above. However, if I remote connect to the primary server first, then run the SP with the remote connection, it works fine.


text:
Q: Multi page Word tables to PowerPoint while preserving headers I have a macro that moves all pictures and tables to a PowerPoint while capturing the figure name and number as well as the table name and number. I am pasting the tables in as .Shapes.PasteSpecial(ppPasteMetafilePicture).
This has worked great in the past but I have come across about 150 documents that need to be converted that contain tables that span more than one page. When the macro pastes the table it cuts off at the first page.
If I split the table using the macro it does not carry over the headers.
What I want is to be able to do is split this table into multiple slides per Word document page that it is on and include the headers of the table.

A: Since you're pasting as a picture the only possibility is to EDIT the Word tables. You'd need to read how many rows comprise the table header, copy those rows, deactivate the table header setting, then paste the row(s) at the top of each page. Then you can copy each page. At the end, close the document without saving so that the original still has the table headers.


text:
Q: fragment inside fragment in MainActivity I hav an activity and inside it I have a fragment (A) that holds fragment (B) and in fragment (B) I have a button that goes back to fragment (A).
The problem is that I want to go back to my MainActivity from fragment (A) that came from that button in fragment (B).
it takes 3 onbackpressed to go back to MainActivity
I just want to go back in 1 onbackpressed

A: Open fragment with TAG, because you check fragment is currently open or not by using TAG
    IntroFragment introFragment = IntroFragment.newInstance(activity);
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.frame, introFragment, "INTRO");
    ft.commit();

in fragment to open fragment replace getSupportFragmentManager() with getChildFragmentManager()
Remove fragment using below code
Fragment oldFragment = getSupportFragmentManager().findFragmentByTag("INTRO");
if (oldFragment != null)
    getSupportFragmentManager().beginTransaction().remove(oldFragment).commit();

Place your own logic in your activity onBackPressed();


text:
Q: Kinetic energy in Lagrangian formalism In reading Goldstein's Classical Mechanics (2nd edition) I came across a confusing derivation. Goldstein (Eq. 1-71) derives the total kinetic energy of a system of (classical) particles as:
$$ T = \sum_i \frac{1}{2}m_iv_i^2 = \sum_i \frac{1}{2}m_i \left( \sum_j \frac{\partial \mathbf{r}_i}{\partial q_j} \dot{q}_j + \frac{\partial \mathbf{r}_i}{\partial t}\right)^2 $$
Where the $q_i$ are the generalized coordinates. He then expands the square to obtain three terms:
$$ T = M_0 + \sum_j M_j\dot{q}_j + \frac{1}{2}\sum_{j,k} M_{jk} \dot{q}_j\dot{q}_k $$
Where $M_0$ only carries the time dependency of $\mathbf{r}$ on $t$, $M_i$'s carry linear dependence on $\frac{\partial \mathbf{r}_i}{\partial q_k}$, and $M_{i,k}$ carry the quadratic dependence.
Goldstein then claims that if the transformation equations do not contain the time explicitly, then only the last (third) term survives.
I don't understand this. The first two terms consist of $\frac{\partial \mathbf{r}_i}{\partial t}$'s, which are not necessarily zero. Nowhere in this definition of $T$ do I see something like $\frac{\partial q_i}{\partial t}$, which would be zero by Goldstein's assumption. How do the first two terms vanish?

A: Hint: If the transformation equations
$$\mathbf{r}_i~=~\mathbf{r}_i(q_1,\ldots, q_n ,t) \tag{1.38} $$
do not contain the time explicitly, then the explicit time derivative $\frac{\partial \mathbf{r}_i}{\partial t}=0$ is zero. Note that the position $\mathbf{r}_i$ of the $i$'th point particle also depends implicitly on time $t$ through the generalized positions $q_1,\ldots, q_n$.
References:

*

*H. Goldstein, Classical Mechanics, Chapter 1.


text:
Q: Efficient way to search string contains in multiple columns using pandas I have a pandas dataframe like as shown below
import pandas as pd
import numpy as np
df=pd.DataFrame({'Adm DateTime':['02/25/2012','03/05/1996','11/12/2010','31/05/2012','21/07/2019','31/10/2020'],
                 's_id':[1,2,3,4,5,6],
                'test_string_1':['test','Thalaivar','Superstar','God','Favorite','Rajinikanth'],
                'test_string_2':['Rajinikanth','God of Cinema','Favorite','Superstar','Rahman','ARR']})
df['Adm DateTime'] = pd.to_datetime(df['Adm DateTime'])

I would like to check whether a substring is present in any of the columns (test_string_1 and test_string_2)
Though I am able to do for one column like as shown below
df['op_flag'] = np.where(df['test_string_1'].str.contains('Rajini|God|Thalaivar',case=False),1, 0)

Can you help me with how can we do this across both the columns?
Should I repeat the above code with a different column name?
Is there any way to provide the column names that I would like to check for in the code?

A: You can do this with a lambda function
In [40]: df[['test_string_1', 'test_string_2']].apply(lambda x: x.str.contains('Rajini|God|Thalaivar',case=False)).any(axis=1).astype(int)
Out[40]:
0    1
1    1
2    0
3    1
4    0
5    1
dtype: int64


text:
Q: PhoneGap 3: Exclude folders from being copied to the platforms I'm using PhoneGap 3.x and to develop the UI I'm using some npm tools like Grunt and Bower. These tools generate some folders with downloaded content (node_modules and bower_components) that, when copied to a platform folder, make my app heavier (~40MB more).
Is there any way to tell phonegap to exclude certain files/folders when building the app for any platform in specific or in general?

A: Found no way to prevent the folder from being copied, added a script instead under hooks/after_prepare/cleanup_platform.sh:
rm -rf ./platforms/ios/www/node_modules

They just on the console:
chmod a+x hooks/after_prepare/cleanup_platform.sh

This will delete the undesired files from my platform slimming my app package.
Note that I'm posting this answer as a reference/temporal/straightforward solution that would work on UNIX workstations; per the hooks README, this script has to be rewritten in node in order to be cross-platform: http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/


text:
Q: How to delete text from Tkinter? I want to know how do u delete text inside the Tkinter. The text is circled in red.
My code is as below:
from tkinter import *
from tkinter.ttk import Combobox
import win32com.client

root = Tk()
root.title('PM1 Digital Checklist')
root.geometry("400x400")

def open_excel():
    if combo.get() == 'PPM8001':
        myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
        myLabel = Label(root, text=combo.get()).pack()
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = True
        file = excel.Workbooks.Open(r"/path/to/PPM8001.xlsx")

    if combo.get() == 'PPM8002':
        myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
        myLabel = Label(root, text=combo.get()).pack()
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = True
        file = excel.Workbooks.Open(r"/path/to/PPM8002.xlsx")

    if combo.get() == 'PPM8003':
        myLabel = Label(root, text="Prime Mover Number Selected is:").pack()
        myLabel = Label(root, text=combo.get()).pack()
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = True
        file = excel.Workbooks.Open(r"/path/to/PPM8003.xlsx")

options = ['PPM8001','PPM8002','PPM8003']

v = list(options)

combo = Combobox(root, values = v, width =40)
combo.set("Select which Prime Mover number")
combo.pack()

button = Button(root, text = "Select", command = open_excel).pack()

root.mainloop()

The image is here:

A: There are 2 things to fix:

*

*use

myLabel = Label(root, text="Prime Mover Number Selected is:")
myLabel.pack()

To actually put a Label instance into a variable

*use

myLabel.destroy()

To get rid of it.
Hope that's helpful!


text:
Q: Can't get jQuery to fire when HOTSPOT is clicked I tried numerous suggestions, but nothing worked with my particular jquery. This script hides the double scrollbar when my popup is opened. It works great on regular images. But I can't get it to fire from a hotspot/map. I tried putting my class "pop-open" in the image tag, area tag, and even the map tag lol. Can somebody help me? Thx in advance.
<map name="hotspot"><area class="pop-open" shape="rect" coords="0, 0, 150, 200" href="#pop_vid"></map><img src="example.com/images/whatever.png" usemap="#hotspot">

$(document).ready(function(){
$('.pop-open').click(function() {
        $('body').css({
        'overflow': 'hidden',
        });
    });
$('.lightbox').click(function() {
        $('body').css({
        'overflow': 'visible',
        });
    });
});

p.s. If somebody can tell me how to put 2 selectors in where I have lightbox it would be VERY appreciated. Really I want to use classes close-x and close-btn, but since I couldn't figure it out, I had to set it to close the whole lightbox. I tried this which made neither class work.
$('.close-x, .close-btn').click(function() {

A: This is solved. It actually DOES work. I'm having a conflict with another modal script, that's the issue. Posting a separate question about that. I didn't figure out my p.s. up there ^ but oh well.


text:
Q: Notation of Derivative and Differential Let $\gamma:[a;b] \to U, \gamma(t)=\big(x(t),y(t)\big)$ be a path. The integral of $\omega$ along $\gamma$ is defined as
$$ \int_\gamma \omega := \int_a^b \omega_x\big(x(t),y(t)\big)\dot{x}(t)+\omega_y\big(x(t),y(t)\big)\dot{y}(t)~ dt$$
where $\dot{x}=\frac{dx}{dt}$, $\dot{y}=\frac{dy}{dt}$.
My Question:
What does $\dot{x}=\frac{dx}{dt}$ exactly mean? And could I replace it with $\dot{x}=\frac{\partial x}{\partial t}$?


text:
Q: Table view content jumping down when using UIRefreshControl and setting contentInset So I have standard subclass of UITableViewController with table view. Now I have set content inset to
self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);

I'm also using UIRefreshControl in standard way.
self.refreshControl = [[CTRefreshControl alloc] init];
[self.refreshControl addTarget:self action:@selector(loadData:) forControlEvents:UIControlEventValueChanged];

All works fine and smoothly if table view contains enough data that it scrolls(so content size height is more than table view's height). When there is not enough data in table (e.g. only 2 rows) then when I start to pull down it goes smoothly and then suddenly it jumps by about 20 points down. Same thing happens when I scroll other direction. It doesn't happen when there's no refresh control or when I don't change contentInset. Any ideas? All on iOS 6.

A: You need to put the change of contentInset in an animation block like this...
[UIView animateWithDuration:0.2
                      delay:0.0
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);
                 }
                 completion:nil];

(Typed from memory so you may have to check code completion).
This should fix your problem.


text:
Q: Textbook Recommentation: Discrete Differential Geometry are there any good books that provide a good introduction to Discrete Differential Geometry to beginners? Thanks a lot.

A: A quick search turned up Digital Geometry Processing with
Discrete Exterior Calculus and Discrete Differential Geometry: An Applied Introduction, both by Crane.  The content of the two seems to be very similar.


text:
Q: MapBox GL custom markers with symbol layer I am trying to cluster custom markers in MapBox GL JS but I cannot figure out how to get a custom marker image from a url into the symbol layer? It either does not work or no markers show up at all.  How is it done? I need to know how to use a custom image from a url with the symbol layer. Thank you very much.
map.addSource('parcelpoints', {
        type: 'geojson',
        data: geojson,
        cluster: true,
        clusterMaxZoom: 14, // Max zoom to cluster points on
        clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
    });

    map.addLayer({
        id: 'clusters',
        type: 'circle',
        source: 'parcelpoints',
        filter: ['has', 'point_count'],
        paint: {
            // Use step expressions (https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
            // with three steps to implement three types of circles:
            //   * Blue, 20px circles when point count is less than 100
            //   * Yellow, 30px circles when point count is between 100 and 750
            //   * Pink, 40px circles when point count is greater than or equal to 750
            'circle-color': [
                'step',
                ['get', 'point_count'],
                '#51bbd6',
                100,
                '#f1f075',
                750,
                '#f28cb1'
            ],
            'circle-radius': [
                'step',
                ['get', 'point_count'],
                20,
                100,
                30,
                750,
                40
            ]
        }
    });

    map.addLayer({
        id: 'cluster-count',
        type: 'symbol',
        source: 'parcelpoints',
        filter: ['has', 'point_count'],
        layout: {
            'text-field': '{point_count_abbreviated}',
            'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
            'text-size': 12
        }
    });

        map.addLayer({
        id: 'unclustered-point',
        type: 'symbol',
        source: 'parcelpoints',
        filter: ['!has', 'point_count'],
        'layout': {
         'visibility': 'visible',
         'icon-image':  { url: "marker.svg" }
        }
    });

A: First you need to:

*

*load the external image with a specific ID, via map.loadImage().

*add the image with a specific ID, via map.addImage(https://docs.mapbox.com/mapbox-gl-js/api/map/#map#loadimage).

There is a worked example here: https://www.mapbox.com/mapbox-gl-js/example/add-image/
// If the style's sprite does not already contain an image with ID 'kitty',
// add the image 'cat-icon.png' to the style's sprite with the ID 'kitty'.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', (error, image) => {
    if (error) throw error;
    if (!map.hasImage('kitty')) map.addImage('kitty', image);
});

To include your loaded image in a symbol layer will look something like:
map.addLayer({
    'id': 'clusters',
    'type': 'circle',
    'source': 'parcelpoints',
    'filter': ['has', 'point_count'],
    'icon-image': 'kitty',
    ...

There is no support for directly loading symbol images from URLs.


text:
Q: MySQL master-slave replication not updating I set up MASTER->SLAVE database replication. Looks like everything fine, but when I change the master, the slave database is not updated. Exec_Master_Log_Pos on slave is updated when I update master db. I am enable logging on slave
log_output              = "FILE"
general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

In the slave log only these records appear when I apply any changes to the master database:
220129 23:10:33      5 Query    BEGIN
                     5 Query    COMMIT /* implicit, from Xid_log_event */

master
5.7.36-0ubuntu0.18.04.1-log
slave
10.6.4-MariaDB-1:10.6.4+maria~focal-log
On the master the base is called alpha, on the slave - beta
master my.cfg
server-id = 1
log-bin = /mnt/sdb/var/lib/mysql/mysql-bin
binlog_do_db = alpha

slave my.cfg
server-id = 3
replicate-do-db     = beta

master
mysql> SHOW MASTER STATUS\G
*************************** 1. row ***************************
             File: mysql-bin.000006
         Position: 24181
     Binlog_Do_DB: alpha
 Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec)

slave
MariaDB [(none)]> SHOW SLAVE STATUS\G
*************************** 1. row ***************************
                Slave_IO_State: Waiting for master to send event
                   Master_Host: 144.217.157.211
                   Master_User: beta_user
                   Master_Port: 3306
                 Connect_Retry: 60
               Master_Log_File: mysql-bin.000006
           Read_Master_Log_Pos: 24181
                Relay_Log_File: mysqld-relay-bin.000010
                 Relay_Log_Pos: 5097
         Relay_Master_Log_File: mysql-bin.000006
              Slave_IO_Running: Yes
             Slave_SQL_Running: Yes
               Replicate_Do_DB: beta
           Replicate_Ignore_DB:
            Replicate_Do_Table:
        Replicate_Ignore_Table:
       Replicate_Wild_Do_Table:
   Replicate_Wild_Ignore_Table:
                    Last_Errno: 0
                    Last_Error:
                  Skip_Counter: 0
           Exec_Master_Log_Pos: 24181
               Relay_Log_Space: 5407
               Until_Condition: None
                Until_Log_File:
                 Until_Log_Pos: 0
            Master_SSL_Allowed: No
            Master_SSL_CA_File:
            Master_SSL_CA_Path:
               Master_SSL_Cert:
             Master_SSL_Cipher:
                Master_SSL_Key:
         Seconds_Behind_Master: 0
 Master_SSL_Verify_Server_Cert: No
                 Last_IO_Errno: 0
                 Last_IO_Error:
                Last_SQL_Errno: 0
                Last_SQL_Error:
   Replicate_Ignore_Server_Ids:
              Master_Server_Id: 1
                Master_SSL_Crl:
            Master_SSL_Crlpath:
                    Using_Gtid: No
                   Gtid_IO_Pos:
       Replicate_Do_Domain_Ids:
   Replicate_Ignore_Domain_Ids:
                 Parallel_Mode: optimistic
                     SQL_Delay: 0
           SQL_Remaining_Delay: NULL
       Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
              Slave_DDL_Groups: 0
Slave_Non_Transactional_Groups: 0
    Slave_Transactional_Groups: 0
1 row in set (0.001 sec)

The binary log on the master is written after each change of the base. The slave also gets change notifications, but why doesn't the slave base get updated? I have tried this scheme on several servers and the result is always the same.


text:
Q: Python TCP Server Stops Responding After A While So I wrote this python code on my RPI to create a digital poster that talks with my crestron control processor. For some reason my code stops responding after a while. I dont know why. I dont know if my Pi is going to sleep but if anyone could point out anything in my code that could cause this please let me know.
EDIT: I FIGURED IT OUT ON MY OWN. Many thanks to everyone who commented.
I was creating a new FBI process every time i went through the loop, and i ended up using up all of the Pi's RAM until it came to a halt because it didnt have any left. I now kill the FBI process after loading the image which fixed that. Thanks for everyones help.
My Functions and Setup Stuff:
import socket
import os
import thread
import sys
import urllib
from time import ctime
from PIL import Image
import time
import random
import logging

frameBufferCommand = "sudo fbi -a -T 1 -d /dev/fb0 -noverbose "
moviePosterLocation = "/home/pi/movieposters/"
openBlackImage = "/home/pi/movieposters/special/black.jpg"
killFrameBuffer = "sudo killall fbi"
turnOffScreen = "sudo /opt/vc/bin/tvservice -o"
turnOnScreen = "sudo /opt/vc/bin/tvservice -p"

def splitString(input):
    stringList = input.split("/x00/")
    return stringList

def displayRandomPoster():
    displayingPoster = False
    fileCount = next(os.walk(moviePosterLocation))[2] #get the number of available posters
    print('Current # Of Posters in Directory: ' + str(len(fileCount)))

    attemptNumber = 0

    while not displayingPoster:
        posterToDisplay = random.randint(0, len(fileCount))
        print('Trying To Display A Random Poster')
        attemptNumber += 1

        try:
            image = Image.open(moviePosterLocation + fileCount[posterToDisplay]) #open the current image
            width, height = image.size
        except IndexError as msg:
            print("encountered an IndexError while opening an image")
            width = 0
            height = 0
        except IOError as msg:
            print(msg)
        try:
            conn.send(msg)
        except socket.error as msg:
            print("Socket Error")

    if width > height:
        if attemptNumber > 5:
            print("Too Many Attempts, Stopping")
            break
        else:
            print("We Think This Isnt A Poster, Trying Again")
            continue
    else:
        try:
            conn.send("  Displaying Poster: " + str(fileCount[posterToDisplay]))
        except socket.error as msg:
            print msg
        os.system(frameBufferCommand + moviePosterLocation + fileCount[posterToDisplay])
        displayingPoster = True
        return

The thread that is listening, and the main loop:
#-- CLIENT THREAD --

def client(conn):
    try:
        conn.send("Connected With Raspberry Pi")
        os.system(frameBufferCommand + openBlackImage)
    except socket.Error as msg:
        print(msg)

print(str(bindSuccess))

while 1:
    dataReceived = conn.recv(1024)
    reply = "OK.. "
    conn.send(reply + dataReceived)
    dataList = splitString(dataReceived)
    print(dataList)
    if dataList[6] == "":
        print("dataList[6] is empty, displaying a random poster")
        displayRandomPoster()
    else:
        try:
            moviePosterURL = dataList[6]
            splitPosterURL = moviePosterURL.split("%")
            moviePosterFilename = splitPosterURL[7]
            urllib.urlretrieve(moviePosterURL, moviePosterLocation + moviePosterFilename)
            conn.send("XBMC Movie Poster Downloading")
            conn.send("Movie Poster saved as: " + moviePosterLocation + moviePosterFilename)
            print("Movie Poster saved as: " + moviePosterLocation + moviePosterFilename)
        except socket.error:
            print("Encountered Socket Error While Downloading Poster - Line 80")
        try:
            os.system(frameBufferCommand + moviePosterLocation + moviePosterFilename)
            print('Opening Downloaded Poster')
        except OSError as msg:
            print(str(msg[0]) + str(msg[1]))
    if not dataReceived:
        break
    time.sleep(1)

#-- MAIN FUNCTION --

host = ''
communicationPort = 5005

bindSuccess = False

crestronSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Socket Created Successfully")

try:
    crestronSocket.bind((host, communicationPort))
    bindSuccess = True
except socket.Error as msg:
    bindSuccess = False
    print("Socket Bind Error" + msg)
    sys.exit()

crestronSocket.listen(1)
print("Crestron Socket Listening")

while bindSuccess == True:
    #wait to accept a connection - blocking call
    conn, addr = crestronSocket.accept()
    print('Connected with Client: ' + addr[0] + ':' + str(addr[1]))
    thread.start_new_thread(client , (conn,))
crestronSocket.close()

A: I was creating a new FBI process every time i went through the loop, and i ended up using up all of the Pi's RAM until it came to a halt because it didnt have any left. I now kill the FBI process after loading the image which fixed that. Thanks for everyones help.
I also figured out some other things that make it operate better/more seamlessly.


text:
Q: headless with rails selenium-webdriver to take a screen of webpage by linux server I use
gem 'selenium-webdriver'

to take screenshot of web page by my linux server with rails like :
def test
  width = 1024
  height = 728
  driver = Selenium::WebDriver.for :firefox
  driver.navigate.to 'http://google.fr'
  driver.execute_script %Q{
   window.resizeTo(#{width}, #{height});
  }
  driver.save_screenshot("#{Rails.root}/screenshot.png")
  driver.quit
end

I need to execute this without install browser on my server with no display.
how execute this in headless mod?

A: You can test it headless on selenium. In order to do so, you will need Xvfb and Firefox. On Ubuntu:
sudo apt-get install xvfb
sudo apt-get install firefox

Then You will need to run xvfb with some display number (prefere higher numbers to avoid conflicts):
sudo Xvfb :99 -ac

Export env var DISPLAY with the same number which You have started Xvfb. If You didn't run xvfb in the background, You will need another terminal:
export DISPLAY=:99

And now try to run Your code

A: I'd use capybara with WebKit to run headless.


text:
Q: All possible combinations of dictionary values given input string. Python I'm trying to get all possible strings from the values in a dictionary given a particular key.  For example, 'A' could mean either 'aaa','aba', or 'aac' and 'B' could mean either 'bbb','bab', or 'bbc', etc.
I've given an example of the output where it shows most combinations of the possible strings
import itertools
in_ = 'ABC'
D = {'A':['aaa','aba','aac'],'B':['bbb','bab','bbc'],'C':['ccc','cac','ccb']}

#out_ = ['aaabbbccc','ababbbccc','aacbbbccc','aaababccc','aaabbcccc','aaabbbcac','aaabbbccb'...]

I started writing the code but it started to get REALLY messy and I feel that there is a way to use itertools or something more pythonic to achieve this goal
output = []
for char in in_:
    out_string = ''
    while char:
        for v in D[char]:
            while v:
                for char2 in in_:
                    out_string
#not pythonic . . .

A: Well, you've got itertools imported there. Let's use it! We want to take the Cartesian product D['A'] × D['B'] × D['C'], so we'll do precisely that using itertools.product.
import itertools

in_ = 'ABC'
D = {'A':['aaa','aba','aac'],'B':['bbb','bab','bbc'],'C':['ccc','cac','ccb']}

iterables = [D[character] for character in in_]
out_ = [''.join(tup) for tup in itertools.product(*iterables)]

Now, out_ is:
['aaabbbccc', 'aaabbbcac', 'aaabbbccb', 'aaababccc', 'aaababcac', 'aaababccb',
 'aaabbcccc', 'aaabbccac', 'aaabbcccb', 'ababbbccc', 'ababbbcac', 'ababbbccb',
 'abababccc', 'abababcac', 'abababccb', 'ababbcccc', 'ababbccac', 'ababbcccb',
 'aacbbbccc', 'aacbbbcac', 'aacbbbccb', 'aacbabccc', 'aacbabcac', 'aacbabccb',
 'aacbbcccc', 'aacbbccac', 'aacbbcccb']

Is that the result you were going for?


text:
Q: Open Microsoft word document from web project to any local machine Below is my code on click to button. If I will run project using localhost it will open word document very well but when I am going to host this project on IIS and try to open it from another machine by IP it will transfer my page to error message.
Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();

object file = "D:\\poForM.docx";

object objFalse = false;
object objTrue = true;
object missing = System.Reflection.Missing.Value;
object emptyData = string.Empty;
object readOnly = false;
object visible = true;
wordApp.Visible = true;
Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref file, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, visible, ref missing, ref missing, ref missing, ref missing);
aDoc.Activate();

A: Your code is relying on there being an instance of Microsoft Word on the server (Microsoft.Office.Interop.Word.ApplicationClass)... and having the object file at a specified location on the server.
If I understand correctly what you are trying to do you want to host the Word document on your IIS server but download it onto the local machine for editing..
You can do this by providing a link in your Web page to where the Word doc is, for example:
Open Word Document

Then when you click the link the browser will download the doc and open it in Word (assuming it's installed locally)
Of course if I've completely misunderstood what you're trying to do feel free to comment....

A: I believe you want to achieve SharePoint alike behaviour where the user can open the file and then save it back to server. Here is a similar thread Possible for Word to edit documents directly off an web server without Sharepoint? . The only bad thing about this solution is that AFAIK it is working only in IE. You can also try new ActiveXObject("Word.Application");instead of the new ActiveXObject("SharePoint.OpenDocuments");


text:
Q: Load static JSON file in Webpack I have somewhere in my code following construction:
var getMenu = function () {
    return window.fetch("portal/content/json/menu.json").then(function (data) {
        return data.json();
    });
};

I tried in my webpack.config.js this:
module: {
    loaders: [
        ...
        {
            test: /\.json$/,
            exclude: /node_modules/,
            use: [
                'file-loader?name=[name].[ext]&outputPath=portal/content/json'
            ]
        },
        ...
   ]
}

Project structure:
dist
  content
     json
        menu.json <- this is missing

src
  content
     json
       menu.json <- source file

Question:
How can webpack copy src/content/json/menu.json to dist/content/json/menu.json ?

A: You're using fetch to request a JSON file and that will only happen at runtime. Furthermore, webpack only processes anything that is imported. You expected it to handle an argument to a function, but if webpack did that, every argument to a function would be considered a module and that breaks any other use for that function.
If you want your loaders to kick in, you can import the file.
import './portal/content/json/menu.json';

You can also import the JSON and use it directly instead of fetching it a runtime. Webpack 2 uses json-loader by default for all .json files. You should remove the .json rule and you would import the JSON as follows.
import menu from './portal/content/json/menu.json';

menu is the same JavaScript object that you would get from your getMenu function.

A: if you'd like your json to be loaded in runtime/deferred you can use awesome webpack's dynamic imports feature:
import(
    /* webpackChunkName: "json_menu" */
    './portal/content/json/menu.json'
);

it will return a Promise which resolves to the module object, with "default" field containing your data. So you might want something like this (with es6 it looks really nice):
import(
    /* webpackChunkName: "json_menu" */
    './portal/content/json/menu.json'
).then(({default: jsonMenu}) => {
    // do whatever you like with your "jsonMenu" variable
    console.log('my menu: ', jsonMenu);
});

Notice that dynamic imports require a babel plugin syntax-dynamic-import, install it with npm:
npm i babel-plugin-syntax-dynamic-import -D

Have a nice day


text:
Q: Opening pdf file I wanna open pdf file from python console, I can do it with os.system(filename), it will open in adobe reader, but the problem is that os.system also opens a command prompt, is there another way that won't open command prompt?

A: Try:
import subprocess
subprocess.Popen([file],shell=True)

A: import webbrowser
webbrowser.open_new(r'file://C:\path\to\file.pdf')

A: import os
os.startfile(filename)

A: This is a bit late but nobody mentioned:
open("file_name.pdf")


text:
Q: How do I change localhost:3000 to "custom.domain.dev" for a React app built with create-react-app for CORS I am running into a CORS issue when trying to have my React app send post requests to an api endpoint while using localhost:3000.
How do I configure my app to use custom.domain.dev instead of localhost:3000?
I have /etc/hosts setup to to include 127.0.0.1    custom.domain.dev as well as my .env file to include HOST=custom.domain.dev.
As noted in this stackoverflow question,

Chrome does not support localhost for CORS requests (a bug opened in 2010, marked WontFix in 2014).

A: I think there are two parts of the question -
Regarding the CORS flag on local host
CORS flag is raised by the Browser when there is a request from a domain/port to an entire new domain/port. If you are doing this for testing, you can disable this security flag in chrome by adding the --disable-web-security flag. Just create a shortcut of chrome to desktop > Right click > Properties >In shortcut tab - Target > Append --disable-web-security --user-data-dir="C:\tmpChromeSession" to target. This will disable the CORS check.
In real cases, if you have access/control on the api server, what you should be doing is to enable CORS on server by adding necessary response headers (Access-Control-Allow-Origin) to the response. If you do not have access, one option will be to route the request through a CORS proxy.
Change port
You can change the running port of the react app on the package.json See this Stack Overflow answer. If you run the app on your machine, you are stuck with localhost.


text:
Q: How would you organize and separate global state with context? I have more of a conceptual question
From what I understand, all child react components are re rendered every time the state is changed in a parent component. For context to work it has to be located in the root parent component and pass down state to all child components through the provider.
So is there any way around re rendering all your child components when you update the global context state?
I have seen people implement multiple context objects but why would this matter since the state is still being changed the root parent so all child components are still being re rendered right? The context provider is just the wrapper but not where the state is actually being updated.
or not having one root parent component but instead middleman parent components that pass only the required global state to only certain child components. But how would you realistically organize this and how would it work with routing?
Please let me know if im mistaken or missing something.
My context looks like this and I need a better way to orginize it
  <Context.Provider
          value={{
            //Reducer1
            stateProp1: stateReducer1.stateprop1,
            stateProp2: stateReducer1.stateprop2,
            dispatchContextTrue: () => handleDispatchTrue(),
            dispatchContextFalse: () => handleDispatchFalse(),

            //Auth Reducer
            authState: stateAuthReducer.is_authenticated,
            profileState:  stateAuthReducer.profile,
            dbProfileState: stateAuthReducer.db_profile,
            handleUserLogin: () => handleLogin(),
            handleUserLogout: () => handleLogout(),
            handleUserAddProfile: (profile) => handleAddProfile(profile),
            handleUserRemoveProfile: () => handleRemoveProfile(),
            handleAddDBProfile: (profile) => handleDBProfile(profile),
            handleRemoveDBProfile: () => handleRemoveDBProfile(),

            //Form Reducer
            useContextChangeState: stateFormReducer.user_textChange,
            useContextSubmitState: stateFormReducer.user_textSubmit,
            useContextSubmit: (event) => handleFormSubmit(event),
            useContextChange: (event) => handleFormChange(event),

            //Posts Reducer
            postsState: statePostsReducer.posts,
            commentsState:  statePostsReducer.comments,
            userPostsState: statePostsReducer.user_posts,
            searchPostsState: statePostsReducer.db_search_posts,
            handleAddPosts: (posts) => handleSetPosts(posts),
            handleRemovePosts: () => handleRemovePosts(),
            handleAddComments: (comments) => handleSetComments(comments),
            handleRemoveComments: () => handleRemoveComments(),
            handleAddUserPosts: (posts) => handleSetUserPosts(posts),
            handleRemoveUserPosts: () => handleRemoveUserPosts(),
            handleSetSearchPosts: (posts) => handleAddSearchPosts(posts),
            handleRemoveSearchPosts: () => handleRemoveSearchPosts(),

            //User Reducer
            otherUserProfileState: stateUserReducer.db_other_user_profile,
            otherUserPostsState: stateUserReducer.db_other_user_posts,
            userMessagesState: stateUserReducer.user_messages,
            handleAddOtherUserProfile: (profile) => handleSetOtherUserProfile(profile),
            handleRemoveOtherUserProfile: () => handleRemoveOtherUserProfile(),
            handleAddOtherUserPosts: (posts) => handleSetOtherUserPosts(posts),
            handleRemoveOtherUserPosts: () => handleRemoveOtherUserPosts(),
            handleAddUserMessages: (messages) => handleSetUserMessages(messages),
            handleRemoveUserMessages: () => handleRemoveUserMessages(),

            //Handle auth
            handleAuth: (props) => handleAuthentication(props),
            authObj: auth
          }}>
          <Routes />
      </Context.Provider>


text:
Q: Why check if child exists in Firebase always return false? In my application, I use below code to check if the child message exists or not.
this.firechats.child(uid).child(touid).orderByChild("time").startAt(time).on('value', (snapshot) => {
       var temp = snapshot.val();
       for (var tempkey in temp) {
         console.log("new message exists")
         console.log(temp[tempkey].message);
       }
       console.log(snapshot.hasChild("message"))
       if(snapshot.child("message").exists()){
            //do something
       }
    });

In fact there is a message "hello", the log output also print it out, but the check function always returns false. What is wrong?
new message exists
hello
false

A: snapshot contains immediate children which are the push IDs of the messages that were added there.  So you can expect snapshot.child('-Lp_cm...') to exist.  If you want the message of that child, you would have to go one deeper: snapshot.child('-Lp_cm...').child('message')
It sounds like you actually want to iterate the list of messages in the snapshot, similar to the way you are doing with for (var tempkey in temp), then dig into those snapshots' children.


text:
Q: Change the code of a booking widget in wordpress I'm building a booking website with wordpress and i'm using a theme called Listeo.
The theme includes a booking widget that returns the products available all the dates between the day X and Y that the user chose. I would like to change the code of this widget so that it returns the products available in at least one day out of the dates X and Y.
I've identified the php file and code lines of the widget
function listeo_date_range_filter( $where ) {

    global $wpdb;

    $date_range = get_query_var( 'date_range' );

    if(!empty($date_range)) :
//TODO replace / with - if first is day - month- year
        $dates = explode(' - ',$date_range);
        //setcookie('listeo_date_range', $date_range, time()+31556926);
        $date_start = $dates[0];
        $date_end = $dates[1];

        $date_start_object = DateTime::createFromFormat('!'.listeo_date_time_wp_format_php(), $date_start);
        $date_end_object = DateTime::createFromFormat('!'.listeo_date_time_wp_format_php(), $date_end);

        $format_date_start  = esc_sql($date_start_object->format("Y-m-d H:i:s"));
        $format_date_end    = esc_sql($date_end_object->format("Y-m-d H:i:s"));

        // $format_date_start = esc_sql ( date( "Y-m-d H:i:s", strtotime( $wpdb->esc_like( $date_start ) ) ) );
        // $format_date_end = esc_sql ( date( "Y-m-d H:i:s", strtotime( $wpdb->esc_like( $date_end ) ) ) );
        // //
        // $booking_hours = Listeo_Core_Bookings_Calendar::wpk_change_booking_hours( $date_start, $date_end );
  //       $date_start = $booking_hours[ 'date_start' ];
  //       $date_end = $booking_hours[ 'date_end' ];

        $table_name = $wpdb->prefix . 'bookings_calendar';

        $where .= $GLOBALS['wpdb']->prepare(  " AND {$wpdb->prefix}posts.ID ".
            'NOT IN ( '.
                'SELECT listing_id '.
                "FROM {$wpdb->prefix}bookings_calendar ".
                'WHERE
                (( %s > date_start AND %s < date_end )
                OR
                ( %s > date_start AND %s < date_end )
                OR
                ( date_start >= %s AND date_end < %s ))
                AND type = "reservation" AND NOT status="cancelled" AND NOT status="expired"
                GROUP BY listing_id '.
            ' ) ', $format_date_start, $format_date_start, $format_date_end,  $format_date_end, $format_date_start, $format_date_end );

       //var_dump($where);
    endif;

    return $where;

Thanks in advance.


text:
Q: How to remove all "xts" "zoo" object from R environment? I need help on removing all "xts" "zoo" object from R (global)environment.
I learned that I can remove dataframes by using the following:
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "data.frame"])
The object I am trying to remove from environment is called temp. Running the following:
class(temp) yields [1] "xts" "zoo".
So I modified the code for deleting data frames like so:
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "xts"])
or
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "zoo"])
and other combinations of the "xts" and/or "zoo" but none of them works.
The temp object was created using temp <- as.xts(as.data.table(data))
Any suggestions?

A: *

*You may try

rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), \(x) class(x)[[1]]) == "xts"])

A: With Filter:
rm(list = Filter(function(x) 'xts' %in% class(get(x)), ls(all = TRUE)))


text:
Q: Python: Not able to parse email message piped to stdin I'm piping an email message from Pigeonhole to the Python script using Sieve filters which looks like
#!/usr/bin/python
import sys
import os
import email

input = sys.stdin

#For manual testing
#input=open(sys.argv[2]).read()

msg=email.message_from_string(input)

But it fails with the error below
Sep 21 11:41:24 lmtp: Error: Traceback (most recent call last):
Sep 21 11:41:24 lmtp: Error: File "message-processor.py", line 11, in <module>
Sep 21 11:41:24 lmtp: Error: msg=email.message_from_string(input)
Sep 21 11:41:24 lmtp: Error: File "/usr/lib64/python2.6/email/__init__.py", line 57, in message_from_string
Sep 21 11:41:24 lmtp: Error: return Parser(*args, **kws).parsestr(s)
Sep 21 11:41:24 lmtp: Error: File "/usr/lib64/python2.6/email/parser.py", line 82, in parsestr
Sep 21 11:41:24 lmtp: Error: return self.parse(StringIO(text), headersonly=headersonly)
Sep 21 11:41:24 lmtp: Error: TypeError: expected read buffer, file found

It works fine when i use email saved as a file but not piped in.
Any tips on that?

A: The error you're getting (TypeError: expected read buffer, file found) is clear: The function message_from_string expects a string (as the name suggests), while you're giving it a file (sys.stdin). If you want to enable piping you need to first save the incoming text as a string, and then pass it on to message_from_string. Something along the lines of:
import sys
import os
import email

# Save the piped input as a string
s = '\n'.join(line for line in sys.stdin)

msg = email.message_from_string(s)

A: I have switched to email.parser which do the job
#!/usr/bin/python
import sys
import os
import email
import email.parser

input = sys.stdin

#For manual testing
#input=open(sys.argv[2]).read()

msg = email.parser.Parser().parse(input)


text:
Q: how can I convert my room entity to my data class in kotlin? I have a data class that I pull from internet and I want to save room database but there is a problem like that.

It always gives an error like this, how can I overcome this problem?
my room entity class
@Entity(tableName = "ExchangeValues")
data class ExchangeEntity(

    @ColumnInfo(name = "base_code") val base_code: String,
    @ColumnInfo(name = "conversion_rates") val conversion_rates: ConversionRates,
    @ColumnInfo(name = "result") val result: String,
    @PrimaryKey(autoGenerate = true) val uid:Int?=null

)

my dao
@Dao
interface ExchangeDao {

    @Query("SELECT * FROM ExchangeValues")
    suspend fun getAll() : List<ExchangeEntity>

    @Query("UPDATE ExchangeValues SET  base_code=:base_code,conversion_rates=:conversion_rates , result=:result")
    suspend fun update(base_code:String,conversion_rates:ConversionRates,result:String)

}

my exchange data class
@Serializable
data class Exchange(
    val base_code: String,
    val conversion_rates: ConversionRates,
    val documentation: String,
    val result: String,
    val terms_of_use: String,
    val time_last_update_unix: Int,
    val time_last_update_utc: String,
    val time_next_update_unix: Int,
    val time_next_update_utc: String
) {
    fun toEntity() = ExchangeEntity(
        base_code = base_code,
        conversion_rates = conversion_rates,
        result = result
    )
}

@Serializable
data class ConversionRates(
    val conversionRates : Map<String,Double>
)

I cant use toEntity function in getAll()
exchangeRepositoryImpl
class ExchangeRepositoryImpl @Inject constructor(
    private val dao:ExchangeDao
) : ExchangeRepository{

    override suspend fun getAll() : Flow<List<Exchange>> {

        return flow {

            emit(dao.getAll())
        }

    }

    override suspend fun update(exchange: Exchange) {
        dao.update(exchange.base_code,exchange.result,exchange.conversion_rates)
    }

}

my exchange converter
class ExchangeConverter {

    @TypeConverter
    fun fromSource(conversionRates: ConversionRates) : String{
        val gson = Gson()
        return gson.toJson(conversionRates)
    }

    @TypeConverter
    fun toSource(json: String): ConversionRates {
        val gson = Gson()
        val typeToken = object : TypeToken<List<ConversionRates>>() {}.type
        return Gson().fromJson(json, typeToken)
    }
}

I wrote a converter like this, but it might not be correct, I'm not so sure. How can I solve this problem?

A: Inside flow you have created call map function the call to toEntity() eg
    flow{
          emit (dao.getAll().map{it.toEntity()})
        }

A: Well your flow returns a flow of
List<Exchange>

and your repo returns
List<ExchangeEntity>

and there's nothing in your code to map an ExchangeEntity to an Exchange.
So you need something like:
override suspend fun getAll() : Flow<List<Exchange>> {

        return flow {

            emit(dao.getAll().map{Exchange(base_code = it.baseCode)})// add in other fields on exchange constructor
        }

    }


text:
Q: Trackpad setup for HiDPI screen I've just gotten the new Dell XPS 13. I've managed to setup almost everything, except for the touchpad.
If I place the cursor to the left edge of the screen, and start moving my finger to the right, I only get to the middle of the screen before I run out of trackpad. I basically need to find a way to change speed at which the cursor is moving while I move the finger.
I've read what I could find about it, and it more or less says I need to change something using xinput command. I can't however figure out what. Here is xinput list-props output:
xinput list-props 13
Device 'DLL082A:01 06CB:76AF Touchpad':
    Device Enabled (138):   1
    Coordinate Transformation Matrix (140): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Tapping Enabled (298): 0
    libinput Tapping Enabled Default (299): 0
    libinput Tapping Drag Enabled (300):    1
    libinput Tapping Drag Enabled Default (301):    1
    libinput Tapping Drag Lock Enabled (302):   0
    libinput Tapping Drag Lock Enabled Default (303):   0
    libinput Tapping Button Mapping Enabled (304):  1, 0
    libinput Tapping Button Mapping Default (305):  1, 0
    libinput Natural Scrolling Enabled (276):   0
    libinput Natural Scrolling Enabled Default (277):   0
    libinput Left Handed Enabled (278): 0
    libinput Left Handed Enabled Default (279): 0
    libinput Accel Speed (280): 0.000000
    libinput Accel Speed Default (281): 0.000000
    libinput Scroll Methods Available (285):    1, 1, 0
    libinput Scroll Method Enabled (286):   1, 0, 0
    libinput Scroll Method Enabled Default (287):   1, 0, 0
    libinput Click Methods Available (306): 1, 1
    libinput Click Method Enabled (307):    1, 0
    libinput Click Method Enabled Default (308):    1, 0
    libinput Middle Emulation Enabled (290):    0
    libinput Middle Emulation Enabled Default (291):    0
    libinput Send Events Modes Available (261): 1, 1
    libinput Send Events Mode Enabled (262):    0, 0
    libinput Send Events Mode Enabled Default (263):    0, 0
    libinput Disable While Typing Enabled (309):    1
    libinput Disable While Typing Enabled Default (310):    1
    Device Node (264):  "/dev/input/event7"
    Device Product ID (265):    1739, 30383
    libinput Drag Lock Buttons (292):   <no items>
    libinput Horizontal Scroll Enabled (293):   1

can anyone help me figure out what I need to change to make the trackpad work properly in HiDPI mode ?

A: I messed around a bit on my laptop, and I think I found an answer. Try:
xinput --set-prop 13 "libinput Accel Speed" <acceleration_value>
libinput devices are strange in that there doesn't seem to be an actual speed parameter, only an acceleration param which goes from -1 to 1, inclusive. Find a number which works to your liking. As you may know, changes with xinput don't persist past reboots. However, you can make a change permanent by modifying your .xsessionrc file. Try:
echo "xinput --set-prop 13 'libinput Accel Speed' <acceleration_value>" >> ~/.xsessionrc
For what it's worth, Synaptics devices (which is what I have) utilize a "Synaptics Move Speed" property. More information on that here: ftp://www.x.org/pub/X11R7.5/doc/man/man4/synaptics.4.html. Just CTRL+F 'move speed'.


text:
Q: Placeholder not showing after textfield is cleared SwiftUI I have 2 textfields...
 TextField("Username", text: $viewModel.usernameStore){}
        .padding(.all, 8)
        .background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
        .cornerRadius(4.0)
        .padding(.bottom, 5)

    SecureField("Password", text: $viewModel.passwordStore){}
        .padding(.all, 8)
        .background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
        .cornerRadius(4.0)
        .padding(.bottom, 5)

And a function that clears them all...
    func clearCredentials(){
    $viewModel.usernameStore.wrappedValue = ""
    $viewModel.passwordStore.wrappedValue = ""
 }

When the function is called and the textfields are cleared password's placeholder repopulates but username's placeholder doesn't, it is only cleared.
I'm assuming this has something to do with the password being a secure field.
How can I get username to repopulate the placeholder text after being cleared?

A: i think this is a SwiftUI Bug, because if you tap in the other field, the placeholder appears again...
I have another solution for you (it is the standard way Apple does it to clear textfields, so the user knows how to handle it...
check this out:
struct CustomTextField: UIViewRepresentable {

    class Coordinator: NSObject, UITextFieldDelegate {

        @Binding var text: String

        init(text: Binding<String>) {
            _text = text
        }

        func textFieldDidChangeSelection(_ textField: UITextField) {
            text = textField.text ?? ""
        }
    }

    @State var secure : Bool
    @State var initialText : String
    @Binding var text: String
    @State var placeholder : String

    func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
        let textField = UITextField(frame: .zero)
        textField.placeholder = placeholder
        textField.delegate = context.coordinator
        textField.text = initialText
        textField.clearButtonMode = .always
        textField.isSecureTextEntry = secure
        return textField
    }

    func makeCoordinator() -> CustomTextField.Coordinator {
        return Coordinator(text: $text)
    }

    func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
        uiView.text = text
        uiView.placeholder = placeholder
    }
}

struct ContentView: View {

    @State var username : String = ""
    @State var password : String = ""

    func clearCredentials(){
        username = ""
        password = ""

    }

    var body: some View {
        VStack {

            CustomTextField(secure: false, initialText: "", text: $username, placeholder: "Username")
                .fixedSize()
                .padding(.all, 8)
                .background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
                .cornerRadius(4.0)
                .padding(.bottom, 5)

             CustomTextField(secure: true, initialText: "", text: $password , placeholder: "Password")
                .fixedSize()
                .padding(.all, 8)
                .background(Color(red:0.5, green: 0.5, blue: 0.5, opacity: 0.3))
                .cornerRadius(4.0)
                .padding(.bottom, 5)
            Button(action: {
                self.clearCredentials()
            }) {
                Text("Clear credentials")
            }

        }.padding()
    }
}

A: SwiftUI's TextField supports placeholder text just like UITextField did – gray text that is shown in the text field when it's empty, either giving uses a prompt ("Enter your password") or showing some example data.
To set a placeholder, pass it in as part of the initializer for your text field, like this:
struct ContentView: View {
    @State private var emailAddress = ""

    var body: some View {
        TextField("johnnyappleseed@apple.com", text: $emailAddress)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding()
    }
}


text:
Q: How to use arrays in routes with Angular? I thought using getAll with a paramMap could help with getting arrays from the URL but apparently not.
Am I using it wrong?
Here's an example : https://stackblitz.com/edit/angular-bjrjz9
I navigate with this
this.router.navigate(['two', {
  id: [1, 2, 3, 4, 5]
}]);

And then I get the values
this.route.paramMap.subscribe(params => {
  const ids = params.getAll('id');
  console.log('ids', ids);
});

console.log says ['1,2,3,4,5'] but I expected it to be [1,2,3,4,5] or even ['1', '2', '3', '4', '5']
I'm just trying to pass an array to a route and then get the array back at the destination.
Of course, I could just split the string but what's the point of having getAll in that case? :)

A: The getAll() method returns duplicate parameters as an array.
Example:
http://www.example.com/?query=a&query=b&query=c

The value would be:
console.log(params.getAll('query')); // prints ["a","b","c"]

All query parameters in the HTTP specification are strings.

A: It works if use routerLink.
But, it's not currently working with your approach.
A bug in Angular's git is already open at https://github.com/angular/angular/issues/19179 for the same. You can track this issue there.


text:
Q: JQuery: URL is opening twice - how to only open once? I have a table in which the rows are clickable.  Also within the row I have a clickable button.  Both when clicked open a new window and the same URL.
The clickable row is achieved by JQuery.
The clickable button by HTML. (in case javascript disabled)
How can I stop the URL opening twice ie when the button within the row is clicked?  I have tried boolean logic but could not get it to work i.e the  and button still need to be functional even after clicking the button once.
I am very new to Javascript and Jquery.  Many Thanks.  Pls find my code below:
Jquery code:
$(document).ready(function() {

    $('#myTable tr').click(function() {
        var href = $(this).find("a").attr("href");
        if (href) {
          window.open(href);
        }
    });

});

the HTML code:

A: event.preventDefault() will stop any default actions from being executed.
$(document).ready(function() {

    $('#myTable tr').click(function(event) {
        var href = $(this).find("a").attr("href");
        if (href) {
          window.open(href);
          event.preventDefault();
        }
    });

});

A: Ok so, I took another look at this and realized the original nugget of advice was correct, but that the child link is the one that needs to have its default behavior prevented.
$(document).ready(function() {
  $('#myTable tr td a').click(function(e) {
    e.preventDefault();
  });
  $('#myTable tr').click(function() {
    var href = $(this).find("a").attr("href");
    if (href) {
      window.open(href);
    }
  });
});

Looking back at the comments Usman suggested this.


text:
Q: Integrating Factor Found by Inspection Solve the equation:
$y(x^3 - y) dx - x(x^3 + y) dy = 0$
Solution:
Regroup the terms:
$x^3(y dx - x dy) = y(y dx + x dy)$
Then, substitute $d(xy)$ to $(y dx + x dy)$ since it is the exact differential form of $(y dx + x dy)$:
$x^3(y dx - x dy) = yd(xy)$
However, according to the book (Rainville, E. D., Bedient, P. E. (1989). Elementary Differential Equation. 7th Edition. New York: MacMillan Publishing Company), there are two exact differential form on the equation. The terms of the equation must be divided by $y^2$ to have an exact differential form, $d(\frac{x}{y})$, for $(y dx - x dy)$.
I don't know how $y^2$ obtained from the equation, $y(x^3 - y) dx - x(x^3 + y) dy = 0$, which can be used to have an exact differential equation for $(y dx - x dy)$. Any help is highly appreciated. Thank You.

A: $$x^3(y dx - x dy) = yd(xy)$$
Divide by $y^2$ both sides. You have the right to do so. Multiply or divide both sides of an equation by the same quantity. The equality still holds.
$$x^3d\frac x y = \frac {d(xy)}{y}$$
Divide by $x^2y$ :
$$ \frac x y d\frac x y = \frac {d(xy)}{(xy)^2}$$
Integrate.
$$ \frac 12  \frac {x^2 }{y^2} =- \frac {1}{xy}+C$$
$$  {x^3 } +{2y}+C_1{xy^2}=0$$

Edit1
$$x^3(y dx - x dy) = yd(xy)$$
You can also choose to divide by $x^2$
$$-x^3d\frac y x = \frac {yd(xy)}{x^2}$$
Divide by $y^3$ :
$$-\frac {x^3}{y^3}d\frac y x = \frac {d(xy)}{x^2y^2}$$
Now you can integrate.


text:
Q: How to center my navigation bar between two uneven elements? I've been messing with my code for about two days now and everything I do does not work. I want the nav bar to be centered between two elements (, <form>). It is roughly centered now but when you re-size the window it messes up at around 1600px. It only needs to work up to 1500px because after that I'm going to go onto a different nav bar location and style.
Codepen: http://codepen.io/anon/pen/KpECd
HTML:

            SHARING
            HOSTING
            PRICING
            ACCOUNT

        <form method="post" action="index.php">
            <button value="SIGNUP" name="signup">SIGNUP</button>
            <button value="LOGIN" name="login">LOGIN</button>
        </form>

CSS:
@charset "utf-8";

header {
    background-color:#464646;
    height:100px;
    width:100%;
}

header .logo {
    max-height:44px;
    max-width:535px;
    margin:28px 28px 28px 28px;
}

header form {
    display:inline;
    float:right;
    margin:28px 28px 28px 28px;
}

header form button {
    height:44px;
    width:125px;
    border:2px solid white;
    border-radius:10px;
    -moz-border-radius:10px;
    -webkit-border-radius:10px;
    background-color:transparent;
    font-family:"Lato Black";
    color:white;
    font-size:22px;
}

header form button:hover {
    background-color:rgba(255, 255, 255, .2);
    cursor:pointer;
}

header form button:active {
    background-color:rgba(255, 255, 255, .8);
}

nav {
    width:47.5%;
    display:inline;;
    position:absolute;
    text-align:center;
}

nav a {
    display:inline-block;
    height:100px;
    width:20%;
    color:white;
    font-family:"Lato Black";
    text-decoration:none;
    font-size:16px;
    line-height:100px;
}

nav a:hover {
    background-color:#00a651;
    cursor:pointer;
}

A: If you have 3 elements and you want one on the left, one on the right and the last one center between the others, you can use a table like this:

    one
    two
    three
    four

    <form method="post" action="index.php" style="width:260px;">
        <button value="SIGNUP" name="signup" style="width:120px;">SIGNUP</button>
        <button value="LOGIN" name="login" style="width:120px;">LOGIN</button>
    </form>

DEMO
If you don't like tables like a lot of people, you can use div with floats and jQuery:
winResize = function(){

    var HeaderWidth = $("#header").outerWidth();
    var div1Width = $("#div1").outerWidth();
    var div3Width = $("#div3").outerWidth();

    var div2Width = HeaderWidth - div1Width - div3Width;
    $("#div2").css("width", div2Width+"px");
}

winResize();

$(window).resize(function(){

    winResize();
});

JQUERY DEMO


text: Q: Patrol Read Aborted on PD Getting "Patrol Read Aborted on PD" warning message on MegaRAID Storage Manager. After research I found that Patrol Read and Consistency Check (CC) was scheduled by controller to run at the same time (which not supposed to happen) on IBM web site if CC and RP are running at the same time I should get " ServeRAID Event Log Message: "Patrol Read can't be started" message. I'm trying to figure out if this error occurs for the same reason or it's related to something else.


text:
Q: Generalized cartesian product function in Scala I wrote the following cartesian product function (which can take an arbitrary number of Iterables on elements of various types):
def cross(a: Iterable[_]*): Iterable[_] =
   if (a.length == 1)
     for (i <- a.head) yield i
   else
     for (i <- a.head; j <- cross3(a.tail:_*))
       yield i :: j :: Nil

Which produces, e.g.:
List(List(1, List(a, -1)), List(1, List(a, 0)) ...

But I wanted something like:
List(List(1, a, -1), List(1, a, 0) ...

Or even better:
List((1, a, -1), (1, a, 0) ...

How would I "flatten" the resulting tuples? I tried a few things, but the type inference seems to get lost inferring that the type of j is Any.

A: I think you want something like this (using Shapeless):

import shapeless._

object CartesianProduct
extends App {

  def cross(a: Iterable[Iterable[_]]): Iterable[HList] = {

    // If a is empty, return HNil to signal the end of this heterogenous list.
    if(a.isEmpty) Iterable(HNil)

    // Otherwise, create a new heterogeneous list for each element in this list,
    // prefixed to each heterogeneous list for the remainder.
    else for {

      i <- a.head // For each element in the head sequence
      t <- cross(a.tail) // For each heterogenous list in the output sequence
    } yield i :: t // Create a new heterogeneous list
  }

  val data = List(List(1, 2, 3), List("a", "b"), List(-1, -2, -3))
  val result = cross(data)
  println(result)
}

Result is:
List(1 :: a :: -1 :: HNil, 1 :: a :: -2 :: HNil, 1 :: a :: -3 :: HNil, 1 :: b :: -1 :: HNil, 1 :: b :: -2 :: HNil, 1 :: b :: -3 :: HNil, 2 :: a :: -1 :: HNil, 2 :: a :: -2 :: HNil, 2 :: a :: -3 :: HNil, 2 :: b :: -1 :: HNil, 2 :: b :: -2 :: HNil, 2 :: b :: -3 :: HNil, 3 :: a :: -1 :: HNil, 3 :: a :: -2 :: HNil, 3 :: a :: -3 :: HNil, 3 :: b :: -1 :: HNil, 3 :: b :: -2 :: HNil, 3 :: b :: -3 :: HNil)

Update: Can you do this without using using Shapeless?
How about this:
object CartesianProduct
extends App {

  def cross(a: Iterable[Iterable[_]]): Iterable[List[_]] = {

    // If a is empty, return Nil to signal the end of this list of Anys.
    if(a.isEmpty) Iterable(Nil)

    // Otherwise, create a new list of Anys for each element in this iterable,
    // prefixed to each list of Anys for the remainder.
    else for {

      i <- a.head // For each element in the head sequence
      t <- cross(a.tail) // For each list of Anys in the output sequence
    } yield i :: t // Create a new list of Anys
  }

  val data = List(List(1, 2, 3), List("a", "b"), List(-1, -2, -3))
  val result = cross(data)
  println(result)
}

It outputs, in effect, a List[List[Any]]:
List(List(1, a, -1), List(1, a, -2), List(1, a, -3), List(1, b, -1), List(1, b, -2), List(1, b, -3), List(2, a, -1), List(2, a, -2), List(2, a, -3), List(2, b, -1), List(2, b, -2), List(2, b, -3), List(3, a, -1), List(3, a, -2), List(3, a, -3), List(3, b, -1), List(3, b, -2), List(3, b, -3))

(The reason type inference gets lost is because, firstly, you do not have any generic types in your function signature, so a generic type of _ is equivalent to saying your iterables contain Any values. Secondly, you're then adding these Any values to a List. So the list contains heterogeneous elements (Int and String in this case). Doing anything with the result implies that you're going to have to cast the types, or pattern match on them. To determine if there's a better approach, I have to ask what you're using this function for?)
Returning a list of tuples is, I think, impossible in the general case (since you'd need to determine how many iterables you had in the input to create a tuple with that many values).
Update 2: If you want output in the form of tuples, you clearly need to know the number and types of each iterable passed to the function. The Shapeless version looks like this:
// Convert result to a tuple.
val generic = Generic[Tuple3[Int, String, Int]]
val tupleResult = result.map {l =>
  val t = l.asInstanceOf[Int :: String :: Int :: HNil]
  generic.from(t)
}
println(tupleResult)

and the non-Shapeless version looks like this:
val tupleResult = result.map {l =>
  (
    l.head.asInstanceOf[Int],
    l.tail.head.asInstanceOf[String],
    l.tail.tail.head.asInstanceOf[Int]
  )
}
println(tupleResult)

In both cases, the output will be:
List((1,a,-1), (1,a,-2), (1,a,-3), (1,b,-1), (1,b,-2), (1,b,-3), (2,a,-1), (2,a,-2), (2,a,-3), (2,b,-1), (2,b,-2), (2,b,-3), (3,a,-1), (3,a,-2), (3,a,-3), (3,b,-1), (3,b,-2), (3,b,-3))


text:
Q: Music metadata missing after mklink I have successfully linked my NAS music folder to my Windows Music Library but there is a problem with the metadata within the symbolic linked folder. I did this with MKLINK
In the original folder on the NAS, the file contains the metadata

However, in the symbolic linked folder I get the below

The problem this causes is that in Windows Media Player none of the proper artist, genre, rating, etc information is available and then I am unable to sync to portable devices.
This was all working previously but I just replaced my NAS and with the new link it is no longer working. How can I resolve this?


text:
Q: Does a loop take longer to execute each time? I'm working on some J2EE project which involves storing postal codes, cities and countries together. We have developed a Java class which handles the integration of every country file (containing each postal code and each city). The problem is that for some countries (Great Britain, Netherlands...), the file is pretty big (400.000 to 800.000 lines).
I've got a while() loop which reads the next line, gets the information and stores it into my database. The problem is that for the 1000 or 10.000 first lines, the process is fast, really fast, then seems to be slowing each time it goes through the loop, then happens to throw a HeapSpaceOverflowException after 150.000 lines.
I thought first that some objects weren't garbage collected and slowed down my algorithm, but I can't figure out which one. Besides, when I run this algorithm on my PC, JConsole tells me that heap space is regularly cleaned (seems to be garbage collected), but the process is still slower and slower.
Below is the code of the method:
FileReader fr = new FileReader(nomFichier);
BufferedReader br = new BufferedReader(fr);

int index = 0; String ligne; String codePostal; String nomVille;
String codePays; PPays pays; String[] colonnes;

while ((ligne = br.readLine()) != null)
{
    System.out.println("line "+ ++index);

    colonnes = ligne.split(Pattern.quote(";"));

    codePostal = colonnes[9];
    nomVille   = colonnes[8];
    codePays   = colonnes[0];

    pays = this.pc.getByCodePays(codePays);

    this.pc.getByCodePostalAndVilleAndINSEE(codePostal, nomVille, pays.getNomPays(), "");
}

Variable this.pc is injected through @Inject annotation.
Can someone help me to figure out why this code gets slower and slower?
For completeness sake, I've added the code of the get...() method:
public Codepostalville getByCodePostalAndVilleAndINSEE(String codePostal, String ville,
                                                       String pays, String codeINSEE) throws DatabaseException
{
    Codepostal cp = null; Ville v = null; PPays p = null; Codepostalville cpv = null;

    try
    {
        // Tout d'abord, il faut retrouver l'objet CodePostal
        cp = (Codepostal) this.em
                        .createNamedQuery("Codepostal.findByCodePostal")
                        .setParameter("codePostal", codePostal)
                        .getSingleResult();
    }
    catch (NoResultException nre1)
    {
        // Si on ne l'a pas trouvé, on le crée
        if (cp == null)
        {
            cp = new Codepostal();
            cp.setCodePostal(codePostal);
            cpc.getFacade().create(cp);
        }
    }

    // On retrouve la ville...
    try
    {
        // Le nom de la ville passé par l'utilisateur doit être purgé (enlever
        // les éventuels tirets, caractères spéciaux...)
        // On crée donc un nouvel objet Ville, auquel on affecte le nom à purger
        // On effectue la purge, et on récupère le nom purgé
        Ville purge = new Ville();
        purge.setNomVille(ville);
        purge.purgerNomVille();
        ville = purge.getNomVille();

        v = (Ville) this.em
                        .createNamedQuery("Ville.findByNomVille")
                        .setParameter("nomVille", ville)
                        .getSingleResult();
    }
    catch (NoResultException nre2)
    {
        // ... ou on la crée si elle n'existe pas
        if (v == null)
        {
            v = new Ville();
            v.setNomVille(ville);
            vc.getFacade().create(v);
        }
    }

    // On retrouve le pays
    try
    {
        p = (PPays) this.em
                        .createNamedQuery("PPays.findByNomPays")
                        .setParameter("nomPays", pays)
                        .getSingleResult();
    }
    catch (NoResultException nre2)
    {
        // ... ou on la crée si elle n'existe pas
        if (p == null)
        {
            p = new PPays();
            p.setNomPays(pays);
            pc.getFacade().create(p);
        }
    }

    // Et on retrouve l'objet CodePostalVille
    try
    {
        cpv = (Codepostalville) this.em
                .createNamedQuery("Codepostalville.findByIdVilleAndIdCodePostalAndIdPays")
                .setParameter("idVille", v)
                .setParameter("idCodePostal", cp)
                .setParameter("idPays", p)
                .getSingleResult();

        // Si on a trouvé l'objet CodePostalVille, on met à jour son code INSEE
        cpv.setCodeINSEE(codeINSEE);
        this.getFacade().edit(cpv);
    }
    catch (NoResultException nre3)
    {
        if (cpv == null)
        {
            cpv = new Codepostalville();
            cpv.setIdCodePostal(cp);
            cpv.setIdVille(v);
            cpv.setCodeINSEE(codeINSEE);
            cpv.setIdPays(p);
            this.getFacade().create(cpv);
        }
    }

    return cpv;
}

So, I have some more information. The getCodePostal...() method needs around 15ms to be executed at the very beginning of the loop, and after 10.000 lines, it needs more than 100ms to be executed (almost 10 times more!).
In this new version I have disabled the commit/rollback code, so each query is committed on the fly.
I can't really find why it needs more and more time.
I've tried to search for some information about JPA's cache :
My current configuration is this (in persistence.xml) :
<property name="eclipselink.jdbc.bind-parameters" value="true"/>
<property name="eclipselink.jdbc.cache-statements" value="true"/>
<property name="eclipselink.cache.size.default" value="10000"/>
<property name="eclipselink.query-results-cache" value="true"/>

I don't know if it is the most efficient configuration, and I would appreciate some help and some explanations about JPA's cache.

A: You might want to read up on JPA concepts. In brief, an EntityManager is associated with a persistence context, which keeps a reference to all persistent objects manipulated through it, so it can write any changes done to these objects back to the database.
Since you never close the persistence context, that's the likely cause of your memory leak. Moreover, a persistence provider must write changes to persistent objects to the database prior to issuing a query, if these changes might alter the result of the query. To detect these changes requires iteration over all objects associated with the current persistent context. In your code, that's nearly a million objects for every query you issue.
Therefore, at the very least, you should clear the persistence context in regular intervals (say every 1000 rows).
It's also worth noting that unless your database is on the same server, every query you issue must travel over the network to the database, and the result back to the application server, before your program can continue. Depending on network latency, this can easily take a milli second each time - and you are doing this several million times. If it needs to be truly efficient, loading the entire table into memory, and performing the checks for existence there, might be substantially faster.

A: Problem "solved" (almost)!
I have configured my persistence.xml this way:
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.jdbc.batch-writing.size" value="10000"/>

At first, it didn't change anything. But then, I tried to cut my file into smaller pieces (when the file has more than 5000 rows, I read the 5000 rows, I store them in a StringBuilder, then I read the StringBuilder to insert 5000 rows at once).
This way, my code doesn't get any slower after 20.000 rows (for now).
It seems to work fine, but I still can't get why my code was getting slower when I worked with bigger pieces of file.
Thanks to everyone who tried to help me on this one.