text:
Q: Spring Batch ChunkRequest throws stackOverflow I am struggling with Spring Batch RemoteChunking with newer versions of Spring boot.
First i try to send ChunkRequest as event, it wasn't possible because it has no public default constructor. As solution I had to create a custom serializer and Deserializer and I set them in my application.properties correctly.
After doing all of that, now i am having Stackoverflow. (i understand the reason just by checking the ChunkRequest class which Has Collection of stepExecutions and the step execution have jobExecution which have stepExecutions)
https://docs.spring.io/spring-batch/docs/current/api/org/springframework/batch/integration/chunk/ChunkRequest.html
What i am missing, even after serializing ChunkRequest as byte[]?
    2022-05-14 00:22:31.880  INFO 11974 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-anonymous.3ac5789f-01ba-493f-a7ce-6f6f4429a0a1-2, groupId=anonymous.3ac5789f-01ba-493f-a7ce-6f6f4429a0a1] (Re-)joining group
    2022-05-14 00:22:31.891  INFO 11974 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [SimpleJob: [name=client-job]] launched with the following parameters: [{run.id=1}]
    2022-05-14 00:22:31.901  INFO 11974 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [dispatchStep]
    2022-05-14 00:22:31.948 ERROR 11974 --- [           main] o.s.batch.core.step.AbstractStep         : Encountered an error executing step dispatchStep in job client-job

    org.springframework.retry.ExhaustedRetryException: Retry exhausted after last attempt in recovery path, but exception is not skippable.; nested exception is org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'clientRequests'; nested exception is org.springframework.messaging.converter.MessageConversionException: Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain: org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.StepExecution["jobExecution"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util
    .Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]), failedMessage=GenericMessage [payload=ChunkRequest: jobId=1, sequence=0, contribution=[StepContribution: read=0, written=0, filtered=0, readSkips=0, writeSkips=0, processSkips=0, exitStatus=EXECUTING], item count=1, headers={id=ae9dbd76-ed32-0410-dacd-b6c700de87b2, contentType=application/json, timestamp=1652484151911}]
        at org.springframework.batch.core.step.item.FaultTolerantChunkProcessor$5.recover(FaultTolerantChunkProcessor.java:429) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.retry.support.RetryTemplate.handleRetryExhausted(RetryTemplate.java:539) ~[spring-retry-1.3.3.jar:na]
        at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:387) ~[spring-retry-1.3.3.jar:na]
        at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:255) ~[spring-retry-1.3.3.jar:na]
        at org.springframework.batch.core.step.item.BatchRetryTemplate.execute(BatchRetryTemplate.java:217) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.item.FaultTolerantChunkProcessor.write(FaultTolerantChunkProcessor.java:444) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:217) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:77) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:407) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:331) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) ~[spring-tx-5.3.19.jar:5.3.19]
        at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:273) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:82) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:375) ~[spring-batch-infrastructure-4.3.5.jar:4.3.5]
        at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-4.3.5.jar:4.3.5]
        at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:145) ~[spring-batch-infrastructure-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:258) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:208) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:152) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:413) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:136) ~[spring-batch-core-4.3.5.jar:4.3.5]
        at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:320) ~[spring-batch-core-4.3.5.jar:4.3.5]
org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.executeLocalJobs(JobLauncherApplicationRunner.java:173) ~[spring-boot-autoconfigure-2.6.7.jar:2.6.7]
        at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.launchJobFromProperties(JobLauncherApplicationRunner.java:160) ~[spring-boot-autoconfigure-2.6.7.jar:2.6.7]
        at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.run(JobLauncherApplicationRunner.java:155) ~[spring-boot-autoconfigure-2.6.7.jar:2.6.7]
        at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.run(JobLauncherApplicationRunner.java:150) ~[spring-boot-autoconfigure-2.6.7.jar:2.6.7]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:768) ~[spring-boot-2.6.7.jar:2.6.7]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:758) ~[spring-boot-2.6.7.jar:2.6.7]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:310) ~[spring-boot-2.6.7.jar:2.6.7]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.7.jar:2.6.7]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.7.jar:2.6.7]
        at pt.bayonne.sensei.importclients.ImportClientsApplication.main(ImportClientsApplication.java:10) ~[classes/:na]
    Caused by: org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'clientRequests'; nested exception is org.springframework.messaging.converter.MessageConversionException: Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain: org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.batch.core.StepExecution["jobExecution"]->org.springframework.batch.core.JobExecution["stepExecutions"]->java.util

Any Idea? Any example of the sample of application using RemoteChunking? Thanks
After adding this:https://github.com/spring-projects/spring-batch/issues/1488
I got a new exception:
Caused by: java.io.StreamCorruptedException: invalid stream header: 7B0A2020
    at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:963) ~[na:na]
    at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:397) ~[na:na]
    at org.springframework.util.SerializationUtils.deserialize(SerializationUtils.java:81) ~[spring-core-5.3.19.jar:5.3.19]
    ... 27 common frames omitted

A:
i understand the reason just by checking the ChunkRequest class which Has Collection of stepExecutions and the step execution have jobExecution which have stepExecutions

You nailed it, and in the end you are hitting https://github.com/spring-projects/spring-batch/issues/1488. This is a  Jackson issue, because other serialization mechanisms are able to serialize/deserialize ChunkRequest objects.

A: As @Mahmoud Ben Hassine mentioned,

This is a Jackson issue because other serialization mechanisms are
able to serialize/deserialize ChunkRequest objects.

Once you create your custom serializer, for example:
package pt.bayonne.sensei.RemoteChunking.job.serde;

import org.apache.kafka.common.serialization.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.integration.chunk.ChunkRequest;
import org.springframework.util.SerializationUtils;
import pt.bayonne.sensei.RemoteChunking.dto.ClientDTO;

public class ChunkRequestSerializer implements Serializer<ChunkRequest>{

    private static final Logger logger = LoggerFactory.getLogger(ChunkRequestSerializer.class);

    @Override
    public byte[] serialize(String topic, ChunkRequest data) {

        if (data == null) {
            return null;
        }

        String dataType = data.getClass().getName();
        logger.debug("--> serializing: {}",dataType);

        byte[] dataBytes = null;
        try {

            dataBytes = SerializationUtils.serialize(data);

        } catch (Exception e) {
            logger.error("Error serializing data", e);
        }

        return dataBytes;
    }

}

You have to specify that it is using the native encoding.
#produces
spring.cloud.stream.bindings.clientRequests.destination=clientRequests
spring.cloud.stream.bindings.clientRequests.producer.use-native-encoding=true
spring.kafka.producer.value-serializer=pt.bayonne.sensei.RemoteChunking.job.serde.ChunkRequestSerializer

Otherwise you will have more exceptions and sometimes it will continue picking the default framework serializer/deserializer. Using the Mixins doesn't help that much


text:
Q: What is actually happening on uploading the files from FileZilla ? Are we hosting it ? , if yes how it is actually linked with web hosting provider? I just want to know what is happening while uploading the files from FileZilla. From FileZilla can we host a website ? In internet its is saying that, FileZilla is used for uploading downloading files from internet.
Need some clarification

A: FileZilla is an FTP (File Transfer Protocol) program used to connect to and transfer files to and from an FTP server. FileZilla itself does not host any websites.
However, many servers running apache or nginx (or any other webserver software) will also run an FTP server that's configured so that items uploaded to that server will be visible on the websites hosted on that server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django: ForeignKey vs related_name I'd like to ask if there is an important distinction between below two ways of expressing a ForeignKey relation, or is it just a "style" difference?
It seems intuitive to first define parts and then collection of parts; a "sub-model" and then use this "parts-table" when populating a "main model". Thus, the Album_1 model fetch a single or several tracks from the Track_1 table (the collection consists of parts), as below.
version_1
class Track_1(models.Model):
    order = models.IntegerField()
    title = models.CharField(max_length=100)
    duration = models.IntegerField()

class Album_1(models.Model):
    album_name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
     # if Album only holds one (1) track,
    tracks = models.ForeignKey(Track_1, on_delete=models.CASCADE)
     # if the "record"/"Album" holds several tracks
    tracks = models.ManyToManyField(Track_1, blank=True)

Meanwhile it is less intuitive to express it as below which verbally could be interpret as Track_2 contains an Album_2 (the part consist of a collection).
version_2
 class Album_2(models.Model):
    album_name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)

 class Track_2(models.Model):
    album = models.ForeignKey(Album_2, related_name='tracks', on_delete=models.CASCADE)
    order = models.IntegerField()
    title = models.CharField(max_length=100)
    duration = models.IntegerField()

I have seen this difference many times and I am curious why the seemingly unintuitive "version_2" is frequently used, e.g. in relation to Django Rest Framework?

A: I would say that you mix the concepts: the Foreign Key defines the relationship between models, and the related_name is a property of the foreign key, that defines how you are going to reference the related model (it is mostly for convenience).
The important thing here is a Foreign Key because it defines the business logic of the app. I would say that the version_1 model is questionable from the business logic perspective, while the version_2 makes sense.
Let me explain, and I will start from the version 2:
In version_2 you are saying: my main model is Album, if I delete a particular album all the tracks from that album will be removed from the Track table. Makes sense!
In version_2 you are saying my main model is Track, if I delete a track from the Track table, all the Albums containing this particular track will be updated, because the track will be removed from all the Albums that contain it. Does it make sense? Maybe in some special cases yes, but in general it doesn't make sense.

A: I think the answer here is what is pointed out in one of the comments by @Blusky, who writes:

[...] Reverse name is a "trick" to ease the use of the ORM, but the
field is not created in the database


text:
Q: Botón que abra word existente y sustituye palabras especificas desde visual studio tengo que realizar un proyectó desde Visual Studio con 3 botones.

*

*Botón que me abra un Word en blanco.

*Botón que abra Word existente.

*Botón que abra un Word existente pero reemplacé del texto unas palabras especificas que tengo entre llaves"{}"

Los 2 primeros los tengo. Es fácil.
protected void Button1_Click(object sender, EventArgs e) {

        //abre word vacio
        System.Diagnostics.Process.Start("winword.exe");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        //abre word existente. la idea es ke el boton 3 ya me lo saque con los datos cambiados.
        System.Diagnostics.Process.Start(@"C:\Users\angel.garcia\Documents\doc\nora\20210810\PRUEBADEPEDRO2COPIA.doc");
    }
}

Pero el tercero no sé cómo llamar al texto y que busque y reemplace.


text:
Q: Weird change of variable in summation? I don't understand the change of variable in this summation
$$
\frac{1}{T}\sum_{k=-\infty}^{\infty} H \Big (\frac{F-k}{T}\Big )=1
$$
Change of variable: $f=\frac{F}{T}$ so
$$
\frac{1}{T}\sum_{k=-\infty}^{\infty} H \Big (f-\frac{k}{T}\Big )=1
$$
Isn't this wrong? $T$ isn't changed?
Shouldn't it instead be
$$
\frac{f}{F}\sum_{k=-\infty}^{\infty} H \Big (f-\frac{f}{F}k\Big )=1 \quad \text{?}
$$

A: In fact, both forms are correct. However when solving certain problems, not substituting the change for all variables is convenient.
You have your summation:
$$\frac{1}{T}\sum_{k=-\infty}^{\infty} H \Big (\frac{F-k}{T}\Big )=1$$
The fractions may be separated to give:
$$\frac{1}{T}\sum_{k=-\infty}^{\infty} H \Big (\frac{F}{T}-\frac{k}{T}\Big )=1$$
And so now, you can apply the substitution $f=\frac{F}{T}$ for only the $\frac{F}{T}$ term:
$$\boxed{\frac{1}{T}\sum_{k=-\infty}^{\infty} H \Big (f-\frac{k}{T}\Big )=1}$$
Note that: $$f=\frac{F}{T} \Rightarrow T=\frac{F}{f}$$
Therefore, you can substitute for $T$ to give your version of the summation, where you do not have the summation in terms of $T$ at all.
$$\frac{1}{(\frac{F}{f})}\sum_{k=-\infty}^{\infty} H \Big (f-\frac{k}{(\frac{F}{f})}\Big )=1$$
$$\boxed{\frac{f}{F}\sum_{k=-\infty}^{\infty} H \Big (f-\frac{f}{F} k\Big )=1}$$


text:
Q: Windows update error: 0xc1900101 on upgrading to windows 11 I was trying to upgrade windows 10 to 11 preview build by windows update and then while installing update(after restarting), my system displays 'undoing changes made to your system...' and after awhile it reverts back to windows 10 itself. After that going to system updates, I get error code: 0xc1900101.  My system meets the system requirements and TPM(2.0) is enabled.
Processor: Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz   1.99 GHz
RAM: 16.0 GB (15.9 GB usable)
System type: 6.0 GB (15.9 GB usable)

Happy to provide more info. Thanks :D


text:
Q: Suffering succotash According to this website:

In the mid-1800s, during the Victorian era, there was a rejection of all profanity and so the common people developed a wide variety of malapropisms to avoid swearing on Holy names. Soon, one could hear Cripes and Crikey replace "Christ" and Dangnabit replace "G*d damn it"  and Cheese 'n' Rice replace "Jesus Christ."  The phrase Suffering Succotash replaced "Suffering Savior."

Today the latter phrase is known only as an expression of annoyance and surprise by animated cartoon characters such as Sylvester the Cat and Daffy Duck.  Was the expression still in vogue when the Looney Tunes cartoons were made, or did the cartoons resurrect an expression that had already lapsed from the American lexicon?

A: I don't see any evidence that it was ever a common expression before the cartoon.
Minced oaths generally date back much further than the 1800s. Socrates and Aristophanes give us examples in ancient Greek, and several slurrings of oaths exist in English from the early modern period on.
They exist today too in people saying "gosh" and so on, along with a variation for lavatorial and sexual expletives (sugar for shit, fricken for fucking and so on). They tend to be often localised in form, with for example jaysus for Jesus only appearing in and around Dublin, Ireland (a pronunciation that would once have been used only in some Dublin accents being adapted by other Dubliners exclusively for non-religious senses) and various expressions coming in and out of favour as with local slang expressions one finds varying greatly around the world.
Because of the great variety in real use, and the added requirement for such uses in some media (where the writer is not allowed to have Sylvester the Cat say "God-damn that fucking mouse!"), and the fact that most writers are writers and writers like playing with words, minced oaths have a greater variety in fiction than in real life (though life often imitates art in this regard). Holy Inventive Phrasing, Batman!
As such, "suffering succotash" was likely used precisely because it wasn't very likely to be heard as an actual minced oath and that, combined with the chiming of /sʌ/ in both words, and so is humorous. Indeed, in this case it would not so much be a matter of the cat's swearing being replaced by a minced oath as with the naff of "Porridge" and the smeg of "Red Dwarf" (where we could expect expletives to be a larger part of the characters' vocabulary if allowed) but rather he uses funny minced oaths purely because they are funny.

A: Usage - "The Dick Van Dyke Show" - Season 3 Episode 21: "The Pen is Mightier Than the Mouth" (19 February, 1964) The character Buddy Sorrell (Buddy Sorrell) verbally reacted to Rob Petrie (Dick Van Dyke) announcing he was going to fire Sally Rogers (Rose Marie) by exclaiming, "suc-co-tash!"

A: When you think about it, Suffering is a star of on going pain, and Succotash is a an American dish. America is, as everyone knows a very religious place and there have been many other ongoing debates as to whether this 'catchphrase' was ever real. There was a rejection of Profanity in the mid 1800's, Victorian Age, so the common people developed a wide variety of malapropisms to avoid swearing on Holy names. They were used for swearing and other types of interjections. With time they came to have a mildly comedic effect.
People are not so concerned about blasphemy, nowadays. We have worse problems.
Crikey = 'Christ'
Cripes = 'Christ'
Jeez = 'Jesus'
Dangnabit = 'Damnation"
by gum = "by g-d"
by gosh =" by g-d"
by golly = "by the name of g-d"
jumping jehosaphat
suffering succotash = 'Suffering Saviour'
 Proof of this came down to many, not many, but some recollected diary entries from young children of this time. Many people claim that their grandparents had told stories about such prevailer things and used the phrase 'Suffering succotash'. You may be sitting in your chai in bliss with a grin on your face thinking, this persons an idiot, people could have easily just said that even if it didn't happen. Well, if you dig a little deeper you find that currently 25% and up of the world still has no interest access. That's right an entire quarter has no access to internet and in many cases those which do don't have many people who can afford it anyway. And the funny things is that many people that remember these stories come from these countries meaning the chances of them knowing what the looney tunes are is rather small.
So to some this up in simple terms, for all those people out there that fell asleep halfway, Yes, 'Suffering Succotash' is a real thing that was used by many people throughout the mid 1800's and I absolutly LOVE the phrase.


text:
Q: How to access DI inside custom ConfigurationProvider I am implementing a custom ConfigurationProvider and I have the following extension method in place
 public static class ConfigurationExtensions
    {
        public static IConfigurationBuilder AddConfigProviderConfiguration(this IConfigurationBuilder configuration)
        {
            configuration.Add(new ConfigurationSource());
            return configuration;
        }
    }

And I am calling the extension method like this
return new ServiceCollection().AddConfigProviderServices()

This is the ConfigurationSource class
 public class ConfigurationSource : IConfigurationSource
    {
        public IConfigurationProvider Build(IConfigurationBuilder builder)
        {
            return new ConfigurationProvider(this);
        }
    }

Inside the ConfigurationProvider I would like to be able to inject or somehow access dependencies like ILogger, that I have registered as DI. How can I access the dependencies?

A: I ended up adding another load method inside the ConfigurationProvider class that takes in IServiceProvider as a parameter like this:
  public class ConfigurationProvider : Microsoft.Extensions.Configuration.ConfigurationProvider
    {
        public void Load(IServiceProvider serviceProvider)
        {
            var logger = serviceProvider.GetRequiredService<ILogger<ConfigurationProvider>>();
// Get other services using serviceProvider, e.g. dbContext and call  Set(s.Key, s.Value); accordingly

Next call the custom load method after ServiceProvier has been initiated and pass it in as a parameter like this:
[TestInitialize()]

    public void InitializeTest()
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory
                .GetCurrentDirectory()) //From NuGet Package Microsoft.Extensions.Configuration.Json
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddConfigProviderConfiguration()
            .Build();

        serviceProvider = ServiceProvider.BuildDi(config);

        var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
        loggerFactory.AddProvider(new LoggerProvider(config));

        var provider = config.Providers.FirstOrDefault(p => p is ConfigurationProvider);
        var cp = (ConfigurationProvider)provider;
        cp.Load(serviceProvider);
    }

Not the nicest solution but it works and all the DI dependencies are accessible from within ConfigurationProvider.


text:
Q: Convert string to char 2d array I was wondering does anyone know how to convert a string into a 2d array? This was my attempt:
string w;
char s[9][9];
int p=0;
getline(cin, w);
while(p != w.size())
{
  for (int k = 0; k < 9; k++)
  {
    for(int j = 0; j < 9; j++)
    {
      s[k][j] = w[p];
      p++;
    }
  }
}
  cout << "nums are: " << endl;
  for(int k = 0; k < 9; k++)
  {
    for(int j = 0; j <9; j++)
    {
      cout << s[k][j];
    }
  }

But the numbers don't print out correctly. I want s[k][j] to print out everything in w but it simply prints out gibberish. I also noticed if i do string[81] then I get a whole bunch of errors. Could anyone help me? Thanks.

A: Try this:
const int NUM_ROWS = 9;
const int NUM_COLS = 9;

string w;
char s[NUM_ROWS][NUM_COLS];

getline(cin, w);

if (w.size() != (NUM_ROWS * NUM_COLS))
{
    cerr << "Error! Size is " << w.size() << " rather than " << (NUM_ROWS * NUM_COLS) << endl;
    exit(1);
}

for (int count = 0; count < w.size(); count++)
{
    if (!isdigit(w[count]) && w[count] != '.')
    {
        cerr << "The character at " << count << " is not a number!" << endl;
    }
}

for (int row = 0; row < NUM_ROWS; row++)
{
    for(int col = 0; col < NUM_COLS; col++)
    {
        s[row][col] = w[col + (row * NUM_COLS)];
    }
}

cout << "Nums are: " << endl;

for(int row = 0; row < NUM_ROWS; row++)
{
    for(int col = 0; col < NUM_COLS; col++)
    {
        cout << s[row][col] << " ";
    }

    cout << endl;
}

Based on our chat, you might want this:
const int NUM_ROWS = 9;
const int NUM_COLS = 9;

string w;
char s[NUM_ROWS][NUM_COLS];

while (!cin.eof())
{
    bool bad_input = false;

    getline(cin, w);

    if (w.size() != (NUM_ROWS * NUM_COLS))
    {
        cerr << "Error! Size is " << w.size() << " rather than " << (NUM_ROWS * NUM_COLS) << endl;
        continue;
    }

    for (int count = 0; count < w.size(); count++)
    {
        if (!isdigit(w[count]) && w[count] != '.')
        {
            cerr << "The character at " << count << " is not a number!" << endl;
            bad_input = true;
            break;
        }
    }

    if (bad_input)
        continue;

    for (int row = 0; row < NUM_ROWS; row++)
    {
        for(int col = 0; col < NUM_COLS; col++)
        {
            s[row][col] = w[col + (row * NUM_COLS)];
        }
    }

    cout << "Nums are: " << endl;

    for(int row = 0; row < NUM_ROWS; row++)
    {
        for(int col = 0; col < NUM_COLS; col++)
        {
            cout << s[row][col] << " ";
        }

        cout << endl;
    }
}

A: You haven't described what you're trying to do very well and you haven't described the problem you're encountering, so the following is just based on guesses.
So it looks what you're trying to do is take a string like:

The quick brown fox jumped over the lazy dogs.

And put that into a 2D array like:
  0 1 2 3 4 5 6 7 8
0 T h e   q u i c k
1   b r o w n   f o
2 x   j u m p e d
3 o v e r   t h e
4 l a z y   d o g s
5 . x x x x x x x x
6 x x x x x x x x x
7 x x x x x x x x x
8 x x x x x x x x x

One thing wrong with your code is that as you copy values from w into s you don't ensure that the index p is actually within the bounds. You seem to have attempted to deal with this in the line that says while(p != w.size()); but that's an outer loop that does not protect p from being incremented out of bounds and used in the inner loops. Instead you'd have to put something like p++; if (p==w.size()) break; inside the inner most loop where you increment p. Or better yet, you should iterate over the string instead of over the array. Something like the following pseudo-code would replace your entire while(p){for(k){for(j){}}} set of loops.:
for(size_t i=0; i<w.size(); ++i) {
    int k = compute target row from i
    int j = compute target column from i
    s[k][j] = w[i]
}

Also, here's some code to better visualize the array as you're debugging.
#include <iostream>

int main() {
    char s[9][9] = {"The","quick","brown","fox","jumped","over","the","lazy","dogs."};

    // your code to get input and copy it into the array goes here
    //
    // for(size_t i=0; i<w.size(); ++i) {
    //     int k = compute target row from i
    //     int j = compute target column from i
    //     s[k][j] = w[i]
    // }

    std::cout << "  0 1 2 3 4 5 6 7 8\n";
    for (int i=0; i<9; ++i) {
        std::cout << i;
        for (int j=0; j<9; ++j)
            std::cout << ' ' << s[i][j];
        std::cout << '\n';
    }
}

If you run this program without any changes the output should look like this:
  0 1 2 3 4 5 6 7 8
0 T h e
1 q u i c k
2 b r o w n
3 f o x
4 j u m p e d
5 o v e r
6 t h e
7 l a z y
8 d o g s .


text:
Q: Powershell text string to CSV I initially thought this problem more complex than it actuially is but after digging around I still cant seem to find a solution that I can re-purpose. I'm trying to use wildcards but perhaps I'm going about this the wrong way
I have a text file as below:
SQL*Plus: Release 11.2.0.1.0 Production on Wed Aug 13 14:20:22 2014
Copyright (c) 1982, 2010, Oracle.  All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options

EXTERNAL ID

--------------------------------------------------------------------------------

'M1

---

12345678-1

M07

18765432-1

M14

19638527-1

M14

EXTERNAL ID

--------------------------------------------------------------------------------

'M1

---

17418529-1

M07

I would like a single CSV with 2 columns such as:
EXTERNAL ID     M01

12345678-1      M07

18765432-1      M14

19638527-1      M14

17418529-1      M07

Any insight or help is appreciated

A: Here is something that I think will do what I want. It could probably be made more efficient and smaller but I went for easy to read and comprehend instead:
$res = @()
$content = get-content SomeFile.txt | ?{($_ -ne 'EXTERNAL ID') -AND (-NOT $_.StartsWith('"-')) -AND ($_ -ne "'M1") -AND (-NOT $_.Startswith('SQL*')) -AND ($_ -ne '')}

for($count = 0; $count -lt $content.Count; $count = $count + 2){
    $id = $content[$count]
    $m = $content[$count + 1]
    $temp = New-Object PSCustomObject -Property @{'External ID' = $id;
                                                  'M01' = $m;
    }
    $res += $temp
}
$res | Export-CSV .\Som\Path\Name.csv -NoTypeInformation

A: Similar to EBGreen's answer, but simpler I think.
$Col2=$false
gc c:\temp\test.txt |Select -skip 6| ?{![string]::IsNullOrEmpty($_) -and $_ -notmatch "^(---|External|'M1)"} | %{
    If($Col2){
        [PSCustomObject][Ordered]@{
            'External ID'=$Col1
            "'M1"=$_}
        $Col2=$false
        }else{
            $Col1=$_
            $Col2=$true
        }
    } | Export-Csv C:\temp\New.csv -NoTypeInformation


text:
Q: PYTHON 3:UnboundLocalError local variable 'x' referenced before assignment this code gave this error: UnboundLocalError: local variable 'x' referenced before assignment
def predict_price(location,sqft,bath,BHK):
loc_index = numpy.where(x.columns==location)[0][0]
x = numpy.zeros(len(x.columns))

x[0] = sqft
x[0] = bath
x[0] = BHK
if loc_index >=0:

    x[loc_index] = 1

return lr_clf.predict([x])[0]

predict_price("calabar",1000, 2, 2)

A: The issue is that you are referencing x.columns in the initializer.
x = numpy.zeros(len(x.columns))
In other words, you are defining x based on the length of columns in x.  If x is not yet defined, then how is it possible to determine how many columns it has?


text:
Q: How can i create a /tmp partition i'm trying to intall RHEL Linux Server 7.4 using VMware through a dvd.iso
i want to create a partition for the /tmp during the installation, knowing that the graphical interface that permit customizing partitions lasts in few seconds !

A: The RHEL7 installation guide has a section specifically describing how to create a custom partition scheme. Create your /tmp along side other partitions there.
Also, please use the RHEL 7.6 installation media instead of 7.4. It has all the latest fixes in it, and will speed up how long it takes to get all your software updates after you install, since there will be fewer.


text:
Q: Read data from a text file using Java I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
    char c = (char)fis.read();
    .....
    .....
}

A: If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)

A: String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    // Uncomment the line below if you want to skip the fist line (e.g if headers)
    // line = br.readLine();

    while ((line = br.readLine()) != null) {

        // do something with line

    }
    br.close();

} catch (IOException e) {
    System.out.println("ERROR: unable to read file " + file);
    e.printStackTrace();
}

A: You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..

A: You should not use available(). It gives no guarantees what so ever. From the API docs of available():

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

You would probably want to use something like
try {
    BufferedReader in = new BufferedReader(new FileReader("infilename"));
    String str;
    while ((str = in.readLine()) != null)
        process(str);
    in.close();
} catch (IOException e) {
}

(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)

A: How about using Scanner? I think using Scanner is easier
     private static void readFile(String fileName) {
       try {
         File file = new File(fileName);
         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       }
     }

Read more about Java IO here

A: The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0

A: In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

A: //The way that I read integer numbers from a file is...

import java.util.*;
import java.io.*;

public class Practice
{
    public static void main(String [] args) throws IOException
    {
        Scanner input = new Scanner(new File("cards.txt"));

        int times = input.nextInt();

        for(int i = 0; i < times; i++)
        {
            int numbersFromFile = input.nextInt();
            System.out.println(numbersFromFile);
        }

    }
}

A: Try this just a little search in Google
import java.io.*;
class FileRead
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

A: Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();

A: Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.

A: user scanner it should work
         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close();

A: public class ReadFileUsingFileInputStream {

/**
* @param args
*/
static int ch;

public static void main(String[] args) {
    File file = new File("C://text.txt");
    StringBuffer stringBuffer = new StringBuffer("");
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            while((ch = fileInputStream.read())!= -1){
                stringBuffer.append((char)ch);
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("File contents :");
    System.out.println(stringBuffer);
    }
}

A: public class FilesStrings {

public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("input.txt");
    InputStreamReader input = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(input);
    String data;
    String result = new String();

    while ((data = br.readLine()) != null) {
        result = result.concat(data + " ");
    }

    System.out.println(result);

A:     File file = new File("Path");

    FileReader reader = new FileReader(file);

    while((ch=reader.read())!=-1)
    {
        System.out.print((char)ch);
    }

This worked for me

A: Simple code for reading file in JAVA:
import java.io.*;

class ReadData
{
    public static void main(String args[])
    {
        FileReader fr = new FileReader(new File("<put your file path here>"));
        while(true)
        {
            int n=fr.read();
            if(n>-1)
            {
                char ch=(char)fr.read();
                System.out.print(ch);
            }
        }
    }
}


text:
Q: Best way to store text data in an android app? I've made an Android application which contains most used German words and sentences. The application contains a CSV file which stores all the data.
Currently it is working as expected but I want to ask if there is a better way to store such data directly in the app?
I'm also thinking about the ability to update the data via internet like adding new words and sentences.
Thanks!
Miretz

A: If you want to modify the content (update, remove etc.) I would suggest using SQLite DB which has a pretty nice built-in integration with the Android platform.

A: There are 2 types SQLDatabaseLite and SharedPreference. Major difference between both is that one is organized and the other not so.
If you need a quick use of a storage facility within your app for example changing text sizes between activity SharedPrefference works best for you.
If you have a complex database system where you need more than one data to be saved for a particular event SQLDatabaseLite is for you example of this is spreadsheet of data for customers; Name, Phone Number, etc.


text:
Q: Отправка капчи на сервис антигейт(java). Ошибка ERROR_ZERO_CAPTCHA_FILESIZE Здраствуйте, хочу отправлять капчу на сервис антигейт, пользуюсь методом post и base64 как сказано в документации - https://anti-captcha.com/apidoc
Получаю ошибку ERROR_ZERO_CAPTCHA_FILESIZE
В параметр post запроса даю key(мой access token  к акаунту-здесь прим.123456789) и ссылку на капчу
Кодирую в base 64 и отправляю
Не понимаю почему сервис не принимает картинку, вроде кодирует правильно, в интернете в онлайн декодере вставлял код картинки в base64 и получал в ответ свою капчу
Вот мой код :
    private static void sendPost(String encodedImage,String key) throws Exception {
        String url = "http://anti-captcha.com/in.php?";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        String urlParameters = "key="+key+"&file="+encodedImage;
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString());

    }

    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

public static void main(String[] args) throws Exception{

    URL url = new URL("http://api.vk.com/captcha.php?sid=579356847070&s=1");
    BufferedImage img = ImageIO.read(url);
    String encodedCaptcha=encodeToString(img, "jpg");
    String key="123456789";
    sendPost(key,encodedCaptcha);

    }
}

A: Как сказано в документации
Во-первых, вы не передаёте method.
Во-вторых, (хотя возможно это и просто ошибка примера к документации), оба метода должны быть в multipart/form-data. Вы в лучшем случае отправляете application/x-www-form-urlencoded, если setRequestMethod("POST") его выставляет.
При том, судя по всему, без urlencode. Тогда как base64 штатно может содержать символ = в конце - т.е. интерпретирован будет ошибочно. Об этом в документации и сказано:

IMPORTANT: Do not forget to encode the body with URLEncode, otherwise picture data will arrive scrambled.

Не знаком с Java, поищите, как по-нормальному формируется тело HTTP-запроса.
Ручная конкатенация "key="+key+"&file="+encodedImage - это не нормально. Наверняка есть штатный способ, принимающий список параметров со значениями и генерирующий корректную строку тела запроса.
Ну или, хотя бы, как делается urlencode вручную.

A: Возможно Вы перепутали порядок аргументов? Отправляете:
 sendPost(key,encodedCaptcha);

Принимает sendPost:
void sendPost(String encodedImage,String key)

И на место encodedImage имеете key, а там где key - encodedImage


text:
Q: What is the easiest way to get the S rank mansion in Luigi Mansion original? I got the A rank, but I can't figure out how to get enough money and gems.
Can anyone maybe tell me about the secret rooms or hidden gems that are available?
Is there a guide to grinding money and gems?

A: From what I've seen in online playthroughs, there is no "griding" for money.
Theres a fixed amount of money in the game and you can permanently lost some.
I would advise you to follow this guide or one of the numerous videos available on YouTube.
Also, remember that the maximum score is different between PAL and NTSC versions of the game.

A: There is no S rank in the original version of Luigi's Mansion. That was added in the 3DS rerelease.
If you are playing the 3DS version, there are guides like this one available online detailing where all the treasure is. While that guide is intended for players going for a perfect score, that's not necessary for an S rank; you'll get it as long as you clear the game with at least 130,000,000G. Keep in mind that obtaining this much (and, by extension, obtaining an S rank) is only possible in the Hidden Mansion.


text:
Q: Setting permissions in SharePoint 2013 Workflow I'm working on a SharePoint Workflow as a proof of concept for one of our clients.  The requirements are that it must be accomplished as a SharePoint 2013 workflow with no custom code, created only in Designer.
I created a List workflow with custom Approvers and Processors defined in separate lists, as suggested by Brij Dammani in this article.  The workflow is working quite well - except there is no security at all; anyone with edit rights can edit the Workflow Tasks list no matter to whom the task is assigned, and complete their task and advance the workflow.
From my searches there are two main suggestions to add security.  One to use a second SharePoint 2010 workflow, which uses the deprecated Set Item Permissions action, to lock down the list item to the person whose task it is.  The second is to roll my own/import a custom SharePoint 2013 action to manipulate the permissions.  Obviously both of these break the requirements.  My own idea (a messy one) is to have the workflow move items to the lists with the correct permissions.  As my Approvers are set dynamically via a list this makes maintenance difficult.
My question is:
What is the preferred way of managing permissions in SharePoint 2013 Workflows?
Surely there must be a way to lock down the tasks to the person to whom it is assigned without having to use deprecated actions or custom code??

A: I've looked into this a lot and I think I can answer the original question.  It is my understanding that SharePoint 2013 has removed impersonation in favour of using the new App Step.  The idea behind this is to create a virtual app that represents workflows, then to give permissions to this virtual app.  The short version of how to do this is below, Microsoft themselves explain here.

*

*First, activate the feature on the site by going to Site Settings > Site Features and set the feature "Workflows can use app permissions" to Active.

*Next, go to Site Settings > Site App Permissions.  There should be a virtual app named "Workflow" there.  Copy the client section of the App Identifier - this first Guid, between "|" and "@"

*Grant permission to the app by going to http://{hostname}/{catalog site}/_layouts/15/appinv.aspx.  Paste the App Id, click Lookup.  Then paste the following verbatim into the Permission Request XML. There are no placeholders in the Scope value above. It is a literal value. Enter it exactly as it appears here.:
<AppPermissionRequests>
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="FullControl" />
</AppPermissionRequests>

*

*Click Create then Trust It to trust the app.  Now, anything running inside an App Step will have FullControl permissions.

This doesn't actually help me lock down the tasks, as there is no custom action that can set the item permission on the task list.  To do exactly what I want, I need a custom action that can set item permissions.  Still, it's good to know that it's not possible OOTB.

Also noteworthy, as a workaround I tried creating two lists, two workflows (one on each list) with two different task lists, with different permissions.  The idea being that the one workflow would create an item in the second list, kicking off the second workflow.  The users would then only be able to approve those items in their own task list.  However this did not work.  List items created by workflows do not kick off that list's workflow as explained in this msdn article:  2013 Workflow not triggered on item created with a workflow.  Nor can a SP2013 workflow start another SP2013 workflow with OOTB actions.  An SP2013 workflow can only start an SP2010 workflow.

I've come to the conclusion that what I'm trying to do is impossible in SP2013 workflows OOTB.  If anyone can correct me I'd be very appreciative.

A: If you want to restrict the users to have permission in only their tasks(ie Assigned to me), you have to use SharePoint 2010 workflow and replace permission on that item to allow only Assigned user edit rights on that item. Choose SharePoint 2010 workflow platform while creating workflow ,
if you are trying this in a SharePoint 2013 site.
Another workaround is to edit all the views in the Task list and filter to show only those items which has Assigned column value = [Me]. But if the users have rights to edit the views they can override this settings or create new view to see other's items.
Edit: Disdavantage using SP 2010 workflow is that it runs under the privilege of the user who created the workflow.So it can break if user privileges are lowered or user left the company.

A: We can also use "If" actions to evaluate who is the currently logged on user and compare that with the item and then allow or disallow updates.


text:
Q: Getting Twitter usernames in Python I'm trying to read tweets for the following keywords on Twitter (cycling, running, sports suck) and would also like to get the username of the person who sent the Tweet.  I've scoured the web, but haven't come up with an answer that seems to work.  I don't think I understand exactly what it is I'm looking for?  Any help would be greatly appreciated, my code so far is below...
Thanks
import tweepy
from time import sleep
import sys
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)

CONSUMER_KEY = 'xxxx'
CONSUMER_SECRET = 'xxxx'
ACCESS_KEY = 'xxxx'
ACCESS_SECRET = 'xxxx'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
auth.secure = True
api = tweepy.API(auth)

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        if 'cycling' in status.text.lower():
                print('BIKE!')
                print(status.text.translate(non_bmp_map))
        elif 'running' in status.text.lower():
            print('RUN!')
            print(status.text.translate(non_bmp_map))
        else:
            print('SPORTS SUCK!')
            print(status.text.translate(non_bmp_map))

myStreamListener = MyStreamListener
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener())

myStream.filter(track=['cycling', 'running', 'sports suck'])

I've added this code... (the lines with # in).  It keeps coming up with an error message: TypeError: 'type' object is not iterable Any ideas?
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
    for tweet in tweepy.Cursor: #I'VE ADDED THIS LINE
        if 'cycling' in status.text.lower():
                print('BIKE!')
                print(status.text.translate(non_bmp_map))
                print(tweet.user.screen_name) #I'VE ADDED THIS LINE
        elif 'running' in status.text.lower():
            print('RUN!')
            print(status.text.translate(non_bmp_map))

A: You should definitely look into this Python API that allows to receive the tweet sent and the username of the sender. I had no experience with python and I made it work really fast and easy.
All useful source code & way of getting it to work is on the git page :-)


text:
Q: Computing the $L^p$ norm of an integral operator Let $T : L^{p}(\mathbb{R}_{>0}) \to L^{p}(\mathbb{R}_{>0})$ be given by:
$$
(Tf)(x) = \int_0^\infty \frac{f(y)}{x+y} \mathrm{d}y
$$
I would like to show that this is a bounded operator for $ p \in (1,\infty)$. I was given a hint for the question, namely to make a linear change of variables $y = xu$.  Thus, to compute $\|T_f\|_p$, we calculate:
$$
\|Tf\|
_p = \left(\int_0^\infty\left(\int_0^\infty \frac{f(y)}{x + y} \mathrm{d}y\right)^p\mathrm{d}x\right)^{1/p} = \left(\int_0^\infty\left(\int_0^\infty \frac{f(xu)}{1 + u} \mathrm{d}u\right)^p\mathrm{d}x\right)^{1/p}
$$
From here, I am stuck. The natural thing to me seems to apply Holder's inequality to the inner integral, and compute:
$$
\left(\int_0^\infty\left(\int_0^\infty \frac{f(xu)}{1 + u} \mathrm{d}u\right)^p\mathrm{d}x\right)^{1/p} \leq \left(\int_0^\infty \|f(x\cdot)\|_{L^p}^p \left\|\frac{1}{1+ \cdot }\right\|_{L^q}\mathrm{d}x\right)^{1/p} \leq \left\|\frac{1}{1+ . }\right\|_{L^q}^{1/p} \left(\int_0^{\infty}\|f(x \cdot)\|_{L^p}\mathrm{d}x\right)^{1/p}
$$
But the integral on the right hand integral does not seem to converge. Does anyone have any ideas?
Another question I have is, how is the operator above related to the Laplace transform:
$$
(\mathcal{L}f)(s) := \int_0^\infty e^{-sx}f(x) dx
$$
?
Many thanks.

A: You could use Minkowski's Integral Inequality. Then
\begin{align}
\left(\int_0^\infty\left(\int_0^\infty \frac{f(xu)}{1 + u} \mathrm{d}u\right)^p\mathrm{d}x\right)^{1/p}
&\leq \int_0^\infty\left(\int_0^\infty \frac{|f(xu)|^p}{(1 + u)^p} \mathrm{d}x\right)^{1/p}\mathrm{d}u\\[0.3cm]
&= \|f\|_p\,\int_0^\infty\frac{1}{(1 + u)^p}\left(\int_0^\infty  |f(xu)|^p\,\mathrm{d}x\right)^{1/p}\mathrm{d}u\\[0.3cm]
&= \int_0^\infty\frac{1}{(1 + u)^p\,u^{1/p}}\,\mathrm{d}u<\infty
\end{align}
As for the Laplace transform, this is one possibility. You have
$$
\frac1{x+y}=\int_0^\infty e^{-(x+y)t}\,dt.
$$
Then (since Fubini applies for any $x>0$ here),
\begin{align}
Tf(x)
&=\int_0^\infty f(y)\,\int_0^\infty e^{-(x+y)t}\,dt\,dy\\[0.3cm]
&=\int_0^\infty \int_0^\infty f(y)\,e^{-(x+y)t}\,dy\,dt\\[0.3cm]
&=\int_0^\infty e^{-xt}\int_0^\infty f(y)\,e^{-yt}\,dy\,dt\\[0.3cm]
&=\int_0^\infty e^{-xt}\,\mathscr L[f](t)\,dt\\[0.3cm]
&=\mathscr L[\mathscr L[f]](x).
\end{align}


text:
Q: Efficient Sparse Matrix-Vector Multiplication I'm trying to do matrix multiplication with a very large, but sparse matrix. I'm first mean centering the sparse matrix by subtracting the average row from each row. Then, I multiply this result to a vector. Is there some manipulation I can do to this expression to make it more efficient to calculate? I'm dealing with a very high dimensional matrix.
I'm reading into CSR representations of a sparse matrix, but I'm not sure how to compute the dot product efficiently in this representation.

A: Subtracting the mean would lose the sparsity. let's switch the order of operation around to take advantage of the sparseness.
Let $ A \in \mathbb{R}^{m \times n}$, you are computing $\left[A-e\left(\frac1{m}e^TA\right)\right]x$  where $e$ is the all one vector, $A$ is sparse and $x$ is an vector.
\begin{align}
\left[A-e\left(\frac1{m}e^TA\right)\right]x &= (I- \frac1m ee^T) (Ax)\\
&= (Ax) -  e\left(\frac1me^T(Ax)\right)
\end{align}


text:
Q: Why is my search box positioned differently in IE and Chrome? please take a look at my site here: http://utilitiessavings.co.uk
The search box at the top-right, in the nav bar is positioned differently in chrome and FF. I can't seem to find a way to change it to make it consistent. Obviously I want it to look like it does in ff in all browsers.
I expect this in IE, but not these two!
Thanks!

A: To this input
body.custom li form input {}

add
margin:0;

Altough chrome sets some user agent style as margin:0em seems like that doesn't affect the input.


text:
Q: Back navigation is broken with nested routes in a lazy-loaded module Angular 7 I have a lazy-loaded module which is loading another lazy-loaded module. In this module, I have nested routes. So when the user goes to the component in this module nested routes and activated but then there is no way to navigate back on click on browser's back button
I have figured out that after clicking on browser's back button it redirects to '' route in a nested routes and then goes to 'nested_route_1'.However, the logical behavior will be settings/lazy-module/nested_route_1 -> settings
const routes: Routes | any = [
  { path: '', component: MainComponent, children: [
    { path: 'nested_route_1', component: Component1 },
    { path: 'nested_route_2', component: Component2 },
    { path: 'nested_route_2', component: Component3 },
    { path: '', redirectTo: 'nested_route_1'},
  ] }
];

Code above is my routes in this lazy-loaded module. This module is loaded from settings module. After it is loaded the nested_route_1 is activated and the url is settings/lazy-module/nested_route_1,from this moment it is impossible to navigate back to settings. How to make it possible?enter code here


text:
Q: Make country default in form as "United States" I am trying to make the default value for the country input in a form to be "United States". I am using the simple form gem and country select gem.
In the simple form initializer, I set this default
  config.country_priority = [ "United States" ]

Which makes the topmost value correct as United States, but the default value is 'Uganda'.
In the _form view, I did the following:
<%= f.input :country, :default => [ 'United States' ] %>

I restarted Rails and it still defaulted to Uganda.
I also tried the following:
<%= f.input :country, :default => 'United States' %>

and
<%= f.input :country, :selected => 'United States' %>

What should I try next?

A: Try this,
<%= form.country_select :country, ["United States"] %>

A: I tried this with gem 'country_select' in simple-form. It's worked for me.
= f.input :country,  priority: [ "Brazil" ]

A: I know this is an old thread, but I just recently did this and thought I'd share to help others. I'm using Rails 4.2.0, country_select (2.1.1), and simple_form (3.1.0). This worked for me:
<%= f.input :country, selected: 'US' %>
If you want to prevent the user from changing the selection, use :disabled like so:
<%= f.input :country, selected: 'US', disabled: true %>
Just to clarify the :priority option in the other answers, that only gives that country higher priority (i.e. it will place the country at the top of the dropdown list), it doesn't actually select that country. Hope this is helpful.

A: Am using this and it works. Using formtastic gem, add below line.
          <% f.input :address_country, :as => :country, :priority_countries => ["United States", "United Kingdom","Australia", "New Zealand"] %>

Note: The countries inside the array are the priority countries which are displayed first before the entire global countries.

A: You need to use the country code instead of the country name:
<%= form.country_select :country, ["US"] %>

A: I ended up not using the gem -- too much complexity. I just created a constant COUNTRIES and used that instead.

A: You should only have to do:
<%= f.country_select("user", "country_name", [ "United States" ]) %>

Where user is the name of the model you are using.

A: I've just encountered this problem. It's working on 3fb63542c085148bcea73198037d37f15c6154d7 github revision of https://github.com/stefanpenner/country_select :
<%= f.country_select :country, selected: 'US' %>


text:
Q: Removing Facebook contact field from user contact not working I'm trying to unset the Facebook link for users who registered in the past 365 days. For users who have completed more than a year, don't unset.
Here's my code which is not working:
function modify_user_contact_methods( $user_contact ) {

    get_currentuserinfo();
        $user_data = get_userdata($user_ID);
        $registered_date = $user_data->user_registered;
        if (strtotime($registered_date) > strtotime('-365 days')){
             // Remove user contact methods
         unset( $user_contact['facebook']    );
        }

    return $user_contact;
}
add_filter( 'user_contactmethods', 'modify_user_contact_methods' );

It shows the field. If I remove the condition, it unsets for every user. So the set/unset is correct, only the 365 condition is wrong, I guess. But it seems correct, what amI doing wrong? Please guide.

A: Firs things first... always, always enable debugging. Secondly, you should accept the $user parameter in your callback - otherwise you are always checking the logged in user, not the user within the current context:
function modify_user_contact_methods( $methods, $user ) {
    if ( ! $user instanceof WP_User ) {
        if ( ! $user = wp_get_current_user() )
            return $methods;
    }

    if ( strtotime( $user->user_registered ) > strtotime( '1 year ago' ) ) {
         unset( $methods['facebook'] );
    }

    return $methods;
}

add_filter( 'user_contactmethods', 'modify_user_contact_methods', 10, 2 );


text:
Q: HTML 5 Video Not Showing / Playing in Android My HTML 5 video is shows up as a blank white screen in Android galaxy. Online search suggest removing "type" parameter and play via JS, but that does not seem to work.
I tried to recreate the issue with jsfiddle but I can't simulate a mobile device.
Any idea how to get mobile video to play on Android and iPhone? I've seen this done by Buzzfeed and the new york times so I know there is a safe way.

    <video preload="none" autoplay loop muted="true"class="video_window videos">
      <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4">
      <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm">
      <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">

        Your browser does not support the video tag.
    </video>

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum

$(window).scroll(function() {
  $('.videos').each(function(){
      if ($(this).is(":in-viewport")) {
         $(this)[0].play();
      } else {
         $(this)[0].pause();
      }
    })
});

.video_container{
    position: relative;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.video_captiont{
  position:absolute;
  margin:5px;
  z-index:100;
  font-size:21px;
  padding:3%;

}


text:
Q: JButton disappears when GUI is clicked I'm making checkers in java and the "New Game" button disappears when I click on the GUI. It reappears when I hover my mouse over it, but will disappear again if I click the GUI. Do you know what I did wrong/am doing incorrectly?
public void setFrame()
    {
        boardSize  = 10;
        squareSize = 50;
        int imageSize = boardSize * squareSize;
        image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
        imageIcon = new ImageIcon(image);
        jLabel = new JLabel(imageIcon);
        button = new JButton("New Game");
        button.setFocusable(false);
        button.setBounds(375, 5, 100, 20);
        pnl = new JPanel();
        pnl.setBounds(400, 10, 200, 100);
        pnl.setLayout(null);
        pnl.add(button);

        jFrame = new JFrame("Checker Board");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.add(jLabel, BorderLayout.CENTER);
        jFrame.add(pnl);
        jFrame.setSize(506, 558);
        jFrame.setResizable(false);
        jFrame.setLocationRelativeTo(null);
        jFrame.setVisible(true);

        jFrame.validate();
    }

    /**
     * Paint the checker board onto the Image.
     */
    public void paint()
    {
        Graphics graphics = jFrame.getGraphics();

        pnl.paint(graphics);
        button.paint(graphics);

        graphics.setColor(Color.black);
        Font font = new Font("Score", Font.BOLD, 20);
        graphics.setFont(font);
        graphics.drawString("Score: ", 150, 47);
        graphics.drawString("Turn: ", 20, 47);
        graphics.setFont(font.deriveFont(0, 16.0F));
        graphics.drawString("Red: " + Game.score.getScoreRed() + "    Black: " + Game.score.getScoreBlack(), 230, 47);
        graphics.drawString((Game.redTurn ? "Red" : "Black"), 80, 47);

        // paint a red  board
        graphics.setColor(Color.red);
        graphics.fillRect(xShift, zShift, boardSize * squareSize, boardSize * squareSize);

        // paint the black squares
        graphics.setColor(Color.black);
        for (int row = 0; row < boardSize; row++)
        {
            for (int col = row % 2; col < boardSize; col += 2)
            {
                graphics.fillRect( row * squareSize + xShift, col * squareSize + zShift, squareSize, squareSize );
            }
        }

        for(int i = 0; i < 10; i++)
        {
            for(int j = 0; j < 10; j++)
            {
                if(Game.board.pieces[i][j] != null)
                {
                    Color pieceColor = Game.board.pieces[i][j].getColor().equals(EnumTeam.BLACK) ? Color.gray : Color.pink;
                    graphics.setColor(pieceColor);
                    graphics.fillOval((i * 50) + 10 + xShift, (j * 50) + 10 + zShift, 30, 30);
                    if(Game.board.pieces[i][j].isKing())
                    {
                        pieceColor = Game.board.pieces[i][j].getColor().equals(EnumTeam.BLACK) ? Color.darkGray : Color.magenta;
                        graphics.setColor(pieceColor);
                        graphics.fillOval((i * 50) + 20 + xShift, (j * 50) + 20 + zShift, 10, 10);
                    }
                }
            }
        }

        graphics.setColor(Color.cyan);
        drawRect(graphics, Game.board.getSelectedX(), Game.board.getSelectedZ(), 5);
    }

A: Do not, ever use Graphics graphics = jFrame.getGraphics(); (or getGraphics generally)!  This is not how custom painting is done in Swing.  The mere fact that you'v then cleared the graphics context is your core problem.
All painting should be done within the context of the painting API, preferably by overriding paintComponent from any component that extends JComponent (I, personally, prefer JPanel)
Create a custom component and use it it perform you custom painting.  Layout it out with your other components on the frame.
Set Performing Custom Painting and  Painting in AWT and Swing for more details about how painting works in Swing.
A MouseListener is not really an appropriate listener to use for buttons, a better choice would be to use a ActionListener which takes into account mouse clicks and keyboard events...
See How to write an Action Listener and How to use buttons for more details...


text:
Q: How to assign the same data but changing column value conditionally in R I am trying to replace the values in a column based on certain condition and assign that data frame to another name. But every time i call the assigned name i get just the changed value , not the entire data. what am i missing here? I am a beginner, so cut me some slack :-)
test = data.frame(a=1:5,b=6:10,c=7:11)
replaced = test$b[test$b>7& test$b<=9]=0
replaced
#[1] 0

when i call replaced, why don't i get the whole data set?
thank you!

A: Just take a copy first and then replace:
test=data.frame(a=1:5,b=6:10,c=7:11)
replaced <- test
replaced$b[replaced$b > 7 & replaced$b <= 9] <- 0
replaced

#  a  b  c
#1 1  6  7
#2 2  7  8
#3 3  0  9
#4 4  0 10
#5 5 10 11

Your original issue is due to the assignments running right to left:
x <- y <- 0
x
#[1] 0
y
#[1] 0

Doing a single assignment is much faster than looping over each row too:
test2 <- test[rep(1:5,3e4),]
nrow(test2)
#[1] 150000

system.time({
  replaced <- test2
  replaced$b[replaced$b>7& replaced$b<=9] <- 0
})
#   user  system elapsed
#      0       0       0

system.time({
  i=1
  for ( i in 1:nrow(test2))
  {
    if(test2[i,]$b>7& test2[i,]$b<=9){
     test2[i,]$b=0
    }
  }
})
#   user  system elapsed
# 210.69    0.01  211.69

A: You could try something like this-
test=data.frame(a=1:5,b=6:10,c=7:11)

i=1
for ( i in 1:nrow(test))
{
  if(test[i,]$b>7& test[i,]$b<=9){
   test[i,]$b=0
  }
}

This would change values of b in the range of 8-9 to 0.


text:
Q: Adding headers to HTTP response when not returning a Response object in JAX-RS I am creating a REST service using CXF 3.1.4 and JAX-RS. I have created an interface that is shared between client and server:
public interface SubscriptionsService {

    @POST
    @Path("/subscriptions")
    SubscriptionResponse create(SubscriptionRequest request);
}

public class SubscriptionResponse {
    private String location;
}

The client is created using JAXRSClientFactoryBean and the server is created using JAXRSServerFactoryBean.
The create() method defined above should return a Location header but I have no idea how to do it.

A: Since you need to return a SubscriptionResponse object instead of a Response object, you can inject the HttpServletResponse in your JAX-RS enpoint class using the Context annotation and set the 201 status code and the Location header:
@Context
HttpServletResponse response;

@POST
@Path("/subscriptions")
public SubscriptionResponse create(SubscriptionRequest subscriptionRequest) {

    // Persist your subscripion to database

    SubscriptionResponse subscriptionResponse = ...
    URI createdUri = ...

    // Set HTTP code to "201 Created" and set the Location header
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setHeader("Location", createdUri.toString());

    return subscriptionResponse;
}

When returning a Response object, you can and use the Response API to add the Location header, as following:
@POST
@Path("/subscriptions")
public Response create(SubscriptionRequest subscriptionRequest) {

    // Persist your subscripion to database

    URI createdUri = ...
    return Response.created(createdUri).build();
}

For more details have a look at the Response.created(URI) method documentation.


text:
Q: How can I get the image url from IPFS info in React.js? I've gotten this IPFS info such as "/ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE" as API response.
I want to display this file(image) on my page, but I can't find out the correct solution.
How can I get the image URL from this info in react app?
Please help with my concern.

A: If you're using js-ipfs, you can retrieve the image over IPFS, and display it:
/** Uses `URL.createObjectURL` free returned ObjectURL with `URL.RevokeObjectURL` when done with it.
 *
 * @param {string} cid CID you want to retrieve
 * @param {string} mime mimetype of image
 * @param {number} limit size limit of image in bytes
 * @returns ObjectURL
 */
async function loadImgURL(cid, mime, limit) {
    if (cid == "" || cid == null || cid == undefined) {
        return;
    }
    const content = [];
    for await (const chunk of ipfs.cat(cid, {length:limit})) {
        content.push(chunk);
    }
    return URL.createObjectURL(new Blob(content, {type: mime}));
}

Then you can display it with something like:
<body>
<img id="myImage" />
<script>
async function setImage() {
    // just an example, make sure to free the resulting ObjectURL when you're done with it
    //
    // if your CID doesn't work, try this one: Qmcm32sVsMYhURY3gqH7vSQ76492t5Rfxb3vsWCb35gVme
    // that's a popular CID, which should resolve every time
    document.getElementById("myImage").src = await loadImgURL("QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE", "image/png", 524288);
}
setImage();
</script>
</body>

The big advantage of this is you're using the IPFS network itself, and not relying on a public HTTP gateway (the recommended way).

A: You can do something like that:
tokenURI.replace("ipfs://", "https://ipfs.io/ipfs/");

A: Try adding https://ipfs.io in the beginning of your ipfs info as suggested in this document https://docs.ipfs.io/concepts/what-is-ipfs/
i.e
ipfs://QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE

becomes
https://ipfs.io/ipfs/QmQqzMTavQgT4f4T5v6PWBp7XNKtoPmC9jvn12WPT3gkSE

A: One thing to note here about fetching images from IPFS that I think isn't being discussed sufficiently in these answers is that you will need to either

*

*Run your own node of IPFS, or

*Get a hosted IPFS node through a service like Infura

I have spent a little bit of time working through this in the last couple of days, and it will always come back to you having to have direct access to your own node.
There are "Gateways," which are nodes hosted by the community, and you can read more about them in the IPFS docs here: https://docs.ipfs.io/concepts/ipfs-gateway/#limitations-and-potential-workarounds
The thing with the gateways is that they are not meant to be relied upon for production sites, as you can see below. It's possible that there is some hosted node out there that somebody is giving out for free, but I doubt it, and you wouldn't want to rely on that anyways.
I think that other questions above have elaborated how you actually process the responses once you get it, but I wanted to cover this extra ground in my answer.
ipfs docs

A: let imgUrl = url?.slice(url.indexOf(":"),url?.lastIndexOf("/"));
let slice = url?.slice(url.lastIndexOf("/"),url?.length)
let renderURL = `https${imgUrl}.ipfs.dweb.link${slice}`;
console.log(renderURL);


text:
Q: Copiar vários registros para a mesma tabela com alteração de valores Possuo a seguinte query:
INSERT INTO tags group_tags, title, active
SELECT group_tags, title, active FROM tags WHERE group_tags = 2;

Primeiro
Como executar está query para cada registro da tabela que contenha group_tags = 2?

Segundo
Para cada novo registro, como definir o valor da group_tags para 1?

A: INSERT INTO tags (group_tags, title, active)
SELECT 1 as 'group_tags', title, active FROM tags WHERE group_tags = 2;

Execute apenas a segunda linha e veja se é o resultado esperado.

A: INSERT INTO tags (group_tags, title, active)
SELECT 1, title, active FROM tags WHERE group_tags = 2;

A: oi,
veja assim
INSERT INTO tags (1, title, active)
SELECT title, active FROM tags WHERE group_tags = 2;

A: Experimente da seguinte forma:
INSERT INTO tags(group_tags, title, active)
    with cte as (
        SELECT group_tags, title, active FROM tags WHERE group_tags = 2
    )
    SELECT  1, title, active FROM cte

A primeira parte
with cte as (
     SELECT group_tags, title, active FROM tags WHERE group_tags = 2
)

Cria um contexto diferente, como sendo outra consulta SQL.
SELECT  1, title, active FROM cte

Fará as alterações necessárias antes de inserir.


text:
Q: Git rebase -i not in terminal / only works with sudo I simply want to edit some commits with git rebase -i HEAD~2 inside the current branch.
I use Ubuntu 10.10 and had to install gvim first to make the command work.
Afterwards, the command opens a gvim window with the normal rebase content.
But when I want to save the file gvim says

".git/rebase-merge/git-rebase-todo" E212

[Cannot open file to write]
Also the rebase command finishes right after starting (with Successfully rebased and updated refs/heads/master.).

*

*When doing the same command with sudo the rebase works, but afterwards it occurs that files are owned by root and I have no write permissions anymore.

*On my ArchLinux system gvim is opened directly in the terminal where I run git rebase -i and everything works.

*I tried different terminals (Gnome terminal, LXTerminal, XTerm) - always the same problem

What is the problem here and how to solve it? It should work without sudo.
Edit 1

*

*Some files in .git/... are owned by root and are read-only. All directories and files in the first level of .git/ are owned by me. With ls -l --recursive .git/ | grep root I tried to detect which files that are but the output does not give the paths of the files...

*Should all files in .git/ belong to the user? May this be the reason for the problem?

EDIT 2

*

*Even after changing ownership and write permissions of all files inside .git to user with sudo chown -R user:user .git/ and chmod u+w -R .git/ (ls -l now shows sth. like -rw-r--r-- 1 user user) the problem stays the same.

A: My solution was:
Run
$ git config --global core.editor "gvim -f"

First, I thought it was because my repository was on an ntfs drive so the file permissions wouldn´t work correctly. But even after mounting the drive with correct file permissions the problem stayed the same. Starting vim with the -f option helps (I read about other people solving it the same way), but I don´t know why.

A: Do a sudo chown -R user .git to giver user back ownership of the files.  You shouldn't ever need to run git with sudo, as doing so can result in problems like this.

A: I have this same problem. changing the permissions in the folder does not eliminate the problem
In my case it is because the umask is set 27 which by default creates files with
-rw-r-----
permissions,
Obviously git tires to create a directory which can't be saved by the user.
This is therefore a bug in git.
Note: I noticed that using the editor vim gets around this bug.
It seems that gedit and kate have problems with the permissions.

A: I'm using  spf13 conf and I solved the issue with following steps:
rm -rf ~/.vimswap
rm -rf ~/.vimviews
rm -rf ~/.vimbackup

It seems that your some rebase process had been broken and remove these dirs can recover it.


text:
Q: Windows Form Components Access What is the best way to access components (e.g. imagelist, timer) from a form instance? I am working on multi form windows forms application on .NET Compact Framework version 3.5 SP1 with C#. I have a Controller class associated with each form for MVC implementation. Here is my sample Controller class.
public class Controller
{
      public void Init(Form f)
      {
            //f.Controls will allow access to all controls
            //How shall I access imagelist, timer on form f.
      }
}

My question is how can I access non visual components without taking a performance hit of reflection? Any code snippets are welcome. If reflection is only way, then can you provide me optimal way for components access please?
Thanks,

A: You should be passing a strongly typed form or interface implementation which either exposes the controls directly (not the preferred choice) or abstracts the operations on the view into methods/properties which can be called from the controller (the preferred choice).

A: No, reflection is not the way. In terms of simply accomplishing what you're going for, you can expose a read-only property that returns the control. For example, say you have an ImageList named imageList1 on your form:
public ImageList ImageList
{
    get { return imageList1; }
}

You can then access the ImageList property to get a reference to imageList1.
HOWEVER
This is smelly code. What you should expose is properties and functions that relate to what you need to DO with the ImageList. Your external code should not care about the particular implementation on your form (in other words, it should know you need to do something with images and provide functions to accomplish those actions; it shouldn't need to know that it's an ImageList control).


text:
Q: How to transfer Pan Gesture Recognizer from one view to other? i have a button which can record voice message. After longpress I create a new view where i can move another button. But pan gesture recognizer doesn't work without tapping again. So could you tell me how to transfer gesture recognizer from one button to another?
So there is 2 methods that i want to use.
 @objc func recordTapped(sender: UILongPressGestureRecognizer){
    textInput.isHidden = true

    self.view.addSubview(audioPlayerView)
    audioPlayerView.setAudioPlayer()

    timer =  Timer.scheduledTimer(timeInterval: 0.0, target: self, selector: #selector(updateTimer), userInfo: NSDate(), repeats: true)
    startRecording()

    self.area.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 0.7026969178)

    UIView.animate(withDuration: 2.0, delay: 0, options: [.repeat, .autoreverse], animations: {
        self.area.backgroundColor = #colorLiteral(red: 0, green: 0.1071770917, blue: 0.3669734589, alpha: 0.6900149829)

    }, completion: { (success) in

    })

    buttonToPlayAudio.isHidden = false
    addImageButton.isHidden = true
}

and the second gesture is for new view
 @objc func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
    //this method i want to call from previous button
}

A: You need to add gesture recognizer to common parent view. When it's called, check if finger is inside the target button. Then add views, and when user releases the finger, check where it happens.


text:
Q: Join 2 JSON objects I have two objects:
o1 = {
    v1: 10,
    v2: 20
}

o2 = {
    v1: 50,
    v2: 60
}

I want:
newO = {
    o1: {
        v1: 10,
        v2: 20
    },
    o2: {
        v1: 50,
        v2: 60
    }
}

I do this and it works, but I am concerned that phpStorn is complaining about syntax (shorthand property names are not supported by the JavaScript version).
newO = {o1, o1};

I tried using jQuery but it returns just the second object withing the new object.
var newO = {};
$.extend(newO, o1, o2);

But I get back newO = o2
What is the correct way of joining / concatenating the two objects? Did I misunderstand the $.extend function? Thanks

A: If you have two objects and you want to merge them than you need to create new object and them into a new object

o1 = {
    v1: 10,
    v2: 20
}

o2 = {
    v3: 50,
    v4: 60
}

var str2 = {}
str2.v5 = o1;
str2.v6 = o2;

console.log(str2)

like this.

A:

o1 = {v1: 10,v2: 20};
o2 = {v1: 50,v2: 60};

var newobj={o1, o2}
console.log(newobj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: js-routes ASP.NET MVC alternative So, I have been tasked with rewriting a prototype ruby app back-end to .NET, and have stumbled onto a gem called js-routes.  You can read about this here: https://github.com/railsware/js-routes/
This gem appears to generate JavaScript objects for all the routes that were defined in the ruby app.  I need to see if there is something that is similar in the ASP.NET MVC world.

A: You can check these options:
ASP.NET MVC JavaScript Routing
JsAction


text:
Q: How to connect to redis cache via redis URL using StackExchange.Redis? Currently, I am using ServiceStack.Redis to connect to Redis Cache server. The redis cache URL structure is like: redis://f:UIOPabcdXYZ@ip-172-31-81-144.manager.{domain}.io:33004
Below is a sample code to connect to Redis Cache using ServiceStack.Redis
var redisClientManagerPool = new RedisManagerPool(ConfigManager.RedisCacheUrl);

using (var client = redisClientManagerPool.GetClient())
{
    //SetClientData(key, client, data);
}

But the free version has certain restrictions and once it reaches the limit, it gives error like

The free-quota limit on '6000 Redis requests per hour' has been
  reached. Please see https://servicestack.net to upgrade to a
  commercial license or visit https://github.com/ServiceStackV3/ServiceStackV3 to
  revert back to the free ServiceStack v3

I want to use StackExchange.Redis to connect to redis cache. But I didn't get any code reference how to use the redis URL from https://stackexchange.github.io/StackExchange.Redis/Basics .
I am looking for any code reference to use redis cache URL like redis://f:UIOPabcdXYZ@ip-172-31-81-144.manager.domain.io:33004 to connect to redis cache server by using StackExchange.Redis nuget. Any help is appreciated.
Note: The current used library is .NET Standard 2.0 version of ServiceStack.Redis. The nuget name is ServiceStack.Redis.Core version 5.7.0.

A: The StackExchange.Redis worked for redis://f:UIOPabcdXYZ@ip-172-31-81-144.manager.{domain}.io:33004 URL format. Below is the code reference:
var url = "redis://f:UIOPabcdXYZ@ip-172-31-81-144.manager.{domain}.io:33004";
var urlParts = url.Split("@ip-");
var password = urlParts[0].Split("redis://f:")[1].Trim();
var host = "ip-" + urlParts[1].Split(":")[0].Trim();
var port = int.Parse(urlParts[1].Split(":")[1].Trim());
var redisConfigurationOptions = new ConfigurationOptions
{
    AllowAdmin = false,
    Ssl = false,
    Password = password,
    EndPoints = {
                    {  host, port }
                }
};

var conn = ConnectionMultiplexer.Connect(redisConfigurationOptions);
var client = conn.GetDatabase();
client.StringSet(cacheKey, Newtonsoft.Json.JsonConvert.SerializeObject(data), TimeSpan.FromMinutes(30));

//To retrieve data
if (client.KeyExists(cacheKey))
{
   var outputString = client.StringGet(cacheKey).ToString();
}
else
{
  //cacheKey doesn't exists
}


text:
Q: Looking for tighter bounds on a certain solution of a nonlinear equation I have to solve an equation which is $$\sum_{i=1}^N x_i = \sum_{i=1}^N y_i,$$ where
$$x_i = \frac{z_i}{1 + (K_i - 1) w}$$  and $$y_i = \frac{K_i z_i}{1 + (K_i - 1) w}.$$
The $z_i$ are all positive and add to $1$; the $K_i$ are positive but range from very small to very large (at least, one is strictly greater than $1$ and one is strictly smaller than $1$).
The solution ($w$) looked for is between two vertical asymptotes corresponding to $-1 / (K_{\text{max}} - 1)$ (which is negative) and $1 / (1 - K_{\text{min}})$ (which is greater than $1$). Considering the fact that, at solution, all $x_i$ and $y_i$ must be positive and smaller than $1$ (since they both must add to $1$), I have been able to find a left bound corresponding to the maximum value of $\dfrac{K_i z_i - 1}{K_i-1}$ (considering only the $K_i > 1$) and a right bound corresponding to the minimum value of $\dfrac{1 - z_i}{1 - K_i}$ (considering only the $K_i < 1$). These bounds are inside the asymptotes but I need a tighter interval.
I have not been able to go further. Any help will be more than welcome.

A: The equation rewrites as
$$\sum_{i=1}^N \frac{(K_i-1)z_i}{1+(K_i-1)w}=0,$$
or with $a_i=1/(1-K_i)$,
\begin{equation}
\sum_{i=1}^N\frac{z_i}{w-a_i}=0.
\end{equation}
Let $Q(w)$ be the monic polynomial of degree $N$ with roots the $a_i$'s, and $P(w)$ some polynomial of degree $N-1$. Assuming all the $a_i$'s are distinct, we have
$$\frac{P(w)}{Q(w)}=\sum_{i=1}^N\frac{P(a_i)}{Q'(a_i)}\frac{1}{w-a_i}.$$
If we choose $P(w)$ as the unique interpolating polynomial such that
$$P(a_i)=z_iQ'(a_i),\qquad i=1,\ldots,N,$$
the equation simply becomes
$$P(w)=0,$$
which has exactly $N-1$ roots. Assume that $$0<K_{1}<\cdots K_i<1<K_{i+1}<\cdots<K_N$$
so that
$$a_{i+1}<\cdots<a_N<0<a_1<\cdots<a_i.$$
Since, by assumption, the $z_i$'s are positive, the signs of the $P(a_{i+1}), P(a_{i+2}),\ldots,P(a_i)$ alternate and thus each of the intervals $(a_{i+1},a_{i+2}),\ldots,(a_{i-1},a_i)$ contains exactly one root of the equation. A lower bound for the smallest root is $a_{i+1}=1/(1-K_{i+1})$, and an upper bound for the largest root is $a_i=1/(1-K_i)$.


text:
Q: IIFE in JS using for fetch data I'm trying to write a function, which would be pull data in array, and then print them into condole. For right work for loop i'm using IIFE function for retrive all data consistently, but code not work correctly. Result is empty array: []. I think that my trouble due to the incorrect IIFE which i made. How I can fix this bug?
var url = [
  'http://www.json-generator.com/api/json/get/cevhxOsZnS',
  'http://www.json-generator.com/api/json/get/cguaPsRxAi',
  'http://www.json-generator.com/api/json/get/cfDZdmxnDm',
  'http://www.json-generator.com/api/json/get/cfDZdmxnDm',
  'http://www.json-generator.com/api/json/get/cfDZdmxnDm'
]

function fetchData(arg) {
  var urls = Array.isArray(arg) ? arg : [...arguments]
  var arr = [];
  for (var i = 0; urls.length < i; i++) {
    (function (i) {
      fetch(urls[i])
        .then(res => res.json())
        .then(res => arr.push(res))
    })(i)
  }
  return arr;
}

console.log(fetchData(...url))   // printed empty array: []


text:
Q: Java 8 - content is not allowed in prolong I have tried all the answers related to this parse error but none worked.
Here is the issue am facing:
org.xml.sax,SAXParseException; lineNumber : 1 ; columnNumber: 1 ; Content is not allowed in prolong
SaxparserImpl.parse(unknown source)
Am using jaxp-api.jar, xml is retrieved from database and while parsing, it throws exception.
There is no extra characters or white space before the start of xml.
Jdk is 1.8
Issue resolved: since my project is related to migration, I have updated the ojdbc jar from ojdbc14 to ojdbc7. So, after retrieving xml type value from DB, in ojdbc14 OracleTypes.OPAQUE is used to convert xml to string. But in ojdbc7, OracleTypes.SQLXML is equivalent for conversion. Hence I have implemented accordingly and code worked happily. Thanks everyone for your valuable thoughts.


text:
Q: Value collectAsMap is not a member of org.apache.spark.sql.Dataset[(Any, Any)] I'm trying to use collectmap() in the following statement but getting the below error.
val Comic_Titles=comics_df.map(array => (array(0), array(1))).collectAsMap()

error: value collectAsMap is not a member of org.apache.spark.sql.Dataset[(Any, Any)]
Any idea how I can turn this into a map?

A: collctAsMap is part of PairRDDFunctions, i.e. it is only available to RDD of 2-Tuples:
val Comic_Titles=comics_df.map(array => (array(0), array(1))).rdd.collectAsMap()

What you can do in Dataset API is
val Comic_Titles=comics_df.map(array => (array(0), array(1))).collect().toMap


text:
Q: Actionscript 3: How do I create a dynamic import statement? I have a file structure that specifies the weapon type ["Axe","Mace","Staff",Sword"], and I want to import a specific .as file from within that folder, depending on the value of a variable (Group).
What i'd like to do is something like this:
Weapon.[Group].Enchantments (obviously not exactly that; that doesn't work)
For example, if Group = "Axe";
I want to import Weapon.Axe.Enchantments.
But if Group = "Mace";
I want to import Weapon.Mace.Enchantments.
Is this possible with AS3, without creating a bunch of if statements or a switch, and handling them accordingly?
package Weapons {

public class Weapon {
    import Math.random;
    import Math.floor;
    import Weapons.*;

    public var groups:Array = ["Axe","Mace","Staff","Sword"];

    public var Group:String;
    public var Quality:Object;
    public var Enchantment:Object;
    public var Material:Object;
    public var Type:Object;
    public var Profession:Object;

    public function Weapon() {
        // constructor code
        Group = Math.floor(Math.random*groups.length);
        var i:Number;
        Enchantment = Weapons.[Group].Enchantments[i]
    }

}

}
Thanks in advance.

A: The import keyword is only use for the compilation of your project, you cannot use the import at runtime. You can dynamicly instantiate your class at runtime by using ApplicationDomain for that.
var myClass:Class = ApplicationDomain.currentDomaint.getClassDefinition("com.package.YourClass");
var myWeapon:Weapon = new myClass() as Weapon;

But I don't think you really need that. Normally the "Axe","Mace","Staff","Sword" classes should extend Weapon class. You can use the Factory Design Pattern to get the right class with string.
http://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29

A: The easiest way to achieve desired effect is to have Array of Classes, not Strings.
The best way would be, as Nambew wrote, to have Factory.


text:
Q: Zend Db Table Abstract add new field to the row I once posted this question, but had no answer at all, this time, the question is best formated so It will be more easy to understand what I need.
I created a Model with Zend_Db_Table_Abstract
Add the primaryKey and the table name, all ok.
Then, I executed the code to retrieve the fonts.
$db = new App_Model_News();

$news = $db->fetchAll("visible = 1", "published_on DESC");

foreach ($news as $i => $new) {

    $images = $this->_helper->News->first_image($new);

}

This method works, but I need to retrieve two view statements:
$this->view->news = $news;
$this->view->images = $images;

What I need is to merge this two results, doing something like this.
$db = new App_Model_News();

$news = $db->fetchAll("visible = 1", "published_on DESC");

foreach ($news as $i => $new) {

    $news[$i]->images = $this->_helper->News->first_image($new);

}
$this->view->news = $news;

I'm not able to do it, because the Abstract is array associative, my Model is like this:
class App_Model_News extends Zend_Db_Table_Abstract{

    protected $_name = 'news';
    protected $_primary = 'id';

    protected $_dependentTables = array('ImagesNews');

}

class ImagesNews extends Zend_Db_Table_Abstract{

    protected $_name = 'news_imagens';
    protected $_primary = 'id_new';

    protected $_referenceMap    = array(
        'Arquivos' => array(
            'columns'           => 'id_new',
            'refTableClass'     => 'App_Model_News',
            'refColumns'        => 'id'
        ));
}

Is there any way to add the images inside the news rows? Then at the view I could loop and print the images.
Thanks and best regard's.
Sorry for my bad english.

A: I think that what you could do is to create your own custom News row class:
class App_Model_Row_News extends Zend_Db_Table_Row_Abstract {
     public $images;
}

Then you would tell App_Model_News to use the custom row class:
class App_Model_News extends Zend_Db_Table_Abstract{

    protected $_name = 'news';
    protected $_primary = 'id';
    protected $_rowClass = 'App_Model_Row_News';

    protected $_dependentTables = array('ImagesNews');

}

Hope this helps.