text:
Q: IntegrityError at /contacts/import in django when i am going to import csv file and parse it i am getting following erro

django.db.utils.IntegrityError: NOT NULL constraint failed: inven_app_clientcontact.author_id
  [29/Apr/2019 17:56:32] "POST /contacts/import HTTP/1.1" 500 188071

here is my code
   @login_required
def contact_upload(request):
    template = 'site/contact_upload.html'
    prompt = {
        'order': 'Order of the CSV should be client_name, client_company_name, email, work_phone'
    }

if request.method == 'GET':
    return render(request, template, prompt)

csv_file = request.FILES['file']

if not csv_file.name.endswith('.csv'):
    messages.error(request, 'This is not a csv file')

data_set = csv_file.read().decode('utf-8')
io_string = io.StringIO(data_set)
next(io_string)

for column in csv.reader(io_string, delimiter=',', quotechar='|'):
    _, created = ClientContact.objects.filter(author=request.user).update_or_create(
        client_name=column[0],
        client_company_name=column[1],
        email=column[2],
        work_phone=column[3]
    )
context = {}

return render(request, template, context)

any help would be appriciated. Thank you. If any code is needed please let me know

A: The error suggests that you are trying to save an object without a user. You haven't showed the full traceback which will show exactly where the error is occurring, but it could be in your update_or_create call - you should set author in the defaults or add it to the kwargs. For example:
_, created = ClientContact.objects.filter().update_or_create(
    client_name=column[0],
    client_company_name=column[1],
    email=column[2],
    work_phone=column[3],
    author=request.user,
)


text:
Q: Running a shell script as a mix alias How can you run a shell script as a mix alias?
I've tried the following with no luck:
defp aliases() do
  [
    "test": [ "./scripts/test.sh" ]
  ]
end

defp aliases() do
  [
    "test": [ "scripts/test.sh" ]
  ]
end

Each returns with a variation of:
** (Mix) The task "./scripts/test" could not be found

A: You can use invoke the Mix.Tasks.Cmd task for this:
"test": ["cmd ./scripts/test.sh"]

$ cat a.sh
#!/bin/bash
echo foo
$ cat mix.exs | grep test
      "test": ["cmd ./a.sh", "cmd echo bar"]
$ mix test
foo
bar

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using tableviews to display data from an array and getting error msg "message sent to deallocated instance" I'm new to iOS programming and I've gotten this error when trying to run my code.
[UIView _forgetDependentConstraint:]: message sent to deallocated instance 0xe65a0f0

I have two views in my project. The first view uses JSONserialization to populate a tableView with items.  And I use the method didSelectRowAtIndexPath to send the corresponding objects to the next view.
The items are displayed fine in the first view, so far so good. But when I try to load the second view after selecting an item in the tableView it crashes and gives back the error written above.
When I set a breakpoint on viewDidLoad in spelControllerView.m, kategorier gets 3 objects but when it tries to count the array kategorier the error message above is thrown.
Here's my code:
1st view ViewController.m in didSelectRowAtIndexPath:
SpelControllerView *spelControllerView = [[SpelControllerView alloc] initWithNibName:@"SpelControllerView" bundle:nil];
spelControllerView.title = [[jsonSnippet objectAtIndex:indexPath.row] objectForKey:@"CategoryName"];
spelControllerView.kategorier = [[jsonSnippet objectAtIndex:indexPath.row] objectForKey:@"Games"];
[self.navigationController pushViewController:spelControllerView animated:YES];

2nd view SpelViewController.m
    - (void)viewDidLoad{
[super viewDidLoad];
kategorier = [[NSMutableArray alloc] init];
tableViewControl.dataSource = self;
tableViewControl.delegate = self;}
    - (int)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;}

    - (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [kategorier count];}

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{static NSString *cellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

cell.textLabel.text = [[kategorier objectAtIndex:indexPath.row] objectForKey:@"Games"];
return cell;}

SpelControllerView.h:
    @interface SpelControllerView : UIViewController <UITableViewDelegate, UITableViewDataSource> {

UITableView *tableViewControl;
NSMutableArray *kategorier;}
    @property (nonatomic, retain) NSMutableArray *kategorier;

Thanks for your help!
Update:
This is my Json file.
    [
      {
        "CategoryName": "Arcade",
        "Games": [
          {
            "GameName": "Arcade game 1"
          },
          {
            "GameName": "Arcade game 2"
          },
          {
            "GameName": "Arcade game 3"
          }
        ],
      },
      {
        "CategoryName": "FPS ",
        "Games": [
          {
            "GameName": "FPS game 1"
          },
          {
            "GameName": "FPS game 2"
          }
        ],

      },
      {
        "CategoryName": "Strategy",
        "Games": [
          {
            "GameName": "Strategy game 1"
          },
          {
            "GameName": "Strategy game 2"
          }
        ],

      },
      {
        "CategoryName": "C64",
        "Games": [
          {
            "GameName": "C64 game 1"
          },
          {
            "GameName": "C64 game 2"
          }
        ],

      }
    ]

A: Remove the following line from viewDidLoad in SpelViewController:
kategorier = [[NSMutableArray alloc] init];

You should not reinitialize kategorier after getting the JSON data from first viewController.


text:
Q: DevExpress GridControl mainview not showing information I have a GridControl from Devexpress and I fill the control with a DataRow object. The row is added to the grid but the cells are empty. Here's the code:
        DataTable dt = new DataTable();
        dt.Columns.Add("Descripcion");
        dt.Columns.Add("Cantidad");
        dt.Columns.Add("Importe");
        gridControl1.DataSource = dt;

        clsLineaTicket newLn = new clsLineaTicket("Gin Tonic Beefeater", "1", "9,20");
        DataRow dr = dt.NewRow();
        dr[0] = newLn.strDescripcion;
        dr[1] = newLn.strCantidad;
        dr[2] = newLn.strImporte;
        dt.Rows.Add(dr);
        gridControl1.DataSource = dt;

The code is pretty simple, any idea why is not working? Thank you.

A: To solve your problem you should set the FieldNames of your GridColumns to the ColumnNames of your DataTable.
But i would strongly recommend you to use List<clsLineaTicket> instead of convert this to DataTable.
At first you already got an object and the Grid can handle this pretty well. So converting this to DataRows seems to be unnecessary. Don't forget any object needs space and a DataRow is still an object.
Further a List<clsLineaTicket>brings you Object access instead of DataRow access. This is more readable and better for refactorings. So you could easily rename a Property via refactoring. But how to rename a column in your DataTable? You access row["ColumnName"] sometimes? Then you are lost because magic string can't be refactored. Let me show small example for better readablity of List<T>:
Think you are in the event for a double click and you would to show the price of your ticket:
//This event is just a dummy and doesn't exists this way
private void grid_click(object sender, EventArgs e)
{
   //DataTable access
   var row = gridview.GetFocusedRow() as DataRowView;
   MessageBox.Show(Convert.ToString(row["Price"]);

   //List access
   var lineaTicket = gridView.GetFocusedRow() as LineaTicket; //You directly see it's a ticket here
   MessageBox.Show(lineaTicket.Price); //You don't need conversion
}

Another goodie is the possibility of Lambda and Linq. You need a SubList with alle Tickets which got a price lower 10$?
List<clsLineaTicket> lowPriceTickets = ticketList.FindAll(ticket=>ticket.Price < 10);

If you using a List make sure your FieldNames correspond to Propertynames. If you want to make the Grid editable you also need to implement setter on your Properties.
Hope this helps.


text:
Q: Exclude columns in Sqoop is there a way in Sqoop to get all the columns except one from SQL Server to Hadoop.
I do not want to write the --query or use --columns as the numbers of columns are more.
There is just one column which is causing the issue and dividing the data into multiple rows, and I don't need that column but need all others.
What is the best way to handle this? I tried looking for some option to exclude the columns but had no luck. Looking for some pointers here.

A: Try creating a View and Sqoop it.
Using SSMS you can right click and generate SELECT statement, remove that one column and create a View around it.
Hope this helps.


text:
Q: Regex match a string and its surrounding 2 characters I want to match a particular word and then retrieve a string containing it along with its 2 neighbours on both sides
The below code achieves this partially. But it fails when the match-word appears in the beginning of the string.
So is there a more efficient, flexible way to achieve this in regex?
text = "The world is a small place, we should try to take care of it"
sub = r'(\w+|.)\W(\w+|.)\W+(try)\W+(\w+|.)\W'
surrounding_text = re.findall(sub, text)

A: You can use the ? quantifier
To match the word "try" and one character of the previous or next word:
Try it out
(. )?try( .)?
Explanation:

*

*(. )?: Matches one character and then a space zero or one times

*try: Literally matches "try"

*( .)?: Matches a space and one character zero or one times

You could modify the . to match \w or \w+ if you want to match a word character or an entire word. Try it out
To match up to two words on either side, you can replace the ? with {0, 2} like so

A: You can make groups optional and use anchors:
(?:^|(?:(\w+)\W+)?(\w+)\W+)(world)(?:\W+(\w+)|$)

RegEx Demo

*

*(?:^|(?:(\w+)\W+)?(\w+)\W+): Match line start or patter after |

*(?:(\w+)\W+)?(\w+)\W+: Match one word or two words

*(?:\W+(\w+)|$) matches a word after 1+ non-word chars or end of string

A: import re
text = "The world is a small place, we should try to take care of it"
sub = re.compile(r'(?P<all>(\w*)\s*try\s*(\w*))')

    rez = [m.groupdict() for m in sub.finditer(text)]
    for item in rez:
       print(item["all"])

    text = "try to take care of it"

    rez = [m.groupdict() for m in sub.finditer(text)]
    for item in rez:
       print(item["all"])

I tested it on:
The world is a small place, we should try to take care of it
try to take care of it

and got:
should try to

try to

https://regex101.com/r/DlSJsJ/1

A: Just use a simple list:
text = "The world is a small place, we should try to take care of it"
d = text.split()

try:
    idx = d.index('world')
    print("{} {} {}".format(d[idx - 1], d[idx], d[idx + 1]))
except ValueError:
    print("Not in the text.")

Which yields
The world is

You need to account for negative indices here.


text:
Q: Communication between popup and opener from distinct domains I am writing an app using Phonegap (js, css and html on local filesystem) and I would like to get an oauth token from it.
So I open a popup to display our authentication server page. After the login process, it is redirected to the page I mentioned providing the code in its URL.
It appears the redirect page can't be a local file ("Not allowed to load local resource: file://...").
If I redirect to a page accessed using http I have an issue with "same origin policy" (SecurityError: Blocked a frame with origin "http://..." from accessing a cross-origin frame), and I can't access the main page (on local file system) from the popup using window.opener.
How could I communicate the code from the popup to a local file (Storage, webSocket, anything else)?

A: Can you not use InAppBrowser to navigate to this authentication page? (See more info here: http://cordova.apache.org/docs/en/3.3.0/cordova_inappbrowser_inappbrowser.md.html).
I am not certain on how your page returns the data, but I am sure there is a way you can return the generated data from InAppBrowser through to your app.


text:
Q: C# List Item counting in the Gridview I am trying to make a cash register.
How it works:
Scan barcode > get price > set amount of items > get total.
Now I have ran into a problem.
As I have tried to find how to get a count going/only get a single list item(in this case a int) but that information is quite rare. As I mainly would be able to find the amount of list in gridview.
what i want: is a way to calculate the total KassaItem.Quantitiy index in my list
My code:
public class KassaItem // making a class for making items in list
{
 public string EanNr { get; set; }
 public string zoekName { get; set; }
 public int Quantity { get; set; } // < i want to count this but, to total it. Not the total list in gridview.
 public double Price { get; set; }

 public KassaItem(string eanNr,string zoekname, int quantity, double price)
 {
  EanNr = eanNr;
  zoekName = zoekname;
  Quantity = quantity;
  Price = price;
 }
}

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
  List<KassaItem> KassaNew = new List<KassaItem>();
  bool isNew = true;

  if (TextBox1.Text != "")
  {
   foreach (var KassaItem in KassaList)
   {
    if (TextBox1.Text == KassaItem.EanNr)
    {
    KassaNew.Add(new KassaItem(KassaItem.EanNr, KassaItem.zoekName, KassaItem.Quantity + 1, KassaItem.Price));
    isNew = false;
    }
    else
    {
    KassaNew.Add(KassaItem);
    }
   }

   if (isNew)
   {
   KassaNew.Add(new KassaItem(TextBox1.Text, "vochtige doekies", 1, 4.99));
   }

   KassaList = KassaNew;

   GridView1.DataSource = KassaList;
   GridView1.DataBind();

   }
   IsTrue = true;
   Counter();
   TotalAmount = TotalQuan.ToString();
   TotalItems.Text = "Quantity " + TotalAmount;
   TextBox1.Text = "";
   TextBox1.Focus();

   }

Thanks in advance and in advance have a amazing holidays for everyone,
Explodeonyou

A: I'm not really sure what your question or goal is but for if you want the count for an item in your whole kassaNew-list this is the following you can use:
using System.Linq;

Here's a dotnetfiddle
or here directly:
using System;
using System.Collections.Generic;

// What you need:
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<KassaItem> KassaNew = new List<KassaItem>();
                KassaNew.Add(new KassaItem("yes", "Beer", 2, 20));
                KassaNew.Add(new KassaItem("yes", "Drink Cola", 1, 3.5));
                KassaNew.Add(new KassaItem("yes", "Drink Fanta", 1, 3.5));
                KassaNew.Add(new KassaItem("yes", "Chocolate Bar", 5, 10));
                KassaNew.Add(new KassaItem("yes", "Flower", 4, 40));

        // get single quantity
        // i have a query that searches the kassanew list after a name, you can use eanNr or anything else
        int singleItemQuantity = KassaNew.First(x => x.zoekName == "Beer").Quantity;
        int totalQuantity = 0;

        // get totalquantity
        foreach(KassaItem kassaItem in KassaNew)
        {
            totalQuantity += kassaItem.Quantity;
        }

        Console.WriteLine(singleItemQuantity);
        Console.WriteLine(totalQuantity);
    }
}

public class KassaItem // making a class for making items in list
{
 public string EanNr { get; set; }
 public string zoekName { get; set; }
 public int Quantity { get; set; } // < i want to count this but, to total it. Not the total list in gridview.
 public double Price { get; set; }

 public KassaItem(string eanNr,string zoekname, int quantity, double price)
 {
  EanNr = eanNr;
  zoekName = zoekname;
  Quantity = quantity;
  Price = price;
 }
}


text:
Q: Momentum gain of a square loop when switching of a wire causing magnetic field
A square frame made of wire with diameter $d_0$ is placed near a long straight wire carrying current $I_0$. When this current is turned off, a momentum $p_0$ is imparted to the frame. What momentum would be imparted to the frame if the initial current is $3I_0$ and diameter of the wire is $2d_0$

My conceptual doubts:

*

*As the current is turned off, the magnetic field and magnetic flux in the downward direction decrease.

*This should induce a current in the wire(if it is conducting)
Since it is not given that the wire is conducting, should it gain a momentum in the downward direction instead of a charge flowing?
Which equations would apply here that would lead me to an answer?

A: Here, the wire must be conducting according to the context of the question. Without a conducting loop , momentum will be not be imparted as far as the given system in question is concerned.
First of all, due to change in flux, a current will be induced.
A current carring wire(each side of square can be considered as a straight current carrying wire) in presence of a magnetic field( in this case,due to the long straight wire) experiences a force , which is due to the change in momentum.
Flux φ can be calculated by ∫B.da  (Remember B will vary with distance here).
Induced current I= E/R , E=dφ/dt  R is assumed to be the resistance of wire.
Force experience by wire= ILB (Again, B will vary,and think where force will be applied and where not due to direction of current).
Momentum imparted can be calculated  by 'solving' the equation F= dP/dt


text:
Q: Complex sql query - count + having + group by - how fix query i'm looking for help with one quite complex query in sql.
Query should sounds like:  (First query below)
I'm looking for products whitch are type: Beds and i would like to show all options assigned to them - group them and count how many of them are. (like in photo below).
Second part of query:  (second query below)
When user click checkbox i would like to show and count only products that have checked options and count how many of this products are. (and here is problem )
First query:
SELECT COUNT(DISTINCT id_product) as productMatched, COUNT(id_product) as haveProducts, product_to_features.id_feature_value, product_to_features.id_feature, feature_value_langs.name,feature_value_langs.id_feature_value, products.active
FROM product_to_features
LEFT JOIN feature_value_langs
   ON product_to_features.id_feature_value = feature_value_langs.id_feature_value
LEFT JOIN products
   ON product_to_features.id_product = products.id
WHERE price_retail >= 655.00
   AND price_retail <= 6455.00
   AND height >= 0.0 AND height <= 120.0
   AND width >= 0.0 AND width <= 262.0
   AND depth >= 0.0 AND depth <= 276.0
   AND product_to_features.id_feature_value IN (15981,15982,15983,16011,16012,16013,16019)  //its shows ids of bed sizes
   AND products.active = 1
GROUP BY product_to_features.id_feature_value

And this shows:

Second query - not working as it should be:
SELECT COUNT(DISTINCT product_to_features.id_feature_value) as productMatched, COUNT(product_to_features.id_product) as haveProducts, product_to_features.id_feature_value, product_to_features.id_feature, id_product as ProductId, feature_value_langs.name, products.active
FROM product_to_features
LEFT JOIN feature_value_langs
   ON product_to_features.id_feature_value = feature_value_langs.id_feature_value
LEFT JOIN products
   ON product_to_features.id_product = products.id
WHERE price_retail >= 655 AND price_retail <= 6455
   AND height >= 0 AND height <= 120
   AND width >= 0 AND width <= 262
   AND depth >= 0 AND depth <= 276
   AND (product_to_features.id_feature_value IN (15981,15982,15983,16011,16012,16013,16019)  // (its first checkbox group where non is checked - so i send all values )
   OR product_to_features.id_feature_value IN ( 1096)  // 1096 - its checked option from second checkbox group)
   OR product_to_features.id_feature_value = 1483 )   // 1483 - is BED TYPE (must be)
  AND products.active = 1
GROUP BY product_to_features.id_product having productMatched>2
ORDER BY product_to_features.id_feature

For example if i check 80x200 it must refresh  all other checkboxes and show how many match current options (checked) and count matching products.
And here is my db structure:
DESCRIBE product_to_features

id  int(11) NO  PRI     auto_increment
id_feature  int(10) unsigned    NO  MUL
id_product  int(10) unsigned    NO  MUL
id_feature_value    int(10) unsigned    NO  MUL

desc `feature_value_langs`

id  int(11) NO  PRI     auto_increment
id_feature_value    int(10) unsigned    NO  MUL
id_lang int(10) unsigned    NO  MUL
name    varchar(255)    YES MUL


text:
Q: How to select a subset of data from a large ER model? I have a quite large ER model in my database and lots of data. Now I would like to take a subset of this data into a different database for testing purposes. The problem is how to get a subset from all tables so that I don't break referential integrity and get orphanded records from the database? I mean that if I choose 100 records e.g. From the "product" table, how can I easily get all the data from the referenced tables (and from the tables these tables are referenced)? Is there any tool availble for this purpose or just pure SQL?

A: Unfortunately there isn't a cookie-cutter way to do this.  You have to start with some base records, write queries that join against them and then repeat.  As you go deeper the queries get more complex as they have to go right back to the root.
If you have the foreign keys then you can automate the generation of the queries, as the joins will just be through the foreign key columns.  It's not as hard as it sounds, but here are a few pointers if you take this approach:

*

*The queries are only going to retrieve the contents of the table at their leaf, so they are fairly straightforward to generate.

*Get the data out in a form that will load through bcp.  As a bonus, you can generate bcp control files from the system metadata.

*You can probably quite safely just copy all of the reference data, which probably accounts for the majority of your tables anyway.

*You may have to start from multiple roots, and you may have to manually add join metadata if you have missing foreign keys.  If your relationships to your leaf tables are not purely hierarchical then you may have to manually edit the metadata for the generator.  In practice this means you probably want to start from the system data dictionary and then make up a configuration file for your generator that works around this.

*You may also need to add custom queries in for certain data items if the selection criteria involve more than one path to the record.

*Generate or write a script that uses bcp to load the tables to the destination in the right order.
Automation will probably get you 95% of the way with some manual intervention and the scripts aren't all that hard to write.  It's not a 5 minute job, but it's certainly possible.
You could programatically generate SSIS packages to do the load, but I think that generating bcp control files is probably easier.  Another option would be to just structure the scripts so they copy the data from the queries into another shadow database.  This can then be backed-up/restored to wherever you want.
It's not a trivial undertaking but it's certainly not beyond the wit of man.  As a bonus, if you can configure your script so the starting keys can be parameterised, then you can make a generalised utility to copy subsets of your application database.  This will be quite useful for rolling out test environments.

A: The strategy would depend on the design of the schema.
You could take the first 1000 rows from each table and go from there. If you have constraints/keys/etc. that you cannot break then you need to identify the data to use. One way to do this is to create a list of key values from one of the tables and then select out from the other tables using a filter like:
WHERE <key value> IN "<key value list>"
or you could just use a subquery to replace the "<key value list>"
Another alternative is the make a copy of your database then delete a bunch of data (is there an associated application to the db that has a suitable delete function?) It may just be easier to recreate some data - especially if the database has an application attached to it.

A: Here at Redgate we're building SQL Clone, a solution that solves this problem but avoids the need to subset the data, as it uses virtualisation tech to provide access to the full data set for dev/test environments.
SQL Clone is still in preview and we're looking for feedback via an Early Access Program to know if this satisfies the database provisioning problem. If you have the problem and are able to help, please sign up!


text:
Q: Is receiving connection in peerjs a blocking action? If for example I want to wait for another peer to connect with peer.on('connection', connect) does it mean that I will be stuck on this instruction until another peer connects?

A: Well if i correctly understand, you don't stuck, because only limit what you have it's a upload and download limit.

Data sent between the two peers do not touch any other servers, so the
  connection speed is limited only by the upload and download rates of
  the two peers. This also means you don't have the additional latency
  of an intermediary server.

Docs


text:
Q: Do Voronoi cells "converge" towards their centroid? If you do the following:

*

*Place random points on a finite surface

*Draw the Voronoi diagram using the points as germs

*Calculate the centroid of each cell

*Repeat step 2 and 3 indefinitely using the centroids obtained in step 3 as germs.

How does that look like? Does it converge to a diagram where all the germs are in the centroid of their cell? I suspect there's a convergence most of the times, but is there a set of starting points where it doesn't converge?
Secondary question: Does the fact that the surface is finite change anything? I suspect it does, considering borders affects the position of the centroid around the edge (so after a few iterations, it affects all cells) but not the Voronoi cell.

A: This paper answers the question (and goes far beyond).
Reformulating theorem 2.1 tells you that, for every finite set of random points over a bounded surface, the iterated centroids will converges to some distribution. Although, as the paper mentions, the distribution limit may not be optimal in the sense that they do not necessarily split the surface evenly (see quantization error in the paper).
Unboundedness implies a lot of theoretical complications, which is in fact the main point of interest of this paper. Convergence can still be ensured by adding constraints to your initial set of points.


text:
Q: Expect Stuck in Infinite Loop I can only seem to get expect commands to work in an expect statement eg, expect {}. So the code below will exectute but the loop continues to see the default prompt which is "# ".
#!/usr/bin/expect -f
set filename [lindex $argv 0]
set timeout -1
spawn ssh user@IP
set pass "pass"
expect {
        password: {send "$pass\r" ; exp_continue}
    "# " {send "show card table all\r" ; exp_continue}
 }

The above code continutes to run the command over and over. I cant seem to be able to isolate expect/send commands.
I can not simply enter:
expect "# "
send "command"

Nothing will execute outside of expect {}
Many thanks.

A: How many times are you supposed to send "show card table all\r"? The way you've written it, every time you see #, you'll send that command.
Assuming you only need to see it once, remove exp_continue from that action:
expect {
    password: {send "$pass\r" ; exp_continue}
    "# " {send "show card table all\r"}
}
expect "# "
send "exit\r"
expect eof

That will send the password as many times as the password prompt appears. Then, if a "prompt" is seen, the "show card" command is sent and that expect command ends. I then expect a prompt, send "exit" (if that's the right command) and wait until the spawned process ends.


text:
Q: Android app sqlite database cannot dump in to android mobile I created database and table in sqlite database after that i can take thedatabaseoutside using file explore. And then i inserted some values into the table again i paste the database in same location in file explore .if i am run in emulator means it takes data from sqlite and populate listview in android mobile. after that the same app i put in mobile means it cannot take sqlite database.i think the sqlite database cannot dumped to the mobile while installing my app..please tell me the solution how to solve?
          This my database class

public Cursor queueAll() {
    String[] columns = new String[] { KEY_ID, KEY_CONTENT };
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
            null, null, null, null);

    int id = cursor.getColumnIndex(KEY_CONTENT);
    cursor.moveToFirst();
    if (cursor != null) {
        do {
            String keyid = cursor.getString(id);
            System.out.println(keyid);
        } while (cursor.moveToNext());
    }

    return cursor;
}

private static class SQLiteHelper extends SQLiteOpenHelper {

    public SQLiteHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(apptable);
        db.execSQL(souptable);
        db.execSQL(vegtable);
        db.execSQL(ricetable);
        db.execSQL(desserttable);
        db.execSQL(FoodMenutable);
        db.execSQL(SCRIPT_CREATE_DATABASE);
        db.execSQL(DATABASE_CREATE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

public long AddUser(String username, String password) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_USERNAME, username);
    initialValues.put(KEY_PASSWORD, password);
    return sqLiteDatabase.insert(DATABASE_TABLE, null, initialValues);

}

public boolean Login(String username, String password) {
    // TODO Auto-generated method stub
    Cursor mCursor = sqLiteDatabase.rawQuery("SELECT * FROM "
            + DATABASE_TABLE + " WHERE username=? AND password=?",
            new String[] { username, password });
    if (mCursor != null) {
        if (mCursor.getCount() > 0) {
            return true;
        }
    }
    return false;
}

  }

please help me

A: enter manually data in your database using your application because you can't modify or import database of your application from android mobile.


text:
Q: Is it just me or are there some new bugs in the Java Threads? This month I had four weird problems with Java methods running something in the UI thread like SwingUtilities.InvokeAndWait() and Display.syncexec().
The code running these methods worked for years but now they just seem to run into a deadlock.
I searched for bugs that would explain that, but all I can find is the Swing Webstart Bug:
NullPointerException in invokeLater while running through Java Webstart
To fix that, I used this solution:
https://stackoverflow.com/a/20102779/1503901
Now to my question:
Is this just my experience or is anyone facing the same problems? Could this be a bug, or is it just my code?
Thanks a Lot!


text:
Q: Converting PDF to Image without non-python dependencies I want to create an exe that can be deployed onto other computers. The program needs to be able to read pdf's and turn them into images, but I don't want other users to have to download dependencies.
My understanding is that py2image and wand both require external dependencies that, if you convert to a exe, other users would also need to download the dependencies themselves.
Are there other options available/ workarounds ?

A: I wasn't able to find a solution, apparently one needs a PDF renderer no matter what. The most lightweight solution is https://pymupdf.readthedocs.io/en/latest/intro.html. It is still a python binding for a PDF renderer (https://www.mupdf.com/), but you can install it, including its dependency, by:
pip install PyMuPDF

No need to install poppler or imagemagick.
Then you can convert a pdf to images as follows:
import fitz

doc = fitz.open(stream=your_pdf_file_stream, filetype="pdf")
for idx, page in enumerate(doc):
    pix = page.get_pixmap(dpi=600)
    the_page_bytes=pix.pil_tobytes(format="PNG")
    with open("page-%s.png"%idx, "wb") as outf:
        outf.write(the_page_bytes)

Unfortunately, mupdf has a copyleft license, so keep that in mind.

A: Actually, it took me a while to handle this, but I think it worth it.
You need to do all steps carefully to make it work.

*

*Install pdf2image with pip install pdf2image.

*Get poppler windows binaries.

*Create a new directory like myproject.

*Create a script converter.py inside myproject and add below code.

*Create another directory inside myproject and name it poppler.

*Copy all files in the binary folder of downloaded poppler into poppler directory. Try to test pdfimages.exe if it is working.

*Use pyinstaller converter.py -F --add-data "./poppler/*;./poppler" --noupx

*Your executable is now ready. Run it like converter.exe myfile.pdf. Results would be created inside the output directory next to the executable.

*Now your standalone PDF2IMAGE converter app is ready!

converter.py:
import sys
import os
from pdf2image import convert_from_path

def current_path(dir_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, dir_path)
    return os.path.join(".", dir_path)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("PASS your PDF file: \"converter.exe myfile.pdf\"")
        input()
        sys.exit(0)
    os.environ["PATH"] += os.pathsep + \
        os.pathsep.join([current_path("poppler")])

    if not os.path.isdir("./output"):
        os.makedirs("output")
    images = convert_from_path(sys.argv[-1], 500)
    for image, i in zip(images, (range(len(images)))):
        image.save('./output/out{}.png'.format(i), 'PNG')

PS: If you like it, you can add a GUI and add more settings for pdf2images.

A: I got the same problem while trying to make .exe file with pyqt5 and pdf2file modules, using pyinstaller.
If you need to add GUI created in PyQt5, do not add --windowed in pyinstaller command. That was ruining my work for 2days


text:
Q: run testcafe tests from Python Summary of my issue:
Goal: I have a javascript package that uses testcafe to perform simple search on python.org. I am trying to use this package in python test framework using js2py but it's giving me error when I try 'require("pyCafe").
Expected: able to use the js package in python without issue. My goal is to use testcafe automation scripts from Python, not sure if it's even possible.
Error: Parsing file /private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/fast-glob/out/readers/sync.js: Unexpected token (15:10)
at Deps.parseDeps (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/module-deps/index.js:519:15)
at getDeps (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/module-deps/index.js:447:44)
at /private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/module-deps/index.js:430:38
at ConcatStream. (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/concat-stream/index.js:37:43)
at ConcatStream.emit (events.js:327:22)
at finishMaybe (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/readable-stream/lib/_stream_writable.js:630:14)
at endWritable (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/readable-stream/lib/_stream_writable.js:638:3)
at ConcatStream.Writable.end (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/readable-stream/lib/_stream_writable.js:594:41)
at DuplexWrapper.onend (/private/var/folders/1n/tr0826l14yv89b5ypl4sbsc46qb010/T/tmpgnnrdlan/node_modules/readable-stream/lib/_stream_readable.js:577:10)
at Object.onceWrapper (events.js:421:28) {
What I have tried so far:

*

*I have created a UI automation framework in javascript/testCafe and published it internally

*created npm package 'pyCafe' of entire javascript/testcafe framework and pushed it to internal artifactory. tested this by running 'npm install pyCafe' which installs just fine but using 'require('pyCafe')' in python gives the above error.

*Also tried calling the above package from js code itself which also gives error.
{"code":"E1","isTestCafeError":true,"callsite":{"filename":"/Users/xxx/work/newjstest/node_modules/pyCafe/features/search.js","lineNum":23,"callsiteFrameIdx":5,"stackFrames":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}],"isV8Frames":true},"errStack":"Error: No ad placements found.\n    at w (https://media.ethicalads.io/media/client/v1.4.0/ethicalads.min.js:2:12068)\n    at https://media.ethicalads.io/media/client/v1.4.0/ethicalads.min.js:2:13187","pageDestUrl":"https://www.python.org/","id":"KgxFSGD"}
Code below as I couldn't upload to git.

*Pycafe/features/serach.js
var  { Selector, t, ClientFunction } =  require('testcafe');

class SearchPageModel {
    constructor () {
        this.TIMEOUT = 500
        this.search = Selector('#id-search-field')
        this.go = Selector('#submit')
        this.noResult = Selector('p').withExactText('No results found.')
    }
}

class SearchPage {
    constructor() {
        this.model = new SearchPageModel()
    }

    async search(item='webdriver') {
        await t
            .typeText(this.model.search, item)
            .click(this.model.go)
            .expect(this.model.noResult.exists).ok()

    }
}

module.exports = new SearchPage()

*index.js

#!/usr/bin/env node

module.exports = {
Search: require('./features/search.js'),
}

*package.json

{
  "name": "pyCafe",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "cd tests; testcafe chrome test.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.1",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babelify": "^10.0.0",
    "browserify": "^17.0.0",
    "browserify-shim": "^3.8.15",
    "js-yaml": "^3.14.1",
    "minimist": "^1.2.5",
    "testcafe": "^1.18.0",
    "winston": "^3.8.1"
  }
}

*test code

var {  t } = require('testcafe');
var {search} = require('../features/search.js')

fixture `Test`
    .page("https://www.python.org/")

test
    .meta({
        'testcase': 'C221913',
    })
    ('Test https://www.python.org/', async t => {
    try {
        console.log('search python.org')
        await search.search()
    } catch (e) {
        console.log('Testcase C221913 failed...')
    }
});

So here are my questions:

*

*Can we call js library from python directly and how.

*Is it possible to just invoke browser from python using testcafe? I guess not but checking anyway.

*how to use the js package in js correctly using the above example.

A: You can execute TestCafe tests using any language with the command-line interface.
As I see, you are already using it.
Code fragment:
"scripts": {
    "test": "cd tests; testcafe chrome test.js"
  },

You correctly run TestCafe tests. You were confused by the Java Script error tracking feature. By default, TestCafe handles JavaScript errors on the tested web page and fails
test if it has occurred.
https://www.python.org/ has a JavaScript error.

TestCafe handles it.
To disable this behavior, you can specify the '--skip-js-error' option.
For your use case, it needs to change the code as follows:
"scripts": {
    "test": "cd tests; testcafe chrome test.js -e"
  },


text:
Q: What average precision is the plot_precision_recall_curve() function plotting? After using the plot_precision_recall_curve() from scikit learn I was wondering what average precision this function is using. When looking in the docs, this is what I find for a binary target:
# %%
# Compute the average precision score
# ...................................
from sklearn.metrics import average_precision_score
average_precision = average_precision_score(y_test, y_score)

print('Average precision-recall score: {0:0.2f}'.format(
      average_precision))

This is my data:
clf_4 = svm.SVC()
clf_4.fit(X_train, y_train)
y_clf_4 = clf_4.predict(X_test)

y1_test = np.array([1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1]

y1_clf4 = np.array([0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1]

average_precision_5 = average_precision_score(y1_test, y1_clf4)
average_precision_5
Out: 0.5625

Now we use the plot_precision_recall_curve with X_test being this (same as above):
X_test= np.array([[0.01167537, 0.04676259, 0.02145552, 0.015625  , 0.        ,
        0.        , 0.        , 0.5       , 0.01020408, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00478415, 0.01258993, 0.06759886, 0.09375   , 0.        ,
        0.        , 0.        , 0.43421053, 0.        , 1.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.01503446, 0.04136691, 0.02600806, 0.015625  , 0.        ,
        0.        , 1.        , 0.13157895, 0.02721088, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        1.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 1.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.017396  , 0.04856115, 0.07737383, 0.046875  , 0.        ,
        0.        , 0.        , 0.44736842, 0.04421769, 0.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        1.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.0072882 , 0.01079137, 0.07866155, 0.078125  , 1.        ,
        0.        , 0.        , 0.63157895, 0.        , 1.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00733909, 0.0323741 , 0.0487578 , 0.046875  , 0.        ,
        0.        , 0.        , 0.44736842, 0.02040816, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 0.        , 1.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        ],
       [0.02579371, 0.11151079, 0.03639438, 0.0625    , 0.        ,
        0.        , 0.        , 0.53947368, 0.02380952, 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00203581, 0.03417266, 0.12611863, 0.125     , 0.        ,
        0.        , 0.        , 0.05263158, 0.00680272, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00527275, 0.03057554, 0.0344563 , 0.03125   , 0.        ,
        0.        , 1.        , 0.09210526, 0.00680272, 1.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00590385, 0.02158273, 0.05135926, 0.046875  , 0.        ,
        0.        , 0.        , 0.43421053, 0.00340136, 1.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.01910608, 0.16366906, 0.05917014, 0.03125   , 1.        ,
        0.        , 1.        , 0.28947368, 0.12244898, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        ],
       [0.12737045, 0.13669065, 0.07280827, 0.078125  , 1.        ,
        0.        , 0.        , 0.46052632, 0.07823129, 0.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        1.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        ],
       [0.0537861 , 0.17446043, 0.14109651, 0.078125  , 0.        ,
        0.        , 0.        , 0.32894737, 0.08843537, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.01027066, 0.05755396, 0.06110172, 0.078125  , 1.        ,
        0.        , 0.        , 0.30263158, 0.01360544, 1.        ,
        0.        , 0.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.0085504 , 0.01978417, 0.03185484, 0.03125   , 1.        ,
        1.        , 0.        , 0.51315789, 0.00340136, 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        ],
       [0.02224122, 0.05215827, 0.06370968, 0.0625    , 0.        ,
        0.        , 0.        , 0.47368421, 0.04081633, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 1.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00896774, 0.05035971, 0.00974896, 0.015625  , 0.        ,
        0.        , 0.        , 0.5       , 0.02721088, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        1.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.03302084, 0.07014388, 0.00779787, 0.015625  , 1.        ,
        1.        , 0.        , 0.25      , 0.03741497, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00630083, 0.06115108, 0.01495838, 0.        , 0.        ,
        0.        , 0.        , 0.10526316, 0.00340136, 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ],
       [0.00951741, 0.03776978, 0.13261576, 0.140625  , 1.        ,
        1.        , 0.        , 0.47368421, 0.0170068 , 1.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 1.        , 0.        , 0.        ,
        0.        , 1.        , 0.        , 1.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        ]])

Now we can use the plot_precision_recall_curve function and print the two results, and they differ:
disp = plot_precision_recall_curve(clf_4, X_test, y1_test)
disp.ax_.set_title(f'2-class Precision-Recall curve:{average_precision_5}')

So where does the difference come from?

A: The y_score parameter of average_precision_score needs to be probability estimates (or a similar continuous score), not the hard classification results.  So your average_precision_5 is incorrect.


text:
Q: Android getWifiState to String I am attempting to get the string representation of an Android device's current WiFi state. I am using the getWifiState() method of the WiFiManager and am getting an integer returned depending on the current state. This makes total sense as getWifiState() is supposed to return an integer. The method's documentation indicates that the possible return values translate to one of the following constant values

*

*0 WIFI_STATE_DISABLING

*1 WIFI_STATE_DISABLED

*2 WIFI_STATE_ENABLING

*3 WIFI_STATE_ENABLED

*4 WIFI_STATE_UNKNOWN

Is there an easy way to translate the integer returned from getWiFiState() to a string representation? I've looked at getIntExtra but am unsure of its use.

A: i know you already accepted an answer but you should not use the code posted because, as you said, it is brittle and difficult to maintain.  There is no reason for it to be so.
  public String getWifiStateStr() {
    switch (mWifiManager.getWifiState()) {
      case WifiManager.WIFI_STATE_DISABLING:
        return "disabling";
      case WifiManager.WIFI_STATE_DISABLED:
        return "disabled";
      case WifiManager.WIFI_STATE_ENABLING:
        return "enabling";
      case WifiManager.WIFI_STATE_ENABLED:
        return "enabled";
      case WifiManager.WIFI_STATE_UNKNOWN:
        return "unknown";
      default:
        return null;  //or whatever you want for an error string
    }
  }

This protects you from changes in the constant assignment, will be much easier to read in 6 months, and assuming you handle the error string correctly should limit bugs if the number of allowed return values increases.
When you see a variable listed as a 'Constant' in Android documentation it means that it is declared public static final.  It can be accessed as ClassName.CONST_VARIABLE_NAME.  It is convention that these variables will be in all caps but it is not a language requirement.  Generally speaking you should never need to use the actual value of such members, you should always access them by member name unless you need to do something odd.

A: How about just:
  public String getWifiStateStr() {
    switch (mWifiManager.getWifiState()) {
      case 0:
        return "disabling";
      case 1:
        return "disabled";
      case 2:
        return "enabling";
      case 3:
        return "enabled";
      default:
        return "unknown";
    }
  }


text:
Q: How can I get a 3.4 version of pdb? I tend to use a Debian wheezy system, that ships with Python 2.6, 2.7 and 3.2.
However I'm developing now using a local installation Python 3.4 because has a very interesting advantage over Python 3.2.
The problem is that I don't know how to install such a thing as a pdb3.4. When I run pdb3 over my Python 3.4 program, it runs as a Python 3.2 program, failing.
I'm on the need of general Python advice on versions and multi-host (Ubuntu precise and trusty, and Debian wheezy) multi-version development, and I particularly need downloading and building a 3.4 version of pdb, but I don't get to find any documentation on that.

A: Every version of Python comes with its own pdb module. It is part of the standard library.
The version in the 3.4 standard library has no special advantages over the version that comes with 3.2 or 2.7. The last time pdb functionality was changed was in the 3.2 and 2.7 releases (the only thing missing in the 2.6 version is the skip keyword argument to pdb.Pdb(), and 3.3 added more tab completion support).
If you have a pdb command line, then that's just an alias for python3 -m pdb; you can use that with any of your versions:
python3.2 -m pdb yourscript.py

Debian and Ubuntu simply copy the pdb module to /usr/bin/ with the Python version appended, so /usr/lib/python3.2/pdb.py is copied to /usr/bin/pdb3.2.


text:
Q: gRPC: How to use dynamically typed values? I'm trying using gRPC dynamically typed values but with the little information about their usefulness, It's almost impossible to do this... So I will show the image/code that I have problems and the questions that are eating my brain

gRPC Method I'm doing:
public override Task<HelloReply2> TestObject(Status request, ServerCallContext context) {

    //The part I may have problems

    var status = new Status();

    //here I want a User that corresponds to my request.Data

    //example -> request.Data = User1 (gives me null if User1 don`t exist in db)
    //           request.Data = 14 (gives me null if 14 don`t exist in db)
    //           request.Data = true (gives me null if true don`t exist in db)

    var a1 = _context.Users_5.FirstOrDefault(x => x.Username.Equals(request.Data));
    var b1 = _context.Users_5.FirstOrDefault(x => x.Email.Equals(request.Data));
    var c1 = _context.Users_5.FirstOrDefault(x => x.Age.Equals(request.Data));
    var d1 = _context.Users_5.FirstOrDefault(x => x.Test.Equals(request.Data));
                                                    //is a bool

    //here i want too Create dynamic values
    status.Data = Value.ForStruct(new Struct {

        Fields =
        {
            ["Integer"] = Value.ForNumber(c1!.Age),
            ["StringName"] =  Value.ForString(a1!.Username),
            ["StringEmail"] =  Value.ForString(b1!.Email),
            ["Boolean"] = Value.ForBool(d1!.Test)
        }

    });

    //Below is just a simple string who gives different string (depending on the
    //data Status (also how to read the message from the status.Data ?)
    HelloReply2 hello = new();

    if(a1 != null)
    {
        hello.Message = "There is a User with the Username " + request.Data + ". His Email is " + a1.Email;
    } else if (b1 != null) {
        hello.Message = "There is a User with the Email " + request.Data + ". His Username is " + b1.Username;
    }
    else if (c1 != null)
    {
        hello.Message = "There is at least one User with that Age of " + request.Data + ". His Username is " + c1.Username;
    }
    else if (d1 != null)
    {
        if(d1.Test == true)
        {
            hello.Message = "There is at least one User who dislikes chocolate: " + request.Data + ". His Username is " + d1.Username;
        } else
        {
            hello.Message = hello.Message = "There is at least one User who likes chocolate: " + request.Data + ". His Username is " + d1.Username;
        }
    }
    else
    {
        hello.Message = "We didn't find something with the value that the User put in. Value:" + request.Data;
    }

    return Task.FromResult(hello);
}

Questions: How to Get the one Value from my gRPC? How to convert a "Object" in c# (one string, one integer or one List) into a ONE value of google.protobuf.Value (so it not give me errors like this Controller from a Web Api below)? Is something wrong with my gRPC Service Method (is something wrong reading the dynamic values? Can I do that calls for getting a User for a DB? How to read dynamic values?)
// I try using Google.Protobuf.WellKnownTypes.Value obj but
//not workings because gives me a lot of values to put
[HttpGet("TypeObject/{obj}")]
public async Task<ActionResult<HelloReply2>> TypeObject([FromRoute] Object obj){

    Status objRequest = new Status { Data = (Google.Protobuf.WellKnownTypes.Value)
    obj };
    //cannot do this (gives me error of casting but the ideia is doing something
    //similar to this)

    var hello = await _greetClient.TestObjectAsync(objRequest);

    return Ok(hello);
}

Any help on how to resolve this error of using Value gRPC or if is something wrong with the code is always welcome.
Edit:
One day after this question I don't have any solutions / progress. I was think of doing Any or OneOf for testing but it also gives me errors (who don't make sense at all). This code from Microsoft (C# Format part is not recognize) doesn't work in my project with the protos reload (the problem is not in the protos)
Link: https://learn.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/protobuf-any-oneof
How I can use Any / OneOf without give me error in the Formating? What is the difference between Value and this two? Can the three (Value, Any, OneOf) be dynamic/Object values (if yes how to convert the types)?
Edit 2:
Still have problems, I'm trying using gRPC Any , and maybe have some progress (not all).
So with Any I have my method in the server gRPC and it is like this
public override Task<HelloReply2> TestObject3(AnyMessage request, ServerCallContext context){
    HelloReply2 anyMessageResponse;

    var y = request.TypeUrl;

       switch (request.TypeUrl)
       {
          case "type.googleapis.com/any.HelloRequest":
            var string_1 = request.Unpack<HelloRequest>();
            anyMessageResponse = new HelloReply2{
             Message = "You type String: " + $"{string_1.Name}"
            };
            break;
          case "type.googleapis.com/any.TestInteger1":
            var integer_1 = request.Unpack<TestInteger1>();
            anyMessageResponse = new HelloReply2{
             Message = "You type Integer: " + $"{integer_1.Message}"
            };
            break;
          case "type.googleapis.com/any.TestBool1":
            var bool_1 = request.Unpack<TestInteger1>();
            anyMessageResponse = new HelloReply2{
             Message = "You type Bool: " + $"{bool_1.Message}"
            };
            break;
          default:
            throw new InvalidOperationException("Unexpected type URL.");}

    return Task.FromResult(anyMessageResponse);
}

This ideia comes from here (https://github.com/grpc/grpc-dotnet/issues/917), but the client part their don't have any much info or I don't understand that part
This is what I did in the WebApi (who is my client and the code is similar to the above one)
using AnyMessage = Google.Protobuf.WellKnownTypes.Any;

[HttpGet("TypeObject3/{obj3}")]
        public async Task<ActionResult<HelloReply2>> TypeObject3([FromRoute] string obj3)
        {

            AnyMessage objRequest = new() { TypeUrl = obj3 };

            var hello = await _greetClient.TestObject3Async(objRequest);

            var l = hello.Message;

            return Ok(hello);
        }

First I had the variable Any declared in the method instead of string but as you can only put string and stringBytes so I preferred to put it like this (with the string as an obj3 variable) but my goal is to see if the variable is of type TestBool1 or TestInteger1 as I have declared in the protos and not be a string that I will be able to see, and the biggest problem was if I had more variables inside the messages how to proceed? So my secondary question is how to use Any on the client side via the Web-Api? I forgot to say but I'm using .Net 6 Core and for testing I'm using Swagger, where at this moment my error hits the Exception dictated by the Server method.
Questions: Why TypeUrl is a string and not object? How to fix my problem? How to test the object type (or string) for more values if the messages was with 1 more types?
Also I will show my test proto too show how I'm doing this
import "google/protobuf/struct.proto";
import "google/protobuf/any.proto";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayNormalHello (Empty_2)  returns (HelloReply);
  rpc SayHello (HelloRequest) returns (HelloReply2);
  rpc TestInt (TestInteger1) returns (HelloReply2);
  rpc TestBoolean (TestBool1) returns (HelloReply2);
  rpc TestObject (Status) returns (HelloReply2); //Not working
  rpc TestObject2 (Status2) returns (HelloReply2); //Not working
  rpc TestObject3 (google.protobuf.Any) returns (HelloReply2); //Also
                                                          //Not working

}

message Empty_2{

}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

// The response message containing the greetings.
message HelloReply2 {
  string message = 1;
}

message TestInteger1 {
  int32 message = 1;
}

message TestBool1 {
  bool message = 1;
}

message Status {
  google.protobuf.Value data = 1;
}

message Status2 {
  google.protobuf.Any data = 1;
}

Any help is welcome.

A: In the project I developed, I needed an infrastructure where I could perform dynamic operations such as REST service using gRPC. As I understand it, what you want is something similar to this.
I have developed a solution for this. It might work for you too.
You can gain some flexibility by making a definition with a single String field for Requests and Responses that you want to be Dynamic, and then using this field to hold JSON data as strings.
For example, instead of defining different responses for different types, you can solve it by making one definition like this.
message HelloReply {
      // Stringified JSON Data
      string data = 1;
}


text:
Q: Unknown red rectangle appears in map window I would like to know where this red rectangle comes from? It's not a polygon or a line, it can't be activated or removed or anything else. It just appeared during the project work (adding shp-files, georeferencing rasters and digitalizising,...)
Maybe it's about extents?!

A: I'm guessing you have a Grass Mapset open?  If so, it's the GRASS 'region' being shown.
EDIT: Note that you can toggle it on/off from the Grass toolbar "Display Current Grass Region" button and edit it with the "Edit Current Grass Region" button.

A: Untoggle the Editing icon, it might be because you're in Editing mode.


text:
Q: Prevent digits to change from English to Arabic on Locale updated android I'm providing Arabic support for the already-completed app. On changing the app language to Arabic, numbers are displaying with Arabic digits for the XML strings.
But my problem is on executing the following code
getString(R.string.value, ++value);

values
<string name="value">Value : %d</string>

values-ar
<string name="value">%d :القيمة </string>

with English, it is working fine.
Value: 1

On changing the language to Arabic (Appearing in Arabic). It must be in English (0-9)
Value : (Number in Arabic)

Please provide a solution to my problem.

A: You can change the locale of the number using String.format to always be shown in English:
String.format(Locale.ENGLISH, getString(R.string.value), ++value)

A: Although it takes a long time to ask this question (7 months), it may be useful for others. I did this  and my problem was solved.
First I created a Locale variable:
val englishLocale = Locale("en")

Then I used this variable in the required functions:
For example for date format:
SimpleDateFormat("yyyy-MM-dd HH:mm:ss", englishLocale)

Or to display elapsed time in milliseconds in normal format:
String.format(englishLocale, "%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, seconds % 60)


text:
Q: Vertical Margin ignored / outside of parent container I have a simple layout, with a container that has horizontal and vertical margin as well as a max width and height. On a computer screen, the max width and height makes it so that the margin is basically irrelevant. When I resize the window to be smaller (horizontally), the container eventually takes up the whole screen minus the margin, then gets smaller as well and the margin makes it so that there is some space between its border and the edge of the screen. However, vertically the margin is simply ignored and the container eventually goes right to the edges. I don't understand why that is happening and how I can fix it.
Here is a working example: I am using Tailwind, so that's what I used for the example as well: https://play.tailwindcss.com/t9LmsfyVfH
Edit: Here's also an image to make my point clearer:

As you can see, the horizontal margin does exist, but it's outside the window/page (or in case of the playground: container which contains the rendered content).

A:

This is because of h-full class in the element. it has height 100%, that forcing element to render and squeezing the inner content. As scroll has not consider margins thus overflow is not causing, though you have given margins to the inner child.
You can override the css by simply adding custom class or parent class minimum height .customClass.h-full{min-height: 100%;}

A: You can easily work around this issue by adding an empty element above the container to hold that space like

 it's top + bottom margins are equal to the top margin of your main.my-12
https://play.tailwindcss.com/nAB8wcyXzV


text:
Q: Since when did SE stop uploading DMCA takedown notices to Lumen Database? There was an answer that was removed from Stack Overflow due to a DMCA takedown notice. According to the comments there, the complaint was not published to Lumen Database (formerly called Chilling Effects), despite the fact that since 2013, SE has uploaded such notices. Also, it appears that there have been no such notices uploaded since September 2017.
Why did SE stop uploading such notices? Has there been a single notice between September 2017 and now? If so, why weren't those uploaded?

A: We do still get DMCA notices, and we tend to get at least one every month. But at some point, Lumen removed the usual submission form that we were using to report these to their database, without warning (or at least we never received any). It actually took me some time to figure this out. I was going to submit a batch of them one day and it took me near half an hour to track down an old link to the form that, sure enough, just said they no longer accept online submissions. So, we stopped submitting the reports.
There is a back-door process for these that larger companies with fancy forms and databases use to report them, but we don't have any of that tooling that would let us send reports to them automatically. So it looks like we're just out of luck for reporting to them unless they decide to re-enable that form or we put a bunch of work into creating those systems, which is unlikely to happen given how few of these we even get (again, we're talking about 1-2 on average per month, because we've worked with some of the people that send them regularly to combine them into a sort of monthly report).
That said, I did recently bring this up internally when I noticed the submission form was gone and couldn't submit further notices, and the idea of creating our own transparency report was even floated. We don't have any hard timeline or idea of what we're going to do, but some expected upcoming changes to how we process DMCA notices may make it a lot easier to generate that transparency report automatically without much, if any, effort on our part - so it may very well become a thing. Fortunately the way we have been processing them will make it quite easy to update and track these reports retroactively for a fair bit of time too.
As of right now, this irks us because the rug was kind of pulled out under out feet. We want to do something to continue reporting this kind of information. We just don't know exactly what that way is going to be or look like at this time.


text:
Q: Writing array to single row I have created an API which iterates through JSON format data, reading 2 items per ID. I'm storing this data in an array called values[].

A: How about this modification?
Modification points:

*

*In order to put the values of values to one row, please modify values.push([timestamp, price]); to values.push(timestamp, price);. By this, each value is put in values which is one dimensional array.

*In order to put values from the row 3, in this modification, it checks whether the row 3 for putting values is empty.

When above points are reflected to your script, it becomes as follows.
Modified script:

From:

    values.push([timestamp, price]);
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("rawStockData");
  ss.getRange("A3:BH3").setValues(values);
}

To:

    values.push(timestamp, price);  // Modified
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("rawStockData");
  var range = ss.getRange(3, 1, 1, values.length);  // Modified
  if (range.isBlank()) {  // Added
    range.setValues([values]);
  } else {
    ss.appendRow(values);
  }
}

References:

*

*push()

*appendRow(rowContents)


text:
Q: Godday SSL certificate not found in the site binding drop down list - IIS 10 My VM setup:
Azure VM: Windows server 2019 datacenter
IIS 10
I have purchased a domain & Standard SSL from GoDaddy and pointed it to the Azure VM. Initially, the website was running on IIS using HTTP on port 80. I have purchased SSL from godaddy and installed them as the following reference  https://in.godaddy.com/help/manually-install-an-ssl-certificate-on-my-iis-10-server-27349

*

*Intermediate certificate using MMC

*Server certificate using IIS

Then I tried to bind the certificate with my website using https on port 443, where newly installed SSL certificate name not showing in add site binding window of the website in SSL Certificate dropdown

A: The common reason behind the issue is when the imported certificate doe s not have a private key associated with it or its broken because of some reason.
to resolve the issue you could try to import the .CER file to your system(from where the certificate is requested) personal store and export it with a private key. Then copy the .pfx file to the required server and import it from the server certificate option under IIS. This would fix the issue.
refer this below link for more detail:
https://serverfault.com/questions/469987/ssl-certificate-not-found-in-the-drop-down-list-iis-7
https://www.namecheap.com/support/knowledgebase/article.aspx/9773/2238/ssl-disappears-from-the-certificate-list-on-windows-server


text:
Q: Big O notation in practice if $P_{n}$ is the $n$'th prime I have that for a constant $a$ $$n\geq \frac{aP_{n}}{\log(P_{n})}$$
and it implies that $$\log(P_{n})=O(\log(n))$$
I'm unsure of how this is implied and where the $\log(n)$ has come from.

A: Simply take the natural log of both sides of the inequality to get
$$\log(n)\geq \log\left(\frac{a P_n}{\log{P_n}}\right)=\log(a)+\log(P_n)-\log(\log(P_n))$$
Since $\log(\log(P_n))$ grows much slower than $\log(P_n)$, for large enough $n$
$$\log(a)+\log(P_n)-\log(\log(P_n))>\frac{1}{2}\log(P_n)$$
We conclude there exists a constant $c$ such that
$$\log(n)>c\log(P_n)$$
Thus
$$\log(P_n)=O(\log(n))$$

A: From your inequality and the monotonicity of the logarithm,
$$ \log n \geq \log(P_n) + \log(a) - \log \log(P_n) \text{.}  $$
Once $P_n$ is large enough that $\log \log P_n > 0$, the right-hand side is $ > \log(P_n) + \log(a)$.  Now you have
$$ \log n \geq \log(P_n) + \log(a)  \text{,}  $$
which is sufficient to show that $\log n$ is greater than or equal to a constant multiple of $\log(P_n)$ for all $n$.  (For instance any constant $\geq 2$ works once $P_n > a$.)

Another method.  After taking logs, factor out the (given or recognized) leading term.
$$  \log n \geq \log(P_n) \left( 1 + \frac{\log{a}}{\log P_n} - \frac{\log\log P_n}{\log P_n} \right)  \text{.}  $$
Set
$$ c(x) =  1 + \frac{\log{a}}{\log x} - \frac{\log\log x}{\log x}  \text{.}  $$
We can check that we have the correct leading order term factored out.  Set $L = | \lim_{x \rightarrow \infty} c(x)|$.  If $L = 0$, the factored term grows too quickly.  If $L$ is finite, the correct leading term has been factored out.  If $L$ diverges to $\infty$, the factored term grows too slowly.  If $L$ is not a positive, finite number, go back and factor out the correct leading term.  Here we don't need the absolute values (because everything is positive for large $n$) and we find \begin{align*}
\lim_{x \rightarrow \infty} c(x) &=  \lim_{x \rightarrow \infty} \left(1 + \frac{\log{a}}{\log x} - \frac{\log\log x}{\log x} \right)   \\
  &= 1 + 0 - 0  \\
  &= 1  \text{.}
\end{align*}
So $\log P_n$ is the correct leading term.  Now two ways to finish:

*

*For any $\varepsilon > 0$, there is an $n_0$ such that for all $n > n_0$, $c(n) < 1 + \varepsilon$ (directly from the definition of limit), so $\log n \geq (1+\varepsilon)\log P_n$ for $n > n_0$, showing $\log P_n \in O(\log n)$.

*$\max_{x \in [1,\infty)} c(x) = 1-\frac{1}{a \mathrm{e}}$ (assuming natural logs, although a different base of logarithm just changes the details of this constant, not that it is a constant).  So $\log n \geq (1-\frac{1}{a \mathrm{e}})\log P_n$ for all $n$, showing $\log P_n \in O(\log n)$.

In the one case, we show that there is a tail for any constant $> 1$, which is what is in the definition of Big-O.  In the second, we are lucky enough that there is a universal constant that works for all $n \geq 1$.

Finally, a third way.  After taking logs, notice
$$  \log n - \log a \geq \log P_n - \log \log P_n \text{.}  $$
Also, \begin{align*}
\log n &\in O(\log n)  \text{,}  \\
\log a &\in O(\log n) \text{, and }  \\
\log \log P_n &\in O(\log P_n)  \text{.}
\end{align*}
Therefore,
\begin{align*}
\log P_n - \log \log P_n &\in O(\log P_n)  \\
&\subseteq O(\log n + \log a)  \\
&\subseteq O(\log n) + O(\log n)  \\
&= O(\log n)  \text{.}
\end{align*}
This says there are $n_1$ and $n_2$ as well as $c_1$ and $c_2$ such that for all $n > \max\{n_1, n_2\}$,
$$  c_1 \log n \geq c_2 \log P_n  \text{.}  $$
But this says
$$  \log n \geq \frac{c_2}{c_1} \log P_n  $$
for $n$ sufficiently large, so $\log P_n \in O(\log n)$.


text:
Q: Pre load core data database coming up black with UIManagedDocument Hi supportive experts...
I'm writing my first iPad app and have a working beta copy that parses an XML file to create a UIManagedDocument Core Data DB on app start up. However this takes a long time and I would like to do it once off line and include the initial data directly into my app bundle.
Needless to say I'm hitting a wall trying to get it to work.
I first followed the command line utility approach see here This worked until I imported the .sqlite file and tried to edit the persistentStoreCoordinator method - I'm using a UIManagedDocument and so don't have a persistenStoreCoordinator method in my AppDelegate - this page quote "In some cases, you do not have to write any code to load a model. If you use a document-based application on Mac OS X, NSPersistentDocument manages the task of finding and loading your application's model for you."
I then tried to copy the UIManagedDocument from a working version of my app in the simulator as per this StackOverFlow question
This seemed to work except that the persistentStore is empty and hence my table is also. This is exactly the problem asked here but the response given to that question takes me right back into modifying the NSPersistentStoreCoordinator method that I don't have.
I added a test NSFetchRequest into my code where I copied the UIManagedDocument from my app bundle into the documents directory - so I know that my UIManagedDocument in my app bundle is empty. I have tried dragging and dropping from finder and coping using terminal - the persistentStore file seems to be correctly moved and have size 106 KB but I still get an empty DB in my App.
Any suggestions on how to get this to work?
Do I need to use configurePersistenStoreCoordinatorForURL:ofType:modleConfiguration:StoreOptions:error: as per the UIManagedDocument Class Reference - if so how would I do it?
Do I need to add some of the core data methods into my AppDelegate so I can modify my persistenStoreCoordinator method - if so what else does this method have to do?
Am I better using the .sqlite DB that my command line utlity created or the persistentStore UIManagedDocument seems to use?

A: You can access the persistent store coordinator through the parentContext:
document.managedObjectContext.parentContext.persistentStoreCoordinator

Or, if you just mean you don't have access to the method that builds the persistent store when the core data stack is built, then it looks like this is the hook that's intended for that purpose, (as you mention):

Override configurePersistentStoreCoordinatorForURL:ofType:modelConfiguration:storeOptions:error: to customize the loading or creation of a persistent store.

But the the discussion for that method in the documentation doesn't explain what to do very well.  Perhaps you could override it and see what objects are and aren't already created in the stack, there maybe an initialised coordinator attached to the parent context for you to configure.  The documentation for the similarly named method on NSPersistentDocument is like this so perhaps UIManagedDocument is also.?


text:
Q: How to isolate a variable in a floor function? I hope someone may be able to help me solve the following equation for $y$?
$$x=\frac b{50}\left\lfloor{50ay\over b}\right\rfloor$$
I'm trying to isolate $y$ so I can program an Excel file to solve the problem when $a$, $b$, and $x$ are known values.  Is there a way to express the formula in a way that can be relied upon with utilizing the "goal seeker" feature on each dataset. I have nearly $3000$ of these.

A: The equation
$$x=\frac{1}{50} b \operatorname{floor}(50ay/b)$$
is equivalent to
$$\frac{50x}{b} = \operatorname{floor}\left( \frac{50ay}{b} \right)$$
so, if $\frac{50x}{b}$ is not an integer, we have to stop, since the equation is impossible (no value of $y$ will satisfy that equation).
In the case that this is an integer, we can go on: the last equation is equivalent to
$$\frac{50x}{b} \le \frac{50ay}{b} < \frac{50x}{b} +1$$
since $\frac{50a}{b} > 0$, we can divide everything by $\frac{50a}{b}$ getting $$\frac{x}{a} \le y < \frac{x}{a} + \frac{b}{50a}$$
So every number in the interval $\left[ \frac{x}{a} , \frac{x}{a}+ \frac{b}{50a} \right)$ may be a correct value for $y$.


text:
Q: Помогите пожалуйста сделать оружие в Pygame Код Игры
import pygame

pygame.init()

# Цвета
white = (255, 255, 255)
red = (255, 0, 0)

sc_w = 500  # Щирина экрана
sc_h = 500  # Высота экрана
sc = pygame.display.set_mode((sc_h, sc_w))
pygame.display.set_caption('Game')

clock = pygame.time.Clock()

x_2 = 370  # Координата x второго игрока
y_2 = 30  # Координата y второго игрока
speed_2 = 2  # Скорость второго игрока

x_1 = 30  # Координата x первого игрока
y_1 = 370  # Координата y первого игрока
speed_1 = 2  # Скорость первого игрока

game_over = False

player_1 = pygame.image.load('sprites/Blue.png')
player_2 = pygame.image.load('sprites/Red.png')

def draw():
    sc.fill(white)
    sc.blit(player_1, (x_1, y_1))
    sc.blit(player_2, (x_2, y_2))
    pygame.display.update()

while not game_over:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x_1 > 20:
        x_1 -= speed_1
    if keys[pygame.K_RIGHT] and x_1 < 460:
        x_1 += speed_1
    if keys[pygame.K_DOWN] and y_1 < 460:
        y_1 += speed_1
    if keys[pygame.K_UP] and y_1 > 20:
        y_1 -= speed_1

    if keys[pygame.K_a] and x_2 > 20:
        x_2 -= speed_2
    if keys[pygame.K_d] and x_2 < 460:
        x_2 += speed_2
    if keys[pygame.K_s] and y_2 < 460:
        y_2 += speed_2
    if keys[pygame.K_w] and y_2 > 20:
        y_2 -= speed_2
    draw()

Цель:

*

*У обоих игроков должна появится возможность стрелять. При нажатии на определённые клавиши они должны пускать пули от туда, где они стоят.

*Пуля должна лететь по тому направлению, в котором ходил игрок последний раз. Т.е. игрок походил налево, и нажал на кнопку, а пуля полетела налево.

*При этом 1 игрок не может содержать на поле более 3 пуль пока они не выйдут за рамки экрана.
Я пытался вникнуть, либо переписывать код с сайтов либо видео, никакого успеха.
Буду благодарен если вы объясните как это делать.


text:
Q: Is a refurbished Macbook Pro's battery new? When you buy a refurbished Macbook direct from Apple, is the battery in it new? I cannot seem to find a definitive answer on their website or on the internet. I am concerned that the savings from buying a refurb will be cancelled out by having to replace the battery in less than a year.

A: I called Apple's Sale Support, and I asked them what their policy was for batteries in a refurbished Macbook. Their answer is that the battery will be replaced if it has a defect, but if nothing is wrong with it, then the laptop will include the original battery which may or may not have many used cycles.

A: This is not answering your question, merely providing a data point, but my refurbished MacBook Air (purchased very late December 2011) currently has a single cycle on its battery. I didn't check the machine when it came out the box, but I'd imagine it was probably at zero cycles when I received it (as I've probably put that cycle on it myself in the month I've had it).

A: mine had 3 cycles when i received it. currently at 7% life left and have not yet charged it since I got it.

A: I just received a refurbished 2015 MacBook Pro today (April 20, 2017) and the power cycles shows 0.  The product also looks brand new.
I have bought several refurbished iPads before, and the same thing.
I would guess the only way Apple leaves the original battery in there is if it had a relatively low power cycle count.  Apple wants you to buy the refurbished products from them.  And I stand by it.  Every refurbished product I have bought through them looks brand new.  Well worth it!

A: I was told by an Apple employee (not a store employee) that most refurb computers are just returns and open boxes, and not computers that were actually used by anyway.


text:
Q: How can i retrieve all data and insert into sql from DataGridView i want to retrieve all cell and row from dataGridView and pase in textbox or label,or insert into sql server
i tried to use this
 string value;
    public void getGridData()
    {
          foreach (DataGridViewRow row in dataGridView1.Rows)
           {

               foreach (DataGridViewCell cell in row.Cells)
               {
                   value = cell.Value.ToString();
                   //MessageBox.Show(value);
                   textBox1.Text = value;

               }

           }

    }

when i  user MessaBox.show it works,but in textBoxt nope, please help me

A: It looks like you keep overwriting the textbox.
Maybe appending to the textbox is what you need:  textBox1.Text += value;


text:
Q: How to select rows in Pandas after a string header in a spreadsheet? I have a .CSV file that has the following structure (when viewed on Excel), in which it has unique section headers (strings) occupying a single cell, followed by a block with column names and data.
This format repeats itself throughout the Excel spreadsheet.
Note that each section has different col names and number, and variable number of rows.
Example:
    Daily Statements

    Date        Desc    Customer ID   Phone          Status
    12/21/21    aaa     1             123-123-1231   OK
    12/21/21    aaa     2             333-123-1231   OK
    12/21/21    bbb     3             222-123-1231   OK
    12/21/21    bbb     3             444-123-1231   OK
                                              <===== one empty row separates sections
    Account History
    Date        Time    Type    Ref #   Balance
    12/21/21    1:00:00 BAL     456     $0.01
    12/21/21    1:00:00 BAL     445     $0.01
    12/21/21    1:00:00 BAL     645     $0.01
                                              <===== one empty row separates sections
    Order History
    ID    Date      Ref #
    1     12/21/21  777
    2     12/21/21  888
    3     12/21/21  999
    4     12/21/21  9995

My goal is to extract only the rows in Account History:
    Date        Time    Type    Ref #   Balance
    12/21/21    1:00:00 BAL     456     $0.01
    12/21/21    1:00:00 BAL     445     $0.01
    12/21/21    1:00:00 BAL     645     $0.01

However I'm unable to find an approach that would work in Pandas, as I'd need to use the string "Account History" as an anchor to indicate the rows of interest.
Do you know how this could be achieved?

A: I don't see a straightforward way to do that just with Pandas.
Why not read the file first just as a text file to find the rows of interest, and only then, use Pandas to import just those rows?
with open(file, 'r') as f:
    # read until the line "Account History"
    for line_n, line_content in enumerate(f):
        if "Account History" in line_content:
            break
    start_row = line_n + 1

    # continue reading, and find the following new line
    for line_n, line_content in enumerate(f):
        if line_content == '\n':
            break
    tab_size = line_n - 1

# import the dataframe, just from the target lines
df = pd.read_csv(file, skiprows=start_row, nrows=tab_size)


text:
Q: Shopify graph call returns lesser data than REST call Shopify REST api returns 141 products in a collection. Shopify graph query returns 110 products in the same collection. Why is there a difference?
{

node(id:"XXXXXXXXXXXXXXXXXXXXXXXX"){__typename,...
on Collection{id,products(first:30){edges{cursor,node{id,title,description,
descriptionHtml,productType,handle,tags,
images(first:10)
{edges{node{src,altText,id,originalSrc}}},
variants(first:10){edges{node{id,price,title,sku,availableForSale,
image{originalSrc,altText,id,src}}}}}}}}}}

This query returns 30+30+30+20 items in pagination. So i am getting only 110 items. But there are actually 141 items in the collection. Why is there a difference? Can anyone please explain?
Thank you in advance

A: I use this simple call and there is a productsCount. You should play with Insomnia to learn the schema and what you can and cannot do with your GQL:
collection(id: $id) {
      id
      title
      description
      productsCount
}

So with this, you can throw in the products too, I am just demo'ing that product count should match RestAPI without a doubt.


text:
Q: jQuery Show php GET variable value in a textarea dynamically Im trying to show GET variable data in a textarea. I tried may solutions in StackOverflow but none of them worked. I have no idea why. Can you please tell me if I'm missing something.
My Story
I have a link on a page and href is /index.php?page=contact-us&performance=Lamborghini
and it takes me to the Contact Us page and the url is still /index.php?page=contact-us&performance=Lamborghini which is what I want.
So, Im tyring to grab performance variables's content which is Lamborghini and print it in a textarea which is
<textarea name="m62b34fbrp__32" cols="19" rows="7" class="cms_textarea" id="fbrp__32"></textarea>

So what I did is added <?php $performanceInfo= $_GET['performance']; ?> to the top of my page. Then added $("#fbrp__32").val(<?php echo $performanceInfo; ?>); in my script.js file. But it never prints Lamborghini in the textarea.
When I try $("#fbrp__32").val('<?php echo $performanceInfo; ?>'); (Notice the ' marks) it prints <?php echo $performanceInfo; ?> in the textarea.
When I <?php echo $_GET["performance"]; ?> it prints Lamborghini fine too.
Can you guys tell me why its not working for me?
NOTE : I cant edit the textarea manually as it is generated using a plugin Thanks a lot.

A: PHP Parse will not parse .js files, you will need to do this outside of the .js file. If not you will need to in your webserver config file set to parse .js files as PHP files.
EDIT
You mentioned that you added <?php $performanceInfo= $_GET['performance']; ?> to the top of the page and then $("#fbrp__32").val(<?php echo $performanceInfo; ?>); to your script.js file. This will not work as per default configuration script.js or any .js file will not be interpreted by the PHP parser. so your statement $("#fbrp__32").val(<?php echo $performanceInfo; ?>); will cause a syntax error.
The best way to handle it without changing server configuration would be to do this at the top of your page.
 <script type='text/javascript'>
  var performance = "<?php echo $_GET['performance']; ?>";
  </script>

and in your script.js file do $("#fbrp__32").val(performance);

A: Try this
<textarea name="m62b34fbrp__32" cols="19" rows="7" class="cms_textarea" id="fbrp__32">

<?php echo $_REQUEST['performance']; ?></textarea>

OR in JS
 $(document).ready(function(){
 var performance='<?php echo $_REQUEST["performance"]; ?>';
 $("#fbrp__32").val(performance);
 });

A: Just add the following right before the textarea (in your PHP/HTML-file, not JS-File!):
var performance = <?php echo '"' . htmlspecialchars( $_GET['performance'] ) . '"'; ?>
$("#fbrp__32").val(performance);

A: Just set value directly using PHP
<?php
 $performanceInfo= $_GET['performance'];
?>

JQuery is a bit tricky.Instead try simple javascript for setting value:
document.getElementById("Enter Here Textarea Id").value = <?PHP echo $_GET['performance']; ?>

A: Ok. Finally this is the solution which worked for me.
In the php file I put
<?php

$performanceInfo= $_GET['performance'];
echo "<script>";
echo "$('#fbrp__32').val('$performanceInfo');";
echo "</script>";

?>

Its weird other solutions didnt work for me for somereason.

A: Try this
var value = <?php $performanceInfo= $_GET['performance']; ?>
    $("#fbrp__32").val(value);

NB: php tags will not not render in js files


text:
Q: fullpage.js: How to add class to next slide? I'm using fullpage.js and the scroll horizontal extension. I would like to add a class to the next slide which is then removed when that next slide becomes the active slide. Alternatively, I would like to add a class to all slides that are inactive (again, removing this class when the slides become active).
Anybody know how I can do this? Is there a way to use the afterSlideLoad callback?
Thanks

A: Fullpage.js already adds the class active to all active sections are slides.
You can read more about state classes added by fullPage.js here in the docs.
Therefore, if what you need is to select those slides that are not active within a section using CSS you'll only need to do this:
.fp-section.active .fp-slide:not(.active)

In fact, you can use the same kind of selectors for Javascript:
document.querySelectorAll('.fp-section.active .fp-slide:not(.active)')


text:
Q: Can't get Sass to work for a website project. Script crashes with npm run sass I am trying to use node sass for creating a website in visual studio. I follow a Guide and in there it says Sass is used to auto create .CSS files. SASS is used as a way to compile down .scss files to .css files.
However, after the installation of npm  and trying to run a script with Sass I always get this error message:
n1c0@nico-linux:~/Documents/modern_portfolio$ npm run sass

> modern_portfolio@1.0.0 sass /home/n1c0/Documents/modern_portfolio
> node-sass -w scss/ -o dist/css/ --recursive

internal/fs/utils.js:220
    throw err;
    ^

Error: ENOENT: no such file or directory, lstat 'scss/'
    at Object.lstatSync (fs.js:922:3)
    at Object.module.exports.parseDir (/home/n1c0/Documents/modern_portfolio/node_modules/sass-graph/sass-graph.js:153:10)
    at Object.watcher.reset (/home/n1c0/Documents/modern_portfolio/node_modules/node-sass/lib/watcher.js:17:21)
    at watch (/home/n1c0/Documents/modern_portfolio/node_modules/node-sass/bin/node-sass:260:20)
    at run (/home/n1c0/Documents/modern_portfolio/node_modules/node-sass/bin/node-sass:319:5)
    at Object.<anonymous> (/home/n1c0/Documents/modern_portfolio/node_modules/node-sass/bin/node-sass:405:3)
    at Module._compile (internal/modules/cjs/loader.js:1121:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14) {
  errno: -2,
  syscall: 'lstat',
  code: 'ENOENT',
  path: 'scss/'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! modern_portfolio@1.0.0 sass: `node-sass -w scss/ -o dist/css/ --recursive`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the modern_portfolio@1.0.0 sass script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/n1c0/.npm/_logs/2019-11-29T19_29_28_755Z-debug.log

First Step I did was getting the "package-json" manifest with npm init command and then I installed node-sass with the npm install node-sass command. The installation went fine, so I went ahead and set up the package.json so that I can call the script and get it to work.
However, this is were it fails every time.
My OS is Ubuntu 18.04.3 LTS and the commands for the versions give back:
npm -v: 6.13.1
node-v: v13.2.0
I tried the process several times, I also reinstalled npm and node and tried it with other versions, but always the same error.
I am new to Linux so maybe I messed something up with the OS, but I have no clue what to do or how to fix this.
I searched this forum and there are some threads with this problem, some of them got it fixed somehow but for me all the suggested commands are not working.
Would be happy if somebody could look into this and unscramble my brian and help with the problem.
Worst case scenario I will reinstall Ubuntu because I just don't know what else to do.
Regards

The File Tree of my project, the error is mentioning some erorr with "no such directory as scss" or something along those lines, but there is a folder with that name in the project folder.

A: Your scss/ folder is inside dist/, so your command should be: node-sass -w dist/scss/ -o dist/css/ --recursive.

A: Okay, 5 minutes after publishing the post I found the answer. The script had a wrong path and could find the scss folder so the only thing I had to do was adding another folder to it.
So I had to run this:
"sass": "node-sass -w dist/scss/ -o dist/css/ --recursive"
insted of
"sass": "node-sass -w scss/ -o dist/css/ --recursive"
Sorry for this, I thought I was going insane, but I finally fixed it.


text:
Q: addTrack after etablished connection I need to add my track and send to other peers after having etablished the connection I've followed the MDN example
pc.onnegotiationneeded = async () => {
  try {
    makingOffer = true;
    await pc.setLocalDescription();
    signaler.send({ description: pc.localDescription });
  } catch(err) {
    console.error(err);
  } finally {
    makingOffer = false;
  }
};

onnegotiationneeded is fired when we call pc.addTrack so I will remake the process offer -> answer -> ICE.
So I have a function which call getUserMedia and set the local video I've added a callback to apply addTrack to my peers
const handleActiveVideo = async (cb) => {
  const devices = await getVideoDevices();
  const localStream = await createLocalStream(devices[0].deviceId);
  setLocalVideoEl(localStream, devices[0].deviceId);

  cb((pc) => {
    localStream.getTracks().forEach((track) => {
      pc.connection.addTrack(track, localStream);
    });
  });
};

But if I do that with an etablished connection when I add my local stream to the track with one peer it's ok all work fine but with my second peer I have this error on Firefox

Remote description indicates ICE restart but offer did not request ICE
restart (new remote description changes either the ice-ufrag or
ice-pwd)

with Chrome

DOMException: Failed to execute 'setRemoteDescription' on
'RTCPeerConnection': Failed to set remote answer sdp: Failed to apply
the description for m= section with mid='0': Failed to set SSL role
for the transport.

To recapitulate

*

*connect my 2 peers without any tracks on both sides

*start the video with my Peer1 ok I can see the video with my Peer2

*start the video with my Peer2 error on Peer2 in the answer

setRemoteDescription(description);