text:
Q: Walkthrough: sum 2 integers using bit manipulation I am trying to understand the logic behind the following code which sums 2 integers using bit manipulation:
def sum(a, b):
    while b != 0:
        carry = a & b
        a = a ^ b
        b = carry << 1

    return a

As an example I used: a = 11 and b = 7
11 in binary representation is 1011
7 in binary representation is 0111
Then I walked through the algorithm:
iter #1: a = 1011, b = 0111
  carry = 0011 (3 decimal)
  a = 1100 (12 decimal)
  b = 0110 (6 decimal)

iter #2: a = 1100, b = 0110
  carry = 0100 (4 decimal)
  a = 1010 (10 decimal)
  b = 1000 (8 decimal)

iter #3: a = 1010, b = 1000
  carry = 1000 (8 decimal)
  a = 00010 (2 decimal)
  b = 10000 (16 decimal)

iter #4: a = 00010, b = 10000
  carry = 00000 (0 decimal)
  a = 10010 (18 decimal)
  b = 00000 (0 decimal)

We Done (because b is now 0).

As we can see, in all iterations a+b is always 18 which is the right answer.
However I failed to understand what is actually happens here. The value of a is going down and down with each iteration until suddenly pops to 18 in the last iteration. Also, can we learn anything from the value of the carry during the process?
I would love to understand the intuition behind this.

Thanks to @WJS answer I think I got it.
let's add 11 and 7 as before, but let's do it in the following order:
First, calculate it without the carry.
Second, calculate only the carry.
Then add both parts.

01011
00111
-----
01100 (neglecting carry)
00110 (finding only the carry)
-----
10010 (sum)

Now, to find the first part, how can we get rid of the carry bits? with XOR.
To find the second part, we use AND and then shift it 1 bit left to place it "under" the right bit.
Now all we have to do is sum both parts. The whole point is not using + operator so how can we do that? Recursion!
We assign the first part to a and the second part to b and we repeat this process until b=0 which means we are done.

A: Perhaps if you take a simpler example it will help.
a = 11
b = 11
a & b == 11 since AND returns 1's where both bits in the same
position are 1. These are the carry bits.

Now get rid of the the carry locations using exclusive or
a = a ^ b == 00

But a `carry` would cause addition to add bits one position to
the left so shift the carry bits left by 1 bit.

b = carry << 1 = 110
now repeat the process

carry = a & b = 0 & 110 == 0 no more carries
b = carry << 1 == 0
done.
11 + 11 = 110 = 3 + 3 = 6

Understanding the roles of (AND) & and (XOR) ^ are key.  Applying those to slightly more complex examples should help. But ignore the interim decimal values as they don't help much.  Think only about what is happening in binary.

A: I think this is easy to understand if you look at what happens with individual bits.
First step is calculating carry which only happens in binary when both bits are 1, so a&b calculates that for every bit. Then bitwise addition is happening via XOR (ignoring carry), and XOR works because:
0+0=0 (==0^0)
1+0=1 (==1^0)
1+1=0 (==1^1, generates carry bit which we ignore)

Next step is to shift carry to the left (<<1), move it to b and repeat until carry is empty.


text:
Q: Is there an API for adding/editing posts and viewing inbox in the works? I'd really like a full blown android-client for Stack Exchange, and I don't mind making one myself, however there are a lack of APIs available for adding, editing, voting and such, and checking if the currently logged in user has permission to add/edit/vote. All in all there is a lack of API where a user can log in at all, which I find kind of frustrating, so I was just wondering (and I'm not even sure I'm asking at the right place) if there is any work in progress to create a more full-blown API for the Stack Exchange sites.

A: The API is currently read-only.  But rest assured you are not the only person pushing for a full API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: If we inscribed all the 6 regular convex four-dimensional polytopes in a sphere, which one would have the highest volume? When a dodecahedron is inscribed in a sphere, it occupies more of the sphere's volume (66.49%) than an icosahedron inscribed in the same sphere (60.54%).
But what about for the 6 regular convex four-dimensional polytopes? The 5-cell, the 8-cell, the 16-cell, the 24-cell, the 120-cell and the 600-cell. If we inscribed all of them in a sphere... classify/sort them from the one that would have the highest volume to the one that would have the less volume. And please also provide the % of the volume of the sphere that each one of them would occupy.

A: Have a look here, this provides a great overview, and 'calculate-yourself'-solutions for your questions: http://davidf.faricy.net/polyhedra/Polytopes.html
For all regular convex polytopes inscribed to spheres the following should hold: The share of the volume covered by the polytope is directly related to the number of it's vertices: --> the more vertices, the more of the spheres volume is covered.
I don't have a formal proof for this, but consider the following: The regular convex polytopes are completely symmetrical, every face is regular and congruent to each other face. That maximizes the distance of each point lying on the surface to it's neighbouring vertices, which is the characteristic edge length (which is a constant for all edges and is directly correlated to the radius of the circumscribed sphere).
For polychora (= 4d-polytopes) I have the following results:

*

*5-cell (5 vertices): 2.95%

*16-cell (8 vertices): 13.51%

*8-cell (16 vertices): 20.26%

*24-cell (24 vertices): 40.53%

*600-cell (120 vertices): 78.27

*120-cell (600 vertices): 84.96%


text:
Q: New IIS7 virtual directory does not show on FTP client. What needs to happen? First, I might have to do this maybe once a year, so my memory is failing me as what exactly I did before to get this work because I've been able to do this times prior.  We are using an ISS 7 ftp server to recieve internal file transfers from an AIX server we have in house.  The only difference between then and now is that the existing virtual directories were migrated from a Windows 2003 (IIS 6) server to a Windows 2008 server.
All permisions from the existing directories are exactly the same as the new directory, yet the new virtual directory will not show in the any of the FTP clients I'm testing.  I do have FTP Directory Browsing turned on for the Default Site which is where all Virtual Directories reside.  The only thing I haven't done is stop/start IIS (which I don't remeber doing in the past), but I didn't want to needlessly restart IIS on a production server to only end up in the same place I am now.  What do I need to do to get this working?
UPDATE
Ok, had some down time to give IIS a restart, but no avail.  I am still not able to browse or view my newly created virtual directory on any FTP client.

A: Ok, figured it out.  We have a login script for all machines that maps a network drive.  It just so happens that the server I was working is the source of the mapped drive, the share on the server gets mapped as a drive.  Instead of using the actual path to directory I was trying to use for the virtural directory, I discovered I accidentally chose the mapped drive instead.  Once I reset virtual directory to the physical location on the drive, the directory appeared.

A: You mentioned that the folder were migrated from IIS/2003. I suggest that you verify the permissions the directories to make sure that the App Pool Identity that your FTP site is running on have permission to them. What authentication method are you using? Does IIS log indicate whether connections from the client are established successfully?


text:
Q: How to make a list of the indexes of capital letters in a word I'm trying to solve a challenge that I found online. It gives an input word and the expected output is a list of the indexes of all the capital letters. My program works unless there's duplicate capital letters. I can't figure out how to deal with it. Here's my code right now:
def capital_indexes(string):
    string = list(string)
    print(string)
    output = []

    for i in string:
        if i.isupper():
            output.append(string. index(i))
    return output

Like I said, it works for words like "HeLlO" but not for words like "TesT"

A: Try this one and compare the difference with OP:
You don't have to use index() method to search the character again, just use enumerate to get the tuple of (index, char) at the same time, and check if the character is capital case.
def capital_indexes(string):
    #string = list(string)   # string is an iterable!
    #print(string)
    output = []

    for i, ch in enumerate(string):    # get index, char
        if ch.isupper():
            output.append(i)
    return output

print(capital_indexes('TesT')) # [0, 3]


text:
Q: configuration of .emacs to use IPython interpreter I am new to lisp and having hard time configuring emacs for ipython. Part of my .emacs file looks like this:
;; Python mode settings
(require 'python-mode)
(add-to-list 'load-path "~/.emacs.d/elpa/")
(let ((default-directory "~/.emacs.d/elpa/"))
  (normal-top-level-add-to-load-path '("."))
  (normal-top-level-add-subdirs-to-load-path))

(autoload 'python-mode "python-mode" "Python Mode." t)
(add-to-list 'auto-mode-alist '("\\.py$\\'" . python-mode))
(add-to-list 'interpreter-mode-alist '("python" . python-mode))

(require 'ipython)

I run emacs --debug -init from command line window and get the following error message when emacs is launched:
Debugger entered--Lisp error: (wrong-type-argument listp "-i")
  nconc("-i" ("-colors" "LightBG"))

  eval-buffer(#<buffer  *load*-610080> nil "c:/Users/xxxx/AppData/Roaming/.emacs.d/elpa/python-mode-20150616.2346/ipython.el" nil t)  ; Reading at buffer position 9523
  load-with-code-conversion("c:/Users/xxxx/AppData/Roaming/.emacs.d/elpa/python-mode-20150616.2346/ipython.el" "c:/Users/xxxx/AppData/Roaming/.emacs.d/elpa/python-mode-20150616.2346/ipython.el" nil t)
  require(ipython)

This might be something that should be very obvious, but not sure how to fix this to be honest. It'd be very helpful if you can point me in the right direction. Thanks.

A: Seems you are using python-mode from python-mode.el: No special setting for IPython should be neccessary. Don't require ipython.el, it's outdated.
Configuring py-shell-name to "ipython" will make it the default shell.
M-x ipython RET should work right out of the box, also sending stuff to ipython-commands.
For special cases overriding defaults have a look into README.org.

A: I have the following in my init.el to make ipython the default python interpreter:
(setq
 python-shell-interpreter "ipython"
 python-shell-interpreter-args ""
 python-shell-prompt-regexp "In \\[[0-9]+\\]: "
 python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
 python-shell-completion-setup-code
   "from IPython.core.completerlib import module_completion"
 python-shell-completion-module-string-code
   "';'.join(module_completion('''%s'''))\n"
 python-shell-completion-string-code
   "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")

To start the interpreter, all you need to do then is call run-python.
Hope this helps!

A: Try change ipython command line as below:
(add-hook 'python-mode-hook
            (lambda ()
              ;You can uncomment next lines
              ;(set (make-variable-buffer-local 'beginning-of-defun-function)
              ;     'py-beginning-of-def-or-class)
              ;(setq outline-regexp "def\\|class ")
              ;(setq tab-width 4)
              ;(define-key py-mode-map "\C-c4" 'uncomment-region )
              ;(outline-minor-mode 1)
              ;(linum-mode 1)
              ;Ipython settings sections
              (require 'ipython)
              (setq-default py-shell-name "ipython")
              (setq-default py-which-bufname "IPython")
              (setq py-python-command-args '("--colors=linux")) ;Command line for run iPython
              ))


text:
Q: Storyboard segues causing memory leaks I have two UIViewControllers with buttons triggering segue (modal) to each other. I wanted to discover if that's causing any memory leaks while jumping back and forth and I see that Living Object && allocated memory is going up, what eventually would leave to app crash. I don't have any single line of code - working with pure UIViewControllers.

What I might be doing wrong? Could have I set something wrong in project settings?  Am I reading profiler's statictics badly? Do I need to make any special release commands while working with segues?

A: You aren't using the modal segues correctly.  The way you have implemented it, you are creating a new instance of each view controller when you segue instead of returning to the instance you came from.  That is why your memory usage continues to increase.
Before iOS 6, the correct way to handle this was to:
1) define a method such as viewController2Done in view controller 1
2) in view controller 2, create a property called delegate of type id.
3) in prepareToSegue for view controller 1, set delegate in view controller 2 to self
4) in view controller 2, when it is time to return to view controller 1, call [delegate viewController2Done]
5) in viewController2Done call [self dismissModalViewControllerAnimated:YES]
This method still works in iOS 6, but there is also a new unwind segue that can be used instead.  To use it, you would define a method in your view controller 1 like so:
Objective-C:
- (IBAction)unwindFromViewController2:(UIStoryboardSegue *)segue
{
    NSLog(@"and we are back");
}

Swift:
@IBAction func unwindFromViewController2(_ segue: UIStoryboardSegue) {
    print("and we are back")
}

Then you'd control drag from the button in view controller 2 to the orange exit icon in the bar above the view controller in the Storyboard.  In the pop up, you'd select unwindFromViewController2 and voila, you're done.


text:
Q: how to update Group policy for the whole domain? I recently found the Group policy of our domain (windows server 2012) is not updated enough to support our Win10 end-user machine. which are the correct ways to update the Group policy definition library?
a. manually install admx files?
b. install one domain controller with server 2016?
c. raise the function level of the domain to the server 2016?

A: You will need the ADMX files for the Windows Server 2012 DC's in order to support any changes in Windows 10  Group Policy, regardless of if you were to deploy a Server 2016 DC.

A: Don't raise domain functional level. If you do, the Server 2012 DCs will no longer be able to service the domain.
My recommendation would be to create a central store. The central store can be created on the SYSVOL partition on any domain controller (SYSVOL replicates through DFS to all domain controllers) and then go to the domain folder and find the Policies folder. An easy way to access this would be to use the following UNC path: "\FQDN of domain\SYSVOL\FQDN of domain\Policies".
From there, presuming that a PolicyDefinitions folder has not yet been configured, none will exist. Go to a Server 2016 DC and copy the C:\Windows\PolicyDefinitions folder to the aforementioned directory.
This will copy all of the ADMX files over to the central store where all DCs can access them, including Server 2012 DCs.

A: When I had Windows 2012 R2 server and Windows 10 clients, I had to download ADMX templates and place them in server policy store with each Windows 10 major version.
This link should help you:
https://support.microsoft.com/cs-cz/help/3087759/how-to-create-and-manage-the-central-store-for-group-policy-administra


text:
Q: TableView cells repeating images during interaction even I am writing cell.imageview.image = nil at the beginning I have created a custom tableviewCell ,
and when I am writing there below code
let cell = tableView.dequeueReusableCell(withIdentifier: "attendanceLogCellIdentifier", for: indexPath) as! AttendanceLogTableViewCell
cell.imageView.image = "someimag from cloud"

so when cells are loading the images inside the cells are repeating,
so what to do now so that cells in the tableview doesn't repeat the images

A: Its looks like you are assigning the same image for every cell.
You should have dataSource where you hold your images and then assign from it.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if let cell = tableView.dequeueReusableCell(withIdentifier: "attendanceLogCellIdentifier", for: indexPath) as? AttendanceLogTableViewCell {
        cell.imageView.image = imagesFromCloud[indexPath.row]
        return cell
    }

    assertionFailure()
    return UITableViewCell()
}


text:
Q: How to remove duplicates from any array and preserve ordering in PostgreSQL? I'm looking for a way to eliminate duplicates from a PostgreSQL array
while preserving the ordering of its elements. What I currently
have are the following functions:
create function array_unique( anyarray )
  returns anyarray immutable strict language sql as $$
  select array( select distinct unnest( $1 ) ); $$;

create function array_unique_sorted( anyarray )
  returns anyarray immutable strict language sql as $$
  select array( select distinct unnest( $1 ) order by 1 ); $$;

/* ### TAINT there ought to be a simpler, declarative solution */
create function array_unique_stable( text[] )
  returns text[] immutable strict parallel safe language plpgsql as $$
  declare
    R         text[] = '{}';
    ¶element  text;
  begin
    foreach ¶element in array $1 loop
      if not array[ ¶element ] && R then
        R :=  R || array[ ¶element ];
        end if;
      end loop;
    return R; end; $$;

In the above, array_unique takes an array of any type and returns a copy
with all duplicates removed; their relative ordering is arbitrary.
array_unique_sorted is like array_unique, but the elements are sorted
relative to each other; this is sometimes useful as all arrays with the
same set of of distinct elements will compare equal after being
normalized by this function.
array_unique_stable already does what I'm looking for: given an array
(which in this exampe must be a text[] array), it scans elements from
left to right; whenever it encounters a previously unseen element, it adds
that one to the result. Thus, only the first occurrence of each value
is kept.
However, the implementation has some drawbacks: First, there seems to be no
way to write it so it accepts the pseudo-type anyarray.
Second, while
the first two functions are written in SQL, they may presumably be inlined,
array_unique_stable is written in PL/pgSQL, and so it cannot be inlined.
Third, it bugs me that I couldn't come up with a solution in pure SQL...

A: This can indeed be done using pure SQL:
create function array_unique_stable(p_input anyarray)
  returns anyarray immutable strict parallel safe
  language sql
as
$$
select array_agg(t order by x)
from (
  select distinct on (t) t,x
  from unnest(p_input) with ordinality as p(t,x)
  order by t,x
) t2;
$$

The unnest(p_input) with ordinality will return the original index of the element in the array which is then used to aggregate them back in the outer query.
select array_unique_stable(array['a','x','x','b']) as text_array,
       array_unique_stable(array[10,1,1,5,8,8]) as int_array

returns
text_array | int_array
-----------+-----------
{a,x,b}    | {10,1,5,8}

and


text:
Q: jQuery .remove() Not Working After Valid Selection of Element JSFiddle: https://jsfiddle.net/coh1xr77/5/
I need to delete an <LI> DOM Element correctly selected with a Selector based on its exact content. My list contains a set of Time LI's and my choice is to delete the first one in the list, 12:15am, based on the exact text match, when I click the button.
I can see that my selection is correct because I'm getting an [Object] reference in the alert box, rather than "Undefined".
However, the subsequent remove() on this element does nothing: the element remains.
var myselection = '12:15am';

$('#remove').click(function() {

    var current = $('.ui-timepicker-list li').filter(function() {
            return $(this).text() ===  myselection;
        });

    alert('current = ' + current);  // This works, element found

    $(current).remove();   // This does nothing (or doesn't remove properly)

});

A: You need to change the condition to check if the li's innerText starts with the selected time string. Like: $(this).text().indexOf(myselection) == 0
Here's the updated fiddle: https://jsfiddle.net/coh1xr77/11/
Update
Considering that all time values have the bracketed relative time strings at the end, you could try splitting based on that bracket (, and compare with the first part of that string. Like: $(this).text().split('(')[0].trim() == myselection
Here's the fiddle with that: https://jsfiddle.net/coh1xr77/12/
Update 2
If you are absolutely certain that the structure of li elements will not change, you could access the text using the childNodes. Like: $(this)[0].childNodes[0].textContent == myselection;
Here's the updated fiddle: https://jsfiddle.net/coh1xr77/14/


text:
Q: 1.4 Django HTTP authentication Starting in 1.5, you can do:
from django.contrib.auth.handlers.modwsgi import check_password

in your wsgi file for Apache HttpAuthentication. I am currently using 1.4, how would I do this?

A: As you can see here, this was a new feature of Django 1.5.
You may check the source code / implementation of check_password and see how it is done and can perhaps recreate it for 1.4, but I would consider updating the project to 1.8 anyway...


text:
Q: IPhone: TableView Add data i'm making app that have table view and i cant add data in table view
I have table view in the .xip file named NewTable in .h file and this is the code that i'm using it in .m file(listData it's array):
- (void)viewDidLoad{
    [super viewDidLoad];
    [self TestTable];
}

-(void)TestTable{
    NSArray *array = [[NSArray alloc] initWithObjects:@"Vishal",@"Vinod",@"Sachin",@"Nilesh",@"Balu",@"Amrita",
                      @"susho",@"Akash",@"Nil",@"Lop",@"Koi",@"Absoulate",@"Dwalin",
                      @"Fili",@"Kili",@"Oin",@"Gloin",@"Bifur",@"Bofur",@"Bombur",nil];

    self.listData = array;
    [array release];
    self.listData= array;

    [self.NewTable reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.listData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SimpleTableIdentifier];
    if(cell == nil){
        cell = [[UITableViewCell alloc] autorelease];
    }
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [listData objectAtIndex:row];
    return cell;
}

{{{{{{{{{{{Also when i add nslog in cellForRowAtIndexPath it's not print anything in consol!}}}}}}}}}}}
{{{{{{{{{{{Also when i add nslog in cellForRowAtIndexPath it's not print anything in consol!}}}}}}}}}}}
{{{{{{{{{{{Also when i add nslog in cellForRowAtIndexPath it's not print anything in consol!}}}}}}}}}}}

A: This is what I typically see used to initialize the data.
-(void)viewDidLoad {
    self.listData = [[NSMutableArray alloc] initWithObjects:@"Vishal",@"Vinod",...,nil];
    [super viewDidLoad];
}

Although, I think your issue is assigning to an array that is no longer being retained.

A: If you are using UIViewController and not UITableViewController you need to make sure your viewController conform to the UITableViewDataSource and to the UITableViewDelegate
@interface MyViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

Next you need to actually set this view controller as the tableView's dataSource and delegate.
You can do this with IB by dragging the mouse from your tableView to your file's owner (that is the MyViewController)
Or do this in code:
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.NewTable.dataSource = self;
    self.NewTable.delegate = self;
}

Also in cellForRowAtIndexPath, change the line
cell = [[UITableViewCell alloc] autorelease];

with
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];


text:
Q: How to get values from current row selected in google sheets using google scripts I am trying to extract the values from each column of the currently selected row in google sheets but my code seems to always select the values from the first row of the spreadsheet.
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var active_range = sheet.getActiveRange();
  var address1 = sheet.getRange(active_range.getRowIndex(),2).getValue()
  var address2 = sheet.getRange(active_range.getRowIndex(),3).getValue()
  var city = sheet.getRange(active_range.getRowIndex(),4).getValue()
  var state = sheet.getRange(active_range.getRowIndex(),5).getValue()

A:
function onSelectionChange(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = e.range;
  var row = range.getRow();
  var val = sheet.getRange(row, 1, 1, 4).getValues();
  sheet.getRange(1, 1, 1, 4).setValues(val);
}


text:
Q: How to declare generic parameters of the same type except for lifetime in rust? I wrote the code below, but I can't write life time constraint to work and get an error:
use futures::Future;

async fn foo<'a>(a: &'a str) -> &'a str {
    let task = get();
    f(a, task).await
}

async fn f<T>(v: T, task: impl Future<Output = T>) -> T {
    if true {
        v
    } else {
        task.await
    }
}

async fn get() -> &'static str {
    "foo"
}

error:
error[E0759]: `a` has lifetime `'a` but it needs to satisfy a `'static` lifetime requirement
 --> src/lib.rs:3:18
  |
3 | async fn foo<'a>(a: &'a str) -> &'a str {
  |                  ^  ------- this data with lifetime `'a`...
  |                  |
  |                  ...is captured here...
4 |     let task = get();
5 |     f(a, task).await
  |     - ...and is required to live as long as `'static` here

playground
I think it can be solved if two parameters in function f can have their own lifetimes.
For example,
v: T,
task: S,
T: 'a,
S: 'b,
'b: 'a,
S == T

How to solve this issue?

A: The same problem can be reproduced with another minimal example, using function interfaces instead of async functions.
fn get() -> impl FnOnce() -> &'static str {
    || "foo"
}

fn foo<'a, T: 'a, F>(_: &'a str, _: F)
where
    F: Fn() -> T,
    T: FnOnce() -> &'a str,
{
}

let x = "".to_string();
foo(&*x, &get);

error[E0597]: `x` does not live long enough
  --> src/main.rs:22:11
   |
22 |     foo(&*x, &get);
   |     ------^-------
   |     |     |
   |     |     borrowed value does not live long enough
   |     argument requires that `x` is borrowed for `'static`
23 | }
   | - `x` dropped here while still borrowed

This example allows us to turn get into a function parameter and observe that passing this function imposes a hard constraint for the lifetime 'a to be 'static. Despite the program's best intentions, a function returning a supplier function (or a promise) does not provide co-variance with respect to the output's lifetime. That is, () -> &'static str does not fulfill for<'a> () -> &'a str. Occasionally, the compiler will fallback to suggesting you to stick to the weakest link that is the 'static lifetime, even though this may not be desirable.
Note that the means of representing types which are generic over their lifetimes is quite limited at the moment. These are a form of higher kinded types, which can be specified only to some level of expressiveness via higher ranked trait bounds (and eventually generic associated types, once they are fully implemented and stabilized). In this case, rather than trying to make f work for a kind T<'a> (pseudo-code), it is much better to just make our get generic over the lifetime 'a. Subtyping may then take place at the implementation, as we know that a string literal can fulfill any lifetime.
fn get<'a>() -> impl FnOnce() -> &'a str {
    || "foo"
}

In the async case (Playground):
async fn get<'a>() -> &'a str {
    "foo"
}

See also:

*

*The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want

*How can this instance seemingly outlive its own parameter lifetime?

*How can we write a generic function for checking Serde serialization and deserialization?


text: Q: AES GCM Encryption with C# in .NET 4.7.2 I wrote a class in Java for encrypting and decrypting data using AES/GCM/NoPadding. I'm using an IV with a length of 12 bytes. I would like to write the remote site (which should run on another system) in C#. Unfortunately I can not find an implementation of the AES/GCM/NoPadding algorithm in C # with .NET 4.7.2. Is there any way to solve my problem with the .NET Framework version 4.7.2?


text:
Q: C Sockets: Comparison between pointer and integer terminal error Here is a simple socket. No matter in which file if statement is declared,
int main()
{

   int sock, bytes_recieved;//, number;
   char send_data[1024],recv_data[1024];

   host = gethostbyname("127.0.0.1");

   server_addr.sin_family = AF_INET;
   server_addr.sin_port = htons(1237);

   while(1)
   {
      bytes_recieved = recv(sock,recv_data,1024,0);
      recv_data[bytes_recieved] = '\0';

      if (recv_data[0] == "q" || recv_data[0] == "Q")
      {
          printf("Why do you want to close socket dude?\n");
          close(sock);
        break;
      }

   }
   close(sock);
   return 0;

}

after running both in client and server are coming with the error below in teminal
client.c:49:26: warning: comparison between pointer and integer
         if (recv_data[0] == "q" || recv_data[0] == "Q")
                          ^

A: Firstly, you should check that bytes_received is not negative before the line
recv_data[bytes_recieved] = '\0';

because not only does this indicate an error, but prevents you from writing to a negative index which is undefined behaviour.
Secondly, the type of recv_data[0] is char while "q" is a string literal and of type char* so
if (recv_data[0] == "q" || recv_data[0] == "Q")

is not a valid comparison (as the compiler indicates).
Replace the above line line with
if (recv_data[0] == 'q' || recv_data[0] == 'Q')

to check for specific characters q and Q at element zero in your receive buffer.

A: You can't compare a character to a string.


text:
Q: is datastore only possible database option if you host app with gae? wont gae allow connecting to mysql even external mysql on other server? I am new in gae and seemed to me you have no way but using datasrore.

A: GAE provides two internal persistent structured storage service: datastore and Cloud SQL.
You could use an external data storage service, but the limitation of GAE is that it can only make HTTP requests to external services, so
There is an option of using outgoing sockets, but in practice this is quite limited and I haven't yet seen a working jdbc implementation using it. Also, you will not be able to do persistent jdbc connections as the lifetime of request on GAE is limited to 30 seconds.


text:
Q: How to test which iterative combinatorics & permutation calculator is the most efficient? I am trying to test which of the two functions is faster at computing the sum of combinations or permutations.
UPDATE: microbenchmark package seems to be the answer to my original question, but I'd like to know why the switches in combo_beast are cheaper than combo_unicorn...
> microbenchmark(combo_beast(5,'yes','yes'))
Unit: microseconds
                         expr   min    lq    mean median    uq    max neval
 combo_beast(5, "yes", "yes") 8.019 8.354 9.94767  8.688 9.022 32.412   100
> microbenchmark(combo_unicorn(5,'yes','yes'))
Unit: microseconds
                           expr   min    lq     mean median    uq    max neval
 combo_unicorn(5, "yes", "yes") 8.354 8.688 10.63269  9.022 9.357 41.768   100

The first function uses nested switches:
combo_beast <- function(n, order, rep){
  switch(order,
         yes = switch(rep,
                      yes = {
                        y <- 0
                        for(i in 1:n){
                          x <- n^i
                          y <- x + y}
                        return(y)
                      },
                      no = {
                        y <- 0
                        for(i in 1:n){
                          x <- factorial(n + i - 1)/(factorial(i)*factorial(n-1))
                          y <- x + y}
                        return(y)
                      }
                     ),
         no = switch(rep,
                     yes = {
                        y <- 0
                        for(i in 1:n){
                          x <- factorial(n)/(factorial(n - i))
                          y <- x + y}
                        return(y)
                      },
                      no = {
                        y <- 0
                        for(i in 1:n){
                          x <- factorial(n)/(factorial(n-i)*factorial(i))
                          y <- x + y}
                        return(y)
                      }
                     )
  )
}

The second function utilizes the if/else if approach:
combo_unicorn <- function(n, order, rep){
  if(order == 'yes' & rep == 'yes'){
    y <- 0
    for(i in 1:n){
      x <- n^i
      y <- x + y}
    return(y)
  } else if (order == 'yes' & rep == 'no'){
    y <- 0
    for(i in 1:n){
      x <- factorial(n + i - 1)/(factorial(i)*factorial(n-1))
      y <- x + y}
    return(y)
  } else if (order == 'no' & rep == 'no'){
    y <- 0
    for(i in 1:n){
      x <- factorial(n)/(factorial(n-i)*factorial(i))
      y <- x + y}
    return(y)
  } else {
    y <- 0
    for(i in 1:n){
      x <- factorial(n)/(factorial(n - i))
      y <- x + y}
    return(y)
  }
}

I have tried putting ptm <- proc.time() at the start of either function and proc.time() - ptm at the end, but it keeps returning 0s no matter how large I make n.


text:
Q: MySQL: Foreign key constraints that exceed max depth I have MySQL Server 5.1.62 installed on production server. I am monitoring mysql server's error log file every day and suddenly I found below error in my error log file.

InnoDB: Cannot delete/update rows with cascading foreign key constraints that exceed max depth of 250
      Please drop excessive foreign constraints and try again

I have a database structure with primary key - foreign key relationships with proper update/delete actions and I need to delete data of child tables if the data in parent table deleted by application or manually (backend).
I had googled this issue but I can't find proper solution. How can I resolve this issue?

A: Have a look at this link - Cascade Delete results in "Got error -1 from storage engine". There is a suggestion.
Also, as a solution you may try to do it without ON DELETE CASCADE option, just use DELETE statement that removes records from some tables (multiple-table syntax).

A: The picture of a schema isn't very useful, because it doesn't show any cascading declarations. For example, if deletes are supposed to cascade from tbl_indentmaster to tbl_tepdetails, but deletes are not supposed to cascade from tbl_tepdetails to tbl_tepnoting, then then I'd expect some deletes to fail. (But with a different error message.)
If there is a circular referential constraint that's causing this, I'd expect it to be caused in part by a cascading reference from tbl_indentmaster to tbl_tepdetails. You might want to try dropping that foreign key constraint for testing. Do that on a tset sserver, not on the production server.
If this started suddenly, and your database worked correctly before, I'd first think about

*

*restoring the database from backup, or

*restoring the schema from backup, and reloading the current data, or

*checking out the current version and rebuilding the database. (You do have the database schema under version control, don't you?)

I'll assume you don't have a good backup, and that you don't have your schema under version control.
Are you starting with a good database? Run mysqlcheck.  Read that documentation carefully. Don't --repair before you have a tested, good backup.
Assuming that your database is good, that cascading deletes ought to work correctly in your database, and that your Google skills are good, I think your best start is to

*

*install MySQL 5.5 or 5.6 on a test server,

*load your database onto that test server, and

*see whether you can reproduce that specific error.

To load your database onto the test server, dump the contents using mysqldump. Don't copy files at the filesystem level--one or more of them might be corrupt.
Although this might not resolve your issue, it might tell you exactly where the issue is. If it works correctly, you know the problem is probably related to the server version, and that it might be resolved with a version upgrade.

A: I agree with the original answers by @Devart and @Catcall here but I'd like to add a few things after exchanging a few comments with the OP.
First, I have reduced the schema image representation to only the tables that are affected by a DELETE query on tbl_indentmaster.
From what I could see there are no circular FK references in this schema diagram.
Also, the OP ran the following query:
DELETE FROM tbl_indentmaster WHERE indentId IN (1,2,3,4,5,6,...,150,151,155,156,....)

That's an aweful lot of rows to delete. On enquiring further the OP claims that the query works for smaller subsets of indentId's.
From this I think we can take two possibilities:

*

*There's a bug in MySQL (highly unlikely but possible) which causes large queries with CASCADE DELETE like yours to fail. Note I am suggesting the possibility of a new bug not the one [posted already][2]. Ideally the number of rows to delete should not matter.

*There is a particular indentId entry within tbl_indentmaster which is causing the entire query to fail.

I'd suggest that you first try to diagnose the issue considering point (2) is the actual culprit. You can break the DELETE query into smaller chunks and find the offending id's.
If this script is something that has to be periodically executed through code (in a larger application) then you should consider executing the query in smaller chunks there as well (probably 15 id's per query is a good start IMO). In addition to doing this I'd suggest logging errors with offending id's in a log file so you know exactly which entries are failing.


text:
Q: Two doubly linked lists concatenation JAVA I'm having trouble implementing concatenation of two doubly linked lists. Here is my concat method. It seems OK, but as a result i get tail element of first list, and all elements of second list.
    public Node<?> concat(Node<?> head1, Node<?> head2)
{
    if(head1 == null)
    {
        return head2;
    }
    if(head2 == null)
    {
        return head1;
    }

    Node<?> n = head1;

    while(n.getNext() != null)
    {
        n = n.getNext();
    }
    n.setNext(head2);

    return head1;
}

Edit: DoubleLinkedList class:
public class DoubleLinkedList<E>
{
protected int size;
protected Node<?> head, tail;

public DoubleLinkedList()
{
    size = 0;
    clear();
}

public void clear()
{
    head = null;
    tail = null;
}

public int size()
{
    return size;
}

public boolean isEmpty()
{
    return head == null;
}

public Node<?> getHead()
{
    return head;
}

public Node<?> getTail()
{
    return tail;
}

public void add(E value)
{
    Node<E> node = new Node<E>(value);
    if(isEmpty())
    {
        head = node;
        tail = node;
    }
    else
    {
        tail.setNext(node);
        node.setPrevious(tail);
        tail = node;
    }
    size++;
}

public int indexOf(E value)
{
    Node<?> find = head;
    for(int i=0;i<size;i++)
    {
        E n = (E}find.getValue();
        if(n.equals(value))
        {
            return i;
        }
        find = find.getNext();
    }

    return -1;
}

public Node<?> concat(Node<?> head1, Node<?> head2)
{
    if(head1 == null)
    {
        return head2;
    }
    if(head2 == null)
    {
        return head1;
    }

    Node<?> n = head1;

    while(n.getNext() != null)
    {
        n = n.getNext();
    }
    n.setNext(head2);
    head2.setPrevious(n);

    return n;
}

private static final class Node<E>
{
    private E value;
    private Node<?> next, previous;

    public Node(E value)
    {
        this(value, null, null);
    }

    public Node(E value, Node<?> n, Node<?> p)
    {
        this.value = value;
        this.next = n;
        this.previous = p;
    }

    public E getValue()
    {
        return value;
    }

    public void setNext(Node<?> n)
    {
        this.next = n;
    }

    public Node<?> getNext()
    {
        return next;
    }

    public void setPrevious(Node<?> p)
    {
        this.previous = p;
    }

    public Node<?> getPrevious()
    {
        return previous;
    }
}

}

A: Instead of returning head1 try returning n.


text:
Q: setExposureCompensation returns "Illegal Argument" I have to change the exposure compensation of a Sony Alpha 7II by using the Sony Camera API (versions: Firmware 3.3, PlayMemories 4.31, API 2.40).
The three commands:

*

*getAvailableExposureCompensation (result: [0,15,-15,1]),

*getSupportedExposureCompensation (result: [[15],[-15],[1]]),

*getExposerCompensation (result: [0])

are returning correct response objects.
The command setExposureCompensation:

*

*("{\"method\":\"setExposureCompensation\",\"params\":[\"2\"],\"id\":1,\"version\":\"1.0\"}")

fails with the response:

*

*"{\"id\":1,\"error\":[3,\"Illegal Argument\"]}"

Regarding the syntax and value I don't see a reason why it fails. Any ideas?
Looking forward for any hints,
Yvo

A: I just stubbled uppon the same problem with my A6000 camera, but found out the correct way to call the api.
You have to send an integer between -15 & 15, so without the quotes.
So

,\"params\":[\"2\"],

becomes !

,\"params\":[2],

The range -15, 15 came from the actual exposure compensation range of -5.0, 5.0 with a incremental step of 1/3 of light stop. (-5.0*3steps=-15, 5*3steps=15).


text:
Q: How to create a form and be able to input the data from the form into a text file and be able to output a contents of a text file in HTML I have successfully hosted an .onion website but I don't have much experience in HTML codes. I need someone to tell me how to create a form + be able to input the submitted stuff inside the form (raw) into a text file + output the contents of a text file. Thanks :) Any help is greatly appreciated.

A: As per my understanding regarding your requirement, try below stuffs.
In view page(page for input form) use the below HTML code.

        <form action="" method="POST">
            <input name="field1" type="text" />
            <input name="field2" type="text" />
            <button type="submit">Save</button>
        </form>
        <button>Get file data</button>

Below the above HTML code use the PHP code below for processing submitted form inputs and to add the submitted form data to a text file(data.txt). The text file will be automatically created if it's not existing.
NB: You can also use a PHP file for this, for eg: form.php. In that case use <form action="form.php" method="POST"> in the above HTML code.
Create a file file_data.php and use below code.
$myFile = "data.txt";
$lines = file($myFile);//file in to an array

foreach($lines as $line)
{
    echo $line.'
';
}

Now, if you click on Get file data button in view page, data added to the text file will be printed.


text:
Q: How can I check a radio button with no id using a single line of javascript (no jQuery)? All right, this is a pretty specific question from a beginner, so bear with me.
I'm a newbie just learning the ropes. Here's the background (skip to next para if you don't care): I'm updating my first android app and I'm using MIT App Inventor 2 to do it. It's a free tool online that uses a WYSIWYG screen editor and Blockly to create behaviors, interactions, etc. The app I'm making loads a specific web page with a form and fills out most of the form for you (specifically, it's to help people enter the online ticket lottery for a theater show). The page is not my own so I can't edit the HTML. But I can run javascript on top of it by plugging single lines of javascript code into the Blockly side of App Inventor. Here's a relevant example of how it looks.
I've figured out how to fill in most of the form using getElementByID(). But there's a set of radio buttons that have no id. Here's a lightly modified version of the HTML (which I cannot edit):

        <input type="radio" name="tickets" value="1" />
        1

        <input type="radio" name="tickets" value="2" />
        2

    <input type="hidden" name="reqField" value="tickets" alt="Radio" req="true" errorMsg="Please enter a valid value." requredErrorMsg="This field is required. Please enter a value."
        patternID="0" customRegex="" />

I've made some progress by using the following:
document.querySelector('input[name=tickets]').checked = true;

But that of course only selects the first radio button. I'd like to able to get a value (1 or 2) and have it select the right button accordingly. The Blockly backend I'm using allows me to define a variable to plug into the line of javascript, but the line of javascript itself has to be essentially a single line. I was hoping one of the following would work if I wanted the value to be 2 for example:
document.querySelector('input[name=tickets][value=2]').checked = true;
document.querySelector('input[name=tickets]').2.checked = true;

But neither does. Any ideas on the correct syntax?
Thank you!

A: You need to place the value that you are trying to select using in quotes:
document.querySelector('input[name=tickets][value="2"]').checked = true;

Example

document.querySelector('input[name=tickets][value="2"]').checked = true;

    <input type="radio" name="tickets" value="1" />
    1

    <input type="radio" name="tickets" value="2" />
    2

  <input type="hidden" name="reqField" value="tickets" alt="Radio" req="true" errorMsg="Please enter a valid value." requredErrorMsg="This field is required. Please enter a value." patternID="0" customRegex="" />


text:
Q: VideoJS - embedded videos not working after number 7 I have a page with 10 videos. They are loaded in colorbox lightboxes.
I am using the standard videoJS markup.
Loading videos via:
View

and:

    <video id="5ways" class="video-js vjs-default-skin" controls
        preload="auto" width="618" height="348"
        data-setup="{}">
         <source src="//contiki-downloads.s3.amazonaws.com/agent/training-tools/video/5ways_converted.mp4" type="video/mp4">
         <source src="//contiki-downloads.s3.amazonaws.com/agent/training-tools/video/5ways_converted.WebM" type="video/webm">

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

    </video>

The bottom-most 3 videos (where they are positioned in the HTML) won't load. Videos 8, 9, 10 just get the loading spinner.
There's nothing wrong with the markup/paths to the videos. I have tested the URLs and they work fine. I have also tested commenting out some of the other video tags, which causes the broken videos to start working.
EG. If I comment out video 1, video 8 starts working.
Comment out video 2, video 9 starts working.
Comment out video 3, video 10 starts working.
The same is true for whatever order I do this in.
VideoJS will only allow 7 videos max to be embedded.
Anyone got any ideas? Or links to pages where more than 7 videos have successfully been embedded?

A: As I said over in the video.js issue tracker, it looks like you're hitting Chrome's max connections per domain. As well as not using preload="auto" you might try suggestions in this question, such as spreading the videos over different domains. You may be able to set up multiple cnames for your s3 bucket.
Increasing Google Chrome's max-connections-per-server limit to more than 6


text:
Q: Version Number Plugin Causes Pipeline Parsing Error The documentation says that the Version Number Plugin works with pipelines, and it is included in the Pipeline Snippet Generator.
The Snippet Generator gave me this as a simple example:
VersionNumber projectStartDate: '', versionNumberString: 'bob', versionPrefix: ''

I put this line into my Pipeline script, and it chokes when trying to parse it:
WorkflowScript: 92: unexpected token: projectStartDate @ line 92, column 22.
          VersionNumber projectStartDate: '', versionNumberString: 'bob', versionPrefix: ''
                        ^

Am I doing something wrong?

A: I came across the same issue. I fixed it with something like
VersionNumber(versionNumberString : '1.0-${BUILDS_ALL_TIME}', projectStartDate : '2017-03-16')

A: VersionNumber(versionNumberString: '1.0.1_${BUILDS_ALL_TIME, XXX}', projectStartDate: '2017-04-03', versionPrefix: '', worstResultForIncrement: 'SUCCESS')
it also worked for me.


text:
Q: Download Binary Data as a File Via Javascript I'm making an ajax call to an API that returns binary data. I'm wondering if its possible to take that binary data and display it for the client in a new window? This is what I'm doing right now. The problem is, the document opens up, but its completely blank.
$.ajax({
    type: "POST",
    url: apiURL,
    data: xmlRequest,
    complete: function(xhr, status) {
        var bb = new window.WebKitBlobBuilder();

        // Append the binary data to the blob
        bb.append(xhr.responseText);

        var blobURL = window.webkitURL.createObjectURL(bb.getBlob('application/pdf'));
        window.open(blobURL);
    }
});

Any ideas?

A: Okay, I figured it out. I had to specify the responseType as 'array buffer':
function downloadPDF() {

    var xhr = new XMLHttpRequest();
    xhr.open('POST', API_URL, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function(e) {
        if (this.status == 200) {
            var bb = new window.WebKitBlobBuilder();
            bb.append(this.response); // Note: not xhr.responseText

            var blob = bb.getBlob('application/pdf');
            var blobURL = window.webkitURL.createObjectURL(blob);

            window.open(blobURL);
        }
    };

    xhr.send(createRequest());
}


text:
Q: FC when send image via SMS in android String message = "HELLO MSM";
    Uri sendSmsTo = Uri.parse("smsto:" + "1111");

    Intent intent = new Intent(android.content.Intent.ACTION_SENDTO,
            sendSmsTo);
    intent.putExtra("sms_body", message);
    intent.putExtra(Intent.EXTRA_STREAM,
            Uri.parse(wallpaperDirectory.getPath() + "/nmc.jpg")); // url

    // intent.setType("audio/mp3");
    intent.setType("image/png");
    startActivity(intent);

But when run , app was FC
02-24 21:56:09.881 E       8333     AndroidRuntime                                            Process: com.example.a, PID: 8333
02-24 21:56:09.881 E       8333     AndroidRuntime                                            android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.SENDTO typ=image/jpg (has extras) }
Please help me check !
Thank you !

A: There is no activity that supports ACTION_SENDTO with a MIME type of image/jpg on your device.
Note that the MIME type for JPEG is image/jpeg.
But, beyond that, there is no requirement for every one of the ~1.5 billion Android devices to have an app that will handle your request. You need to either handle this exception or use PackageManager to check ahead of time whether your request will succeed.


text:
Q: How to add an active CSS property to a React component? I'm trying to add some styling so that when I click on an item it has a different background color.
I have a class App that imports class ItemSection that imports class ItemList. In both ItemSection and ItemList I have activeItem: React.PropTypes.object.isRequired declared in my propTypes.
I think the problem is in my App's render method:
  render(){
return(

 {/*Need a better className*/}
      <ItemSection
        items = {this.state.items}
        addItem = {this.addItem.bind(this)}
        setItem = {this.setItem.bind(this)}
        deleteItem = {this.deleteItem.bind(this)}
        editItem = {this.editItem.bind(this)}
        activeItem = {this.state.activeItem} /*THIS LINE I BELIEVE*/
      />

)
}

And this is my traceback:
bundle.js:1251 Warning: Failed prop type: Required prop activeItem was not specified in ItemList.
    in ItemList (created by ItemSection)
    in ItemSection (created by App)
    in div (created by App)
    in div (created by App)
    in App

A: You are stating in your question that you have activeItem: React.PropTypes.object.isRequired declared in your propTypes but you are specifically asking for activeItem in the state object - activeItem = {this.state.activeItem}. If you want to use the value of activeItem in the props you are passing to the component, then you must use this.props.activeItem.
Hope this helps!


text:
Q: Has anyone done a Javascript front end to a commercial rules engine? If so, did you use a JS templating framework (like Moustache or Jade) and CSS preprocessor (like LESS or Stylus) or let the BRE handle it all?

A: If I understood correctly you want to use the rules engine to control the client side.
One example that does something like this is TOHU.

Tohu is an engine built on Drools to create dynamic UIs.  It is an alternative to the traditional MVC approach which instead uses a generic UI layer to render arbitrary UIs defined using simple business rules.

A: I am working on a product that uses a quite sophisticated rule engine, so that you can "drop in" a set of rules to radically change the behavior of the system without having to change the system code.
Initially our rule engine was .NET based, but we are now considering migrating to a JS rule engine so that we can execute both client and server side. Then we can use handlebars to keep the view in sync with the js model and bind the rules to model events.
Of course you'll want to double check server side that the rules executed on the client have been adhered to, so you can execute the same code server side to verify.


text:
Q: Windows 10 and starting a program as administrator How to run program as administrator and how to run it normally in Windows 10 by simple clicking when you are logged as administrator? (this is my first question, so feel free to correct it)

A: We can run as administrator simply by right clicking on the shortcut and clicking "Run as administrator".
Another possibility is to change properties of the shortcut so that right clicking is not necessary. The steps to do this are as follows:

*

*Right click on the program (shortcut)

*Click on Properties

*Navigate to the Shortcut tab and find "Choose enhanced properties of this shortcut"

*Click on Advanced...

*Check Run as administrator

*Click OK twice

*(Optional) Rename the shortcut to know it runs under administrator rights

Previous method can make two independent shortcuts.
Another option:
Note that following method changes rights to the whole program, so you cannot have two independent shortcuts for a single program. If you just want to run program as administrator by right clicking, that is also valid option. The below changes rights to all shortcuts of the program.

*

*Right click on the program (shortcut)

*Click on Properties

*Navigate to the Compatibility tab

*Check Run this program as administrator

*Click OK


text:
Q: Hibernate Filter an associated entity in SpringBoot I have this structs of tables
tb_country
 id | name
-------------------------------
  1 | EUA
  2 | FRANCE
  3 | JAPAN

tb_cities
 id | name                  | country_id | save
-------------------------------------------------
  1 | CHICAGO               |     1      | true
  2 | NY                    |     1      | true
  3 | SEATLE                |     1      | false
  4 | PARIS                 |     2      | true
  5 | NICE                  |     2      | true
  6 | TOKIO                 |     3      | true
  7 | NAGOIA                |     3      | false

So I need to return the country and the cities with save = false, in sql I create:
"SELECT * FROM tb_country c1 JOIN tb_cities c2 ON c2.country_id = c1.id WHERE c2.save = false;

the will return only
EUA -> SEATLE
JAPAN -> NAGOIA.

SO if I put that select in a HQL
SELECT t FROM TbCountry c JOIN c.cities c2 WHERE c2.save = false;

he will return the country EUA and JAPAN but he will return all cities from that country
If I put in my entity @Where(clause = "save = false ")  will return only SEATLE and NAGOIA but if I need to change that clause, how can I make this dynamic?
tks


text:
Q: React Native Error: undefined is not an object when passing data to component I am getting an error when passing data to my component with props and trying to access it from there.
I have my data in the following format
export const data = [
  {
    id: 0,
    title: 'Test',
    price: 1500,

  },
];

I import it and pass the data like via props this:
const post0 = data[0];
...
<Post post={post0}/>

In my component I receive the data succesfully which I can verify via log like this console.log(props); and get the following log entry
{"post": {"id": "0", "price": "1500", "title": "Test"}}

When I now try to access a certain property like id in my component
<Text> { props.post.id } </Text>

I get the error 'TypeError: undefined is not an object (evaluating 'props.post.title')'
How can I use the data in my component? I am assuming I somehow have to map the data but couldn't resolve it.

A: Is your component a class based component or a functional component? If it is a class based component, you should access your props using "this" keyword. For example
export class Post extends React.Component {
  render() {
    return (
     <View>
      <Text>{this.props.post.id}</Text>
      <Text>{this.props.post.title}</Text>
     </View>
    )
  }

}

If it is a functional component, you can access the props directly. For example:
export function Post(props) {
  return (
    <View>
      <Text>{props.post.id}</Text>
      <Text>{props.post.title}</Text>
    </View>
  )
}

A: I found the problem myself.
I used the post component in my code a second time without any props so therefore it was indeed undefined. Getting the object properties like {post.id} works perfectly fine when always having an object handed to the component.


text:
Q: All GA4 page titles showing the same using bootstrap boilerplate I setup GA4 on my website and application but all the traffic is aggregating to the same page in my GA4 dashboard.
I believe this is because I have a title tag in the head of my boilerplate.ejs template which I render on every page on the app, so even if visitors click around the site GA4 interprets all the views taking place on the same page.
Changing the title changes the text in the tab header in the users browser.
Boilerplate.ejs

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to my app!</title>

Top code of all subsequent pages
<% layout('layouts/boilerplate')%>

Is there a way to get GA to recognize pages by section heading elements instead of the title?
(eg., the text from the top h1/h2/h3/etc).
Adding answer after comment from user
I had to pull my title tag out of the boilerplate template and add it around the H1 of each page I wanted to tile. Example:

<title>Pricing</title>

Then I also added the below script to the body of my boilerplate template:

Hopefully that helps anyone experiencing a similar issue!

A: normally, you don't use page titles to recognize pages. You use URLs.
Go to your site, open the Network tab or use a plugin like this, make sure you really fire page views on every SPA navigation and it's not just the first page.
Now compare those calls, see what's different in them. Use the dimension that indicates the difference in your reports to differentiate.
Also, not changing your titles (and URLs) is probably one of the worst mistakes one can make SEO-wise.


text:
Q: Groovy method that takes multiple arguments of type Maps i have a groovy method that works with hard coded variable of map containing maps. I would like to make, such that the maps are passed as arguments. The number of maps will vary as well. A simple representation that i am trying to achieve will be like so:
def name(Map p...) {
 //code to loop through each of the maps
    p.each { k ->
      "${k.first}, ${k.last}"
 //another loop with the internal map
    something {
       k.details.each { name, value ->
  //some code
        }
   }
 }
}

And example of the Map of maps that i would need to pass as Args looks like so:
def persons = [
[first: 'Jack', last: 'Smith', details: [gender: 'male', Age: 25]],
[first: 'Sean', last: 'Dean', details: [gender: 'male', Age: 26]]
]

Then down the line, i would like to call something like
name(persons)

how can i achieve this? My test so far in the groovyConsole isn't taking me anywhere...

A: I think the problem is, that you don't have a map of maps but a list of maps. So to be able to call your method with the persons as parameter you have to change its signature to:
def map(List p) {
    ...
}

This is my snippet in the groovyConsole:
def persons = [
    [first: 'Jack', last: 'Smith', details: [gender: 'male', Age: 25]],
    [first: 'Sean', last: 'Dean', details: [gender: 'male', Age: 26]]
]

class Person {
    def name(List p) {
        println p
    }
}

def p = new Person()
p.name(persons)

A: The problem is that you're passing a list to varArgs, you have to use *(list) to extract each element out of the list and pass them:
Example:
def name( Map... p ) {
  p.each{ println it}
}

def persons = [
[first: 'Jack', last: 'Smith', details: [gender: 'male', Age: 25]],
[first: 'Sean', last: 'Dean', details: [gender: 'male', Age: 26]]
]

name(*(persons))

Note: I am not quite sure I am using the right terminology but I hope you get the gist :)


text:
Q: can reset parameterized SQL? I'm new to Parameterized SQL, What I'm about doing is updating stuff with it, It's fine there, But i have a (log) table that holds that Parameterized SQL as Description of what happened, When i insert Parameterized SQL to log_table
it keeps showing "?" this symbol
code to save log:
    PreparedStatement stat;
    ResultSet rs;
    String sql="insert into rozhanai_log values (null,?,?,?)";
    try
    {
        stat = conn.prepareStatement(sql);
        stat.setString(1,sqlParadanan);//(sqlParadanan) is my parameterized SQL String
        stat.setTimestamp(2,time);
        stat.setString(3,empName);
        stat.execute();
    }
    catch (Exception e)
    {
        System.out.println("log Nabw");
        e.printStackTrace();
    }

and SQL String in (log) table shown like this:
update rozhanai_customer_account set rozhanai_money_balance = rozhanai_money_balance + 1000.0 where rozhanai_account_id=?

what can i do here?
i was thinking about something like (re-set the parameters)?
thanks

A: thanks for a_horse_with_no_name for helping, simply with PreparedStatement.toString() can get SQL String without any ? symbol
    .
    .
    stat.setString(3,empName);
    String fullSQL = stat.toString();
    System.out.println(fullSQL);
    .
    .
    .

output :

com.mysql.jdbc.JDBC4PreparedStatement@6b179d: insert into rozhanai_log values (null,update rozhanai_customer...,2018-05-23,'Hama')

thanks for you


text:
Q: Echo PHP variable from function for width: Style I need to get the variable  $percent_format outside of the loop for usage in my style to get the dynamical width für the div. But the Problem is i parameterized the funcion  Ofen_Auslastung with a sql result from the Loop. Any idea how to fix this?
foreach ($connection->query($sql) as $row) {

                        $j=0;
                        echo "
";
                            echo " <button onclick='myFunction()'></button>	";       //Bezeichnung1
                            echo "".$row[$j]."	";       //Bezeichnung1
                            list($total, $percent_format, $Anzahl) = Ofen_Auslastung($row[$j]);
                            $j++;
                            echo "".$row[$j]."	";       //Bezeichnung2
                            $j++;
                            echo "".$row[$j]."	";       //Bezeichnung3
                            $j++;
                            echo "

$percent_format%
 $Anzahl belegte Plätze sind $percent_format% Auslastung von $total Plätzen.
	";
                        echo "
";
                    }

                $connection = null; //reset connection

            }
            catch(PDOException $e)
                {
                    echo $e->getMessage();
                }
    echo "
";

            //echo "
";
            //print_r($sort);
            //echo " ******************************************************************
";
            //print_r($sorted);

            //echo "
";

            ?>

<button  value="Zurück" class="Button3" onclick="location.href='ma_QualiOverview.php'">Zurück</button>

thx for your help.

A: This line you are echo-ing a string:
 echo "

$percent_format%
 $Anzahl belegte Plätze sind $percent_format% Auslastung von $total Plätzen.
	";

Would help to close and reopen php around the variable...
 echo "

" . $percent_format . "%
 $Anzahl belegte Plätze sind " . $percent_format . "% Auslastung von $total Plätzen.
	";

A: You can always declare a variable outside of the loop then set it within the loop:
$percent_format = "";

foreach ($connection->query($sql) as $row) {

                        $j=0;
                        echo "
";
                            echo " <button onclick='myFunction()'></button>	";       //Bezeichnung1
                            echo "".$row[$j]."	";       //Bezeichnung1
                            list($total, $pcnt_format, $Anzahl) = Ofen_Auslastung($row[$j]);
$percent_format = $pcnt_format;
                            $j++;
                            echo "".$row[$j]."	";       //Bezeichnung2
                            $j++;
                            echo "".$row[$j]."	";       //Bezeichnung3
                            $j++;
                            echo "

{$percent_format}%
 $Anzahl belegte Plätze sind $percent_format% Auslastung von $total Plätzen.
	";
                        echo "
";
                    }

                $connection = null; //reset connection

            }
            catch(PDOException $e)
                {
                    echo $e->getMessage();
                }
    echo "
";

            //echo "
";
            //print_r($sort);
            //echo " ******************************************************************
";
            //print_r($sorted);

            //echo "
";

            ?>

A: I think you are trying to add dynamic width in the element div with class named inner. According to me you doesn't need variable $percent_format value outside the loop if you want to change the style css of the element div dynamically, which is already inside the loop. You just need to add inline css in div with class named inner like the code line in bold written below:
foreach ($connection->query($sql) as $row) {
  $j=0;
  echo "
";
  echo " <button onclick='myFunction()'></button>	";       //Bezeichnung1
  echo "".$row[$j]."	";       //Bezeichnung1
  list($total, $percent_format, $Anzahl) = Ofen_Auslastung($row[$j]);
  $j++;
  echo "".$row[$j]."	";       //Bezeichnung2
  $j++;
  echo "".$row[$j]."	";       //Bezeichnung3
  $j++;
  echo "

$percent_format%
 $Anzahl belegte Plätze sind $percent_format% Auslastung von $total Plätzen.
	";
  echo "
";
}

You doesn't need to call the variable $percent_format outside the foreach for this. And if you still want to call the variable outside the loop, you can use it. But doing so will only display the last item's value from the loop.
I hope this might solve your problem.


text:
Q: Sharing Sidekiq between two apps I am looking for a solution for communicating between two Rails app. I have two servers, one for web, and one for analytics. When an user signs up via web server, this server needs to notify analytic server to create some result (which may take a few minutes), then get the result from it.
Is it possible to have a Sidekiq server that can access to two servers at the same time (without setting up API)? How should I go about it?

A: Yes its possible. You can have shared redis database for both server. In your initializers/sidekiq.rb file,
Sidekiq.configure_server do |config|
    config.redis = { url: 'redis://localhost:6379/0', namespace: "sidekiq_app_name_#{Rails.env}" }
end

Sidekiq.configure_client do |config|
    config.redis = { url: 'redis://localhost:6379/0', namespace: "sidekiq_app_name_#{Rails.env}" }
end

A: Sidekiq uses Redis to store the jobs. You could have a shared redis database where you:

*

*push data into redis from one app

*pull data from redis from one other app


text:
Q: how to change all the label tags from one file I have a web application where I have used mustache.js. Now I need to be able to change all the text labels from one common file. Suppose I have a "start"  button and I need to change this "start" text to "you can start" and similarly for all other html text labels, so that I don't need to go to the individual mustache files to make the changes.
So how can I put all the texts in one file so that I can make changes from only that file? Please help.


text:
Q: I am trying to know the reason my code is not running I want to know where I have mistakes in my codes I am trying to fix it , hope someone will help )
def make_list(number) :
names = []
for item in number:

names.append(input("Enter your name') )
print (names)

number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
if name[1] == "A":
print("Name", name, "Starting from the work A")

A: I hope I've fixed all the indentations:
def make_list(number) : # function to make a list of numbers
    names = [] # create an empty list
    for i in range(number): # range(number) is a list of numbers from 0 to number-1
        names.append(input("Enter your name: ")) # append() adds an element to the end of the list

    return names # return the list

number = int(input("How many names need to be entered?")) # ask the user for the number of names
names = make_list(number) # call the function make_list()
for name in names: # for each name in the list
    if name[1] == "A": # if the second letter of the name is "A"
        print("Vmsa", name, "Starting from the work A") # print the name and the message


text:
Q: Use Heroku addon mongolab with node.js I am using node.js with mongo lab and I have followed the mongolab tutorial (https://devcenter.heroku.com/articles/mongolab#getting-your-connection-uri) to change my url of db like this in my code:
module.exports = new Db(settings.db, new Server('mongodb://heroku_app3178:e6dd5g3btvanua3gfbmk6@ds051740.mongolab.com', 51740, {}), {safe: true});

I tested with local run, and I indeed see node is trying to connect to this new URL.
But when I deploy to Heroku. Heroku always complain about this.
I tried different things for 3 hours got no clue.
This is my log, could you please help?
2014-11-20T06:35:55.290572+00:00 heroku[api]: Release v17 created by abcc@gmail.com
2014-11-20T06:35:57.385492+00:00 heroku[web.1]: Starting process with command `node app.js`
2014-11-20T06:35:58.836675+00:00 heroku[web.1]: State changed from starting to up
2014-11-20T06:35:59.876883+00:00 app[web.1]: app.usr local
2014-11-20T06:36:00.396662+00:00 app[web.1]:     at Socket.emit (events.js:95:17)a
2014-11-20T06:36:00.394396+00:00 app[web.1]:
2014-11-20T06:36:00.396664+00:00 app[web.1]:     at net.js:440:14
2014-11-20T06:36:00.394894+00:00 app[web.1]:           throw err;
2014-11-20T06:36:00.396665+00:00 app[web.1]:     at process._tickCallback (node.js:419:13)
2014-11-20T06:36:00.396651+00:00 app[web.1]: Error: Error connecting to database: failed to connect to [127.0.0.1:27017] ====> why is this? so confused
2014-11-20T06:36:00.394918+00:00 app[web.1]:                 ^
2014-11-20T06:36:00.396654+00:00 app[web.1]:     at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:553:74)
2014-11-20T06:36:00.396656+00:00 app[web.1]:     at emit (events.js:106:17)
2014-11-20T06:36:00.396659+00:00 app[web.1]:     at emit (events.js:98:17)
2014-11-20T06:36:00.396658+00:00 app[web.1]:     at null.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
2014-11-20T06:36:00.396661+00:00 app[web.1]:     at Socket.<anonymous> (/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/connection.js:512:10)
2014-11-20T06:36:00.394676+00:00 app[web.1]: /app/node_modules/connect-mongo/lib/connect-mongo.js:178
2014-11-20T06:36:00.415816+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=enigmatic-coast-5373.herokuapp.com request_id=165ef7e7-a68a-44b0-9706-f72fcd9a0ba4 fwd="54.83.129.179" dyno=web.1 connect=2ms service=540ms status=503 bytes=0
2014-11-20T06:36:01.075007+00:00 heroku[web.1]: State changed from crashed to starting
2014-11-20T06:36:01.074333+00:00 heroku[web.1]: State changed from up to crashed
2014-11-20T06:36:01.057123+00:00 heroku[web.1]: Process exited with status 8
2014-11-20T06:36:02.976453+00:00 heroku[web.1]: Starting process with command `node app.js`
2014-11-20T06:36:04.328809+00:00 heroku[web.1]: State changed from starting to up

A: Your error message is showing that you're trying to connect to your local database on localhost (127.0.0.1).
What you should be doing in your code is using your Herkou environment variables, eg:
module.exports = new Db(settings.db, new Server(process.env.MONGOLAB_URL, {}), {safe: true});

A: You can connect to your remote mongodb specifying it in the code, and this will affect to the local and cloud implementation, or in heroku, you can use environment variables for cloud use. Go to your app-settings-reveal config vars, and add,
first field: MONGOLAB_URI
second field: mongodb://yourmongolabuser:yourmongolabpass@dsnumber.mongolab.com:number/yourapp
MongoLab shows you the uri, you only must change de User and Password.
Another thing can helps your node app not to crash is changing mode to production, again in env variables:
NODE_ENV=production


text:
Q: Pip installing tensorflow on Ubunutu EC2 instance - No space left on device, even though TMPDIR has plenty of space? I have an EC2 instance running Ubuntu 18.04. I had tensorflow 1.14 installed as I was trying to run a cloned repo but I needed to upgrade to tensorflow 2.2. I uninstalled tensorflow 1.14 and tried running pip install tensorflow but I get the following output:
Defaulting to user installation because normal site-packages is not writeable
Collecting tensorflow
  Using cached tensorflow-2.2.0-cp36-cp36m-manylinux2010_x86_64.whl (516.2 MB)
Requirement already satisfied: termcolor>=1.1.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied: opt-einsum>=2.3.2 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (3.2.1)
Requirement already satisfied: google-pasta>=0.1.8 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (0.2.0)
Requirement already satisfied: absl-py>=0.7.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (0.9.0)
Requirement already satisfied: gast==0.3.3 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (0.3.3)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (2.10.0)
Requirement already satisfied: wrapt>=1.11.1 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.12.1)
Requirement already satisfied: wheel>=0.26; python_version >= "3" in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (0.34.2)
Requirement already satisfied: tensorboard<2.3.0,>=2.2.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (2.2.2)
Requirement already satisfied: numpy<2.0,>=1.16.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.18.5)
Requirement already satisfied: grpcio>=1.8.6 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.29.0)
Requirement already satisfied: tensorflow-estimator<2.3.0,>=2.2.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (2.2.0)
Requirement already satisfied: scipy==1.4.1; python_version >= "3" in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.4.1)
Requirement already satisfied: keras-preprocessing>=1.1.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.1.2)
Requirement already satisfied: six>=1.12.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.15.0)
Requirement already satisfied: astunparse==1.6.3 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (1.6.3)
Requirement already satisfied: protobuf>=3.8.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorflow) (3.12.2)
Requirement already satisfied: google-auth<2,>=1.6.3 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.16.1)
Requirement already satisfied: markdown>=2.6.8 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (3.2.2)
Requirement already satisfied: requests<3,>=2.21.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (2.23.0)
Requirement already satisfied: setuptools>=41.0.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (47.1.1)
Requirement already satisfied: werkzeug>=0.11.15 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.0.1)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.0.post3)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.1.0)
Requirement already satisfied: rsa<4.1,>=3.1.4 in /home/ubuntu/.local/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (4.0)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/lib/python3/dist-packages (from google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.2.1)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /home/ubuntu/.local/lib/python3.6/site-packages (from markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.6.1)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.22)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2018.1.18)
Requirement already satisfied: idna<3,>=2.5 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (2.6)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/lib/python3/dist-packages (from requests<3,>=2.21.0->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.0.4)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (1.3.0)
Requirement already satisfied: pyasn1>=0.1.3 in /usr/lib/python3/dist-packages (from rsa<4.1,>=3.1.4->google-auth<2,>=1.6.3->tensorboard<2.3.0,>=2.2.0->tensorflow) (0.4.2)
Requirement already satisfied: zipp>=0.5 in /home/ubuntu/.local/lib/python3.6/site-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)
Requirement already satisfied: oauthlib>=3.0.0 in /home/ubuntu/.local/lib/python3.6/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.3.0,>=2.2.0->tensorflow) (3.1.0)
Installing collected packages: tensorflow
ERROR: Could not install packages due to an EnvironmentError: [Errno 28] No space left on device

I have an EBS volume with 11 GiB of free space mounted as /data/. This is the output of df -h:
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           376M  772K  375M   1% /run
/dev/xvda1      7.7G  5.6G  2.2G  73% /
tmpfs           1.9G     0  1.9G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/loop0       94M   94M     0 100% /snap/core/8935
/dev/loop1       18M   18M     0 100% /snap/amazon-ssm-agent/1566
/dev/xvdb        50G   40G   11G  79% /data
/dev/loop2       98M   98M     0 100% /snap/core/9289
tmpfs           376M     0  376M   0% /run/user/1000

With pip, I tried specifying running with --no-cache-dir but it did not work. I set TMPDIR as my data partition; here is the output of echo $TMPDIR: /home/ubuntu/../../data (which is where my partition is)
I also tried pip install --build=/ tensorflow inside my data partition and got really odd behavior; it output:
Defaulting to user installation because normal site-packages is not writeable
Collecting tensorflow
  Using cached tensorflow-2.2.0-cp36-cp36m-manylinux2010_x86_64.whl (516.2 MB)
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/tensorflow/tensorflow'
Check the permissions.

I ran the same command with sudo and got:
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: tensorflow in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: mock>=2.0.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: keras-applications>=1.0.6 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: enum34>=1.1.6 in /usr/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: tensorboard<1.15.0,>=1.14.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: gast>=0.2.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: wheel in /usr/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: numpy<2.0,>=1.14.5 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: six>=1.10.0 in /usr/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: tensorflow-estimator<1.15.0rc0,>=1.14.0rc0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: backports.weakref>=1.0rc1 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python2.7/dist-packages (from tensorflow)
Requirement already satisfied: futures>=2.2.0; python_version < "3.2" in /usr/local/lib/python2.7/dist-packages (from grpcio>=1.8.6->tensorflow)
Requirement already satisfied: funcsigs>=1; python_version < "3.3" in /usr/local/lib/python2.7/dist-packages (from mock>=2.0.0->tensorflow)
Requirement already satisfied: h5py in /usr/local/lib/python2.7/dist-packages (from keras-applications>=1.0.6->tensorflow)
Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python2.7/dist-packages (from tensorboard<1.15.0,>=1.14.0->tensorflow)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python2.7/dist-packages (from tensorboard<1.15.0,>=1.14.0->tensorflow)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python2.7/dist-packages (from tensorboard<1.15.0,>=1.14.0->tensorflow)

But this did not actually install tensorflow (as evidenced by pip list)

A:
Requirement already satisfied: termcolor>=1.1.0 in /home/ubuntu/.local/lib/python3.6/site-packages

vs

Requirement already satisfied: tensorflow in /usr/local/lib/python2.7/dist-packages

When you are using sudo. It seems to be switching to a different python.

pip install --build=/ tensorflow

You used this with the absolute path pointing to root. Try with . relative to current directory or the absolute e.g. /home/ubuntu/../../data to your data partition. Making sure you have write permissions to that folder.


text:
Q: Copying files defined in a list from network location I'm trying to teach myself enough powershell or batch programming to figure out to achieve the following (I've had a search and looked through a couple hours of Youtube tutorials but can't quite piece it all together to figure out what I need - I don't get Tokens, for example, but they seem necessary in the For loop). Also, not sure if the below is best achieved by robocopy or xcopy.
Task:
Define a list of files to retrieve in a csv (file name will be listed as a 13 digit number, extension will be UNKNOWN, but will usually be .jpg but might occasionally be .png - could this be achieved with a wildcard?)
list would read something like:
9780761189931
9780761189988
9781579657159

For each line in this text file, do:
Search a network folder and all subfolders
If exact filename is found, copy to an arbitrary target (say a new folder created on desktop)
(Not 100% necessary, but nice to have) Once the For loop has completed, output a list of files copied into a text file in the newly created destination folder
I gather that I'll maybe need to do a couple of things first, like define variables for the source and destination folders? I found the below elsewhere but couldn't quite get my head around it.
set src_folder=O:\2017\By_Month\Covers
set dst_folder=c:\Users\%USERNAME&\Desktop\GetCovers
for /f "tokens=*" %%i in (ISBN.txt) DO (
    xcopy /K "%src_folder%\%%i" "%dst_folder%"
)

Thanks in advance!

A: This solution is in powershell, by the way.
To get all subfiles of a folder, use Get-ChildItem and the pipeline, and you can then compare the name to the insides of your CSV (which you can get using import-CSV, by the way).
Get-ChildItem -path $src_folder -recurse | foreach{$_.fullname}

I'd personally then use a function to edit the name as a string, but I know this probably isn't the best way to do it. Create a function outside of the pipeline, and have it return a modified path in such a way that you can continue the previous line like this:
Get-ChildItem -path $src_folder -recurse | foreach{$_.CopyTo (edit-path $_.fullname)}

Where "edit-directory" is your function that takes in the path, and modifies it to return your destination path. Also, you can alternatively use robocopy or xcopy instead of CopyTo, but Copy-Item is a powershell native and doesn't require much string manipulation (which in my experience, the less, the better).
Edit: Here's a function that could do the trick:
function edit-path{
Param([string] $path)
     $modified_path = $dst_folder + "\"
     $modified_path = $path.substring($src_folder.length)
     return $modified_path
}

Edit: Here's how to integrate the importing from CSV, so that the copy only happens to files that are written in the CSV (which I had left out, oops):
$csv = import-csv $CSV_path
Get-ChildItem -path $src_folder -recurse | where-object{$csv -contains $_.name} | foreach{$_.CopyTo (edit-path $_.fullname)}

Note that you have to put the whole CSV path in the $CSV_path variable, and depending on how the contents of that file are written, you may have to use $_.fullname, or other parameters.

A: This seems like an average enough problem:
$Arr = Import-CSV -Path $CSVPath

Get-ChildItem -Path $Folder -Recurse |
  Where-Object -FilterScript { $Arr -contains $PSItem.Name.Substring(0,($PSItem.Length - 4)) } |
  ForEach-Object -Process {
    Copy-Item -Destination $env:UserProfile\Desktop
    $PSItem.Name | Out-File -FilePath $env:UserProfile\Desktop\Results.txt -Append
  }

I'm not great with string manipulation so the string bit is a bit confusing, but here's everything spelled out.


text:
Q: Converting heximal to decimal I am trying to parse a BLOB (binary object) from an api.
Supposedly a0acb90300000000 in hex represents 62500000 in decimal format.
However, when I convert 62500000 to hexadecimal I get 3b9aca0
I'm not sure what type of conversion it is.

A: Hopefully putting everything in a code block is okay, it makes things easier to format.
a0acb90300000000
Lets add some spaces and capitalize letters:
A0 AC B9 03 00 00 00 00

62500000
Windows calculator converts to:
3B9ACA0
This is a number from a calculator, lets add spaces right to left
3 B9 AC A0
Lets add some zeros to the left side, we have:
00 00 00 00 03 B9 AC A0
Before:
A0 AC B9 03 00 00 00 00

Your initial hex blob is in little endian, and is a 64-bit integer, possibly unsigned.
Wikipedia has further reading on: Endianness
The language you're using should have something to unpack that for you.


text:
Q: Mapping between scatter plot points and image pixels I started with a set of points from a laser scan which I plotted as a scatter plot using matplotlib. I then used plt.savefig to be able to open the plot as an image and use openCV to find contours around the points. Now, I want to be able to find the centers of the contours and plot them as points in the original scatter plot. The problem is I don't know how to create a mapping between the original scatter plot points and the image pixels. Is there a way to do this? Or another way to mark the center of the contours in matplotlib?
Note: the reason I need to draw contours is that later I need to use openCV's matchShapes function to compare the contours.
Here are the images from each step:
scatter plot
,
contours with centers marked in red

Now I basically want to be able to add the red markings from the image to the scatter plot.
Here is my code:
    plt.scatter(X[:,0], X[:,1], s=2)
    plt.axis('equal')
    plt.axis('off')
    plt.savefig(name)
    plt.clf()
    img = cv2.imread(name)
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgGray, 127, 255, 0)

    im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    height = img.shape[0]
    width = img.shape[1]
    blank_image = np.zeros((height,width,3), np.uint8)

    cv2.drawContours(blank_image, contours, -1, (255,0,0))

    for contour in contours:
        M = cv2.moments(contour)
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        cv2.circle(blank_image, (cX, cY), 2, (0, 0, 255), -1)
    cv2.imwrite(name, blank_image)

UPDATE:
Based on suggestions I looked at matplot's transforms function and tried the following:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x_coords, y_coords, 'bo', markersize=2)
ax.axis('equal')
ax.axis('off')
height1 = fig.get_figheight()*fig.dpi
width1 = fig.get_figwidth()*fig.dpi
inv = ax.transData.inverted()

plt.savefig('img.png')

img = cv2.imread('img.png')
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgGray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

height = img.shape[0]
width = img.shape[1]
blank_image = np.zeros((height,width,3), np.uint8)

centers_x = []
centers_y = []

for contour in contours:
    M = cv2.moments(contour)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    centers_x.append(inv.transform((cX, height1-cY))[0])
    centers_y.append(inv.transform((cX, height1-cY))[1])

    cv2.drawContours(blank_image, [contour], -1, (255,0,0),1)
    cv2.circle(blank_image, (cX, cY), 2, (0, 0, 255), -1)

cv2.imwrite("test.png", blank_image)

ax.plot(centers_x, centers_y, 'ro', markersize=4)

plt.show()

This got me close but it seems like the x coordinates are still slightly off
new result]
.
I also tried
centers_x.append(inv.transform((width1-cX, height1-cY))[0])
centers_y.append(inv.transform((width1-cX, height1-cY))[1])

but that also didn't work.
FINAL UPDATE: adding
plt.tight_layout()

solved the problem.

A: x = np.linspace(0,1,10)
y = 5*x+2

fig, ax = plt.subplots()
ax.scatter(x,y)

height = fig.get_figheight()*fig.dpi
width = fig.get_figwidth()*fig.dpi

# the coordinates in pixel
cX = 147
cY = 142

# we need to invert the y value as matplotlib considers (0,0) to be
# on the lower left, while opencv uses upper left as origin
tX,tY = ax.transData.inverted().transform([cX,height-cY])
ax.scatter(tX,tY, s=50, c='r')
fig.savefig('test.png', dpi=fig.dpi)


text:
Q: Размещение элементов - Flex 3 контейнера одинаковой длины, хочу понять, как  разместить кнопку в нижней части контейнера на все три одном уровне. Это можно сделать с помощью относительного позиционирования, но я хочу понять как это сделать с помощью флексов или каким-то другим способом.

*{
  margin: 0;
  padding: 0;
}

#sail{
  width: 100%;
  max-width: 1200px;
  margin: auto;
  display: flex;
  justify-content: center;
  padding-top: 80px;
  gap: 1rem;

}

.product{
  width: 25%;
  border: 2px solid black;
  text-align: center;
  /*position: relative;*/
}

.product-pages{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

}

.product-page{
  margin: 20px;
  margin-bottom: 50px;

}

h3{
  text-align: center;
  padding: 5px;
  background: #dcd5d5;
  font-size: 1.5rem;
}

.product-price{
  font-size: 1.3rem;
  font-weight: bold;
  margin-bottom: 10px;
}

button{
  width: 50%;
  font-weight: bold;
  font-size: 1rem;
  background: #a9e5db;
  color: #326;
  border: none;
  padding: 5px;
  margin-bottom: 10px;
  text-transform: uppercase;
 /* position: absolute;
  bottom: 0;*/

}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />

 <container id="sail">

TENOR TROMBONE

                600
                $

Духовой инструмент, изготовляемый из меди, способный воспроизводить звуки басово-тенорового регистра.

      <button>Выбрать</button>

BASS TROMBONE

                900
                $

 С большим отверстием, раструбом и мундштуком для облегчения игры в низких регистрах, и обычно двумя клапанами для заполнения недостающего диапазона непосредственно над тонами педалей.

      <button>Выбрать</button>

VALVE TROMBONE

                1200
                $

Духовой инструмент семейства тромбонов, который имеет набор клапанов для изменения высоты тона вместо (или в дополнение к) ползуна.

      <button>Выбрать</button>

 </container>

A: Можно таким способом
https://codepen.io/GRCR13/pen/MWBrNNm

.wrapper {
  display: flex;
  justify-content: space-evenly;
}

.product {
  display: flex;
  width: 25%;
  border: 2px solid black;
  text-align: center;
  flex-direction: column;
}

.product_title {
  text-align: center;
  padding: 5px;
  background: #dcd5d5;
  font-size: 1.5rem;
}

.product_price {
  font-size: 1.3rem;
  font-weight: bold;
  margin: 15px;
}

.product_description {
  margin-bottom: 30px;
}

.product_button {
  margin-top: auto;
  width: 50%;
  font-weight: bold;
  font-size: 1rem;
  background: #a9e5db;
  color: #326;
  border: none;
  padding: 5px;
  margin-bottom: 10px;
  text-transform: uppercase;
  align-self: center;
  display: flex;
  justify-content: center;
}

TENOR TROMBONE

600 $

Духовой инструмент, изготовляемый из меди, способный воспроизводить звуки басово-тенорового регистра.
<button class="product_button">Выбрать</button>

BASS TROMBONE

900 $

С большим отверстием, раструбом и мундштуком для облегчения игры в низких регистрах, и обычно двумя клапанами для заполнения недостающего диапазона непосредственно над тонами педалей.

    <button class="product_button">Выбрать</button>

VALVE TROMBONE

1200 $

Духовой инструмент семейства тромбонов, который имеет набор клапанов для изменения высоты тона вместо (или в дополнение к) ползуна.
<button class="product_button">Выбрать</button>