text:
Q: Spark-Cassandra very slow when using IN for composite partition key I have a cassandra Table with a composite partition key as (time_bucket timestamp, node int). time_bucket value is the time the data was inserted with seconds converted to 00 and node values range from 0 to 100
A spark job runs every minute picking up data from the table. The table contains close to 25 million records with records being added every minute.
If my spark job selects all the records every time it runs, the job completes in 2 minutes. But if i query using:
sc.cassandraTable(keyspace_name,table_name).where("time_bucket = ? ", from).where("nodeid_bucket IN ? ", nodeid_bucket_range)
where val nodeid_bucket_range = 0 to 100,
the job takes 10 minutes to complete.
My cluster has 6 nodes and am using DSE 4.8.9. Each executor uses 8 cores and 20GB of memory. Increasing these values does not help to make the spark job faster.
Any idea why my job takes 10 minutes? Does spark-cassandra not function well when using IN clause?

A: You probably want joinWithCassandraTable. Almost always an In clause is better served by doing a join if you have a large number of values. This will execute all of your requests in parallel on different executors.
https://github.com/datastax/spark-cassandra-connector/blob/master/doc/2_loading.md#using-joinwithcassandratable

A: IN statements translate into key OR key OR key3 ... OR key100, which is very inefficient for the optimizer to make something useful of. In your case you could use:
sc.cassandraTable(keyspace_name,table_name).where("time_bucket = ? ", from).where("nodeid_bucket > ? AND nodeid_bucket < ? ", nodeid_bucket_range)
Watch the edges of the range and of course this assumes your range is continuous.


text:
Q: How to trace which image is currently seen in my Uiscrollview? I am new to iOS.
I am working on UIScrollView based application. I have 3 images in UIScrollView.
I have 2 UIButtons which have selector method for Facebook and Twitter sharing.
I want to share image which is currently seen in UIScrollView to Facebook & Twitter.
I am stuck at extracting image at current scroll point.
After Googling I think something like UIPageController is the solution for me.
But I do not have any idea about how to implement it.
Please help me sort it out. Thank You!

A: You can use a page controller (basically, you allow the user to end its scrolling on specific index).
Or when the user touches a button, you can retrieve the contentOffset of the scrollView and compare this value with the origin of the frame your images.
Assume, you created your images with these frames:
image1.frame = CGRectMake(0,0,320,250);
image2.frame = CGRectMake(0,250,320,250);
image3.frame = CGRectMake(0,500,320,250);

Now when you get the action:
-(IBAction)share:(id)sender {
    CGPoint offset = self.scrollView.contentOffset;
    if (offset.y < 250) {
        //First image selected
    }else if (offset.y > 500) {
        //Third image selected
    } else {
       //Second image selected
    }
}

A: I would say you have multiple options here, this is really a design question.
An easy (but also not very elegant) approach would be to fetch the current offset of the scroll view using its contentOffset property (depending on whether your scroll view scrolls horizontically or vertically, you have ease to use the x or y value of the contentOffset).
Next, you get the position values from your image views (again either myImageView.frame.origin.x or myImageView.frame.origin.y) and you can then calculate which of the image views is currently in the offset of the scroll view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create tables in sql database with Entity framework at runtime and update model at runtime? I know that when I use ado.net, I can create database or table at run-time programmatically like:
String str;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
}

But I am using entity framework and I have some work in which I have to create tables at runtime. I have searched a lot about it but no way I got. Any help would be appreciated.

A: Entity framework is not for scenarios where you don't have static database schema.
Reasons:

*

*Entity framework mapping is static - dynamic modification requires, changes of XML files describing the mapping at runtime and using modified files instead.

*Even with changed mapping you still don't have changed or newly created entity classes in your code. EF doesn't support dynamic so the only way is either dynamically load assembly with new classes created prior to creating tables or heavy usage of Reflection.Emit and let your program "write itself".

If you only need to create a database but tables will be always same you should be fine. You can use that ADO.NET code to create database and tables and pass only modified connection string to the constructor of your context. But the requirement is static database schema = no changes in table's definition.

A: Entity Framework also has similar functions like myCommand.ExecuteNonQuery();, you may try SomeEntities.ExecuteStoreCommand("some sql statements").
Considering Entity Framework requires mappings between data models and database, it looks not possible to create/modify tables directly with integrated query language (otherwise the data models need to be modified at run time). Therefore, with no solid references supporting this point of view, I think SomeEntities.ExecuteStoreCommand() may be the only way.

A: Please read this thread:
NHibernate / Fluent NHibernate Dynamic Column Mapping

better off using a key-value store such as Redis or a schema-less database like CouchDB instead of SQL


text:
Q: Excel - leading zero - duplicate values I have column A formated as Text, and I fill this data:
0
00
000
010
011
10
11

When I make conditional formatting for duplicate values it show me all value like duplicate. Problem it's cause Excel convert to number all values and then it's duplicated.
How to solve this? I try with apostrophe, but it's not working. I have try with Custom formating, but it's same.

A: Use formula in CF:
=SUM((A1=A:A)*(A1<>""))>1


text:
Q: Decisions on the order of integration with double integrals (when Deriving PDF via CDF) (Bank Problem) Consider the following problem:
Gandalf, Saruman and Radagast go to a bank together. There are two
open counters which Gandalf and Saruman immediately go to get their service. Radagast
goes to the first counter that becomes available after that. Each of them independently takes an exponentially distributed amount of time (with parameter λ) to get their service from the counter. Each one of them leaves the bank immediately after getting their service.
Find the probability distribution of the time that Radagast spends in the bank (you can
provide either the distribution, the density, or the moment generating function).
Here is a solution provided for reference:

Although it is clear to me how the order of integration is chosen in the intermediate steps determining P(min(X,Y) < a), of which I believe is due to the fact that the inner integrals always have the tighter conditions, restrictions, or the smaller domains, I am having difficulty understanding how the order of integration is chosen in the intermediate steps that eventually determine P(T < a). I tried to integrate with respect to du from u = 0 to u = a-z, before integrating the result with respect to dz from z = 0 to z = a. However, I couldn't get the same answer as what is written in the solution. Does the order of integration matter that much (will I get a different solution if I start integrating with respect to a wrong variable, or is there something wrong with the limits that I have chosen?), and if so, why is the order of integration chosen in this way for the second part (P(T < a)?
More importantly, is there ever a general way to determine the order of integration and the limits involved, given questions like this (other examples include the problem of finding the probability density function of two people or two vehicles meeting each other within a certain time interval or distance interval)? Or does logic and pure reasoning come into place? My class instructor often treats such intermediate steps as if they are of common knowledge,  and he tends to skip or occasionally go very briefly through them, but the subtleties are where the difficult parts lie for me...
Any assistance/explanation would be greatly appreciated! (pardon the lengthy description!) Thank you!


text:
Q: Splitting string values in list into individual values, Python I have a list of values in which some values are words separated by commas, but are considered single strings as shown:
l = ["a",
     "b,c",
     "d,e,f"]

#end result should be
#new_list = ['a','b','c','d','e','f']

I want to split those strings and was wondering if there's a one liner or something short to do such a mutation. So far what, I was thinking of just iterating through l and .split(',')-ing all the elements then merging, but that seems like it would take a while to run.

A: import itertools
new_list = list(itertools.chain(*[x.split(',') for x in l]))

print(new_list)
>>> ['a', 'b', 'c', 'd', 'e', 'f']

A: Kind of unusual but you could join all your elements with , and then split them:
l = ["a",
     "b,c",
     "d,e,f"]

newList = ','.join(l).split(',')
print(newList)

Output:
['a', 'b', 'c', 'd', 'e', 'f']

A: Not exactly a one-liner, but 2 lines:
>>> l = ["a",
     "b,c",
     "d,e,f"]
>>> ll =[]
>>> [ll.extend(x.split(',')) for x in l]
[None, None, None]
>>> ll
['a', 'b', 'c', 'd', 'e', 'f']

The accumulator needs to be created separately since x.split(',') can not be unpacked inside a comprehension.

A: Here's a one-liner using a (nested) list comprehension:
new_list = [item for csv in l for item in csv.split(',')]

See it run here.


text:
Q: error with f# generic follow Expert Fsharp book example I'm reading Expert F# book and I found this code
open System.Collections.Generic
let divideIntoEquivalenceClasses keyf seq =
// The dictionary to hold the equivalence classes
  let dict = new Dictionary<'key,ResizeArray<'T>>()
  // Build the groupings
  seq |> Seq.iter (fun v ->
                          let key = keyf v
                          let ok,prev = dict.TryGetValue(key)
                          if ok then prev.Add(v)
                          else let prev = new ResizeArray<'T>()
                             dict.[key] <- prev
                             prev.Add(v))

 dict |> Seq.map (fun group -> group.Key, Seq.readonly group.Value)

and the example use:
> divideIntoEquivalenceClasses (fun n -> n % 3) [ 0 .. 10 ];;
val it : seq<int * seq<int>>
= seq [(0, seq [0; 3; 6; 9]); (1, seq [1; 4; 7; 10]); (2, seq [2; 5; 8])]

first for me this code is really ugly, even if this is safe, It looks more similar to imperative languages than to functional lang..specially compared to clojure. But the problem is not this...I'm having problems with the Dictionary definition
when I type this:
let dict = new Dictionary<'key,ResizeArray<'T>>();;

I get this:
pruebafs2a.fs(32,5): error FS0030: Value restriction. The value 'dict' has been inferred to have generic type
val dict : Dictionary<'_key,ResizeArray<'_T>> when '_key : equality

Either define 'dict' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.

is It ok?...
thanks so much

improve question:
Ok I've been reading about value restriction and I found this helpfull information

In particular, only function definitions and simple immutable data
  expressions are automatically generalized

...ok..this explains why
let dict = new Dictionary<'key,ResizeArray<'T>>();;

doesn't work...and show 4 different techniques, although in my opinion they only resolve the error but aren't solutions for use generic code:
Technique 1: Constrain Values to Be Nongeneric
 let empties : int list [] = Array.create 100 []

Technique 3: Add Dummy Arguments to Generic Functions When Necessary
let empties () = Array.create 100 []
let intEmpties : int list [] = empties()

Technique 4: Add Explicit Type Arguments When Necessary (similar to tec 3)
let emptyLists = Seq.init 100 (fun _ -> [])
> emptyLists<int>;;
val it : seq<int list> = seq [[]; []; []; []; ...]

-----    and the only one than let me use real generic code   ------
Technique 2: Ensure Generic Functions Have Explicit Arguments
let mapFirst = List.map fst //doesn't work
let mapFirst inp = List.map fst inp

Ok, in 3 of 4 techniques I need resolve the generic code before can work with this...now...returning to book example...when the compile knows the value for 'key and 'T
let dict = new Dictionary<'key,ResizeArray<'T>>()
in the scope the code is very generic for let key be any type, the same happen with 'T
and the biggest dummy question is :
when I enclose the code in a function (technique 3):
let empties = Array.create 100 [] //doesn't work
let empties () = Array.create 100 []
val empties : unit -> 'a list []

I need define the type before begin use it
let intEmpties : int list [] = empties()

for me (admittedly I'm a little dummy with static type languages) this is not real generic because it can't infer the type when I use it, I need define the type and then pass values (not define its type based in the passed values) exist other way define type without be so explicit..
thanks so much..really appreciate any help

A: This line
let dict = new Dictionary<'key,ResizeArray<'T>>();;

fails because when you type the ;; the compiler doesn't know what 'key and 'T are.  As the error message states you need to add a type annotation, or allow the compiler to infer the type by using it later or make it a function
Examples
Type annotation change
let dict = new Dictionary<int,ResizeArray<int>>();;

Using types later
let dict = new Dictionary<'key,ResizeArray<'T>>()
dict.[1] <- 2

using a function
let dict() = new Dictionary<'key,ResizeArray<'T>>();;

A:
for me this code is really ugly, even if this is safe, It looks more similar to imperative languages than to functional lang.

I agree completely – it's slightly tangential to your direct question, but I think a more idiomatic (functional) approach would be:
let divideIntoEquivalenceClasses keyf seq =
    (System.Collections.Generic.Dictionary(), seq)
    ||> Seq.fold (fun dict v ->
        let key = keyf v
        match dict.TryGetValue key with
        | false, _ -> dict.Add (key, ResizeArray(Seq.singleton v))
        | _, prev  -> prev.Add v
        dict)
    |> Seq.map (function KeyValue (k, v) -> k, Seq.readonly v)

This allows sufficient type inference to obviate the need for your question in the first place.

A: This actually doesn't cause an issue when it's defined all together. That is, select the entire block that you posted and send it to FSI in one go. I get this:
val divideIntoEquivalenceClasses :
  ('T -> 'key) -> seq<'T> -> seq<'key * seq<'T>> when 'key : equality

However, if you type these individually into FSI then as John Palmer says there is not enough information in that isolated line for the interpreter to determine the type constraints. John's suggestions will work, but the original code is doing it correctly - defining the variable and using it in the same scope so that the types can be inferred.

A: The workarounds proposed by the other answers are all good.  Just to clarify based on your latest updates, let's consider two blocks of code:
let empties = Array.create 100 []

as opposed to:
let empties = Array.create 100 []
empties.[0] <- [1]

In the second case, the compiler can infer that empties : int list [], because we are inserting an int list into the array in the second line, which constrains the element type.
It sounds like you'd like the compiler to infer a generic value empties : 'a list [] in the first case, but this would be unsound.  Consider what would happen if the compiler did that and we then entered the following two lines in another batch:
empties.[0] <- [1] // treat 'a list [] as int list []
List.iter (printfn "%s") empties.[0] // treat 'a list [] as string list []

Each of these lines unifies the generic type parameter 'a with a different concrete type (int and string).  Either of these unifications is fine in isolation, but they are incompatible with each other and would result in treating the int value 1 inserted by the first line as a string when the second line is executed, which is clearly a violation of type safety.
Contrast this with an empty list, which really is generic:
let empty = []

Then in this case, the compiler does infer empty : 'a list, because it's safe to treat empty as a list of different types in different locations in your code without ever impacting type safety:
let l1 : int list = empty
let l2 : string list = empty
let l3 = 'a' :: empty

In the case where you make empties the return value of a generic function:
let empties() = Array.create 100 []

it is again safe to infer a generic type, since if we try our problematic scenario from before:
empties().[0] <- [1]
List.iter (printfn "%s") (empties().[0])

we are creating a new array on each line, so the types can be different without breaking the type system.
Hopefully this helps explain the reasons behind the limitation a bit more.


text:
Q: Execute react-apollo-hooks useQuery Only the First Time a Component Renders Idiomatically and Elegantly I'm using the most excellent react-apollo-hooks library, specifically the useQuery hook:
function Index() {
    ...
    const [dialogOpen, setDialogOpen] = useState({ show: false, id: '0' });
    ...
    const { data, error } = useQuery(GET_JOBS, { suspend: true });
    if (error) {
        return
Error! {error.message}
;
    }
    const jobs = data.cxJobs; //This is our data
    ....
    function editCallback(e, more) {
        setDialogOpen({ show: true, id: e });
    }
....
}

Of course as soon as I change the dialogOpen state the component re-renders and the graphql query is executed again. Based on a suggestion on the library github repo I rewrote the code to set some state along with useEffect:
function Index() {
    ...
    const [dialogOpen, setDialogOpen] = useState({ show: false, id: '0' });
    const [jobs, setJobs] = useState([]);

    useEffect(_=> {fetchData()}, []);

    const fetchData = async _ => {
        const result = await client.query({query:GET_JOBS});
        setJobs(get(['data','cxJobs'], result));
    }

    async function onEventChanged(id, event) {
        await mutateOne(client, jobGQL, eventToJob(event));
    }
    ...
}

This is pretty good. But can I do better?

A: You could do something like this. Also, you might also want to avoid setting the result of the query to useState and just use data directly.
const [skip, setSkip] = React.useState(false)
const { loading, data } = useQuery(QUERY, { skip })

React.useEffect(() => {
  // check whether data exists
  if (!loading && !!data) {
    setSkip(true)
  }
}, [data, loading])

@Robert, I found that you have raised this issue on apollo-hooks github. And I found that there is an answer which helped me solve this issue, hence adding it here as well so that it can help someone else.


text:
Q: How to process an image from another domain in JavaScript? Is there any good way to drag and drop an image form a web page in another domain into my web page and then do some processing on the data?
I have tried a variety of methods, but every method I try seems to run into cross-origin related restrictions.
I can understand say, not running scripts from foreign servers.
But given the following I don't see how inspecting the image data poses any additional security concern.

*

*The image is publicly available without any credentials.

*The user can already see the image on the original site.

*The user can already right click and save the image if they want, and after saving it, drop it into my web page and do the same processing.  I just want to save them the step.

*If I want to load the image into my web page and then draw it there, the browser displays the foreign image on my web page.

*If I wanted to show the user an altered version of the image, I could still easily do so by just overlaying another transparent canvas on top of it, and drawing on that.

*The fact that the browser won't let someone process the foreign image, doesn't stop someone from making a desktop application that could pull the image from the same URLs and do whatever they want with it.

So if I can already do all those things, how is it a security concern for my script to read the color data from the image?  What bad things can possibly happen if I find out the color of a pixel at coordinate (55, 73) is red?  What possible security attacks could result?

A: No, I don't think there is a way to do it with javascript.
On this point:

The user can already right click and save the image if they want, and after saving it, drop it into my web page and do the same processing. I just want to save them the step.

you could do automatically download that image to your server and process the image on it.

A: Create a dropzone element (I used a  element but you can create a different element):
<main></main>
<script>
  const dropzone = document.querySelector('main');
</script>

Give the dropzone a dashed border style:
<style>
  main {
    border: 1px border lightgray;
    width: 100px;
    height: 100px;
  }
</style>

Highlight the dropzone when the dragenter event is fired (image is dragged over the dropzone):
<style>
  .active {
    border: 1px dashed black;
  }
</style>

<script>
  // ...
  dropzone.addEventListener('dragenter', event => {
    event.preventDefault();
    dropzone.classList.add('active');
  });

event.preventDefault() is necessary or else the image will be opened from your local file explorer.
Remove the dropzone highlight when the dragleave event is fired (image is no longer dragged over the dropzone):
<script>
  // ...
  dropzone.addEventListener('dragleave', event => {
    event.preventDefault();
    dropzone.classList.remove('active');
  });
</script>

It's necessary to handle the dragover event before drop happens:
<script>
  // ...
  dropzone.addEventListener('dragover', event => {
    event.preventDefault();
  });
</script>

Now handle the drop event (when the image is released inside the dropzone):
<script>
  // ...
  dropzone.addEventListener('drop', event => {
    event.preventDefault();
    dropzone.classList.remove('active');

    const file = event.dataTransfer.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.addEventListener('loadend', () => {
      const img = document.createElement('img');
      img.src = reader.result;
      dropzone.append(img);
    });
  });
</script>


text:
Q: center a div-based popup window on the screen from iframe I have an iframe, and from the iframe I am calling a javascript code to display a small window (actually a div tag).  The window should be displayed on the center of the screen independent from the iframe.  I saw some codes for dialog box (e.g., alert box), but could not find a way to center a div-based custom window.  Any suggestions?
Thanks!


text:
Q: FlareGet Browser Integration extension I am working on Ubuntu 12.04.I installed FlareGet and I am unable to add it to Firefox.It is given that "Not available for Firefox 18.0". What can I do now.

A: It seems you never performed a system upgrade.
As you can see in your screenshot you have Firefox version 18 installed and version 41 is available.
Run these commands:
sudo apt-get update
sudo apt-get dist-upgrade

to upgrade Firefox to version 41 and many many other things.
After upgrading you can install the plug-in.


text:
Q: numpy asmatrix sometimes produces an array of lists I am using numpy of python to convert multi dimensional data into matrix by using numpy.asmatrix().
data_array = [[] for k in range(K)]
while Append data to data_array:
   data_array[k].append(data)
mymatrix = numpy.asmatrix(data_array)

The data_array ends up with K*E. While I try to use mymatrix for further manipulation, it turns out some of them works but others still remains as list. When I print it out, it looks like
[[ list([..., ...]), list(..., ...) ]]

Does anyone knows the potential reason for that?

A: My guess is that you are doing the equivalent of:
In [5]: np.matrix([[1,2,3],[2,3],[3]])
Out[5]: matrix([[list([1, 2, 3]), list([2, 3]), list([3])]], dtype=object)

A: You should change your approach to create the entire 2D array first, then fill it in.  Something like this:
mymatrix = np.empty((K, N))
for k in range(K):
    mymatrix[k] = data


text:
Q: "Missing host to link to!" for Devise I installed Devise and things seem to stop up whenever I try to create an account.
The full error reads:
Missing host to link to! Please provide :host parameter or set default_url_options[:host]
I've got the following code sitting in inside the development.rb block.  I've tried it with and without the added smtp configurations.
config.action_mailer.default_url_options = { :host => 'localhost' }
config.action_mailer.delivery_method = :smtp
...

Have I defined host incorrectly?

A: Inherit your Application's default_url_options from ActionMailer.
By default, the default_url_options that you set for config.action_mailer in your environment files (development.rb, production.rb, etc.) do not get used as the default_url_options of your Application as a whole.
$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

$ MyApp::Application.default_url_options
#=> {}

So, when you try and use anything that requires the host and port (e.g. url) outside of the mailer, it doesn't know what to do.
You can solve this by hard coding the host and port in multiple places for the same environment, but you don't want to do that unless your ActionMailer actually uses a different host and port than the rest of your Application.
To solve this (and keep things as DRY as possible), you can automatically use the config.action_mailer.default_url_options as your entire Application's default_url_options.
Simply add the following line to your config/environment.rb file (changing MyApp to your app's name):
# Set the default host and port to be the same as Action Mailer.
MyApp::Application.default_url_options = MyApp::Application.config.action_mailer.default_url_options

This will fix your problem and automatically set your Application's default_url_options to the same as your config.action_mailer.default_url_options:
$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

$ MyApp::Application.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

A: Setting it dynamically solved the problem.
  # application_controller.rb
  before_filter :mailer_set_url_options

  ...

  def mailer_set_url_options
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end

I realize this configuration doesn't belong in a controller by convention, but for development purposes it seems to suffice. I can always code it into into the production environment configuration.

A: Add to the end of fileconfig/environment.rb line:
Rails.application.routes.default_url_options[:host] = 'yourhost.com'

It is not only problem in action_mailer, but also setting default host for the routes as well.

A: The files under config/ are not automatically reloaded in development. If you have made changes to this file, ensure that you have restarted the Rails server, and any Rails console sessions for the changes to take effect.


text:
Q: Echo AFC image subfield Im trying to echo an image from a AFC image field, but cant get it to work.
For a regular textfield with a subfield with group name header_usps and subfield name usp_1 im using below code:
<?php $ups1 = get_field('header_usps_usp_1', 'option'); ?>
<?php echo $ups1; ?>

That works great, but when Im trying this with an image field, I cant seems to fetch the url, instead it displays "Array". Image is loaded as URL.
<?php $image1 = get_field('section_one_sideimage_one', 'option'); ?>
<img src="<?php echo $image1; ?>" alt="Image">

Section_one is the group name and sideimage_one the subfield. What is the correct way to do this?
Var_dump:
/app/public/wp-content/themes/bz-onlinehoortoestel/woocommerce/emails/email-footer-quote.php:52:
   array (size=24)
  'ID' => int 156974
  'id' => int 156974
  'title' => string 'sideimage (1)' (length=13)
  'filename' => string 'sideimage-1.png' (length=15)
  'filesize' => int 16778
  'url' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
  'link' => string 'https://localsite/sideimage-1/' (length=44)
  'alt' => string '' (length=0)
  'author' => string '11' (length=2)
  'description' => string '' (length=0)
  'caption' => string '' (length=0)
  'name' => string 'sideimage-1' (length=11)
  'status' => string 'inherit' (length=7)
  'uploaded_to' => int 0
  'date' => string '2020-06-25 09:31:41' (length=19)
  'modified' => string '2020-06-25 09:31:41' (length=19)
  'menu_order' => int 0
  'mime_type' => string 'image/png' (length=9)
  'type' => string 'image' (length=5)
  'subtype' => string 'png' (length=3)
  'icon' => string 'https://localsite/wp-includes/images/media/default.png' (length=68)
  'width' => int 200
  'height' => int 254
  'sizes' =>
    array (size=66)
      'thumbnail' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-140x140.png' (length=82)
      'thumbnail-width' => int 140
      'thumbnail-height' => int 140
      'medium' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'medium-width' => int 200
      'medium-height' => int 254
      'medium_large' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'medium_large-width' => int 200
      'medium_large-height' => int 254
      'large' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'large-width' => int 200
      'large-height' => int 254
      '1536x1536' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      '1536x1536-width' => int 200
      '1536x1536-height' => int 254
      '2048x2048' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      '2048x2048-width' => int 200
      '2048x2048-height' => int 254
      'small' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'small-width' => int 200
      'small-height' => int 254
      'logo' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'logo-width' => int 200
      'logo-height' => int 254
      'posts-archive' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'posts-archive-width' => int 200
      'posts-archive-height' => int 254
      'watermark' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-200x250.png' (length=82)
      'watermark-width' => int 200
      'watermark-height' => int 250
      'logo-small' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-33x42.png' (length=80)
      'logo-small-width' => int 33
      'logo-small-height' => int 42
      'header-product' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-170x216.png' (length=82)
      'header-product-width' => int 170
      'header-product-height' => int 216
      'best-sold' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-114x145.png' (length=82)
      'best-sold-width' => int 114
      'best-sold-height' => int 145
      'mini-cart' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-90x90.png' (length=80)
      'mini-cart-width' => int 90
      'mini-cart-height' => int 90
      'product-selected' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-200x219.png' (length=82)
      'product-selected-width' => int 200
      'product-selected-height' => int 219
      'favicon' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-64x64.png' (length=80)
      'favicon-width' => int 64
      'favicon-height' => int 64
      'woocommerce_thumbnail' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'woocommerce_thumbnail-width' => int 200
      'woocommerce_thumbnail-height' => int 254
      'woocommerce_single' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'woocommerce_single-width' => int 200
      'woocommerce_single-height' => int 254
      'woocommerce_gallery_thumbnail' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-100x100.png' (length=82)
      'woocommerce_gallery_thumbnail-width' => int 100
      'woocommerce_gallery_thumbnail-height' => int 100
      'shop_catalog' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'shop_catalog-width' => int 200
      'shop_catalog-height' => int 254
      'shop_single' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1.png' (length=74)
      'shop_single-width' => int 200
      'shop_single-height' => int 254
      'shop_thumbnail' => string 'https://localsite/wp-content/uploads/2020/06/sideimage-1-100x100.png' (length=82)
      'shop_thumbnail-width' => int 100
      'shop_thumbnail-height' => int 100

A: To access the subfield you first need to get the group like so :
$section_one = get_field("section_one");

You can then get the subfield through this variable :
$image1 = $section_one["sideimage_one"];

If you want to get the url of the image, make sure when creating the field that the return format is set to "URL".
Hope this helps.


text:
Q: Azure Redis cache premium deployment failure I'm deploying a P1 Redis cache in Azure, using the new portal. There's not much to the deployment, and everything checks out as valid and it lets me start the creation process. I'm adding the Redis to a VNET, and an empty subnet within that VNET, as I'll need a static IP.
After about an hour of "creating", it fails. It just lists the status as "Failed", and the console is not available. I can't find any details about the failure.
I've rolled out plenty of Redis caches that were Basic and Standard tier with no problems. Any idea why this one might be failing?

A: My problem here was actually the result of the section on the following page titled:
What are some common misconfiguration issues with Azure Redis Cache and VNets?
https://docs.microsoft.com/en-us/azure/redis-cache/cache-how-to-premium-vnet
The fairly large table of required network settings has to all be exactly right. Mine was too locked down (and opening up this many things has kind of defeated the purpose my organization was after in adding the Redis to a VNET, but that's a whole other topic.)

A: Had the same problem. The correct hint is on the page you linked in your answer, but I will outline it here directly for others: "When you deploy Azure Cache for Redis to a Resource Manager virtual network, the cache must be in a dedicated subnet that contains no other resources except for Azure Cache for Redis instances. If you attempt to deploy an Azure Cache for Redis instance to a Resource Manager virtual network subnet that contains other resources, the deployment fails."
I tried it with a subnet where other resources where in. This does not work. Hope that helps.


text:
Q: Leanback rowsfragment Actually I'm developing an app for Android TV. I used the BrowseFragment, from leanback support library v17, to navigate by the submenus. But, now I'm trying to build the home activity, like Android TV device app. You can see it here: https://medium.com/building-for-android-tv/building-for-android-tv-episode-1-2d03f9ba541e. And I have problems to know how i can to make a simple row layout, like recommendations. I've tried to do it with a RowsFragment class but ever i have an error inflating XML.
Just I would like the BrowseFragment without the left "drawer".
Thank you four your time and sorry for my poor english.

A: Inside of your activity that extends BrowseFragment, this will remove the left drawer with the headings...
setHeadersState(HEADERS_DISABLED);

If you're using the Android TV sample app, this would be in the MainFragment class in the following method...
setupUIElements()


text:
Q: Editing a QGIS script to use field values as input parameters rather than introducing a constant value I have edited the QGISPolygonSplitting.py script of Pedro Venancio (https://github.com/PedroVenancio/qgis_polygon_splitting) to use values of a selected field as input parameters rather than introducing a constant numeric value. However, I keep getting "Incorrect parameter value" warning.
Any thoughts on what the problem might be?
The original and edited scripts can be found below:
Original Script:
from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterFeatureSource
from qgis.core import QgsProcessingParameterNumber
from qgis.core import QgsProcessingParameterFeatureSink
import processing

class PolygonSplitting(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterFeatureSource('poligonfeatures', 'Polygon to Split', types=[QgsProcessing.TypeVectorPolygon], defaultValue=None))
        self.addParameter(QgsProcessingParameterNumber('numberofpoints', 'Number of Random Points', type=QgsProcessingParameterNumber.Integer, minValue=0, maxValue=100000, defaultValue=10000))
        self.addParameter(QgsProcessingParameterNumber('numberofparts', 'Number of Parts to Split Polygon', type=QgsProcessingParameterNumber.Integer, minValue=0, maxValue=100, defaultValue=5))
        self.addParameter(QgsProcessingParameterFeatureSink('splittedpolygon', 'Splitted Polygon', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(6, model_feedback)
        results = {}
        outputs = {}

        # Random points inside polygons
        alg_params = {
            'INPUT': parameters['poligonfeatures'],
            'MIN_DISTANCE': None,
            'STRATEGY': 0,
            'VALUE': parameters['numberofpoints'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RandomPointsInsidePolygons'] = processing.run('qgis:randompointsinsidepolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # K-means clustering
        alg_params = {
            'CLUSTERS': parameters['numberofparts'],
            'FIELD_NAME': 'CLUSTER_ID',
            'INPUT': outputs['RandomPointsInsidePolygons']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['KmeansClustering'] = processing.run('native:kmeansclustering', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Concave hull (k-nearest neighbor)
        alg_params = {
            'FIELD': 'CLUSTER_ID',
            'INPUT': outputs['KmeansClustering']['OUTPUT'],
            'KNEIGHBORS': 3,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ConcaveHullKnearestNeighbor'] = processing.run('qgis:knearestconcavehull', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # Centroids
        alg_params = {
            'ALL_PARTS': False,
            'INPUT': outputs['ConcaveHullKnearestNeighbor']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Centroids'] = processing.run('native:centroids', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(4)
        if feedback.isCanceled():
            return {}

        # Voronoi polygons
        alg_params = {
            'BUFFER': 100,
            'INPUT': outputs['Centroids']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['VoronoiPolygons'] = processing.run('qgis:voronoipolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(5)
        if feedback.isCanceled():
            return {}

        # Intersection
        alg_params = {
            'INPUT': parameters['poligonfeatures'],
            'INPUT_FIELDS': [''],
            'OVERLAY': outputs['VoronoiPolygons']['OUTPUT'],
            'OVERLAY_FIELDS': [''],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['splittedpolygon']
        }
        outputs['Intersection'] = processing.run('native:intersection', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['splittedpolygon'] = outputs['Intersection']['OUTPUT']
        return results

    def name(self):
        return 'Polygon Splitting'

    def displayName(self):
        return 'Polygon Splitting'

    def group(self):
        return 'Polygon Splitting'

    def groupId(self):
        return 'Polygon Splitting'

    def createInstance(self):
        return PolygonSplitting()

Edited Script:
from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterFeatureSource
from qgis.core import QgsProcessingParameterNumber
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsProcessingParameterField
import processing

class PolygonSplittingEdited(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterFeatureSource('poligonfeatures', 'Polygon to Split', types=[QgsProcessing.TypeVectorPolygon], defaultValue=None))
        self.addParameter(QgsProcessingParameterNumber('numberofpoints', 'Number of Random Points', type=QgsProcessingParameterNumber.Integer, minValue=0, maxValue=10000, defaultValue=300))
        self.addParameter(QgsProcessingParameterField('numberofparts', 'Number of Parts to Split Polygon', type=QgsProcessingParameterField.Numeric, parentLayerParameterName='poligonfeatures', allowMultiple=False, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('splittedpolygon', 'Splitted Polygon', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(6, model_feedback)
        results = {}
        outputs = {}

        # Random points inside polygons
        alg_params = {
            'INPUT': parameters['poligonfeatures'],
            'MIN_DISTANCE': None,
            'STRATEGY': 0,
            'VALUE': parameters['numberofpoints'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RandomPointsInsidePolygons'] = processing.run('qgis:randompointsinsidepolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # K-means clustering
        alg_params = {
            'CLUSTERS': parameters['numberofparts'],
            'FIELD_NAME': 'CLUSTER_ID',
            'INPUT': outputs['RandomPointsInsidePolygons']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['KmeansClustering'] = processing.run('native:kmeansclustering', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Concave hull (k-nearest neighbor)
        alg_params = {
            'FIELD': 'CLUSTER_ID',
            'INPUT': outputs['KmeansClustering']['OUTPUT'],
            'KNEIGHBORS': 3,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['ConcaveHullKnearestNeighbor'] = processing.run('qgis:knearestconcavehull', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # Centroids
        alg_params = {
            'ALL_PARTS': False,
            'INPUT': outputs['ConcaveHullKnearestNeighbor']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Centroids'] = processing.run('native:centroids', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(4)
        if feedback.isCanceled():
            return {}

        # Voronoi polygons
        alg_params = {
            'BUFFER': 100,
            'INPUT': outputs['Centroids']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['VoronoiPolygons'] = processing.run('qgis:voronoipolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(5)
        if feedback.isCanceled():
            return {}

        # Intersection
        alg_params = {
            'INPUT': parameters['poligonfeatures'],
            'INPUT_FIELDS': [''],
            'OVERLAY': outputs['VoronoiPolygons']['OUTPUT'],
            'OVERLAY_FIELDS': [''],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['splittedpolygon']
        }
        outputs['Intersection'] = processing.run('native:intersection', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['splittedpolygon'] = outputs['Intersection']['OUTPUT']
        return results

    def name(self):
        return 'Polygon Splitting Edited'

    def displayName(self):
        return 'Polygon Splitting Edited'

    def group(self):
        return 'Polygon Splitting Edited'

    def groupId(self):
        return 'Polygon Splitting Edited'

    def createInstance(self):
        return PolygonSplittingEdited()

Simple test data can be reached below:
https://we.tl/t-jo2lXpSBKQ

A: Based on your comments you can use this modified script:
from qgis.core import QgsProcessing, QgsProcessingAlgorithm, QgsProcessingMultiStepFeedback, QgsProcessingParameterFeatureSource, QgsProcessingParameterNumber, QgsProcessingParameterFeatureSink, QgsProcessingParameterField, QgsProperty
import processing

class PolygonSplittingEdited(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterFeatureSource('poligonfeatures', 'Polygon to Split', types=[QgsProcessing.TypeVectorPolygon], defaultValue='Polygons'))
        self.addParameter(QgsProcessingParameterField('numberofparts', 'Number of Parts to Split Polygon', type=QgsProcessingParameterField.Numeric, parentLayerParameterName='poligonfeatures', allowMultiple=False, defaultValue='Divisions'))
        self.addParameter(QgsProcessingParameterFeatureSink('splittedpolygon', 'Splitted Polygon', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(3, model_feedback)
        results = {}
        outputs = {}

        # Random points inside polygons
        alg_params = {
            'INPUT': parameters['poligonfeatures'],
            'MIN_DISTANCE': None,
            'STRATEGY': 0,
            'VALUE': QgsProperty.fromExpression(parameters['numberofparts']),
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['RandomPointsInsidePolygons'] = processing.run('qgis:randompointsinsidepolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Voronoi polygons
        alg_params = {
            'BUFFER': 100,
            'INPUT': outputs['RandomPointsInsidePolygons']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['VoronoiPolygons'] = processing.run('qgis:voronoipolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Intersection
        alg_params = {
            'INPUT': parameters['poligonfeatures'],
            'INPUT_FIELDS': [''],
            'OVERLAY': outputs['VoronoiPolygons']['OUTPUT'],
            'OVERLAY_FIELDS': [''],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['splittedpolygon']
        }
        outputs['Intersection'] = processing.run('native:intersection', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['splittedpolygon'] = outputs['Intersection']['OUTPUT']
        return results

    def name(self):
        return 'Polygon Splitting Edited'

    def displayName(self):
        return 'Polygon Splitting Edited'

    def group(self):
        return 'Polygon Splitting Edited'

    def groupId(self):
        return 'Polygon Splitting Edited'

    def createInstance(self):
        return PolygonSplittingEdited()

Changes made:

*

*Import of QgsProperty added

*Removed number input

*Changed number of MultiStepFeedback (6 to 3)

*Changed Value-Input of random points inside polygons algorithm to QgsProperty.fromExpression(parameters['numberofparts']). This will take the field (or better the values this field contains) chosen in input parameters as the number of random points for each feature.

*Removed K-Means-Clustering

*Removed Concave hull (k-nearest neighbor)

*Removed Centroids

*Changed input of voronoi polygons to outputs['RandomPointsInsidePolygons']['OUTPUT']

For means of completeness the answer to the original question:
The issue is that the script is using QGIS processing algorithms. One of them is K-Means-Clustering which expects a number as input, not a field. This makes sense as this algorithms builds clusters from a layers features. This value needs to be fixed by means of it logic. So I am afraid there is no answer to your question, except "not possible".


text:
Q: Parsing Dates using JSON.NET I am using JSON.NET's LINQ to JSON to parse data, which includes dates.  My sample JSON looks like this:
{"2013" : [
    { "date":"2/5/2013 11:13 AM","id":23 }],
"2012" : [
    { "date":"28/9/2012 5:29 PM","id":24 }]
}

The format of the date is in d/m/yyyy h:mm.  I tried parsing it first using DateTime.Parse:
var postTitles = jobject.Children().SelectMany(x => x.First).
    Select(p =>
    new Report
        {
            Date = DateTime.Parse((string)p["date"]),
            Height = (int)p["height"]
        });

However, it throws a FormatException on the second date so I tried using DateTime.ParseExact instead:
var postTitles = jobject.Children().SelectMany(x => x.First).
    Select(p =>
    new Report
        {
            Date = DateTime.ParseExact(p["date"].ToString(), "dd/mm/yyyy hh:mm", new
                CultureInfo("en-US")),
            Height = (int)p["height"]
        });

This time, I get a FormatException on the first date.  Are there any alternatives on how to parse this dates?  I tried using Extension Methods as I am used to doing XML but it seems my extension methods are not recognized.

A: Your format string for ParseExact is very broken. Basically, you really need to pay attention to the format of your actual data, and look at the MSDN documentation for custom date/time strings. You can't just put any old pattern in and expect it to work: it's got to match your data.
So you probably want a format string of "d/M/yyyy h:mm tt". I would also suggest using the invariant culture:
Date = DateTime.ParseExact(p["date"].ToString(), "d/M/yyyy h:mm tt",
                           CultureInfo.InvariantCulture);

(The invariant culture is mostly the same as the US culture, but the important aspect is that it indicates that this is intended for machine-generated data rather than genuinely US-centric data.)
There may well be a better way of doing this in JSON.NET, but that should at least be a starting point.


text:
Q: How to add a Package.swift into a CommandLine projects? I currently have a XCodeProj but want to use the Package.swift file to add dependencies for other libraries.
This project currently generates a binary as a target file, then the binary file takes in arguments and runs some things based on the arguments. The main reason to use the Package.swift is for me to use the argparser using Vapor (not the base ArgumentParser because you have to do the swift run..) or other argument parser libraries.
How can I correctly add the Package.swift file to the XCodeProj? Or how can I add packages to this XCodeProj?


text:
Q: For json "r+", why can't I do dump and load within the same "with" statement? This gives me an error:
with open('username.json', "r+") as f:
    json.dump(current_contents, f)
    newlist= json.load(f)
print(newlist)

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This works:
with open('username.json', "r+") as f:
    json.dump(current_contents, f)

with open('username.json') as f:
    current_contents = json.load(f)
print(current_contents)

But I have to open up 2 'with' blocks to do it. What's the point of "r+" if it can't read and write within the same block?


text:
Q: EF7 (Code First) + SQLite doesn't create a database and the tables for the models Im currently trying to recreate the example, done in the documentation http://ef.readthedocs.org/en/latest/getting-started/uwp.html , using EF7 and SQLite to create a Universal Windows Platform app.
I've installed the required EF7 and EF7 Commands package, and created the model and context:
 public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
            string dirPath = ApplicationData.Current.LocalFolder.Path;
            string connectionString = "Filename=" + Path.Combine(dirPath, "blogging.db");
            optionsBuilder.UseSqlite(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

My problem now is, that after building the solution, the command that should scaffold a migration to create the initial set of tables for my model fails with the following exception:
PM> Add-Migration MyFirstMigration
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
 at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
 at System.Reflection.RuntimeAssembly.get_DefinedTypes()
 at Microsoft.Data.Entity.Design.Internal.StartupInvoker..ctor(String startupAssemblyName, String environment)
 at Microsoft.Data.Entity.Design.DbContextOperations..ctor(ILoggerProvider loggerProvider, String assemblyName, String startupAssemblyName, String environment)
 at Microsoft.Data.Entity.Design.MigrationsOperations..ctor(ILoggerProvider loggerProvider, String assemblyName, String startupAssemblyName, String environment, String projectDir, String rootNamespace)
 at Microsoft.Data.Entity.Design.OperationExecutor.<>c__DisplayClass3_0.<.ctor>b__3()
 at Microsoft.Data.Entity.Internal.LazyRef`1.get_Value()
 at Microsoft.Data.Entity.Design.OperationExecutor.<AddMigrationImpl>d__7.MoveNext()
 at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
 at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
 at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
 at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

Does anyone have a solution for this problem ?
Thanks in advance

A: In my case the solution to the problem was to create the database and tables through code in the app.xaml, before the app starts.
using (var db = new BloggingContext())
{
    db.Database.EnsureCreated();
    db.Database.Migrate();
}

Context + Model:
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        string path = ApplicationData.Current.LocalFolder.Path;
        if (!File.Exists(Path.Combine(path, "blogging.db")))
        {
            File.Create(Path.Combine(path, "blogging.db"));
        }
        optionsBuilder.UseSqlite("Data Source=" + Path.Combine(path, "blogging.db")+";");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Make Blog.Url required
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired();
    }
}

[Table("Blog")]
public class Blog
{
    [Key]
    public int BlogId { get; set; }
    [MaxLength(100)]
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}

[Table("Post")]
public class Post
{
    [Key]
    public int PostId { get; set; }

    [MaxLength(30)]
    public string Title { get; set; }
    [MaxLength(250)]
    public string Content { get; set; }

    public int BlogId { get; set; }
    [ForeignKey("BlogId")]
    public Blog Blog { get; set; }
}

Additionally before accessing the database, i ensure that its created, e.g.
 using (var db = new BloggingContext())
 {
     db.Database.EnsureCreated();
     Blogs.ItemsSource = db.Blogs.ToList();
 }


text:
Q: DB Selection for a dynamic query usecase Use case that I'm looking at is that a file is being shared for import and it may have parameters present for a given user record like first name, last name, phone number, productId ....
Here I need to find matches in system database for these records, all the present parameters from file record must be considered for finding a match.
Example :

FirstName
LastName
mobilePhone
homePhone
email
productId

Ankit
Jain
123456789

a.j@xyz.com
QW123478ASAD1

Paul
John
123456780

p.j@xyz.com
QW123478ASAD1

Senthil

123456781

s.j@xyz.com
QW123478ASAD1

X
John

x.j@xyz.com
QW123478ASAD1

here data should be found for all the records from file if all record details are matched with any of the record present in table.
for     ->
Ankit, Jain, 123456789, a.j@xyzcom, QW123478ASAD1
db record     ->
ankit, Jain, 123456789, a.j@xyzcom, QW123478ASAD1
match found
for     ->
Ankit, Jain, 123456789, a.j@xyzcom, QW123478ASAD1
if db record had ->
ankit, ahuja, 123456789, a.j@xyzcom, QW123478ASAD1
no match found
Records with less than 2 parameters present can be discarded, so that validation will be added before the condition.
Currently I'm storing all file relevant fields information in a denormalised table customer_product_details .
Expected max load : file with 50K records


text:
Q: Using ng-model-options with ngModelController I am trying to delay validation of an custom textbox component. I only want to validate the input on blur. The existing component does not use ng-model inside the input but uses the ngModelController inside the controller of the custom component like so:
<input type="text" name="name" ng-required="true"/>

Can I still use ng-model-options onblur to delay the binding between the template and the controller?
If I'm using ngModelController inside component controller and not using ng-model inside the input element, can I still use ng-model-options in some way to delay input binding? Or is there another clever way to do this?

A: https://jsfiddle.net/28j92bzk/
Use ng-blur
<input type="text" name="name" ng-required="true" ng-blur="validate($event)"/>
$scope.validate = (e) => {
  console.log(e.target.value); // value of input
  // use your logic here
}


text:
Q: Node.js not only opening my code in a specific place My question is, is it possible to do so that when I have a code and a text file, but when I want to open or locate the text file, I dont need to specify it everytime where it is or like when I send it to someone else, they dont need to change the let file = C:\Users\etc...
My code:
const { readFile, readFileSync } = require('fs');

let file = 'C:\\Users\\eeroj\\Desktop\\word-counter\\TextFile2.txt';

function countRepeatedWords(sentence) {
const words = sentence.split(" ").filter(word => !!word);
const wordMap = {};

for (let word of words) {
    const key = word.trim().toLowerCase();
    const currentWordCount = wordMap[key];
    wordMap[key] = (currentWordCount ?? 0) + 1;
}

const sortedEntries = Object.entries(wordMap).sort(([a,], [b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);

//returning the wordMap and the sorting of the wordMap
return sortedWordMap
return wordMap;

}

words = readFileSync(file).toString();
console.log(countRepeatedWords(words));

A: Yes you can, through the path (built-in Nodejs) module and the __dirname constant. The __dirname environment variable will automatically get the current folder's path for you, and then you can use path.join to join the current directory with the filename you want to access. Something like this
const path = require("path");

// Assuming that the current script file are inside the 'C:\\Users\\eeroj\\Desktop\\word-counter' folder
const file = path.join(__dirname, "TextFile2.txt");

// file = 'C:\\Users\\eeroj\\Desktop\\word-counter\\TextFile2.txt'

If you put "TextFile2.txt" in a relative position not in the current folder, you can also use path.join with the folder traversal syntax such as .. to go back a folder
const path = require("path");

// Assuming that the current script file are inside the 'C:\\Users\\eeroj\\Desktop\\word-counter' folder
const file = path.join(__dirname,"../../", "TextFile2.txt");

// file = "C:\\Users\\eeroj\\TextFile2.txt"

As a result, this way should work regardless of anywhere you put the project, even on a different machine, as long as the project folder structure stays relatively the same and the "TextFile2.txt" file is in the right place relative to the script file.

A: If your txt file is in the same directory as the script you can simply use the relative path with a '.' as
let file = "./TextFile2.txt"

Just note that the textfile will have to always have the same name.


text:
Q: Does the series $\;\sum\limits_{n=0}^{\infty}\left(\frac{\pi}{2} - \arctan(n)\right)$ converge or diverge? I tried everything that I know but I couldn't solve this series:
$$\sum_{n=0}^{\infty} \left(\frac{\pi}{2} - \arctan(n)\right)$$
Does it diverge or converge?

A: The serie $\sum \arctan \frac{1}{n}$ is divergent for two reasons: first, it's a positive serie and second $\arctan\frac{1}{n}\sim \frac{1}{n}$ so by comparaison we conclude since the serie $\sum \frac{1}{n}$ is divergent.
To explain more why the positivity of the serie is important to use comparaison test, this is a counterexample : the serie $\sum \log(1+\frac{(-1)^n}{\sqrt{n}})$ is divergent while $\log(1+\frac{(-1)^n}{\sqrt{n}})\sim\frac{(-1)^n}{\sqrt{n}}$ and the serie $\sum \frac{(-1)^n}{\sqrt{n}}$ is convergent

A: Hint: $$\sum_{n=0}^{\infty} \left(\frac{\pi}{2} - \arctan(n)\right) = \dfrac{\pi}{2} + \sum_{n=1}^{\infty} \left(\arctan\left(\frac 1n\right)\right)$$
Then clearly, as $\;n \to \infty,\; \dfrac 1n \to 0$
Perhaps use the limit comparison test? Perhaps the integral test?

Additional hint:
To use the limit comparison test, as suggested by Mhenni in the comment below, consider $\displaystyle \sum b_n = \sum \left(\dfrac 1n\right)\,,\;\,$ and note that $$\;\lim_{n \to \infty} \frac{\arctan(1/n)}{1/n}=1,\;$$ meaning the two series either converge together or diverge together. So apply what you know about the behavior of $\displaystyle \sum_{n=1}^\infty \dfrac 1n\;$ to the task at hand.


text:
Q: Angular multiple ng-options parent / child I have a number of select input children thats data changes depending on the parents selection.
Please see this Codepen for the type of data that will form my parent child relationship.
My starting piece of code is here:
Controller
$scope.params = ['Sets', 'Reps', 'Colour', 'Time', 'Weight'];

$scope.children = [{
    'Sets': ['1', '2', '3', '4', '5']
  }, {
    'Reps': ['1', '2', '3', '4', '5']
  }, {
    'Colour': ['Red', 'Green', 'Blue', 'Yellow', 'Pink']
  },

];

HTML

        Param

    <select ng-model="param">
        <option ng-repeat="param in params" value="{{param}}">{{param}}</option>
    </select>

        Sets

    <select ng-model="param">
        <option ng-repeat="param in params" value="{{param}}">{{param}}</option>
    </select>

The children will only be visible if the corresponding parent is selected.

A: I would change the model like this:
$scope.params = ['Sets', 'Reps', 'Colour', 'Time', 'Weight'];

$scope.children = {
  'Sets': ['1', '2', '3', '4', '5'],
  'Reps': ['1', '2', '3', '4', '5'],
  'Colour': ['Red', 'Green', 'Blue', 'Yellow', 'Pink']
};

And then do something like this:
http://codepen.io/anon/pen/RPZzdM

A: I'm not sure I see a question here ;) But looking at your code the odd thing is that you set the same model in two different selects.
Try and change the ng-model in the second one to something distinct, e.g. childParam:


text:
Q: How to get data from user for linked list I tried to create linked list in C which will allow the user to insert data, print the list and exit from the program. I can insert the data and print the list one time but when I try to print the list again it shows list as empty. The address of the header has been changed to NULL.
#include <stdio.h>
#include <stdlib.h>
struct Node* head;
struct Node
    {
int data;
struct Node* next;
    };
void Insert(int x)
{
    struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;
    head=temp;
}
print()
{
    printf("%d",head);
    printf("\nthe list is\n");
    while(head!=NULL)
    {
        printf("%d\t",head->data);
        head=head->next;
            }
}
int main()
{
    //head=NULL;
    int n,i,x,option;
do
{
    printf("\n1.Insert 2.Print 3.Exit");
    printf("\nenter option:");
    scanf("%d",&option);
    if(option==1){
    printf("\nTotal no to be entered:");
    scanf("%d",&n);
for(i=0;i<n;i++)
{
    printf("\nEnter the number:");
    scanf("%d",&x);
    Insert(x);
}}
else{
if(option==2){
    print();
    }
}
}while(option!=3);
}

A: Your print method changes the head pointer, so next time you access the list, head will point to null. You should use a different pointer for the iteration:
void print()
{
    Node* iter = head;
    printf("%d", iter);
    printf("\nthe list is\n");
    while(iter!=NULL)
    {
        printf("%d\t",iter->data);
        iter=iter->next;
    }
}

A: You are lopping over the linked list with the pointer head to the head of your list, so at the end of the loop, head reaches the end of the list and nothing remains to print.
To resolve the problem you need to keep head on its place (the head of the list) and loop with a second pointer loop_ptr
print()
{   Node* loop_ptr = head;// create a pointer to loop with
    printf("%d",loop_ptr);
    printf("\nthe list is\n");
    while(loop_ptr!=NULL)
    {
        printf("%d\t",loop_ptr->data);
        loop_ptr=loop_ptr->next;// at the end head points always to the head of your list
    }
}

Nota Bene:
struct Node* next;
struct Node* head;

This is a bad practice when dealing with pointers. Unlike other data structures, a pointer must always properly initialized to avoid unexpected mess. In your case, you can do this:
struct Node* next= NULL;
struct Node* head= NULL;


text:
Q: Is this proof of the limit of the product of a bounded function and a function that goes to zero correct? I have to learn a long list of proofs. In order to understand them I try to reformulate them and make them easier for me to grasp. In the process of doing so I often make them incorrect. I wonder if the following is correct?
Prove that: $$\lim_{x \to \infty} f(x)g(x) = 0$$ if $$\lim_{x \to \infty} f(x) = 0$$ and $g(x)$ is bounded.
Proof: Since $g(x)$ is bounded $\exists M: |g(x)|< M$, and since $\lim_{x \to \infty} f(x)$ we have $$\forall \varepsilon > 0, \exists \delta: x > \delta \Rightarrow |f(x)| < \varepsilon.$$
We then get
$$|g(x)|< M \Rightarrow |f(x)g(x)| < |f(x)\cdot M|$$
and combine this with the limit definition
$$\forall \varepsilon > 0, \exists \delta: x > \delta \Rightarrow |f(x)| < \varepsilon \Leftrightarrow \varepsilon \cdot M > |f(x) \cdot M| > |f(x) g(x)|$$
q.e.d.

A: Almost. Here are some things that I would modify:
Let $\varepsilon >0$. Since ${\displaystyle \lim_{x\rightarrow\infty}}f(x)=0$, there exists $\delta >0$ such that $|f(x)|<\varepsilon/M$ whenever $x>\delta$. Assume $x>\delta$. Then $|f(x)g(x)|=|f(x)||g(x)|< |f(x)|M<(\varepsilon/M)M=\varepsilon$.


text:
Q: background color not changing in circular application I'm playing around with visual controls and colors in a simple background color changing program I've written. I also wanted to incorporate the circular application window, which I did by creating a bitmap of a solid circle surrounded by black and making the black transparent. Now my back ground color doesn't loop. Can anyone tell me how to fix this. Ill include my code just in case it helps but I think this is a form properties problem. Thanks for any help!
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public Point mouse_offset;
    public int c;

    private void button1_Click(object sender, EventArgs e)
    {
        using (SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer())
        {
            synth.Speak("This is a test of the emergency see sharp broadcasting network!");
            synth.Speak("The man to the left is actually trying to dance without graphics capabilities");

        }
        while (Visible)
        {
            using (SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer())
            {
                synth.Speak("Flash dance commencing in three. two. one.");
            }
            while (Visible)
            {
                for (int c = 0; c < 255 && Visible; c++)
                {
                    this.BackColor = Color.FromArgb(c, 255 - c, c);
                    Application.DoEvents();
                    //slow();

                }

                for (int c = 255; c > 0 && Visible; c--)
                {
                    this.BackColor = Color.FromArgb(c, 255 - c, c);
                    Application.DoEvents();
                    //slow();

                }

            }
        }
    }

    public static void slow()
    {
        System.Threading.Thread.Sleep(3);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        mouse_offset = new Point(-e.X, -e.Y);

    }

    private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            Point mousePos = Control.MousePosition;
             mousePos.Offset(mouse_offset.X, mouse_offset.Y);
            Location = mousePos;
        }
    }

}

}

A: Every time you have changed the looks of a component and want to display this change, call
myComponent.Invalidate();

This forces the conponent to redraw itself. Now that you're there, there are a number of ways to optimize redraws, but I think the above should get you started.


text:
Q: Large set of data, DataTables render time awful I have a view that displays a set of data of about 3000+ records (multiple objects combined into a QuerySet. The result is rendered into a table using DataTables but the render time is terrible - 15 seconds at least.
I dug deeper into DataTables and found deferRender API option together with AJAX thing. As I never used it before I'd like to ask for guidance on how to approach in my particular case. Below are views.py and template with DataTables.
views.py:
def index(request):
    clients = Client.objects.all().prefetch_related('loan_set', 'loan_set__case_set')
    return render(request, 'app/index.html',
                  {'clients': clients})

index.html:

                    Imię i nazwisko
                    Edycja

                {% for c in clients %}

                    {{ c.firstName }} {{ c.lastName }}
                    {% if c.editLock %}
                     {{ c.lockedBy }}
                    {% else %}
                    <form method="post">
                        {% csrf_token %}

                    </form>
                    {% endif %}

                {% endfor %}

A: Look at the documentation for datatables.
    $('#case_list').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "{yourdata_url}"
    } );

In your view, you have to send the data in json format. Note that you need to do the search etc with your logic in the view.
I would also look into django-datatable-view package.


text:
Q: boost unable to move a scoped_lock with gcc The following compiles under VS2010 (Express) but not gcc (4.6.2 here).
Lockable.h:
#include <boost/thread/mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

template<typename T>
class LockedProxy : boost::noncopyable
{
public:
    inline LockedProxy(boost::mutex & m, T * obj)
        :lock(m),
        t(obj)
    {}
    inline LockedProxy(const LockedProxy && other)
        :lock(std::move(other.lock)),
        t(std::move(other.t))
    {}

    inline       T * operator->()       { return t; }
    inline const T * operator->() const { return t; }

    inline const T & operator*() const { return *t; }
    inline       T & operator*()       { return *t; }

private:
    boost::interprocess::scoped_lock<boost::mutex> lock;
    T * t;
};

template<typename T>
class Lockable
{
public:

    // Convenience typefed for subclasses to use
    typedef T LockableObjectType;

    inline Lockable(const T & t)
        :lockableObject(t)
    {}

    inline LockedProxy<LockableObjectType> GetLockedProxy() {
        return LockedProxy<LockableObjectType>(mutex, &lockableObject);
    }

protected:
    LockableObjectType lockableObject;
    boost::mutex mutex;
};

main.cpp:
#include <iostream>
#include <string.h>
#include "Lockable.h"

void f(Lockable<std::string> & str)
{
    auto proxy = str.GetLockedProxy();

    *proxy = "aa";
    proxy->append("bb");

    std::cout << "str = " << *proxy << std::endl;
}

void g(Lockable<int> & i)
{
    { // reduce lock's lifespan
        auto proxy = i.GetLockedProxy();
        *proxy = 321;
    }

    // relock, lock lives for the statement
    std::cout << "i = " << *i.GetLockedProxy() << std::endl;
}

int main()
{
    Lockable<std::string> str("abc");
    //Can't use str here, it is not locked
    f(str);

    Lockable<int> i(123);
    g(i);

    return 0;
}

The errors:
In file included from main.cpp:3:0:
C:/Users/DrGibbs/Documents/code/boost_1_46_0/boost/interprocess/sync/scoped_lock.hpp: In constructor 'LockedProxy<T>::LockedProxy(const LockedProxy<T>&&) [with T = std::basic_string<char>, LockedProxy<T> = LockedProxy<std::basic_string<char> >]':main.cpp:7:37:   instantiated from here
C:/Users/DrGibbs/Documents/code/boost_1_46_0/boost/interprocess/sync/scoped_lock.hpp:56:4: error: 'boost::interprocess::scoped_lock<Mutex>::scoped_lock(const boost::interprocess::scoped_lock<Mutex>&)[with Mutex = boost::mutex, boost::interprocess::scoped_lock<Mutex> = boost::interprocess::scoped_lock<boost::mutex>]' is privateLockable.h:14:29: error: within this context
C:/Users/DrGibbs/Documents/code/boost_1_46_0/boost/interprocess/sync/scoped_lock.hpp: In constructor 'LockedProxy<T>::LockedProxy(const LockedProxy<T>&&) [with T = int, LockedProxy<T> = LockedProxy<int>]':
main.cpp:18:36:   instantiated from here
C:/Users/DrGibbs/Documents/code/boost_1_46_0/boost/interprocess/sync/scoped_lock.hpp:56:4: error: 'boost::interprocess::scoped_lock<Mutex>::scoped_lock(const boost::interprocess::scoped_lock<Mutex>&)[with Mutex = boost::mutex, boost::interprocess::scoped_lock<Mutex> = boost::interprocess::scoped_lock<boost::mutex>]' is private
Lockable.h:14:29: error: within this context

Well as far as I understand, in LockedProxy's move-constructor, the scoped_lock is not moved but copy-constructed, which really should not work. Shouldn't the std::move guanrantee its move-construction ? What am I missing ?

A: Your move constructor declares its parameter const:
inline LockedProxy(const LockedProxy && other)

It should be declared non-const:
inline LockedProxy(LockedProxy && other)

Your std::move(other.lock) is taking other.lock as a const reference, and so returning a const rvalue reference const boost::interprocess::scoped_lock<boost::mutex> &&, which cannot be passed to the move constructor of boost::interprocess::scoped_lock<boost::mutex>.
See also C++0x const RValue reference as function parameter, which explains that const rvalue references are almost entirely useless.


text:
Q: N word of EOF using json_encode from a SQL Query This is a php code that retrieve de data from a SQL Query and then use json_encode
$app->get('/myapp/data.json', function () use($app) {
    $sql = "SELECT id, name FROM users;";

    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $results = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        $app->contentType("application/json; charset=utf-8");
        $app->response()->status(200);
        $app->response()->body(json_encode(array('users'=>$results)));
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
});

Everything ok but appears a N word in the EOF.
{"regiones":[{"id":"13","user":"peter"},
{"id":"14","user":"ben"},
{"id":"15","user":"harry"}]}n

And don't let me validate the json data
i try not using PDO (mysql_connect, mysql_select_db, mysql_query, etc) and the same, the N word in the end of the line. But i change the server and work fine. WHY???


text:
Q: verificando se a data de um EditText é maior que a data de outro EditText Tenho dois EditText no meu aplicativo e  seleciono a data usando um DatePicker preciso fazer com que o usuário não informe uma data menor que a informada no primeiro EditText.

A: Assumindo que as datas dos dois EditText estão no formato dd-MM-yyyy pode fazer o seguinte:
EditText editData1 = (EditText)findViewById(R.id.meu_edit1); //id para o seu 1º EditText
EditText editData2 = (EditText)findViewById(R.id.meu_edit2); //id para o seu 2º EditText

//criar formato para interpretação da data
SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");

try {
    Date data1 = formato.parse(editData1.getText().toString()); //interpretar data1
    Date data2 = formato.parse(editData2.getText().toString()); //interpretar data2

    if (data2.getTime() < data1.getTime()){
        //código para quando segunda data é menor
    }
}
catch (ParseException ex){
    Log.d("Debug", "Um dos campos não tem uma data válida");
}

Utilizando os seguintes imports:
import android.util.Log;
import android.widget.EditText;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


text:
Q: AlarmManager doesn't update push notification time (hours and minutes) after the first notification sent I'm using an AlarmManager to repeat a Push Notification Service every 60 seconds. So, every 60 seconds, the service sends a new push notification, but with the wrong time (hours and minutes): for example, if the service starts at 00:39, it sends a push notification with time=00:39; then, after 60 seconds (so when the clock is on 00:40), the service sends a new push notification with the same time of the first notification, and it will send push notification with the same time "forever".  You can see how the service behaves in this image

Here my code ("ServicesDemo.java" calls the service named "MyService.java"):  ServicesDemo.java
public class ServicesDemo extends Activity implements OnClickListener {
  Button buttonStart, buttonStop;
  AlarmManager alarmManager;
  PendingIntent pendingIntent;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
        Intent myIntent = new Intent(ServicesDemo.this , MyService.class);
        alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        pendingIntent = PendingIntent.getService(ServicesDemo.this, 0, myIntent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000 , pendingIntent);  //set repeating every 60 seconds
      break;
    case R.id.buttonStop:
      alarmManager.cancel(pendingIntent);
      break;
    }
  }
}

MyService.java
public class MyService extends Service {
    private static final String TAG = "MyService";
    NotificationManager NM;
    Notification notify;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notify=new Notification(android.R.drawable.
                stat_notify_more,"Notification",System.currentTimeMillis());
        PendingIntent pending=PendingIntent.getActivity(
                getApplicationContext(),0, new Intent(),0);
        // Hide the notification after its selected
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        notify.setLatestEventInfo(getApplicationContext(),"Title","Body",pending);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        NM.notify(0, notify);
    }
}

I got frustrated about it. Does anyone knows how to fix this problem? Every help will be greatly appreciated :)

A: Thanks to FoggyDay's suggestion, I've solved my problem: since the push notification was built only the first time into the onCreate() method, it's obvious that its time never changed. I've also used a deprecated way to build push notifications, but the problem was not caused by this.  So my code may be changed in two ways:  1) in this (deprecated) way:
public class MyService extends Service {
    private static final String TAG = "MyService";
    NotificationManager NM;
    Notification notify;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");

        NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notify=new Notification(android.R.drawable.
                stat_notify_more,"Notification",System.currentTimeMillis());
        PendingIntent pending=PendingIntent.getActivity(
                getApplicationContext(),0, new Intent(),0);
        // Hide the notification after its selected
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        notify.setLatestEventInfo(getApplicationContext(),"Title","Body",pending);
        NM.notify(0, notify);
    }
}

2) ...and in this (better) way:
public class MyService extends Service {
    private static final String TAG = "MyService";
    NotificationManager NM;
    NotificationCompat.Builder mBuilder;
    NotificationManager mNotificationManager;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        mNotificationManager.cancelAll();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.icon)
                .setContentInfo("Ciao!")
                .setSubText("Hey!")
                .setTicker("Hoy!")
                .setContentTitle("My notification")
                .setContentText("Hello World!");

        Intent resultIntent = new Intent(this, ResultActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(ResultActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        mBuilder.setAutoCancel(true);
        mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.notify(0, mBuilder.build());
    }
}

I don't know if it is a good practice to leave the onCreate() method empty, but it works :D however, I accept other suggestions about it


text:
Q: How to download old versions of plugins? I have previously been able to go the the plugin repository to locate previous versions of plugins in order to restore compromised websites. Since the design for the plugin repository has changed I can no longer find where they are stored.
I have scrolled down to the "Contributors & Developers" section then followed various links to try and download older versions but can only seem to download files that have had changes (not all files). Please if someone could help me out that would be much appreciated.

A: For now you can use an SVN checkout from https://plugins.svn.wordpress.org/
Please see: https://developer.wordpress.org/plugins/wordpress-org/how-to-use-subversion/
(I've passed the suggestion to the WordPress meta team) Here's the ticket url: meta.trac.wordpress.org/ticket/2365


text:
Q: Which quantity is mass (tensor, vector or scalar)? Mass and spin are fundamental characteristics of particle. Those quantities are eigenvalues of the Casimir operators of the Poincaré group. My book then writes that
$$
p^\mu p_\mu = m_0^2,
$$
where $m_0$ is mass of idle and mass $m=\gamma m_0$ is mass of moving (relativistic mass).

If we boost the first equation, we have
$$
({\Lambda_{\nu }^{\mu }}p_{\mu })({\Lambda_{\mu }^{\nu }}p^{\mu })=\gamma^2m_{0}^2=(\Lambda_{\nu }^{\mu }\Lambda_{\mu }^{\nu })p_{\mu }p^{\mu }=1\cdot p_{\mu }p^{\mu } =m_{0}^2,
$$
and this is a contradiction! One other author says that exist only mass of idle, and no sense that we speak about mass of moving. Why we hadn't speak about mass of moving?
P.S. Casimir operators are scalar operators, but and $m_0$ is scalar, but it is change as which quantity (scalar, tensor or vector)? This transform as $m=m_0\times gamma$ if we has relativistic mass, but this concept I think that is not valid, it is interpretation.

A: The idea that mass changes as speed increases is being phased out of teaching, precisely because it leads to the type of confusion that you're having now. The quantity $\gamma m_0$ has only one name, and that's the total energy of the moving body. Total energy is neither a Lorentz scalar, vector, nor tensor; it changes with the reference frame in a way that is not compatible with any of those concepts. Mass (or, as older textbooks will call it, "rest mass") is a Lorentz scalar, as it doesn't change with reference frame.


text:
Q: Gradient fill in PDF figure turns out solid filled in compiled document UPDATE:
It turns out it was a compatibility issue with the PDF viewers.
Apple Preview, Adobe Acrobat Professional 8 and Firefox display the compiled document wrongly. Under TeXWork and Adobe Reader 11, Google Chrome it is displayed as intended.
I have a pdf file included as a figure in my document.
It has a shape with a gradient fill. I'am afraid, in the compiled (pdflatex) document the shape is filled with a solid colour.
Since there is no compile error or warning indicating the gradient fill, I would like to know where to start correcting this misbehaviour.
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}[htbp]
\centering
\includegraphics[width=100mm]{filename}
\caption{figure caption}
\label{fig:figurelable}
\end{figure}
\end{document}

Link to pdf file
Link to compiled pdf file
I included screenshots to illustrate the situation.


text:
Q: FileTransfer DWR and input file MULTIPLE. Uploading files my problem: I use DWR3 (FileTransfer) for upload files from jsp without any problem, but now we want to use the file in MULTIPLE mode, this is:
input type="file" multiple="multiple" name="... (HTML5)

this avoid to the typical dialog for searching files to select more than one file of the client system. But, How I catch them in the server?
I attempt without success:
public String catchMultipleFiles(FileTransfer[] files, HttpServletRequest req) throws Exception{ ...}
public String catchMultipleFiles(ArrayList<FileTransfer> files, HttpServletRequest req) throws Exception{ ...}

Always my older version for catch one works perfectly, simply:
public String catchOneFile(FileTransfer file, HttpServletRequest req) throws Exception{ ...}

Anyone have this problem?
Thanks a lot in advance.


text:
Q: "__defineGetter__(0x1000, () => 1)", what does mean? How is __defineGetter__(0x1000, () => 1) valid?
The first argument of __defineGetter__ should be a property, and the second argument a function.
Is 0x1000 a valid property name? or does __defineGetter__ accept something else as a first agument?

A: Although confusing, 0x1000 is indeed a valid property.
let x = {}
x.__defineGetter__(0x1000, () => 1)
x[0x1000] // == x['4096'] == 1

More generally though, object property keys are strings, and if you use something that is not a string, it will be converted to one using String(key). A more explicit example:
let x = {}
let y = {}
x.__defineGetter__(y, () => 1)
x[y] // == x['[object Object]'] == 1

Consequently, if the string representation of two different  values (e.g. two different objects) is not the same, they will act as the same key (and map to the same value).


text:
Q: Samples with no label assignment using multilabel random forest in scikit-learn I am using Scikit-Learn's RandomForestClassifier to predict multiple labels of documents. Each document has 50 features, no document has any missing features, and each document has at least one label associated with it.
clf = RandomForestClassifier(n_estimators=20).fit(X_train,y_train)
preds = clf.predict(X_test)

However, I have noticed that after prediction there are some samples that are assigned no labels, even though the samples were not missing label data.
>>> y_test[0,:]
array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> preds[0,:]
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
    0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

The results of predict_proba align with those of predict.
>>> probas = clf.predict_proba(X_test)
>>> for label in probas:
>>>    print (label[0][0], label[0][1])
(0.80000000000000004, 0.20000000000000001)
(0.94999999999999996, 0.050000000000000003)
(0.94999999999999996, 0.050000000000000003)
(1.0, 0.0)
(1.0, 0.0)
(1.0, 0.0)
(0.94999999999999996, 0.050000000000000003)
(0.90000000000000002, 0.10000000000000001)
(1.0, 0.0)
(1.0, 0.0)
(0.94999999999999996, 0.050000000000000003)
(1.0, 0.0)
(0.94999999999999996, 0.050000000000000003)
(0.84999999999999998, 0.14999999999999999)
(0.90000000000000002, 0.10000000000000001)
(0.90000000000000002, 0.10000000000000001)
(1.0, 0.0)
(0.59999999999999998, 0.40000000000000002)
(0.94999999999999996, 0.050000000000000003)
(0.94999999999999996, 0.050000000000000003)
(1.0, 0.0)

Each output above shows that for each label, a higher marginal probability has been assigned to the label not appearing. My understanding of decision trees was that at least one label has to be assigned to each sample when predicting, so this leaves me a bit confused.
Is it expected behavior for a multilabel decision tree / random forest to be able to assign no labels to a sample?
UPDATE 1
The features of each document are probabilities of belonging to a topic according to a topic model.
>>>X_train.shape
(99892L, 50L)
>>>X_train[3,:]
array([  5.21079651e-01,   1.41085893e-06,   2.55158446e-03,
     5.88421331e-04,   4.17571505e-06,   9.78104112e-03,
     1.14105667e-03,   7.93964896e-04,   7.85177346e-03,
     1.92635026e-03,   5.21080173e-07,   4.04680406e-04,
     2.68261102e-04,   4.60332012e-04,   2.01803955e-03,
     6.73533276e-03,   1.38491129e-03,   1.05682475e-02,
     1.79368409e-02,   3.86488757e-03,   4.46729289e-04,
     8.82488825e-05,   2.09428702e-03,   4.12810745e-02,
     1.81651561e-03,   6.43641626e-03,   1.39687081e-03,
     1.71262909e-03,   2.95181902e-04,   2.73045908e-03,
     4.77474778e-02,   7.56948497e-03,   4.22549636e-03,
     3.78891036e-03,   4.64685435e-03,   6.18710017e-03,
     2.40424583e-02,   7.78131179e-03,   8.14288762e-03,
     1.05162547e-02,   1.83166124e-02,   3.92332202e-03,
     9.83870257e-03,   1.16684231e-02,   2.02723299e-02,
     3.38977762e-03,   2.69966332e-02,   3.43221675e-02,
     2.78571022e-02,   7.11067964e-02])

The label data was formatted using MultiLabelBinarizer and looks like:
>>>y_train.shape
(99892L, 21L)
>>>y_train[3,:]
array([0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

UPDATE 2
The output of predict_proba above suggested above that the assigning of no classes might be an artifact of trees voting on labels (there are 20 trees and all probabilities are approximately multiples of 0.05). However, using a single decision tree, I still find there are some samples that are assigned no labels. The output looks similar to predict_proba above, in that for each sample there is a probability a given label is assigned or not to the sample. This seems to suggest that at some point the decision tree is turning the problem into binary classification, though the documentation says that the tree takes advantage of label correlations.

A: This can happen if the train and test data are scaled differently, or otherwise drawn from different distributions (e.g., if the tree learned to split on values that occur in train but don't occur in test).
You could inspect the trees to try to get a better understanding of what's happening. To do this, look at the DecisionTreeClassifier instances in clf.estimators_ and visualize their .tree_ properties (for example, using sklearn.tree.export_graphviz())