text:
Q: C# Can't get this json deserialized I've been trying to deserialize an array of objects in C# with JsonConvert.DeserializeObject<>().
I don't know how to do it.
I tried with List ListFotos = JsonConvert...
I tried  to modify my Fotos object adding a List and a List<Dictionary<object, string>>
Help me please.
JSON:
{
      "error": {
        "id": 0,
        "msg": "OK"
      },
      "parte": {
        "datos": {
          "id_parte": "",
          "titulo": "",
          "hotel": "",
          "bloque": "",
          "planta": "",
          "habitacion": "",
          "tipo": "",
          "fechacreacion": "",
          "creador": "",
          "departamentocreador": ""
        },
        "fotos": [
          {
            "id_foto": "3574",
            "archivo": "2021060411202834031400.jpg"
          },
          {
            "id_foto": "3575",
            "archivo": "2021060411203492625800.jpg"
          }
        ],
        "historico": [
          {
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          },
          {
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          },
          {
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          },
          {
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          },
          {
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          },
          {
            "fechaevento": "",
            "estado": "",
            "observaciones": "",
            "usuarioasignado": "",
            "proveedor": "",
            "tipoterceros": "",
            "fechaaplazado": ""
          }
        ]
      }
    }

C#:
...
if (item.Key.ToString() == "fotos")
{
    parte_fotos = item.Value.ToString();
    List<Model.Fotos> fotos = await App.Database.GetFotosAsync();
    Model.Fotos foto = new Model.Fotos();
    foto = JsonConvert.DeserializeObject<Model.Fotos>(parte_fotos);
    foto.ID_Parte = id;
}
...

The error i have:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WorkersApp.Model.Fotos' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract) [0x00058] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id) [0x00012] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0007f] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader r06-22 12:56:32.085 V/mono-stdout(31636):   at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <7ca8898b690a4181a32a9cf767cedb1e>:0
  at 06-22 12:56:32.086 V/mono-stdout(31636):   at WorkersApp.Pageviews.Partes.GetDatosParteFromApi (System.String url, System.String id) [0x0066c] in C:\Users\CGarcia\source\repos\WorkersApp\WorkersApp\WorkersApp\Pageviews\Partes.xaml.cs:155

The error hits on this line:
foto = JsonConvert.DeserializeObject<Model.Fotos>(parte_fotos);

EDIT:
I have been asked to post:
string parte_fotos contains:
"[\n  {\n    \"id_foto\": \"3566\",\n    \"archivo\": \"2021060312461958641800.jpg\"\n  }\n]"

and Model.Fotos code is:
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace WorkersApp.Model
{
    public class Fotos
    {
        [PrimaryKey]
        public string ID_Foto { get; set; }
        public string ID_Parte { get; set; }
        [NotNull]
        public string Archivo { get; set; }
    }
}

A: This error is due to incorrect conversion from JSON object to Fotos model, for solving that first you must cast your JSON object to model, then you fetch Fotos list from your model:
fotos = (JsonConvert.DeserializeObject<Model>(parte_fotos)).parte.fotos;

Model object shown below:
public class Model
{
    public Error error { get; set; }
    public Parte parte { get; set; }
}

public class Error
{
    public int id { get; set; }
    public string msg { get; set; }
}

public class Parte
{
    public Datos datos { get; set; }
    public List<Foto> fotos { get; set; }
    public List<Historico> historico { get; set; }
}

public class Datos
{
    public string id_parte { get; set; }
    public string titulo { get; set; }
    public string hotel { get; set; }
    public string bloque { get; set; }
    public string planta { get; set; }
    public string habitacion { get; set; }
    public string tipo { get; set; }
    public string fechacreacion { get; set; }
    public string creador { get; set; }
    public string departamentocreador { get; set; }
}

public class Foto
{
    public string id_foto { get; set; }
    public string archivo { get; set; }
}

public class Historico
{
    public string fechaevento { get; set; }
    public string estado { get; set; }
    public string observaciones { get; set; }
    public string usuarioasignado { get; set; }
    public string proveedor { get; set; }
    public string tipoterceros { get; set; }
    public string fechaaplazado { get; set; }
}

A: try
foto = JsonConvert.DeserializeObject<List<Model.Fotos>>(parte_fotos);

A: What you can do is try https://json2csharp.com/
This site converts JSON documents to C# classes...
So the generated classes are:
public class Error
{
    public int id { get; set; }
    public string msg { get; set; }
}

public class Datos
{
    public string id_parte { get; set; }
    public string titulo { get; set; }
    public string hotel { get; set; }
    public string bloque { get; set; }
    public string planta { get; set; }
    public string habitacion { get; set; }
    public string tipo { get; set; }
    public string fechacreacion { get; set; }
    public string creador { get; set; }
    public string departamentocreador { get; set; }
}

public class Foto
{
    public string id_foto { get; set; }
    public string archivo { get; set; }
}

public class Historico
{
    public string fechaevento { get; set; }
    public string estado { get; set; }
    public string observaciones { get; set; }
    public string usuarioasignado { get; set; }
    public string proveedor { get; set; }
    public string tipoterceros { get; set; }
    public string fechaaplazado { get; set; }
}

public class Parte
{
    public Datos datos { get; set; }
    public List<Foto> fotos { get; set; }
    public List<Historico> historico { get; set; }
}

public class Root
{
    public Error error { get; set; }
    public Parte parte { get; set; }
}

You can acces it through:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);


text:
Q: How to convert JavaDStream into RDD ? OR Is there a way i can create new RDD inside map function of JavaDStream? The streaming data which i am getting from kafka is the path of hdfs file and i need to get the data of that file .
batchInputDStream.map(new Function<Tuple2<String,String>, FreshBatchInput>() {

            @Override
            public String call(Tuple2<String, String> arg0)
                    throws Exception {
                StringReader reader = new StringReader(arg0._2);
                 JAXBContext jaxbContext = JAXBContext.newInstance(FreshBatchInput.class);

                    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                    FreshBatchInput input = (FreshBatchInput)jaxbUnmarshaller.unmarshal(reader);

                return input.getPath();
            }
        });

here input.getPath() is the hdfs path of file .
There is no option to collect JavaDstream Object otherwise i would have used that by first collecting data and than getting data from file.
Iam not able to create new RDD inside map function it is giving error Task Not Serializable.
Is there any other option ?

A: You can use foreachRDD. It is executed on driver, so rdd actions are allowed
transformed.foreachRDD (rdd -> {
    String inputPath = doSomethingWithRDD(rdd)
    rdd.sparkContext.textFile(inputPath) ...
});

Remember that you cannot create RDD inside transformations or actions - RDDs can be created only on the driver. Similar question with example of foreachRDD is here. This means, you cannot use SparkContext inside map, filter or foreachPartition

redpajama_set_name: RedPajamaStackExchange


text:
Q: Harnack's inequality for gradient How to prove the following:
If u is a function harmonic and
positive in the disk |z| < R, then
$|∇u(0)| ≤ 2u(0)/R$?
Any hint is welcome. Thanks in advance.

A: Let $v(z)=u(Rz)$ so we are in the disc of radius $1$ and $|∇v(0)|=R|∇u(0)|, v(0)=u(0)$, so we need to prove $|∇v(0)| \le 2v(0)$.
Now we can do a proof using Schwarz Lemma and one using Herglotz.
Using Herglotz there is a positive finite measure $\mu(t)$ on the circle st:
$v(re^{i\theta})=\frac{1}{2\pi}\int_0^{2\pi} P(r, \theta-t)d\mu(t)$ where $P(r,\theta)=\frac{1-r^2}{1-2r\cos \theta+r^2}$ is the Poisson kernel which we also can write as $1+2\sum_{n \ge 1}r^n\cos n\theta$
But then for $z \ne 0$, $|∇v(z)|^2=v_r^2+\frac{1}{r^2}v_{\theta}^2$ and since by differentiating the Poisson kernel (using second form is easier to see as we have absolute convergence for $r<1$ so we can differentiate term by term) $\frac{1}{r}v_{\theta} \to 0$ uniformly in $\theta$ as $r \to 0$, while $v_r(re^{i\theta}) \to \frac{1}{2\pi}\int_0^{2\pi}2\cos(\theta-t)d\mu(t)$, and $|\frac{1}{2\pi}\int_0^{2\pi}2\cos(\theta-t)d\mu(t)| \le \frac{1}{2\pi}\int_0^{2\pi}2d\mu(t)=2v(0)$ it follows that for any $\epsilon >0$ there is $\delta$ s.t $|z|<\delta$ implies $|∇v(z)| \le 2v(0)+\epsilon$ and we are done by continuity.
To use Schwarz, wlog we make one more assumption, namely that $v(0)=1$ (by positivity $v(0)=c>0$ and dividing by it doesn't change anything). Then we let $f=v+iw, f(0)=1$ the analytic completion of $v$ and by C-R we have $f'(0)=v_x(0)-iv_y(0)$ so $|f'(0)|=|∇v(0)|$. But now $B=\frac{f-1}{f+1}$ is a Schwarz (in the analytic not distribution sense) function on the unit disc ($B(0)=0, |B|<1$), so $|B'(0)| \le 1$
Since $f=\frac{1+B}{1-B}, f'=\frac{2B'}{(1-B)^2}$, $f'(0)=2B'(0)$ so $|∇v(0)|=|f'(0)|\le 2=2v(0)$ and we are done again!

A: Yet another proof is via mean value property for harmonic functions. Note that $\nabla u$ is harmonic as well. Therefore, by mean value property \begin{align*} |\nabla u(0)| &= \frac{1}{\pi R^2}\left|\int_{B_R(0)} \nabla u(x)\,dx \right| \tag{1} \\&= \frac{1}{\pi R^2}\left|\int_{\partial B_R(0)} u \cdot \hat{\mathbb{n}}\,d\sigma \right| \tag{2} \\ & \le  \frac{1}{\pi R^2}\int_{\partial B_R(0)} u \,d\sigma \tag{3} \\&= \frac{2\pi R}{\pi R^2}u(0) = \frac{2}{R}u(0) \tag{4}\end{align*}
where, in lines $(1)$ and $(4)$ we used mean value property of harmonic functions, in line $(2)$ we used integration by parts and in line $(3)$ triangle inequality with the fact that $u$ is positive in ball.


text:
Q: gradient box dynamically append jquery If click on button some boxes are append. next you will click on that boxes gradient box will append but gradient boxes are not appending.its append only first box if click on another box gradient box doesn't append

My Fiddle

<button class="clbtn" name="button" value="button">button</button>

A: Gradient box appending on other div click but it's stick to first div
use this to set:
$(this).append('

').myFunction();

});

$(document).ready(function(){

var f = 0;

    $(".clbtn").click(function(el){

  $.fn.myFunction = function(){

gradX("#clrpik", {
targets: [".target"]
});
//f++;

  }

    $(".appenddiv").append('

Click Here for gradient

');

 $(".target").one('click', function(){

$(this).append('

').myFunction();

});

    });

});
.targets {
                margin:0 auto;
                text-align: center;
                border: 1px solid #ccc;
                background: #f8f8f8;
                margin: 0 auto;
                border-radius: 4px;
                width:auto;
                padding:10px;
            }

            .target_text {
                margin: 0px auto;
                margin-top: 40%;
                background: #f8f8f8;
                width: 70px;
                border: 1px solid #ddd;
                padding: 2px;
                border-radius: 2px;
                color: #111;
            }

            .target {
                border: 1px solid;
                margin: 0px 10%;
                width: 150px;
                height: 150px;
                display:inline-block;
            }
            #target {
                border-radius: 150px;
            }

            .result {
                text-align: center;
                text-transform: uppercase;
                font-weight: bold;
                padding:12px;
                padding-left: 15px;
                margin: 10px 0px;
                border: 1px solid #ddd;
                background: #f8f8f8;
            }

            .clrpik {
                height: 200px;
                margin: 100px 34%;
            }
<link href="https://cdn.office24by7.com/add-templates/colorpicker.css" rel="stylesheet"/>
<link href="https://cdn.office24by7.com/add-templates/gradX.css" rel="stylesheet"/>

<button class="clbtn" name="button" value="button">button</button>


text:
Q: Formik's forms don't recognize material UI component's text field value? I built a simple contact page using formik and material UI. Everything works except for when I use the Material UI components instead of regular input tags. It seems like the program can't read the value inside the Material UI TextField component.
This works:
                     <Field
                        name="name"
                        id="outlined-textarea"
                            label="First Name"
                            variant="outlined"
                            margin="dense"
                            component='input'
                            />
                    <ErrorMessage name="name" className="errorMsg" component="p" />

This doesn't work:
                      <Field
                        name="lastName"
                        id="outlined-textarea"
                        label="Last Name"
                        component={TextField}
                        variant="outlined"
                        margin="dense"
                    />
         <ErrorMessage name="lastName" className="errorMsg" component="p" />

I created a sandbox of the code here.

A: To hook formik properly with material ui, use render prop (instead of component) and grab the formik field which you get and pass it down to material ui Textfield
Like this
<Field
    name="lastName"
    id="outlined-textarea"
    label="Last Name"
    render={({ field }) => <TextField {...field} />}
    variant="outlined"
    margin="dense"
  />


text:
Q: RXJS subscribe method not working when invoked from HTML Page I'm trying to invoke a observable from the HTML page but it doesn't work. The method works as intended when angular invokes it and displays an output. But when I try to invoke it via a button, it doesn't work.

Service

deltasHistory = this.socket.fromEvent<any[]>('deltasHistory');

Component

constructor(private codeeditorservice: CodeeditorService){}
ngOnInit() {
this.deltaHistory$.subscribe(delta => {
      console.log(delta[30]); // Works perfectly
    })
}

Now this invoke() is initiated by <button (click)="invoke()">Button</button> but it displays nothing.

Button inside the Component's HTML

  invoke(){
    console.log("invoking") // displays
    this.deltaHistory$.subscribe(delta => {
      console.log(delta[30]);
}) //nothing
  }

How do I fix the scope issue?

A: You will want to update your service deltaHistory to return the last given result. You can do this by utilizing the shareReplay operator from rxjs:
deltasHistory = this.socket.fromEvent<any[]>('deltasHistory').pipe(
  shareReplay(1)
);

Now any subscriptions done after the last emit, will get the last emitted value


text:
Q: What does Maxwell's equations predict for the propagation of EM waves converging to a point? Maxwell's equations model EM radiation as propagating away from an accelerating charge. Suppose instead the propagation of this EM radiation is reversed and presented as a source-free boundary condition so that it converges upon a source-less point: How would Maxwell's equations model this?
In particular: would the EM fields converge and then propagate away from the point, or would the temporary EM singularity at the point invalidate modelling after this time?

A: Nice question.
The answer I think is that you have to compare like with like.
Let's take field propagating from the accelerated charge at the origin. Once the field is in the vacuum, the Maxwell's equations are time-reversible, so you could simply 'play the video backwards' and see the waves converging into a point. BUT, once the waves get to the origin, in your video playback, there must be a charge there. If there is one, good, the charge will simply absorb the power (where would the power go? no-where. you did not specify how you made the charge move in the first place - that is the fudge-factor).
What if there is no-charge at the origin? What if you built a spherical distribution of antennas aiming to launch the field back into the origin with the same distribution as that from an accelerated charge, but there is no charge there? My intuition tells me that this would not be possible, i.e. you would find it impossible to launch just that field and nothing else. Because that field would not be a solution to Maxwell's equations.
To go any further, I think you need to specify more precisely what field would you launch.


text:
Q: How to change the image in the tabbar without going to that viewcontroller? I have an IPhone application in which i am using the custom images for the tabbar.when selecting the tabbar i have to show one image and unselecting showing the another.I have successfully implemented that by using the bellow code in the appdelegate.
`
 UIImage *selectedImage0 = [UIImage imageNamed:@"pinboard_hvr2.png"];
    UIImage *unselectedImage0 = [UIImage imageNamed:@"pinboard2.png"];

    UIImage *selectedImage2 = [UIImage imageNamed:@"scan_hvr2.png"];
    UIImage *unselectedImage2 = [UIImage imageNamed:@"scan2.png"];

    UIImage *selectedImage3 = [UIImage imageNamed:@"places_hvr2.png"];
    UIImage *unselectedImage3 = [UIImage imageNamed:@"places2.png"];

    UITabBar *tabBar = self.tabBarController.tabBar;
    tabBar.TintColor = [UIColor clearColor];
    UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
    UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
    UITabBarItem *item2 = [tabBar.items objectAtIndex:2];

    [item0 setFinishedSelectedImage:selectedImage0 withFinishedUnselectedImage:unselectedImage0];
    [item1 setFinishedSelectedImage:selectedImage2 withFinishedUnselectedImage:unselectedImage2];
    [item2 setFinishedSelectedImage:selectedImage3 withFinishedUnselectedImage:unselectedImage3];

`but now the problem with me is i have a tutorial view in the secondindex.when clicking on that button i need each of my tabbar icons to be changed according to the explanation in the tutorial.but I dnt need to gothere.I want to stay at the tutorial view itself.but need to change the icons .can anybody help me in achieving that?

A: finally i have sorted out the problem.actually its a simple thing.set your selected and deselected image according to the tutorial button actions.For example if you have 3 buttons there to show each tabs significance set the selected image of the appdelegate.tabbar according to the view like this.`
TabNavAppDelegate *appdelegate = ( TabNavAppDelegate *)[[UIApplication sharedApplication] delegate];

    UIImage *unselectedImage0 = [UIImage imageNamed:@"pinboard_hvr2.png"];
    UIImage *unselectedImage2 = [UIImage imageNamed:@"scan2.png"];

    UIImage *selectedImage3 = [UIImage imageNamed:@"places2.png"];
    UITabBar *tabBar = appdelegate.tabBarController.tabBar;
    tabBar.TintColor = [UIColor clearColor];
    UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
    UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
    UITabBarItem *item2 = [tabBar.items objectAtIndex:2];

    [item0 setFinishedSelectedImage:unselectedImage0 withFinishedUnselectedImage:unselectedImage0];
    [item1 setFinishedSelectedImage:unselectedImage2 withFinishedUnselectedImage:unselectedImage2];
    [item2 setFinishedSelectedImage:selectedImage3 withFinishedUnselectedImage:selectedImage3];

`and in the third button action set it back to normal way as it done in the appdelegate.

A: Send a notification to AppDelegate or call a delegate method. In that method you can also pass your parameters if required and do the specific tab changes over there.
Hope this will work for you.


text:
Q: Like a Facebook Wall Post - Javascript I'm developing a Facebook application that retrieves specific facebook wall posts. I simply want to allow the user to "like" the post from within my application using the javascript sdk.  Anyone know how to accomplish this?

A: UPDATE:
Issuing a POST request to the likes connection of the post object is all you need:

You can like a Post by issuing a HTTP POST request to the
  POST_ID/likes connection with the publish_stream permission. No
  parameters necessary.

Example:
FB.api("/POST_ID/likes", 'post',function(response) {
    if(response === true) {
        alert("done!");
    }
});

The above request should return true on success.


text:
Q: find pattern in string Find the pattern "[Number1, Number2]" in any given string and get the integer (32bit) values for Number1 and Number2:
Example Input: "Foo Bar [45,66] Bash"
Example Result:
Number1 = 45
Number2 = 66
I have this example in my deitel book and I can't seem to get the Regex Exp. syntax correct. Can anyone help me out?

A: This should work for your exact case of [number,number]:
var match = Regex.Match(input, @"\[(\d+),(\d+)\]");

var first = match.Groups[1].Value;
var second = match.Groups[2].Value;

var result = string.Format("Number1={0} Number2={1}", first, second);

Tested a myregextester.com.

A: Regular expressions... they're so helpful now.  Before the standard however, programmers didn't have the luxury of asking for community support on StackOverflow.  In fact... many programmers encountered "stack overflows" while trying to perform a simple string search back in the day.
If you want to find a string with in a string and you don't have the ability to use regular expressions you have to search through the string for the expression in a very specific way.  A string is a null terminated array of characters.  That construct is implemented with the string class, but under the hood it's a character array with a null value in the final position.
Assume you had the following string:
string arrayOfCharactersToSearch = "This is the null terminated array of characters to search.";

Now assume you wanted to search for "array" with in that string.  You would have to examine "chunks" of the characters in the string.  But you couldn't do that by just moving one character at a time and then looking for "array" because it would be inefficient.  You also can't do it by looking at chunks that are the same length as "array" because it might miss a combination of characters.
The solution is to advance each "chunk" by the length of the search criteria, in this case "array", divided by two, plus one:
    *chunk = ( string length / 2 ) + 1*

Fortunately, we have regular expressions now and all that BS is done for us under the hood, but it's still important to understand how it works... right??


text:
Q: How to deploy only part of a multi module maven project? I have a multi-module maven project, and would like to deploy only 2 sub modules:
pom.xml // parent pom
module1
--pom.xml
module2
--pom.xml
module3
--pom.xml

only module1.jar and module2.jar should be deployed.

A: I have found the solution in the following question:
How to Deploy only the sub-modules using maven deploy?
The following property should be added to the pom.xml set to false for the modules that should not be deployed:
 <properties>
     <maven.deploy.skip>true<maven.deploy.skip>
 <properties>

A: From my personal experience, we had a multi maven project. Where many modules was features that some clients had it and some other clients dint had them. For example when we build for 'clientA' we wanted Jenkins to package 'module1', 'module2' and 'module3' but when we build for 'clientB' we wanted only to package 'module1' and 'module2' to just give him the base functionality.
So, its not absolutely wrong to deploy/release part of a multi module project. In the above example there are a case where you need to build some of the modules and a case where you want to build all the modules. In those cases you can do that with profiles.
Example: in parent pom.xml
    <profiles>
        <profile>
            <id>base-functionality</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <modules>
                <module>/module1</module>
                <module>/module2</module>
            </modules>
        </profile>
        <profile>
            <id>new-feature</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <modules>
                <module>/module3</module>
            </modules>
        </profile>
    </profiles>

and then on Jenkins job for "clientA":
clean package -Pbase-functionality,new-feature

where on Jenkins job for 'clientB':
clean package -Pbase-functionality

Note: as khmarbaise stated on comment below this approach has same pitfalls and should be avoided if possible.


text:
Q: How to delete some strings with non-English letters? I am new to regular expressions and Python. For example, my string list is:
my_try = ['Aas','1Aasdf','cc)','ASD','.ASD','aaaa1','A']

Now, I want to delete all the strings with non-English letters. So, I just want to keep:
['Aas','ASD','A']

I do not know how to use ^ or something else to do this?
And, if my data is:
my_try=pd.DataFrame({'try':
                         ['Aas','1Aasdf','cc)','A2SD','.ASD',
                          'aaaa1','A','123%']})

Then I use:
[x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]

Why do I have such error:
Traceback (most recent call last):
  File "C:\feng\myCode\infoExtract\venv\lib\site-packages\IPython    \core\interactiveshell.py", line 3319, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-58-4bd95f31bd0c>", line 1, in <module>
    [x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
  File "<ipython-input-58-4bd95f31bd0c>", line 1, in <listcomp>
    [x for x in my_try if re.match(r'^[a-zA-Z]+$', x['try'])]
 TypeError: string indices must be integers

How can I fix this and why does it happen?

A: You have a list and want to filter it to only contain elements that match some condition, list comprehensions with an if are perfect for that:
my_list = [1, 2, 3, 4, 5, 6]
# just even numbers:
print([x for x in my_list if x % 2 == 0])

And you want to filter for anything that consists of only letters 'a' through 'z' and 'A' through 'Z', which is where a regex is easy to use:
my_try = ['Aas','1Aasdf','cc)','ASD','.ASD','aaaa1','A']
print([x for x in my_try if re.match('^[a-zA-Z]+$', x)])

The regex starts with ^ and ends in $ to tell re.match() that it should match the entire string, from start to end. [a-zA-Z] defines a character class containing the letters you're after. Often you'd use \w but that also includes numbers. And finally, the + means there needs to be 1 or more of the characters in the string (as opposed to 0 or more if you use *)


text:
Q: Flash: automatic/infinite/horizontal slider What I want to do is actually quite simple :p
I have a couple of (let's say 10) pictures (photographs actually) that should automatically scroll from right to left in a 500x500px container. In an infinite loop. So all the pics are horizontally next to each other, each 500px of height, variable width.
That's not all unfortunately... Some pictures need to be animated, i.e. a simple sequence of like 2-3 pictures.
That means we now have pictures and animations sliding through a 500x500 frame from right to left. The animations should simply switch pictures every ~1-2 seconds, which should be easy with Flash.
Unfortunately I'm a complete newbie when it comes to Flash.
Could someone please help me out here? Maybe a tutorial or even a smallish example .fla?
Thanks so much in advance!
(Oh my Flash version is CS5)

A: The best solution would be to do this programmatically, but as you are "a complete newbie", you are probably better off using the timeline for now.
Here is how you might like to approach it:

*

*import all your images to the library

*create a graphic for each image

*create a movieclip from each graphic which is not part of an animation

*create one movieclip, to hold the animated images, for each animated set, putting the images ontop of each other on separate layers and tween the alpha of them over time, revealling the next image below.

*create another movieclip and place all the previously created movieclips next to each other within it

*create one more movieclip and place two instances of the above movieclip alongside each other

*add this final movieclip to the stage and tween from right to left making sure that the
final frame of the tween looks the same as the first frame.


text:
Q: Appending values in sub-arrays of an array in python The goal here is to construct the one-particle distribution function of a system evolving under Brownian dynamics; one has to produce a random number drawn from a Gaussian distribution. To construct this quantity, I am thinking of running several simulations, and for specific times in each of the simulations, save the distances of each particle from the center of the 2D square and only in the end, create a histogram of all the values.
My problem is that during each of the simulations, time begins from zero and goes on with a certain time-step, for each of which the particles move randomly. So, the distances to be saved have to be labeled correctly for their corresponding times.
So, my thought was to create an array that will have in each row, 5 sub-arrays, one for each time I want to save the distances of the particles from the center of the square. I am trying to work this with numpy, but with no success. For each simulation, and for specific times, I create an array with all the distances, and I try to append it with numpy.append to the specific subarray, but this doesn't work correctly; as I understand the problem lies in the fact that I don't know how to index properly( and for all the simulations) the sub-arrays.
Beyond that, I think that the approach is not the best: either I will have to abandon the idea of using numpy and figure out how I can index with two indices the array properly, or figure out a way to use numpy more effectively.
So, to the point, the general question here is how I could add/append values to specific sub-arrays of an array ( either pre-constructed with numpy or not and treated as a list).
The alternative would be for someone to mention a more efficient way of creating the one-particle distribution function of a Brownian motion problem, which would be really helpful.
I am adding the relevant code below. Thank you all in advance.
Code:
    import random
    import math
    import matplotlib.pyplot as plt
    import numpy as np

    # def dump(particles,step,n):
    #   fileoutput = open('coord.txt', 'a')
    #   fileoutput.write("ITEM: TIMESTEP \n")
    #   fileoutput.write("%i \n" % step)
    #   fileoutput.write("ITEM: NUMBER OF ATOMS \n")
    #   fileoutput.write("%i \n" % n)
    #   fileoutput.write("ITEM: BOX BOUNDS \n")
    #   fileoutput.write("%e %e xlo xhi \n" % (0.0, 100))
    #   fileoutput.write("%e %e xlo xhi \n" % (0.0, 100))
    #   fileoutput.write("%e %e xlo xhi \n" % (-0.25, 0.25))
    #   fileoutput.write("ITEM: ATOMS id type x y z \n")
    #   i = 0
    #   while i < n:
    #       x = particles[i][0]
    #       y = particles[i][1]
    #       #fileoutput.write("%i %i %f %f %f \n" % (i, 1, x*1e10, y*1e10, z*1e10))
    #       fileoutput.write("%i %i %f %f %f \n" % (i, 1, x, y, 0))
    #       i += 1

    #   fileoutput.close()

    num_sims = 2
    N = 49
    L = 10
    meanz = 0
    varz = 1
    sigma = 1
    # tau = sigma**2*ksi/(kT)

    # Starting time
    t_0 = 0

    # Time increments
    dt = 10**(-4)  # dt/tau

    # Ending time
    T = 10**2  # T/tau

    # Produce random particles and avoid overlap:

    particles = np.full((N, 2), L/2)
    times = np.arange(t_0, T, dt)

    check = 0
    distances = np.empty([50*num_sims, 5])

    for sim in range(0, num_sims):
        step = 0
        t_index = 0
        for t in times:
            r=[]
            for i in range(0,N):
                z = np.random.normal(meanz, varz)
                particles[i][0] = particles[i][0] + ((2*dt*sigma**2)**(1/2))*z
                z = random.gauss(meanz, varz)
                particles[i][1] = particles[i][1] + ((2*dt*sigma**2)**(1/2))*z

            if (t%(2*(10**5)*dt) == 0):
                for j in range (0,N):
                    rj = ((particles[j][0]-L/2)**2 + (particles[j][1]-L/2)**2)**(1/2)
                    r.append(rj)
                distances[t_index] = np.append(distances[t_index],r)
                t_index += 1


text:
Q: why is SwiftUI modal view updating parent variable here (code attached) In the code below if I change the value of the TextField and then click "Cancel" (i.e. will not then do a coredata save), after this modal view is hidden the value is changed in the parents UI list?
Is this line effectively passing my ref?  If yes how to change to be effectively by value?
UPDATE:  Actually it appears the code in the Save button is getting call directly after the Code in the cancel button, that is in the case I'm clickon on Cancel.  Not sure why this would be occurring?
Code:
import SwiftUI

struct GCListsViewEdit: View {
    @Environment (\.presentationMode) var presentationMode
    @State var titleStr : String = ""
    var gcItem : GCList?

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Enter Details")) {
                    TextField("List Title", text: self.$titleStr)
                        .onAppear {
                            self.titleStr = self.gcItem?.title ?? ""  // ** HERE **
                        }
                }
                HStack {
                    Button("Cancel") {
                        self.presentationMode.wrappedValue.dismiss()
                    }
                    Spacer()
                    Button("Save") {
                        guard !self.titleStr.isEmpty else {
                            return
                        }
                        guard let item = self.gcItem else {
                            return
                        }
                        item.title = self.titleStr
                        GCCoreData.save()
                        self.presentationMode.wrappedValue.dismiss()
                    }
                }
            }
            .navigationBarTitle("Edit List")
        }
    }
}

PARENT - just the body part
var body : some View {
    NavigationView {
        VStack {

            // -- Main List  --
            List() {
                ForEach(gcLists) { gcList in
                    HStack {
                        if self.editMode {
                            Button(action: {}) {
                              Text("\(gcList.title)")
                            }
                            .onTapGesture {
                                self.selectedListViewItem = gcList
                                self.newListItemTitle = gcList.title
                                self.showEditView.toggle()
                            }
                            .sheet(isPresented: self.$showEditView, content: {
                                GCListsViewEdit(gcItem: self.selectedListViewItem!)
                            })
                        } else {
                            NavigationLink(destination: GCTasksView(withGcList: gcList)) {
                                Text("\(gcList.title)")
                            }
                        }
                    }
                }
                .onDelete(perform: self.deleteList)
                .onMove(perform: self.move)

            }
            .environment(\.editMode, editMode ? .constant(.active) : .constant(.inactive))
            .alert(isPresented: $showingAlert) {
                Alert(
                    title: Text(verbatim: "Important Message"),
                    message: Text(self.alertString),
                    dismissButton: Alert.Button.default(Text(verbatim: "Cancel"))
                )
            }
            .navigationBarTitle( Text("Todo Lists") )
            .navigationBarItems(
                trailing: Button(action: {
                    print("Edit" as Any)
                    self.editMode = !self.editMode
                } ) {
                    Text(editMode ? "Done" : "Edit")
                }
            )

            // -- Add List Item ---selectedListViewItem
            Button("Add List") {
                self.newListItemTitle = ""
                self.showAddView.toggle()
            }
            .sheet(isPresented: $showAddView, content: { GCListsViewAdd() } )

        }
    }
}

A: Form is kind of List and List has specific handling of standard buttons in a row - it makes active entire row, so when row tapped in any place a button (or buttons) got activated.
In your example even if you tap in between Cancel and Save, both action are executed.
There are several possible solutions:
1) use tap gestures (keeping buttons or replacing them with other views, Text, Image, etc.), like

HStack {
    Button("Cancel") {}
    .onTapGesture {
        print(">> do cancel")
    }
    Spacer()
    Button("Save") {}
    .onTapGesture {
        print(">> do save")
    }
}

2) use custom button style, because List intercepts only DefaultButtonStyle buttons
struct CustomButton: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .foregroundColor(configuration.isPressed ? Color.gray : Color.blue)
        }
}

HStack {
    Button("Cancel") {
        print(">> do cancel")
    }.buttonStyle(CustomButton())
    Spacer()
    Button("Save") {
        print(">> do save")
    }.buttonStyle(CustomButton())
}

3) move buttons out of Form for this screen (eg. in NavigationBar)


text:
Q: Microsoft Exchange Server support in my iOS app I want to read calendar events in my app from on-premise Exchange server. For exchange online, Office 365, I could use Microsoft's SDK for iOS. I want to know

*

*Is there any SDK from Microsoft to support on-prem exchange server in iOS app

*Is there any extension/plug in that enables my app to read calendar events from exchange server

*Is there framework/service offered by Apple that can be used in custom apps to read calendar events?

Any link/info would be greatly appreciated.

A: As written in the comment. I personally would never ever enter my Exchange password in a strange app, which then access my Exchange mailbox (which also would explain the downvote). The app would then be able to write emails, read all emails ... means access everything in my mailbox.
So I think the best way to access the calendar in your app would be that your app access the user's Calendar database using the EKEventStore class. However this has some limitations so normally not the whole calendar is visible here and most users sync only a subset. But for most apps this might be enough.
Via this approach your app also becomes more "universal" and can also work with WebDAV/CalDav calendars (e.g. Shared Calendars like google calendar).
Additional via that way you do not need to deal with:

*

*bad network connections

*Different authentication methods (e.g. two factor authentication)

*SSL encryption (cipher vs. protocols vs. ...)


text:
Q: iPad UI design options I have an app that main layout is a custom top bar (with actions similar to a web browser, back, forward, etc.), a left main menu and a center view where all the information is displayed.
So at first I think of this app as a Master-Detail one but the top bar and the navigation options seems to prevent this option.
Then I remember the view controllers containment option. Basically I will try to build the root view controller with a view representing the top bar, a table view as the main menu and in the central view add the child view controllers. This option also allows me to build view controllers with similar layout (left menu and center display view).
The truth is that I'm not 100% sure that this is the better option, so I'm asking here if anyone has experience with something like this and if you think this is the best option to build this kind of layout.
Cheers!
EDIT1: Here is an image that represent the layout. In the content view there could be other views similar to a Master-Detail view.

A: I would create it like this:
Start with a UINavigationController.
This will allow you to use the UINavigationBar at the top in order to get your Top Menu Bar.
Then, create a custom UIViewController which contains a UITableView and a UIView (not controllers) and push it onto the navigation stack.  This allows you to control both views from the same controller, making interaction between them trivial.
On the other hand, if you need to swap out the right or left views a lot and want them to be "stand-alone" then you will be better off using view controller containment as you initially thought.  This is slightly more involved, but the UIView class reference has very good documentation on how to accomplish this.


text:
Q: How do I declare global variables in Pact lang? I'm writing a smart contract and I want to declare global variables. I want the functions in my smart contract to be able to access and update these variables.
For example, in Solidity I can do this as follows:
pragma solidity ^0.5.0;
contract SolidityTest {
   uint someSmartContractVar;      // State variable
   constructor() public {
      someSmartContractVar = 10;   // Setting the variable
   }

   ...

}

I see the coin contract makes use of defconst here:
  (defconst COIN_CHARSET CHARSET_LATIN1
    "The default coin contract character set")

This approach is good for variables that need to be accessible by the rest of the contract, but I don't think I can change the values of these variables at some later point.
One possibility is creating a table named "global-variables" and storing the specific variables there. So then the functions can access and change these variables via table reads and updates. For example:
  (defschema global-variable-schema
    someSmartContractVar:decimal)

  (deftable global-variables:{global-variable-schema})

  (defconst GLOBAL_VAR_KEYNAME "global-vars")

  (defun constructor:string ()
    (insert global-variables GLOBAL_VAR_KEYNAME
          { 'someSmartContractVar: 10.0 }
    )
    "Global variables set"
  )

  (defun get-someSmartContractVar:decimal ()
    (at "someSmartContractVar" (read global-variables GLOBAL_VAR_KEYNAME))
  )

Is this the recommended approach for this type of use case?

A: Great question and that solution should work!
I don't know of any other practical way to do it.


text:
Q: const commandFolders = readdirSync('./commands'); ReferenceError: Cannot access 'readdirSync' before initialization at Object. error I got this error today trying to change a little bit of my command handler from an youtube video.The video is from april and it seems to work for the guy but for me it doesnt.I tried many things but i didnt get any clue.Im not pretty good with this but i want to have an start like many others and this comunity is so good an helps me so much, thank you so much for the support you offer to me!!I hope i will get past this problem.

const Timeout = new Discord.Collection();

const bot = new Discord.Client();

const prefix = '$';

bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');

const ms = require('ms');

const {readdirSync , read} = require('fs');

for(const folder of commandsFolders){
    const commandFiles  = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
    for(const file of commandFiles){
        const command = require(`./commands/${folder}/${files}`);
        bot.commands.set(command.name, command);
    }
}

bot.on("error" , console.error);

bot.once('ready' , () => {
    console.log('M-am trezit din morti!');
});

bot.on("message" , async (message) =>{
     if(message.author.bot) return;
     if(message.channel.type === 'dm') return;

     if(message.content.startsWith(prefix)){
         const args = message.content.slice(prefix.length).trim().split(/ +/);

         const commandName = args.shift().toLowerCase();

         const command = bot.command.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
         if(!command) return;

         if (command) {
             if(command.cooldown){
                 if(Timeout.has(`${command.name}${message.author.id}`)) return  message.channel.send(`Te rog asteapta! \`${ms(Timeout.get (`${command.name}${message.author.id}`) - Date.now(), {long: true})}\`Pana folosesti comanda din nou!`);
                 command.run(bot, message, args)
                 Timeout.set(`${command.name}${message.author.id}` , Date.now() + command.cooldown)
                 setTimeout(() =>{
                     Timeout.delete(`${coomand.name}${message.author.id}`)
                 }, command.cooldown)
             } else command.run(bot, message, args);
         }
     }
})

A: So what you did wrong is, that you want to use readdirSync before you included the fs library in your code. Just move the require statement over the readdirSync and it should work:
const bot = new Discord.Client();

const prefix = '$';

const {readdirSync , read} = require('fs');

bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');

const ms = require('ms');

for(const folder of commandsFolders){
    const commandFiles  = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
    for(const file of commandFiles){
        const command = require(`./commands/${folder}/${files}`);
        bot.commands.set(command.name, command);
    }
}

bot.on("error" , console.error);

bot.once('ready' , () => {
    console.log('M-am trezit din morti!');
});

bot.on("message" , async (message) =>{
    if(message.author.bot) return;
    if(message.channel.type === 'dm') return;

    if(message.content.startsWith(prefix)){
        const args = message.content.slice(prefix.length).trim().split(/ +/);

        const commandName = args.shift().toLowerCase();

        const command = bot.command.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
         if(!command) return;

         if (command) {
             if(command.cooldown){
                 if(Timeout.has(`${command.name}${message.author.id}`)) return  message.channel.send(`Te rog asteapta! \`${ms(Timeout.get (`${command.name}${message.author.id}`) - Date.now(), {long: true})}\`Pana folosesti comanda din nou!`);
                 command.run(bot, message, args)
                 Timeout.set(`${command.name}${message.author.id}` , Date.now() + command.cooldown)
                 setTimeout(() =>{
                     Timeout.delete(`${coomand.name}${message.author.id}`)
                 }, command.cooldown)
             } else command.run(bot, message, args);
         }
     }
})


text:
Q: Reading serial port using cat gets me nothing, but screen works? I'm trying to read a serial port using cat, but I get absolutely nothing, using
cat /dev/tty.usbserial-FTZ29YKM

I'm assuming that even if the baudrate is wrong, I should at least get some garbage data.  However, it works if I try to open a screen session with:
screen /dev/tty.usbserial-FTZ29YKM 115200

I want to use another utility to simultaneously write to the serial port, so I can't just use screen.  How would I make cat, or some similar utility, work?


text:
Q: Join more than 2 tables ( n Number files ) files with awk tab delimited Hi I have more than 10 files ( Only two columns ) and i want to join them with row names,
file1
a   3
b   4
c   6

file2
c   7
b   33
f   56

file3
d   4
e   9
f   44
a   99

Output
    file1   file2   file3
a   3   0   99
b   4   33  0
c   6   7   0
e   0   0   9
d   0   0   4
f   0   56  44

below link answers perfect to my requirement, but it works only for two files
Join multiple tables by row names
How do i do same for multiple (n)  files. New to shell commands

A: With GNU awk for arrays of arrays and sorted_in:
$ cat tst.awk
BEGIN { OFS="\t" }
{ vals[$1][ARGIND] = $2 }
END {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    printf "%s", OFS
    for (fileNr=1; fileNr<=ARGIND; fileNr++) {
        printf "%s%s", ARGV[fileNr], (fileNr<ARGIND ? OFS : ORS)
    }
    for (key in vals) {
        printf "%s%s", key, OFS
        for (fileNr=1; fileNr<=ARGIND; fileNr++) {
            printf "%s%s", vals[key][fileNr]+0, (fileNr<ARGIND ? OFS : ORS)
        }
    }
}

$ awk -f tst.awk file1 file2 file3
        file1   file2   file3
a       3       0       99
b       4       33      0
c       6       7       0
d       0       0       4
e       0       0       9
f       0       56      44

A: For the case that the input files are not sorted, explicit sort is needed. Using process substitution keep solution simple
#! /bin/sh

# Helper function - join with required parameters
function j {
    join -a1 -a2 -oauto -e0 "$@"
}

echo "file1" "file2" "file3"
j <(sort file1) <(sort file2) | j - <(sort file3)

Output:
file1 file2 file3
a 3 0 99
b 4 33 0
c 6 7 0
d 0 0 4
e 0 0 9
f 0 56 44

Or with column -t:
echo "key" "file1" "file2" "file3"
j <(sort file1) <(sort file2) | j - <(sort file3) | column -t

key  file1  file2  file3
a    3      0      99
b    4      33     0
c    6      7      0
d    0      0      4
e    0      0      9
f    0      56     44


text:
Q: Wait for EOF when using stdin So I am working on something that requires me to let the user type as much as they want in the command window, including new lines, and then after they press CTRL+D (EOF character) I should be able to print out everything that has been typed.
I am able to figure out how to do it every new line.
#include <stdio.h>

int main()
{
  int C;

  C = getc(stdin);

  while(C != EOF)
  {
    putc(C, stdout);
    C = getc(stdin);
  }

  return 0;
}

I can also only use getc and putc. Eventually I want to let the user type as much as they want and then depending on flags they send with the command I will modify the input they give me using getopt.
EDIT: Sorry forgot to add my question. What I want to be able to do is wait for the user to enter all their input and then print it all back out, not line by line. How would I go about doing this.

A: You are going to need some way to buffer the user's input (because they might type out a whole novel before hitting Ctrl+D).
Here's an example of how you might do it (note that reading character-by-character is very slow, and using printf won't handle embedded NULs so you may want to use read and write instead in "real" code):
size_t bufsize = 1024; // starting size
char *buf = malloc(bufsize);
off_t i = 0;
char c;

while((c = getc(stdin)) != EOF) {
    buf[i++] = c;
    if(i == bufsize) {
        bufsize *= 2; // double buffer size to avoid constant reallocation
        buf = realloc(buf, bufsize);
        if(!buf) {
            fprintf(stderr, "YOU TYPED TOO MUCH\n");
            exit(-1);
        }
    }
}

buf[i++] = 0;
printf("%s", buf);

A: Have you looked at using termios? (termios.h) you can set stdin to non canonical and non echo mode which will let you catch every single key pressed, including control characters
http://www.gnu.org/software/libc/manual/html_node/Noncanon-Example.html


text:
Q: Getting rabbitmq weird queues Listing the queues for the virtualhost gives very strange results:
rabbitmqctl list_queues -p rabbitmqvhost | head
Listing queues ...
0842e72ea3c84379b93d2efc21e4d245        1
aec06fbdc10545e8891c4cc2c8c71939        1
f6763cdbee9d47659bc4b662b6f8e90a        1
1776868c0cbb47ee8c08ebf421d624c7        1
5cabd24bb55348e18a8c9cdb5794e17c        1
9248e8c5502a4f608f6f4766fc91b0df        1
32d8c6ba0e7644eba7c6d6c3915db55f        1
aa6e8ddac7dc496d99107e539aee150b        1
09616cffdb1b4f25a1a3548532b0589f        1

There are a lot of these queues: around 20-30k. The amount is constantly growing.
Any advice why this happens?

A: AMQP backend creates a queue for each task


text:
Q: Как запретить дочернему элементу выходить за границы родителя? Здравствуйте. Делаю мини чатик, но есть проблема. Если сообщение длинное и без переносов через enter то блок с текстом вылазит за пределы контейнера для сообщений. Как можно решить эту проблему? Спасибо.

A: Например с помощью word-wrap: break-word;

.box {
  width: 400px;
  background: lightblue;
  padding: 10px;

  word-wrap: break-word;
}

  lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

P.S: Вариант 2 для конкретно вашего примера с display: inline-flex;

.divStyles {
  padding: 5px;
  display: inline-flex;
  word-break: break-word; /* doesn't work in firefox */
  word-wrap: break-word;
  white-space: normal;
  max-width: 350px;
  max-height: 200px;

  background: green;
}

  testttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt

A: можно использовать word-break

.chat {
background:#f4f4f4;
border-radius:3px;
border:1px solid #666;
color:#666;
padding:10px;
font-family:sans-serif;
}
.message {

background:#00AAFF;
border-radius:3px;
border:1px solid #005B88;
color:#005B88;
word-break:break-word;
box-sizing:border-box;

padding:10px;
}

texttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttextv


text:
Q: libpq library in centos I'm using Centos 7 and I have a challenge find a postgresql library called libpq. I have it installed but when I run 'pkg-config libpq --cflags --libs' I get 'No package 'libpq' found'.
when I run 'rpm -qa | grep libpq' I get this here:
libpqxx-devel-5.0.1-2.rhel7.x86_64
libpqxx-5.0.1-2.rhel7.x86_64.
What could be the issue here. Thanks in advance!

A: I got it working by assigning the path to the libpq library an environment variable like this:
export PKG_CONFIG_PATH=/usr/pgsql-10/lib/pkgconfig
This command will help find the correct path to the library  'locate libpq.pc'.


text:
Q: Create a timer within a spark context We have a spark application that streams from Kafka, and consume customer activity. I am trying to determine if a customer has stopped being active on our system for 3 minutes, (i.e. not received another transaction for this customer for 3 minutes).
I'm not sure if I am trying to implement this the right way, or if it doesn't make sense to have this logic in Spark, but I am trying to use the RecurringTimer class to do this. Has anybody implemented something similar, and if so what utility function was used in the spark libraries?
Any example, pointers etc. would also be greatly appreciated

A: Have a look at mapWithState, basically you would aggregate into a key/value pair consisting of some identifier for the customer and the timestamp of the last transaction received.
Each micro batch after performing this aggregation, you can check and see if there is any user in there that has a timestamp < now() - 3min and do something (i.e. push a message into another kafka queue etc)
A sample on mapWithState is available here


text:
Q: How many ways are for creating a new thread in Java? Actually, what other ways are available apart from extending the Thread class and implementing the Runnable interface?

A: Or you can create a Callable which is an interface which is similar to Runnable except that it defines a method call that can return a value. To instantiante a Callable, you can pass it to an executor. You can find a full explanation of multithreading and callable examples here

A: There is exactly one way to create a new thread in Java and that is to instantiate java.lang.Thread (to actually run that thread you also need to call start()).
Everything else that creates threads in Java code falls back to this one way behind the cover (e.g. a ThreadFactory implementation will instantiate Thread objects at some point,  ...).
There are two different ways to specify which code to run in that Thread:

*

*Implement the interface java.lang.Runnable and pass an instance of the class implementing it to the Thread constructor.

*Extend Thread itself and override its run() method.

The first approach (implementing Runnable) is usually considered the more correct approach  because you don't usually create a new "kind" of Thread, but simply want to run some code (i.e. a Runnable) in a dedicated thread.

A: The preferred way of starting threads in Java 6 is using Executors:
    ExecutorService es = Executors.newCachedThreadPool();
    Runnable r = <your runnable here>;
    es.execute(r);

A: There are actually total 4 ways to create thread in java :

*

*By extending java.lang.Thread class

*By implementing java.lang.Runnable interface

*By using anonymous inner class

*By implementing Callable interface.

A: Threads can be created mainly in 3 different ways

*

*Extend the java.lang.Thread class'

class SampleThread extends Thread {

    //method where the thread execution will start
    public void run(){
        //logic to execute in a thread
    }

    //let's see how to start the threads
    public static void main(String[] args){
       Thread t1 = new SampleThread();
       Thread t2 = new SampleThread();
       t1.start();  //start the first thread. This calls the run() method.
       t2.start(); //this starts the 2nd thread. This calls the run() method.
    }
}

*Implement the java.lang.Runnable interface

class A implements Runnable{

    @Override
    public void run() {

        // implement run method here
    }

    public static void main() {
        final A obj = new A();

        Thread t1 = new Thread(new A());

        t1.start();
    }

}

*Implement the java.util.concurrent.Callable interface

class Counter implements Callable {

    private static final int THREAD_POOL_SIZE = 2;

    // method where the thread execution takes place
    public String call() {
        return Thread.currentThread().getName() + " executing ...";
    }

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        // create a pool of 2 threads
        ExecutorService executor = Executors
                .newFixedThreadPool(THREAD_POOL_SIZE);

        Future future1 = executor.submit(new Counter());
        Future future2 = executor.submit(new Counter());

        System.out.println(Thread.currentThread().getName() + " executing ...");

        //asynchronously get from the worker threads
        System.out.println(future1.get());
        System.out.println(future2.get());

    }
}

Favor Callable interface with the Executor framework for thread pooling.
The Runnable or Callable interface is preferred over extending the Thread class

A: There are only Two ways for creating a Thread already you have mentioned but a third way is there to invoke the Thread.
In java1.5 there is another way to invoke a thread. That is by "ExecutorService". All these classes are from the "java.util.concurrent" package. There are various ways to create a "ExecutorService" using "Executors" factory class. The following is one of the way to create "ExecutorService"..
ExecutorService es= Executors.newSingleThreadExecutor();
RunnableImpl r = new RunnableImpl();
Future fu=es.submit(r);
Using "ExecutorService" methods we can submit eighter Runnable or Callable to the service for execution.
How ever this cannot be said as the new way to create a Thread. It is because ExecutorService internally uses "ThreadFactory" class to create a new thread which internally uses eighter first or second method. So we have to say that there are only two ways to create threads but there is a new way in java1.5 to invoke a thread but not to create a Thread.

A: for creating a thread there is only one way in java
ie. Thread class start()  method but there are different ways to run the thread
by using different ways
like 1.Thread
     2.Runnable
     3.RunnableFeature
     4.Callable
     5.ERxecutorService...etc


text:
Q: How to append or add multiple items to an array in Swift 4 Here is what I want to archive:
I have a couple of names, let's say it 100 names. These names are listed in a text file or an excel file. I would like to add those names to an array, when I tap a button.
var namesPool: [String] = []

But I have no ideas how to get it work. Any suggestions would be appreciated.

A: The first step is to read the text from your file. There is a good example on how to do this here: Read and write data from text file
The second step is to convert the output String to an array. Since every name is on one line, you can separate each value by the \n newline character.
let names = fileNames.components(separatedBy: "\n")

A: First : add the text file into the project.
Second: make sure it's present in Build Phases -> Copy Bundle Resources.
 func getNames(fileName: String) -> [String]?
 {
     guard let path = Bundle.main.path(forResource: fileName, ofType: "txt") else
     {
         return nil
     }

     do
     {
         let content = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
            return content.components(separatedBy: "\n")
     }
     catch _ as NSError
     {
         return nil
     }
 }

Usage:
let namesPool = getNames(fileName:"names")


text:
Q: Representing graphs as induced subgraphs of $\text{Hom}(H,K)$ Let $H, K$ be simple, undirected graphs, and let $\text{Hom}(H,K)$ the collection of graph homomorphisms $f: H\to K$. (Note that $\text{Hom}(H,K)$ might be empty.) For $f,g\in \text{Hom}(H,K)$ we say that they form an edge if $\{f(v),g(v)\}\in E(K)$ for all $v\in V(H)$ (which implies $f\neq g$ if $V(H) \neq \emptyset$). With this construction, we make $\text{Hom}(H,K)$ into a simple, undirected graph.
Given any simple, undirected graph $G$, are there simple, undirected graphs $H, K$ such that $|V(H)|>1$ and $G$ is isomorphic to an induced subgraph of $\text{Hom}(H,K)$?


text:
Q: Is it possible to use a profile based filter in your web.xml Is it possible to use a profile based filter in your web.xml ? For example
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
         <init-param>
            <param-name>spring.profiles.active</param-name>
            <param-value>secured</param-value>
        </init-param>
    </filter>

I know this is possible for servlets, but I cant seem to get it to work for filters.
Thanks

A: Original Answer
Filters use the ApplicationContext loaded from the ContextLoaderListener, so the <init-param> to the Filter is not used. Instead, you will want to use one of the ways of activating the profile for the ContextLoaderListener. One way is to use a  as shown below:
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>secured</param-value>
</context-param>

Follow Up
Following up based upon the comments. There is no way to omit the Filter using Spring profiles since the web.xml will always load the DelegatingFilterProxy which always tries to load its delegate. If the delegate is missing you will get an error. Instead, you can create a profile that disable Spring Security as shown below:
<b:beans profile="default,secured">
  <http auto-config="true" use-expressions="true">
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
  </http>
  <authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="user" password="password" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>
</b:beans>
<b:beans profile="insecure">
  <http security="none" />
</b:beans>

You could then disable Spring Security by activating the insecure profile in your web.xml as shown below.
<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>insecure</param-value>
</context-param>

If you are not using Spring Security you can disable the Filter by creating a Filter that does nothing but continue the FilterChain an placing that in the disabled profile. For example:
public class DoFilterChainFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
    public void destroy() { }
    public void init(FilterConfig filterConfig) throws ServletException { }
}


text:
Q: How to get the X position of a transform and convert it into a float in Unity2D I'm trying to get the x position of a gameobject in unity2D and converting the data of the X position into a float which I can use to detect if the position is -24 or 24 and then taking the x position of that gameobject and setting it back to 0.
Code
I've no idea how to do it in any other way
Error Messages In Console
Error CS1612 Cannot modify the return value of 'Transform.position' because it is not a variable  Assembly-CSharp

A: You should flip line 17
X = Background.transform.x;

A: You inverted the position and your X variable. Change it so it is
 X = Background.transform.position.x; so you assign the position to X.


text:
Q: OpenXML returns number instead of strings when reading from Excel file in VB.NET I'm developing a windows forms written in VB.NET.
In a form I need to import an Excel file and read it's data then show or store it in database. When I get cells containing numbers, the value is right but when I get cells containing strings, it just returns single digit numbers.
Here is the code :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim frm_sample As New frm_saple_importexcel
    frm_sample.ShowDialog()

    Dim ofd As New OpenFileDialog
    ofd.Filter = $"Excel File (*.xlsx)|*.xlsx|Excel File (*.xls)|*.xls|All files (*.*)|*.*"
    ofd.ShowDialog()

    Using spreadsheetDocument As SpreadsheetDocument =
        SpreadsheetDocument.Open(ofd.FileName, False)
        Dim dtSet As DataSet = New DataSet("JustAName")
        Dim workbookPart As WorkbookPart = spreadsheetDocument.WorkbookPart
        Dim worksheetPart As WorksheetPart = workbookPart.WorksheetParts.First()
        Dim sheetData As SheetData = worksheetPart.Worksheet.Elements(Of SheetData)().First()
        Dim dt = New DataTable("tt")
        dt.Columns.Add(New DataColumn("k_code"))
        dt.Columns.Add(New DataColumn("k_name"))
        dt.Columns.Add(New DataColumn("k_unit"))
        dt.Columns.Add(New DataColumn("k_group_name"))

        For Each r As Row In sheetData.Elements(Of Row)()
            Dim row As DataRow = dt.NewRow
            row("k_code") = r.ChildElements.ElementAt(0).InnerText
            row("k_name") = r.ChildElements.ElementAt(1).InnerText
            row("k_unit") = r.ChildElements.ElementAt(2).InnerText
            row("k_group_name") = r.ChildElements.ElementAt(3).InnerText
            dt.Rows.Add(row)
        Next

        dtSet.Tables.Add(dt)
        DataGridView1.DataSource = dtSet.Tables(0)
    End Using
End Sub


text:
Q: Single quote issue I have to update a column where I am giving query which is
Update Table
Set col = '[189] IS NOT NULL and [189] <> '''
Where colid= 198

But it's giving output:-     [189] IS NOT NULL and [189] <> '
I want output    :-     [189] IS NOT NULL and [189] <> ''
I am not getting single quotes at last. Please let me know how to give update query?
Thanks in advance.

A: For each single quote you want in a string constant, you need to use two to represent it
Two quotes in the string requires you to use 4 like this:
Update Table Set col = '[189] IS NOT NULL and [189] <> ''''' Where colid= 198


text:
Q: How to send and receive data in Magento? How can I send and receive data in Magento and AJAX? When I am sending data using AJAX, its not taking the URL?
Please let me know what is wrong in this code:
$(document).ready(function(){

    $("#category").on('change',function(){

        var prize = "<?php echo $spac_name;?>";
        $.ajax({
            url: "<?php echo Mage::getSingleton('core/url')->parseUrl(Mage::helper('core/url')->getCurrentUrl())->getPath()?>",
            type: 'POST',
            data: {prize :prize},
            success: function(data) {
                $('#da_ta').html("haha");
            }
        });
    });
});


text:
Q: SQL Select Top 3 into separate columns I have a very simple query that selects the top 3 codes from a table and I would like to either store them in a temp table as separate column values or fetch into a separate declared fields.
Top 3 query:
 select  top 3 code
 from table1 t1 (NOLOCK)
 join table2 t2 (NOLOCK) on t1.codeid = t2.codeid
 where t2.recordid = '123456789'
 and t1.codetype = '987654'

Results:
  code
  1111
  2222
  3333
Preferred output:
  code1     code 2     code3
  1111      2222       3333
I also could go for something else like:
 Declare @code1 as varchar(4)
 Declare @code2 as varchar(4)
 Declare @code3 as varchar(4)
 DECLARE RULE_CURSOR CURSOR STATIC FOR
 {select statement here}

 OPEN RULE_CURSOR
    FETCH NEXT FROM RULE_CURSOR into @code1, @code2, @code3

The Declare and Fetch into is actually my preferred method if someone could help me out.
Thank you!

A: I think I figured it out from a separate post I had inquired about previously:
 DECLARE RULE_CURSOR CURSOR STATIC FOR
      WITH    cte
      AS ( SELECT   top 3 code,  ROW_NUMBER() over( order by code) rn
           from  Table1 T1 (NOLOCK)
           join table2 t2 (NOLOCK) on t1.codeid = t2.codeid
           where t2.recordid = '123456789'
           and t1.codetype = '987654')
 SELECT [1] AS Code1 ,
        [2] AS Code2 ,
        [3] AS Code3
 FROM cte PIVOT( MAX(code) FOR rn IN ( [1], [2], [3] ) ) a
        Open RULE_CURSOR
     FETCH NEXT FROM RULE_CURSOR into @code1, @code2, @code3


text:
Q: Conversion from XSLX to TXT asks for exit method As per other posts I saw on stackoverflow, I wrote the following code to convert an XLSX to TXT however it throws: AttributeError: exit :
import xlrd
import csv

with xlrd.open_workbook('data.xlsx').sheet_by_index(0) as in_xslx:
    in_reader = csv.reader(in_xslx)
    with open("data.txt", "w", newline='', encoding='utf8') as out_text:
        out_writer = csv.writer(out_text, delimiter = '\t')
        for row in in_reader:
            out_writer.writerow(row)

However it successfully converts a CSV if I replace the first two rows with:
with open("data.csv", "r", encoding='utf-8') as in_csv:
    in_reader = csv.reader(in_csv)

Any idea why is that happening when converting XSLX->TXT and how to correct?
Thank you

A: What you need is:
import xlrd
import csv

with open("data.txt", "w") as out_text:
    # define output writer
    out_writer = csv.writer(out_text, delimiter = '\t')
    # Open and read an Excel file
    data_file = xlrd.open_workbook('data.xlsx')
    # get the first worksheet
    worksheet= data_file.sheet_by_index(0)
    # get the row values and write into output file
    for rownum in xrange( worksheet.nrows ):
        out_writer.writerow(worksheet.row_values(rownum))


text:
Q: Ruby on rails: Rspec routing error when testing for a successful http status So I am having trouble passing these specs in a ruby on rails application:
require 'rails/all'

RSpec.describe WikisController, type: :controller do
let(:user) { User.create!(email: "user@email.com", password: "password") }
let(:wiki) { Wiki.create!(title: "New Wiki Title", body: "New Wiki Body", private: false, user: user) }

   describe "GET show" do
     it "returns http success" do
       get :show
       expect(response).to have_http_status(:success)
     end
   end

   describe "GET edit" do
     it "returns http success" do
       get :edit
       expect(response).to have_http_status(:success)
     end
   end
end

when I run these specs, i get these errors:
Failures:

  1) WikisController GET show returns http success
     Failure/Error: get :show

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"wikis"}
     # ./spec/controllers/wikis_controller_spec.rb:16:in `block (3 levels) in <top (required)>'

  2) WikisController GET edit returns http success
     Failure/Error: get :edit

     ActionController::UrlGenerationError:
       No route matches {:action=>"edit", :controller=>"wikis"}
     # ./spec/controllers/wikis_controller_spec.rb:23:in `block (3 levels) in <top (required)>'

the reason i am confused is because they work fine in the browser. Also, when i run rake routes, i get this:
                    root GET    /                              wikis#index
                   wikis GET    /wikis(.:format)               wikis#index
                         POST   /wikis(.:format)               wikis#create
                new_wiki GET    /wikis/new(.:format)           wikis#new
               edit_wiki GET    /wikis/:id/edit(.:format)      wikis#edit
                    wiki GET    /wikis/:id(.:format)           wikis#show
                         PATCH  /wikis/:id(.:format)           wikis#update
                         PUT    /wikis/:id(.:format)           wikis#update
                         DELETE /wikis/:id(.:format)           wikis#destroy

So, these errors don't make sense to me because clearly i do have those routes with those controllers. Can someone provide me some insight as to what's going on here?

A: Your rspec includes show, edit actions which require id as your results from rake routes.
Try get :show, id: 1


text:
Q: C++ How to tell apart specific object types from a Heterogeneous Collection? So if i have a heterogeneous collection of Car objects
Car* c = {truck, van, convertible}
If the collection of objects was random and I wanted to go through the collection with a for loop, how can I test for the specific object type?

A: You would use a dynamic_cast:
if (truck* truck_p = dynamic_cast<truck*>(car_p)) {
  // car_p points at a truck
}

dynamic_cast will check the dynamic type of the object being pointed to by car_p and only allow the cast if it is a truck. If it is not a truck, it will give the null pointer value and therefore the if condition will fail.
However, the need to test a dynamic type like this suggests bad code design. The whole point of polymorphism is that you can treat any of the derived objects as though it were a base object - there should be no need to test exactly which derived type it was. If you need to check the dynamic type of a Car so that you can do some truck-specific operation on it, then you shouldn't be throwing that truck into a container of Car*.

A: If you have to know the derived type then polymorphism isn't the right tool for the job. I would suggest using a boost::variant or equivalent to implement a visitor pattern.

A: Try looking at RTTI:
http://en.wikipedia.org/wiki/Run-time_type_information
It's Run Time Type Information. You could also add a member variable into each derived type stating what type it is, and use that to check.


text:
Q: How i can create License Management Org (LMO). I am Parnter Portal member. i submitted many cases for it I am a partner portal member i want to upload a a package to appExchange but i don't kow how to create LMO Org and also also to get LMA for that. I submitted many cases for all these but get no idea and response.

A: You need to be a salesforce partner first.
Once you are a partner you will have the LMO org on which LMA is just a package from appexchange that you need to install.
Refer to this link for more details - https://developer.salesforce.com/docs/atlas.en-us.workbook_lma.meta/workbook_lma/lma_overview.htm

A: if you are a Partner you can submit a case in the Partner Portal which it sounds like you have already done. You will need to make sure your app has passed the security review which you can also do in the Partner Portal. Is your app free or paid? My App is free and this is the response I received once I submitted a case:

Free app partners are eligible for the LMA and their 2 free CRM
  licenses once they create a listing for their application on the
  Appexchange, set the pricing to free, and accept our terms &
  conditions.

Once I had met this criteria they set up an org with the required apps installed.
Note, they have recently changed the Partner Portal to make the process easier, in fact it is no longer the Partner Portal but the Partner Community entirely where these used to be two separate things.
I hope that helps!


text:
Q: SSRS Reporting Syntax Using the following filter for a SSRS report.
Expression:
=If((Parameters!GroupA.Value() In Fields!Related_GroupA.Value) Or (Parameters!GroupB.Value() In Fields!Related_GroupB.Value) Or (Parameters!GroupA.Value() In Fields!GroupA.Value) Or (Parameters!GroupB.Value() In Fields!GroupB.Value))
Operator:
=
Value:
True
Believe the syntax for the "If statement" and use of "in" and "Or" may be incorrect. Need to return the results if the value selected in the report parameter, appears in one of two places. (e.g. if Parameters!GroupA is in Fields!Related_GroupA or in Fields!GroupA)
Current Error:
'If' operator requires either two or three operands.

A:
'If' operator requires either two or three operands.

You have the "if" part in your statement but you don't specify what to do if it returns true or false. Also, use "iif" instead of "if."
=iif(
(Parameters!GroupA.Value In Fields!Related_GroupA.Value) Or
(Parameters!GroupB.Value In Fields!Related_GroupB.Value) Or
(Parameters!GroupA.Value In Fields!GroupA.Value) Or
(Parameters!GroupB.Value In Fields!GroupB.Value), <Value if true>, <Value if false>)

If you only want to return true or false then you don't need to use the iif operator because the "=" operator returns a boolean value (True/False).
If this is the case then you can simply use:
=(Parameters!GroupA.Value = Fields!Related_GroupA.Value) Or
 (Parameters!GroupB.Value = Fields!Related_GroupB.Value) Or
 (Parameters!GroupA.Value = Fields!GroupA.Value) Or
 (Parameters!GroupB.Value = Fields!GroupB.Value)

Note that I changed "In" to "=" because there isn't an IN operator you can use in the ssrs expressions but there are a few workarounds. See here and here.


text:
Q: Query and Match from Two Database Collections (Mongoose/MongoDB) I need help making a mongoose query that finds the requesting user's likes in the user collection, then searches for the user's likes in the posts collection. Hopefully, someone can tell me what I am doing wrong in my query or how I can do it better.
Users and Posts Collections:
const users = [
{
  _id: "1",
  likes: ["1", "2"]
},
{
  _id: "2",
  likes: ["3"]
}
]

const posts = [
{
  _id: "1",
  stuff: "stuff1"
},
{
  _id: "2",
  stuff: "stuff2"
},
{
  _id: "3",
  stuff: "stuff3"
}
]

Aggregate query:
router.post("/", authUser, async (req, res) => {
  User.aggregate([
    {
      $match: {
        _id: ObjectId(req.user._id), //user 1
      },
    },
    {
      $unwind: "$likes",
    },
    {
      $lookup: {
        from: "posts",
        let: { like: "$likes" },
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: ["_id", "$$like"],
              },
            },
          },
        ],
        as: "matched_posts",
      },
    },
    {
      $unwind: "$matched_posts",
    },
  ]).then((d) => {
    console.log(d);
  });
});

Desired output:
const output = [
{
  _id: "1",
  stuff: "stuff1"
},
{
  _id: "2",
  stuff: "stuff2"
}
]

A: *

*$match your conditions

*$lookup with posts collection, pass likes as localField and _id as foreignField

*$unwind deconstruct likes array

*$replaceRoot to replace likes object

router.post("/", authUser, async (req, res) => {
  User.aggregate([
    { $match: { _id: ObjectId(req.user._id) } },
    {
      $lookup: {
        from: "posts",
        localField: "likes",
        foreignField: "_id",
        as: "likes"
      }
    },
    { $unwind: "$likes" },
    { $replaceRoot: { newRoot: "$likes" } }
  ])
  .then((d) => {
    console.log(d);
  });
});

Playground


text:
Q: C# Collection was modified error with garbled text reading from file I'm new to C# and have been asked to write a custom task in a plugin for our deployment software, but I just can't wrap my head around this. I'm simply trying to log some data that is in a certain directory on my deployment server to the output log, but I only get the first file logged (and then even the text is garbled, I think it's loading the bytes wrong somehow) before getting strange errors about "Additional information: Collection was modified; enumeration operation may not execute."
Here is the code I have so far:
class Clense : AgentBasedActionBase
{
    public string dataPath { get; set; }

    protected override void Execute()
    {
        IFileOperationsExecuter agent = Context.Agent.GetService<IFileOperationsExecuter>();
        GetDirectoryEntryCommand get = new GetDirectoryEntryCommand() { Path = dataPath };
        GetDirectoryEntryResult result = agent.GetDirectoryEntry(get);
        DirectoryEntryInfo info = result.Entry;
        // info has directory information
        List<FileEntryInfo> myFiles = info.Files.ToList();
        foreach (FileEntryInfo file in myFiles)
        {
            Byte[] bytes = agent.ReadFileBytes(file.Path);
            String s = Encoding.Unicode.GetString(bytes);
            LogInformation(s);
            // myFiles.Remove(file);
        }
    }
}

Does anyone know what I can do to try to fix this?
Update
Removing the myFiles.Remove() fixed the error (I thought it would loop too many times but it doesn't) and it looks like I'm getting one log entry per file now, but the messages are still garbled. Does anyone have any idea why this is happening?

A: You can either iterate the myFiles collection in the reverse direction (so that you don't corrupt the collection when you remove each individual file), or you can simply clear the collection when you are done iterating it (which would accomplish the same thing).

A: You are modifying the collection with
    myFiles.Remove(file);
Delete that line (since it's the cause).

A: In his comment, Blorgbeard is almost certainly correct with regards to the encoding used to read the files on disk. Remember that Encoding.Unicode is actually UTF16, which is somewhat confusing, and if I had to guess, probably not the encoding your files were created with.
For completeness, I will add the BuildMaster-idiomatic way to handle your scenario using the ReadAllText() extension method on IFileOperationsExecuter:
protected override void Execute()
{
    var agent = this.Context.Agent.GetService<IFileOperationsExecuter>();
    var entry = agent.GetDirectoryEntry(new GetDirectoryEntryCommand() { Path = dataPath }).Entry;
    foreach(var file in entry.Files)
    {
        string contents = agent.ReadAllText(file.Path);
        this.LogInformation(contents);
    }
}

The ReadAllText() method will internally assume UTF8 encoding, but there is an overload that accepts a different encoding if necessary.


text:
Q: Data types and non exhaustive patterns If have a data type
data Arith  = Con Int
              | Add Arith Arith
              | Sub Arith Arith
              | Mul Arith Arith
              | Div Arith Arith

an instance:
instance Show Arith where
    show (Con i)     = show i
    show (Add e1 e2) =  "(" ++ show e1 ++ " + " ++ show e2 ++ ")"
    show (Sub e1 e2) =  "(" ++ show e1 ++ " - " ++ show e2 ++ ")"
    show (Mul e1 e2) =  "(" ++ show e1 ++ " * " ++ show e2 ++ ")"
show (Div e1 e2) =  "(" ++ show e1 ++ " / " ++ show e2 ++ ")"

and a function evaluate which is expected behave like:
ghci> eval (Mul (Con 5) (Div (Con 6) (Con 2) ))
15

this is what I've come up with that's not working when I try anything more complex then the basic case.
eval :: ArithExp -> Int
eval (Con e1)                = e1
eval (Add (Con e1) (Con e2)) = e1 + e2
eval (Sub (Con e1) (Con e2)) = e1 - e2
eval (Div (Con e1) (Con e2)) = e1 `div` e2
eval (Mul (Con e1) (Con e2)) = e1 * e2

When I try anything that isn't in this case, of course I get an error about exhaustive patterns.
So my question is, how do I catch all of the patterns without doing it the naive way?
I did notice that Add is defined as Add Arith Arith, Sub Arith Arith so how would I take advantage of that in my eval function? I tried doing:
eval (Add Arith Arith) = Arith + Arith

But that didn't work either, (not in scope error).
You don't need to give me a full working code example or anything, I'm just trying to get pointed in the right direction. Still new at haskell.
Thanks.

A: You should use recursion.
eval (Add a1 a2) = (eval a1) + (eval a2)

etc..

A: Here is a little refactoring to reduce duplication:
data OpT = Add | Sub | Mul | Div

data Arith  = Con Int
            | Op OpT Arith Arith

eval :: Arith -> Int
eval (Con a) = a
eval (Op f a b) = evalOp f (eval a) (eval b) where
    evalOp Add = (+)
    evalOp Sub = (-)
    evalOp Mul = (*)
    evalOp Div = div

You can do the same with show.


text:
Q: Converting the datatype of columns in shiny app I am trying to build a shiny app.
For this app, I have first created a fileinput() where user can upload the csv file they want and look at the dataset with statistics.
I would like to change the datatype of the columns from factors to numeric inthe displayed dataset and then perform analytics online.
I searched through web to get a starting point for developing this idea, but could not find any.
any lead on how i could select my required variable and change its datatype , would be helpful
here is the code i have tried so far.
UI
ui<- shinyUI(

  fluidPage(
  titlePanel("File Input - Upload multiple files"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file","Upload the file", multiple = TRUE, accept = c("text/csv",
                                                                      "text/comma-seperated-values, text/plain",
                                                                      ".csv")), # fileinput() function is used to get the file upload contorl option
      helpText("Default max. file size is 5MB"),
      helpText("Select the read.table parameters below"),
      checkboxInput(inputId = 'header', label = 'Header', value = TRUE),
      checkboxInput(inputId = "stringAsFactors", "stringAsFactors", FALSE),
      radioButtons(inputId = 'sep', label = 'Separator', choices = c(Comma=',',Semicolon=';',Tab='\t', Space=''), selected = ','),
      uiOutput("selectfile")
    ),
    mainPanel(
      uiOutput("tb")

    )

  )
))

SERVER code:
server<- shinyServer(function(input,output) {

  ## input$file is a data frame and contains the details around the name, size and temp location of the files uploaded
  # this reactive output display the content of the input$file dataframe
  output$filedf <- renderTable({
    if(is.null(input$file)){return ()}
    input$file # the file input data frame object that contains the file attributes
  })

  # Extract the file path for file
  output$filedf2 <- renderTable({
    if(is.null(input$file)){return ()}
    input$file$datapath # the file input data frame object that contains the file attributes
  })

  ## Below code to display the structure of the input file object
  output$fileob <- renderPrint({
    if(is.null(input$file)){return ()}
    str(input$file)
  })

  ## Side bar select input widget coming through renderUI()
  # Following code displays the select input widget with the list of file loaded by the user
  output$selectfile <- renderUI({
    if(is.null(input$file)) {return()}
    list(hr(),
         helpText("Select the files for which you need to see data and summary stats"),
         selectInput("Select", "Select", choices=input$file$name)
    )

  })

  ## Summary Stats code ##
  # this reactive output contains the summary of the dataset and display the summary in table format
  output$summ <- renderPrint({
    if(is.null(input$file)){return()}
    summary(read.csv(file=input$file$datapath[input$file$name==input$Select],
                       sep=input$sep,
                       header = input$header,
                       stringsAsFactors = input$stringAsFactors))})

  ## Dataset code ##
  # This reactive output contains the dataset and display the dataset in table format
  output$table <- renderTable({
    if(is.null(input$file)){return()}
    read.csv(file=input$file$datapath[input$file$name==input$Select], sep=input$sep, header = input$header, stringsAsFactors = input$stringAsFactors)

  })

  ## MainPanel tabset renderUI code ##
  # the following renderUI is used to dynamically generate the tabsets when the file is loaded.
  # Until the file is loaded, app will not show the tabset.
  output$tb <- renderUI({
    if(is.null(input$file)) {return()}
    else
      tabsetPanel(
        tabPanel("Input File Object DF ", tableOutput("filedf"), tableOutput("filedf2")),
        tabPanel("Input File Object Structure", verbatimTextOutput("fileob")),
        tabPanel("Dataset", tableOutput("table")),
        tabPanel("Summary Stats", verbatimTextOutput("summ")))
  })
})
shinyApp(ui, server)

ui <- shinyUI(fluidPage(
  titlePanel("Claim Model"),
  sidebarLayout(
    sidebarPanel(
      numericInput("1"),
    ),
    mainPanel(
      textOutput('dynamicText')
    )
    )
  )
)


text:
Q: Listar Pastas e Subpastas de um FTP com C# Alguém saberia dizer se é possível, se sim, como se faz para listar todas as pastas e subpastas de um FTP?
A ideia é a seguinte.
Estou listando todos os Arquivos e Diretórios desse FTP, mas diferente do DirectoryInfo().GetFiles(), via FTP não tem essa opção.
Alguém já fez algo assim?

A: Eu utilizo o Regex, junto ao retorno detalhado do ftp. Segue o código:
static string regex =
    @"^" +                          //# Start of line
    @"(?<dir>[\-ld])" +             //# File size
    @"(?<permission>[\-rwx]{9})" +  //# Whitespace          \n
    @"\s+" +                        //# Whitespace          \n
    @"(?<filecode>\d+)" +
    @"\s+" +                        //# Whitespace          \n
    @"(?<owner>\w+)" +
    @"\s+" +                        //# Whitespace          \n
    @"(?<group>\w+)" +
    @"\s+" +                        //# Whitespace          \n
    @"(?<size>\d+)" +
    @"\s+" +                        //# Whitespace          \n
    @"(?<month>\w{3})" +            //# Month (3 letters)   \n
    @"\s+" +                        //# Whitespace          \n
    @"(?<day>\d{1,2})" +            //# Day (1 or 2 digits) \n
    @"\s+" +                        //# Whitespace          \n
    @"(?<timeyear>[\d:]{4,5})" +    //# Time or year        \n
    @"\s+" +                        //# Whitespace          \n
    @"(?<filename>(.*))" +          //# Filename            \n
    @"$";                           //# End of line

static void Main(string[] args)
{
    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.isi.edu/");
    ftpRequest.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");
    ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
    FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
    StreamReader streamReader = new StreamReader(response.GetResponseStream());

    List<string> directories = new List<string>();

    string line = streamReader.ReadLine();
    while (!string.IsNullOrEmpty(line))
    {
        directories.Add(line);
        line = streamReader.ReadLine();
        if (line != null)
        {
            var split = new Regex(regex).Match(line);//separo no formato regex
            string dir = split.Groups["dir"].ToString();//vejo a parte dir
            string filename = split.Groups["filename"].ToString(); //vejo a parte de arquivo
            bool isDirectory = !string.IsNullOrWhiteSpace(dir) && dir.Equals("d", StringComparison.OrdinalIgnoreCase);//verifico se e uma pasta atravez do dir

             if(isDirectory)//é pasta
               Console.WriteLine(filename + " é um diretorio");
             else//nao e pasta
               Console.WriteLine(filename + " é um arquivo");
        }
    }

    streamReader.Close();

    Console.ReadKey();
}

Minha saída fica:
atomic-doc é um diretorio
bin -> usr/bin é um arquivo
...

A: No blog oficial do MSDN tem um artigo com um exemplo de como listar conteúdo da pasta com o FTP.
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("anonymous","janeDoe@contoso.com");

var response = (FtpWebResponse)request.GetResponse();

var responseStream = response.GetResponseStream();
var reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());

Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

reader.Close();
response.Close();


text:
Q: Sum of projection vectors Let say i have an orthogonal base $B$ which is some base of $R^3$, and now i want to find the vector coordinates of $[1,2,3]$ by base $B$ using the sum of projection vectors.
1.Is there some formula for this calculation?
2. I would like to get the idea behind this question.
Thanks!

A: Hint:
The scalar projection of a vector $\vec v$ in the direction of another vector $\vec b$ is:
$$
v_b=\frac{\vec v \cdot \vec b}{||\vec b||}
$$
where ''$\cdot$'' is the dot product.
If you know the vectors $\{\vec b_i\}$  of the basis $B$ and $\vec v=[1,2,3]^T$ is your vector, these scalar projections are the component of $\vec v$ in the basis $B$.


text:
Q: Регулярные выражения: найти 5 слов и меньше Всем привет!
Нужно найти в тексте выражения с нижними подчеркиваниями, которых не больше 5 во фразе.
Например, в тексте "kjmkjd _lsvsdlk xclc_ sfojlfkl _cslv_ podksckjsfskwofj skfl _lsklsl slcslsla sll dfla ljfk_ sfpowlwfk sladjl _d d d d d d d d_ cjvkdsm _f_" должно найтись:
_lsvsdlk xclc\_
_cslv\_
_lsklsl slcslsla sll dfla ljfk\_
_f\_

Я пишу регулярное выражение: _(?:\B\D+?\s?){,5}?\_
И оно находит все вхождения, что перечислены выше, и _d d d d d d d d\_ (чего я не хочу искать).
Подскажите, пожалуйста, в чем ошибка.

A: Если я правильно понял, то в группах, ограниченных подчеркиванием _, должно быть не более 5 слов, т.е. последовательностей символов, разделенных пробелами.
Попробуйте так:
_(?:[^_\s]+\s?){0,5}_

Если не нужны совпадения с __ (нулевое кол-во слов внутри подчеркиваний, что формально соответствует задаче), замените 0 в фигурных скобках на 1.
В выражении:
находим от 0 до 5 групп символов между подчеркиваниями _, которые не являются подчеркиваниями и пробелами [^_\s]+, но могут быть разделены пробелами \s?.
_d d d d d d d d_ не соответствует, поскольку содержит 8 слов, что больше 5.
Демо