text:
Q: How to upload Video from computer in CMS Page in magento-1.9? I am trying to upload video in CMS Page and static block, but video is not uploaded. I recheck the video format i.e. Mp4 . Please tell me how to upload a video in CMS Page?
Thanks in advance.

A: You have to create a module that edits the configuration you find at app/code/core/Mage/Cms/etc/config.xml on line 123.
you have to create a new module for example Himani_Video that contains the following xml:
<config>
    <modules>
        <Himani_Video>
            <version>0.0.1</version>
        </Himani_Video>
    </modules>
    <adminhtml>
        <cms>
            <browser>
                <extensions>
                    <media_allowed>
                        <mp4>1</mp4>
                    </media_allowed>
                </extensions>
            </browser>
        </cms>
    </adminhtml>
</config>

This will allow you to upload mp4 videos from the backend:


text:
Q: C++: function to append file, called within other functions So, I am trying to log information about the status of the c++ project code in a text file. The program terminates unexpectedly, so I need to append the file as I go rather than storing info in an array along the way. I wanted to call the function to write to the file from within other functions, eventually in the other c++ files as well.
The code is a huge project that has many files and the "main()" technically exists in a separate file from all of the functions that are called throughout the function of the code (therefore not a useful file for me). My plan was to open the file in the setup() function, and then call the function within other functions along the way. Just in case I did not explain the setup of the code well enough, here is the link to the file I am trying to add to: https://github.com/cstracq2/ardupilot/blob/master/ArduCopter/ArduCopter.cpp
I have seen other notes on what may help, but I am not that familiar with c++ and I don't know what most of it means. From what I saw, this is one of the ways I tried, and it is failing to compile.
#include "<existing header>.h"
#include <fstream>
#include <iostream>

void log_data( ofstream &datafile, int value);

void <>::function1()
{ ....<stuff that was already there>
    log_data( datafile, <value> );
}

void <>::function2()
{ ....<stuff that was already there>
    log_data( datafile, <value> );
}

void setup()
{ ....<stuff that was already there>
    ofstream datafile;
    datafile.open("data_log_file.txt");
}

void log_data( ofstream &datafile, int value)
{
    data_file << value << endl;
}

If there is any advice that you could give me, I would really appreciate it.

A: In your case I would suggest to use the Singleton Pattern. Here is an example of how you could do it:
class Logger
{
    std::ifstream logF;
    static Logger *s_instance;
    Logger(std::string &path)
    {
        logF.open(path, std::ios_base::in);
    }
public:
    void log_data(int val)
    {
        logF << val << std::endl;
    }

    static void create_instance(std::string &path)
    {
        s_instance = new Logger(path);
    }
    static Logger *instance()
    {
        return s_instance;
    }
};

Now you can just include the header with the class def and call something like:
Logger::instance()->log_data(<value>);

And do not forget to init the class before calling the static method (somewhere in main for instance):
Logger::create_instance(<path>);

Of course, you can just make it easier by hard-coding a value for your path, but if the path changes you'll have to re-compile everything.
Or just use something already implemented like log4cpp

A: Ah yes now that you mentioned the use of datafile in other function I see the error: The variable datafile is a local variable inside the setup function.
It should either be a member variable or possible a global variable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: communicating between classes with pointers Hi all,
I'm having a hard time understanding how to use pointers
(my first time using them) hoping someone can point me in the right
direction (no pun intended) :P
(it controls the sound,pagenumber,bg,audio int, and text to be displayed)
(NSString *)textFromPlist pointer which points to the plist containing the text for @"Page01Text"
I want to take @"Page01Text" and use it in the HighLighter class
I am able to log the output for the sound,pagenumber,bg,audio int, and text etc in the hello world layer (its logging the TextManagerWithpageNum) so I know that the plist is reading,
but for some reason I cant link textFromPlist  I'd like to be able to use the textFromPlist from the TextManagerWithpageNum class and let the hilighter class work with it (this class will hilight the text and work with the audio intervals supplied by the plist)
this piece of code it returns (NULL)
    @interface HighLighter.h

    TextManagerWithpageNum *myClassAccess;
    //declaring the TextManagerWithpageNum class so I can access textFromPlist

    @implementation HighLighter.m
     -(NSString *)Sentance01
    {
    NSString *textFromTextManager = myClassAccess.textFromPlist;
    NSString *storyText = [NSString stringWithFormat:@"%@",textFromTextManager];
        return [[[NSString alloc]initWithString:StoryText]autorelease];
        //doesn't crash but doesn't load text

    NSLog(@"text form plist @%",storyText);

    }

What is it that I am doing wrong? (I have an int array I also wish to link, but thought I'd start with the NSString as I thought this would be simpler.)
any help would be wonderful, kind regards,
Natalie.
    @interface TextManagerWithpageNum : CCLayer
    NSString* textFromPlist_Pntr;
    @property(nonatomic, readonly) NSString* textFromPlist;
   //NSString* textFromPlist is an item on the plist  @"page01"  which contains text for  the page

   @property(nonatomic, readonly) NSString* audioInterval;
   //NSString* AudioInterval is an array on the plist  @"AudioTimings_PG01"

   @implementation TextManagerWithpageNum
   @synthesize textFromPlist = textFromPlist_Pntr;
   @synthesize audioInterval = _audioInterval;

A: There are a couple of options when communicating any data between classes.  I will show both, using an example SomeData object that is being sent from ObjectA to ObjectB.  You can also use class level methods to, for example, send or receive data in a pointer to a singleton object.  I won't show you how to do that because it doesn't sound like that fits your problem.
Option 1
Define a receiving message in ObjectB.
@interface ObjectA
{
    SomeData *someDataPointer;
    ObjectB *someObjectB;
}
@end

@implementation ObjectA

-(void)someMethod
{
    someDataPointer = [[SomeData alloc] init]; // Or whatever way you want to create and set someDataPointer
    [someObjectB receiveData:someDataPointer];

    // Note: if you will be calling receiveData on someObjectB much later than the
    //    time of creation of someDataPointer, you should retain someDataPointer to
    //    hold onto it until you need to pass it on.
    //    ie)
    // [someDataPointer retain];
}

@end

@interface ObjectB
-(void)receiveData:(SomeData *)dataPtr;
@end

@implementation ObjectB

-(void)receiveData(SomeData *)dataPtr
{
    // Here the data from someDataPointer will also be pointed to by dataPtr
    // Use dataPtr now
    [self doSomethingWithData:dataPtr];
}

@end

Option 2
Define a sending message in ObjectA.
@interface ObjectA
{
    SomeData *someDataPointer;
}

@property (nonatomic, retain) SomeData *someDataPointer;

@end

@implementation ObjectA
@synthesize someDataPointer = someDataPointer_;
@end

@interface ObjectB
{
    ObjectA *someObjectA;
}
@end

@implementation ObjectB

-(void)someMethod
{
    SomeData *dataPtr = [someObjectA getSomeDataPointer];
    // Now do something with dataPtr
}

@end

I hope that helps.  I wanted to show you these two techniques generally so that you can learn to apply it to your case specifically.  Let me know if you have questions.


text:
Q: Relationship between 2 tables with a relationship table I have 3 tables like the following diagram:
https://i.imgur.com/zL7ouGu.png
I created a relationship table between users and organizations
I would like to retrieve a collection with the list of organizations for each user.
Currently I am getting a collection in which a user comes back several times.
Collection {#226 ▼
  #items: array:4 [▼
    0 => {#232 ▼
      +"name": "GotExx"
      +"avatar_path": "gotexx.jpg"
      +"orga-name": "My orga 1"
      +"slug": "my-orga-1"
      +"orga-avatar": "myorga1_logo.png"
    }
    1 => {#228 ▼
      +"name": "GotExx"
      +"avatar_path": "gotexx.jpg"
      +"orga-name": "My orga 2"
      +"slug": "my-orga-2"
      +"orga-avatar": "myorga2_logo.png"
    }
    2 => {#234 ▼
      +"name": "GotExx"
      +"avatar_path": "gotexx.jpg"
      +"orga-name": "My orga 3"
      +"slug": "my-orga-3"
      +"orga-avatar": "myorga3_logo.png"
    }
    3 => {#233 ▼
      +"name": "root"
      +"avatar_path": null
      +"orga-name": "My orga 2"
      +"slug": "my-orga-2"
      +"orga-avatar": "myorga2_logo.png"
    }
  ]
}

select users.name, users.avatar_path, organizations.name, organizations.slug, organizations.avatar_path
from relation_organization
right join users on relation_organization.user_id = users.id
left join organizations on relation_organization.organization_id = organizations.id

ideally I would like to get this:
Collection {#226 ▼
  #items: array:2 [▼
    0 => {#232 ▼
      +"name": "GotExx"
      +"avatar_path": "gotexx.jpg"
      +"organizations" => {
        0 => {
          +"orga-name": "My orga 1"
          +"slug": "my-orga-1"
          +"orga-avatar": "myorga1_logo.png"
        }
        1 => {
          +"orga-name": "My orga 2"
          +"slug": "my-orga-2"
          +"orga-avatar": "myorga2_logo.png"
        }
        2 => {
          +"orga-name": "My orga 3"
          +"slug": "my-orga-3"
          +"orga-avatar": "myorga3_logo.png"
        }
      }
    }
    1 => {#232 ▼
      +"name": "root"
      +"avatar_path": "null"
      +"organizations" => {
        0 => {
          +"orga-name": "My orga 2"
          +"slug": "my-orga-2"
          +"orga-avatar": "myorga2_logo.png"
        }
      }
    }
  ]
}

A: This is where Laravel really shines with relationships.  Pull your users with an eager load with organizations all in one query.  e.g.
$users = User::with('organizations')->get().

Your $users will now have all users in the system, with their attached organizations, listed one time per user, as your question asks for.
If you want to limit the fields drawn as you had in your SQL, you can use select:
$users = User::select('avatar_path', 'name')->with(['organizations' => function($query){
      $query->select('name', 'slug', 'avatar_path );
}])->get().

This all assumes you have the organizations relationship set up correctly on your Users model.

A: Laravel preferred way.

*

*Create models.

*Define relationships.

*Use eager loading when retrieving data.

Creating models and relationships.
User model
public class User extends Model
{
    public function organizations()
    {
        return $this->belongsToMany(Organization::class);
    }
}

Organization model
public class Organization extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

Using eager loading when fetching.
Controller function
$usersWithOrganizations = User::with('organizations')->get();


text:
Q: Как равномерно распределить нагрузку на ядра? у нас есть несколько ядер на сервере, все они используются для показа баннеров. Я хочу распределить нагрузку на эти ядра равномерно.
Например мы хотим показать 1000 баннеров и имеем 10 ядер, а значит каждое ядро должно показать 100 баннеров.
! Я пробовал разделить количество необходимо показываемых баннеров на количество активных ядер. Однако столкнулся с некоторыми проблемами:
? Что если мы хотим показать 3 баннера, а свободных ядер у нас 10, значит нужно дать по одному баннеру на 3 ядра, а не по 0.3 баннера на 10 ядер.
? Что если мы хотим показать 4 баннера, а свободных ядер у нас 3,  значит мы должны одному ядру дать два баннера, а остальным по одному.
Что вы мне посоветуете?


text:
Q: Divide a set by other set in all possible variations Imagine we have a set S = [a,b,c,d,e,f]. And we have a set N = [1,2,3].
How can we assign elements of S to elements of N in all possible combinations?
The desired result will hold something like this:

*

*[1,[a]], [2,[b,c]], [3,[d,e,f]].

*[1,[a]], [2,[b,c,d]],[3,[e,f]].

*etc.

Is it a powerset generation problem or anything else? How can I find its complexity and space complexity?
How can I generate those subsets?

A: This problem is related to the powerset generation. You will get |N|^|S| possible mappings.


text:
Q: find an orthogonal basis for the space of solutions of the following equations Q.find an orthogonal basis for the space of solutions of the following equations
2x+y-z=0
y+z=0
How select solution? And how solve this question? ?

A: As I see, you have a intersection of two plans which is the solution of $\{2x+y-z=0,~y+z=0\}$. First solve it to find the solution: $$X= \left( \begin{array}{ccc}
z \\
-z \\
z  \end{array} \right)=z\left( \begin{array}{ccc}
1 \\
-1 \\
1  \end{array} \right)$$ Now you have a requested vector.


text:
Q: iText7 reading out lines in a wrong order Im trying to read out an pdf document table but im facing an issue.
If i open the PDF regularly
It shows as:
item[tab]item[tab]item[tab]item[tab]item
item[tab]item[tab]item[tab]item[tab]item
item[tab]item[tab]item[tab]item[tab]item

Reference
I convert a PDF using:
StringBuilder result = new StringBuilder();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC));

LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();

PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy);
for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
{
    result.AppendLine("INFO_START_PAGE");
    string output = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(i));
    /*Note, in the GetTextFromPage i replaced the method to output [tab] instead of a regular space on
    big spaces*/
    foreach(string data in output.Replace("\r\n", "\n").Replace("\n", "×").Split('×'))
    {
        result.AppendLine(data.Trim().Replace("   ", "[tab]"));
    }

    result.AppendLine("INFO_END_PAGE");
}

pdfDoc.Close();
return result.ToString();

When i try to read this out using Pdf to Text convertion in some cases it reads as:
item[tab]item[tab]item[tab]item[tab]item
item[tab]item[tab]item[tab]
item[tab]item
item[tab]item[tab]item[tab]item[tab]item

Is there a way to fix this issue?

A:
is extracted as
Artikelnr. Omschrijving Aantal
Per stuk Kosten
VERHUUR L. GELEVERDE ARBEID PDC 8 € 43,70 € 349,60
VERHUUR O. GELEVERDE ARBEID PDC 3 € 60,95 € 182,85
VERHUUR L.L. GELEVERDE ARBEID EM 24
€ 32,20 € 772,80

First off, why does it happen
As conjectured in the comments to the question, there indeed is a small vertical step, in all rows the first three columns are set at the same vertical position and the vertical position of the last two columns differs slightly,
    Row       First columns y   Last columns y
Heading row               536          535.893
First row                 516          516.229
Second row                495          495.478
Third row                 475          474.788

One recognizes in particular that the rows broken by text extraction are those in which the pre-decimal point digits of the y positions differ (536 vs 535, 475 vs 474) while those with equal pre-decimal point digits are not broken.
The reason for this is that the class TextChunkLocationDefaultImp (which by default is used to store text chunk locations and methods to compare such locations) stores the y position of a chunk (actually an abstraction of it also working for text not written horizontally) in an integer variable (private readonly int distPerpendicular) and in the test method SameLine requires equality of the distPerpendicular values.
namespace iText.Kernel.Pdf.Canvas.Parser.Listener {
    internal class TextChunkLocationDefaultImp : ITextChunkLocation {
        ...
        /// <summary>Perpendicular distance to the orientation unit vector (i.e. the Y position in an unrotated coordinate system).
        ///     </summary>
        /// <remarks>
        /// Perpendicular distance to the orientation unit vector (i.e. the Y position in an unrotated coordinate system).
        /// We round to the nearest integer to handle the fuzziness of comparing floats.
        /// </remarks>
        private readonly int distPerpendicular;
        ...
        /// <param name="as">the location to compare to</param>
        /// <returns>true is this location is on the the same line as the other</returns>
        public virtual bool SameLine(ITextChunkLocation @as) {
            ...
            float distPerpendicularDiff = DistPerpendicular() - @as.DistPerpendicular();
            if (distPerpendicularDiff == 0) {
                return true;
            }
            ...
        }
        ...
    }
}

(Actually SameLine further down allows a small deviation if one of the compared text chunks has a zero length. Apparently chunks with zero length sometimes are used for diacritical marks, and such marks sometimes are applied at different heights. This is of no concern in your example file, though.)
How to fix it
As we've seen above, the problem is due to the behavior of TextChunkLocationDefaultImp.SameLine. Thus, we have to change this behavior. Usually, though, we don't want to change the code of the iText classes themselves.
Fortunately, the LocationTextExtractionStrategy has a constructor that allows to inject an ITextChunkLocationStrategy implementation, i.e. a factory object for ITextChunkLocation instances.
Thus, for our task we have to write an alternative ITextChunkLocation implementation which is not so strict, and an ITextChunkLocationStrategy implementation that generates instances of our ITextChunkLocation implementation.
Unfortunately, though, TextChunkLocationDefaultImp is internal to iText and has numerous private variables. Thus, we cannot simply derive our implementation from it but have to copy and paste it as a whole and apply our changes to that copy.
Thus,
class LaxTextChunkLocationStrategy : LocationTextExtractionStrategy.ITextChunkLocationStrategy
{
    public LaxTextChunkLocationStrategy()
    {
    }

    public virtual ITextChunkLocation CreateLocation(TextRenderInfo renderInfo, LineSegment baseline)
    {
        return new TextChunkLocationLaxImp(baseline.GetStartPoint(), baseline.GetEndPoint(), renderInfo.GetSingleSpaceWidth());
    }
}

class TextChunkLocationLaxImp : ITextChunkLocation
{
    private const float DIACRITICAL_MARKS_ALLOWED_VERTICAL_DEVIATION = 2;
    private readonly Vector startLocation;
    private readonly Vector endLocation;
    private readonly Vector orientationVector;
    private readonly int orientationMagnitude;
    private readonly int distPerpendicular;
    private readonly float distParallelStart;
    private readonly float distParallelEnd;
    private readonly float charSpaceWidth;

    public TextChunkLocationLaxImp(Vector startLocation, Vector endLocation, float charSpaceWidth)
    {
        this.startLocation = startLocation;
        this.endLocation = endLocation;
        this.charSpaceWidth = charSpaceWidth;
        Vector oVector = endLocation.Subtract(startLocation);
        if (oVector.Length() == 0)
        {
            oVector = new Vector(1, 0, 0);
        }
        orientationVector = oVector.Normalize();
        orientationMagnitude = (int)(Math.Atan2(orientationVector.Get(Vector.I2), orientationVector.Get(Vector.I1)) * 1000);
        Vector origin = new Vector(0, 0, 1);
        distPerpendicular = (int)(startLocation.Subtract(origin)).Cross(orientationVector).Get(Vector.I3);
        distParallelStart = orientationVector.Dot(startLocation);
        distParallelEnd = orientationVector.Dot(endLocation);
    }

    public virtual int OrientationMagnitude()
    {
        return orientationMagnitude;
    }

    public virtual int DistPerpendicular()
    {
        return distPerpendicular;
    }

    public virtual float DistParallelStart()
    {
        return distParallelStart;
    }

    public virtual float DistParallelEnd()
    {
        return distParallelEnd;
    }

    public virtual Vector GetStartLocation()
    {
        return startLocation;
    }

    public virtual Vector GetEndLocation()
    {
        return endLocation;
    }

    public virtual float GetCharSpaceWidth()
    {
        return charSpaceWidth;
    }

    public virtual bool SameLine(ITextChunkLocation @as)
    {
        if (OrientationMagnitude() != @as.OrientationMagnitude())
        {
            return false;
        }
        int distPerpendicularDiff = DistPerpendicular() - @as.DistPerpendicular();
        if (Math.Abs(distPerpendicularDiff) < 2)
        {
            return true;
        }
        LineSegment mySegment = new LineSegment(startLocation, endLocation);
        LineSegment otherSegment = new LineSegment(@as.GetStartLocation(), @as.GetEndLocation());
        return Math.Abs(distPerpendicularDiff) <= DIACRITICAL_MARKS_ALLOWED_VERTICAL_DEVIATION && (mySegment.GetLength() == 0 || otherSegment.GetLength() == 0);
    }

    public virtual float DistanceFromEndOf(ITextChunkLocation other)
    {
        return DistParallelStart() - other.DistParallelEnd();
    }

    public virtual bool IsAtWordBoundary(ITextChunkLocation previous)
    {
        if (startLocation.Equals(endLocation) || previous.GetEndLocation().Equals(previous.GetStartLocation()))
        {
            return false;
        }
        float dist = DistanceFromEndOf(previous);
        if (dist < 0)
        {
            dist = previous.DistanceFromEndOf(this);
            //The situation when the chunks intersect. We don't need to add space in this case
            if (dist < 0)
            {
                return false;
            }
        }
        return dist > GetCharSpaceWidth() / 2.0f;
    }

    internal static bool ContainsMark(ITextChunkLocation baseLocation, ITextChunkLocation markLocation)
    {
        return baseLocation.GetStartLocation().Get(Vector.I1) <= markLocation.GetStartLocation().Get(Vector.I1) &&
             baseLocation.GetEndLocation().Get(Vector.I1) >= markLocation.GetEndLocation().Get(Vector.I1) && Math.
            Abs(baseLocation.DistPerpendicular() - markLocation.DistPerpendicular()) <= DIACRITICAL_MARKS_ALLOWED_VERTICAL_DEVIATION;
    }
}

Now to make your code use these classes, replace
string output = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(i));

by
LocationTextExtractionStrategy laxStrategy = new LocationTextExtractionStrategy(new LaxTextChunkLocationStrategy());
string output = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(i), laxStrategy);

and the text extraction result becomes
Artikelnr. Omschrijving Aantal Per stuk Kosten
VERHUUR L. GELEVERDE ARBEID PDC 8 € 43,70 € 349,60
VERHUUR O. GELEVERDE ARBEID PDC 3 € 60,95 € 182,85
VERHUUR L.L. GELEVERDE ARBEID EM 24 € 32,20 € 772,80

as was desired.
Additional questions
How to examine the pdf to know the exact locations of the rows
In a comment you asked

May i ask how you exemined the pdf to know the exact locations of the rows?

I inspected the page using iText RUPS:

In the contents of the stream selected in the screen shot I found:
q
...
q
1 0 0 1 60 536 cm
BT
8 0 0 8 0 0 Tm
/F3 1 Tf
(Artikelnr) Tj
8 0 0 8 31.84 0 Tm
(.) Tj
ET
Q
Q
q
...
q
1 0 0 1 147 536 cm
BT
8 0 0 8 0 0 Tm
/F3 1 Tf
(Omschrijving) Tj
ET
Q
Q
q
...
q
1 0 0 1 370 536 cm
BT
8 0 0 8 0 0 Tm
/F3 1 Tf
(Aantal) Tj
ET
Q
Q
q
...
q
1 0 0 1 433.404 535.893 cm
BT
8 0 0 8 0 0 Tm
/F3 1 Tf
(Per stuk) Tj
ET
Q
Q
q
...
q
1 0 0 1 504.878 535.893 cm
BT
8 0 0 8 0 0 Tm
/F3 1 Tf
(Kosten) Tj
ET
Q
Q

Before the first three headings you see
1 0 0 1 XXX 536 cm

while before the last two headings you see
1 0 0 1 XXX 535.893 cm

As the text matrix always is set with 8 0 0 8 XXX 0 Tm to have no translation part along the y axis, the cm instructions above set the coordinate system so that text is drawn at y position 536 or 535.893 respectively.


text:
Q: Is there a Meter to indicate current Network Activity to the xfce4-panel I already have a meter on the xfce4 panel which indicates the current CPU load (blue themometer), the current memory load (green thermomeer) and the current swap storage load (a yellow thermometer).
I am looking for one more which shows the current network activity level - either as such a thermometer or even better as something to click on th show the input and output als a graph for say the last quarter of an hour.

A: The command
ip link show

gave me an overview about the network adapter names of my computer.
From observing results of ip link show with the LAN pluged/unplugged and the WLAN enabled/disabled, I concluded that in my case enp0s25 designates my LAN adapter and wlp3s0 designates my WLAN adapter.
But the sampling time of 0.25s was a bit too short. Setting it to 1 second made the activity bar show up when I let firefox show a Bing map. One should set the upper scale ends for incoming and for outgoing traffic to what one expects. I tried it with 50 KiB/s incoming, 1 KiB/s outgoing because in most cases my question is: "is there any network activity".
It would be nice if the scales could be made logarithmic (however since the logarithm of 0 is -Infinty, clipping off all network activity below one packet per sampling)!
It is possible to place e.g. two instances of Network Monitor: one for WLAN, the other for LAN. I called them W and L. - Thank you, HattinGokbori87!


text:
Q: Importacion Plantillas a Wordpress soy nuevo en el tema de Wordpress, les agradeceria me ayudaran a solucionar el siguiente problema que tengo, para un tema universitario necesito montar una pagina web sencilla en mi hosting y encontre unas plantillas .zip para importarlas en WordPress pero al instalarlas me sale el siguiente error:

lo trate de subir por FTP y el WP lo que muestra es otro error el cual es el siguiente:

por favor les agradezco cualquier luz que me puedan dar para solucionar esto, es un trabajo de la universidad.

A: Por lo que veo el theme que quieres instalar es un child theme (tema hijo), osea que tienes que instalar el theme 'padre' para poder usar ese theme. Puede que el theme 'Elegant' necesite de otro para poder usarse.
Normalmente los themes que son así en el archivo style.css viene el theme que necesitas, un ejemplo:

Vienen las dos partes señaladas, revisa el archivo style.css del theme
Actualización:
Haciendo pruebas, el error es causado por la falta del archivo index.php en el theme, intenta generar el archivo (poniendo código HTML con la información del theme o simplemente generando el archivo), o vuelve a obtener el theme ya que está incompleto.


text:
Q: Worst case time complexity lists I know that the best, average and worst case time complexities of binary search are at
Best O(1);
Average O(log n);
Worst O(log n); for an array implementation. Likewise, I know that the best, average and worst case time complexities of insertion sort are at
Best O(n);
Average O(n^2);
Worst O(n^2); for an array implementation.
However, how would I work out the time complexities of say binary search and insertion sort of singly linked lists; doubly linked lists; and circular linked lists implementations?

A: A brief answer would be to look at the computer steps done by your algorithm. You might want to look at at Algorithm Proofs, and BigO, Omega, and Theta notations. Different algorithms have different worst case and best case scenarios. Given a function F(n) with n given inputs. It has G(n) computer steps. Lets say G(n) = 5x^2 + 3x + 1. Most people usually look at Big-O. For Big(O) you drop all the coefficient and just take the leading Term. SO your Big-O would be  x^2

A: You simply can't implement binary search with a linked list (neither single linked nor any of the others). It requires O(1) access to any index, that's simple with an array, but impossible with a list. Think of how you would pass from element n/2 to n/4 for e.g without traversing all the elements in the middle, or from the beginning.
Insertion sort on the other hand is based on traversing the elements consecutively, which is not a problem in a linked list, and therefore will retain the same complexity. Note that the O(N^2) is still the case even if you have to walk over the entire list from the beginning for each element (in case of a single linked list), instead of swapping your way backwards as you would with an array. It does however require to modify the algorithm, which shows you a very fundamental lesson - the specific algorithm dictates the data structure, using a different data structure will usually require a change in the algorithm, and in some cases - also the complexity.

A: Whether you can use binary search or not depends on whether you can access items randomly or not(i.e access item by index). You can never access item from list( singly linked lists; doubly linked lists; and circular linked lists)by index, so you can't implement binary search on list. However, you can use Skip List instead. You can get O(1)(best case) O(lnN)(average and worst) search in Skip List.
Since, you don't need access by index in insertion sort, there will be no difference between array and list for insertion sort. Typically, you need access the previous item to insert the current item, however, you can also order the items by reversed order and find the position from the beginning(ie head of the list) and reverse the list at last. It won't change the time complexity.

A: BinarySearch :
require random access to the elements , can you get it in liked lists ? NO .  (though you can use extra space to convert it into array , but that beats the fact you have to use linked lists only)
Insertion sort :
you need to get access the elements before a particular index , surely you can't do it in O(1) for singly linked lists .
you can traverse the list from beginning for each element, but that will make time complexity very high .
In doubly linked list , you can apply insertion sort easily as you can access previous element in O(1) time.
On above discussion you can easily think about circular lists also.
hope this helps!


text:
Q: What would the MVC and overall structure for a command line interface look like in Swift 4? For example my app will have a database (model), text based interface(view) and behaviour (view controller) as well as data retrieval from network sources. I still don't know how to create main event loops, create notifications or listen for events (save that for the next question) but just want to get the structure right.
So far I have:

main.swift

This would have to be the setup for the main event loop which I have no idea how to do; so using NSApplication.
import AppKit

let app = NSApplication.shared
app.delegate = AppDelegate()
NSApp.run()

AppDelegate.swift

import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let viewController = ViewController()
        let dataBase = DataBase()
        let networking = Networking()
    }
    func applicationWillTerminate(_ aNotification: Notification) {
    }
}

ViewController.swift

Which I'm guessing needs to have it's own event loop and listening for keypresses from the view.
class ViewController {
    let view = View()
    func update() {
        view.display()
    }
}

View.swift

Which isn't supposed to hold data only layout but does contain default labels.
class View {
    let clear = "\u{001B}[3J"
    let title1 = "app:\n"
    let title2 = "message log:\n"
    var log: [String] = ["welcome to app!"]
    var menu: [String] = ["o = open", "f = find items", "v = verify items"]
    let question = "enter option followed by return:"
    var input: String?
    func display() {
        print(clear)
        print(title1)
        print(title2)
        if log.count < 10 {
            for text in stride(from: 0, to: log.count, by: 1) {
                print("\(text + 1): \(log[text])")
            }
        } else {
            for text in stride(from: log.count - 10, to: log.count, by: 1) {
                print("\(text + 1): \(log[text])")
            }
        }
        print()
        if menu.count != 0 {
            print("menu: ", terminator: "")
            for option in stride(from: 0, to: menu.count - 1, by: 1) {
                print("\(menu[option])", terminator: ", ")
            }
            print("\(menu[menu.count - 1])", terminator: "\n")
        }
        print(question, terminator: " ")
        input = readLine()
    }
}

Database.swift

import Foundation

class Item: Codable {
    let url: URL
    let dateAdded: Date
    var dateModified: Date
    var isReal: Bool?
    var isRealChecked: Date?
    var lowestPrice: Double?
    var medianPrice: Double?
    var volumeSold24Hr: Int?
    init (_ url: String) {
        self.url = URL(string: url)!
        self.dateAdded = Date()
        self.dateModified = Date()
    }
}

Networking.swift

This would contain the code that grabs my data structure from the net.


text:
Q: Reloading tableView - Objective C When calling [self.tableView reloadData]; my cellForRowAtIndexPath will not run.
This is what is happening:
First Sequence -
- (void)startProcess:(NSInteger)number {
    NSInteger testing = number;
    cellID = testing;
    // MAKE REQuEST TO SERVER
    [self makeRequests];

}

Second sequence -
-(void)makeRequests
{
/* GRAB USERNAME TO BE SENT OVER FOR NOTIFICATIONS */
NSArray *get = [[SSKeychain allAccounts] init];
NSString *username = [get[0] objectForKey:@"acct"];

NSDictionary *dictionary = @{@"function": @"populateNotfications", @"username" : username};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error)
    NSLog(@"%s: JSON encode error: %@", __FUNCTION__, error);

NSURL *url = [NSURL URLWithString:@"mySite.com/dev/iphone/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
NSString *params = [NSString stringWithFormat:@"json=%@",
                    [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[paramsData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:paramsData];

// issue the request
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
    NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);

// GRAB STATUS OBJECT
NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:returnData //1

                      options:kNilOptions
                      error:&error];
self.impactsGrabed = [json objectForKey:@"requested_data"];
NSLog(@"grabbing data");
[self.tableView reloadData];
}

Now this will cause my numberOfRowsInSection to run and work correctly but cellForRowAtIndexPath never runs.  Here is my numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.impactsGrabed count];
}

impactsGrabed count will return for example, 2.
OUTPUT of tableView:
<UITableView: 0x10e00ee00; frame = (0 20; 320 548); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x10c244950>; layer = <CALayer: 0x10c23ffc0>; contentOffset: {0, 0}>
UPDATE:
CELL TABLE CODE:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.impactsGrabed count]; <!-- this does return an positive integer.
}

- (double) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"working cell");
    static NSString *CellIdentifier = @"timelineCell";
    impactTimelineCell *cell = (impactTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    cell = [[impactTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell initTimelineCell];
    cell.statusLabel.text = [self.impactsGrabed[indexPath.row] objectForKey:@"message"];
    cell.timestampLabel.text = [self.impactsGrabed[indexPath.row] objectForKey:@"time_post"];

    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // WHEN CLICKING ON A NOTIFICATION FOR THE PAGE

}

Here is what I notice:
When calling the function startProcess from another class that starts the whole process of loading the tableView cells it does not work.  If I call the startProcess method inside the viewDidLoad in that file, on initiation the tableView cells do load.

A: cellForRowAtIndexPath won't be called if numberOfRowsInSection returns zero. Just Make sure by debugging your code that numberOfRowsInSection is returning nonzero value.

A: first of all, no need to reload since you are not doing the request asynchronously
//[self.tableView reloadData];

Make sure you return at least one section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

A: Check if self.tableView 's delegate and dataSource are not properly connected.

A: Okay after some wonderful help from Mr.rdelmar. This was the issue:
So because I was calling the code from a child container of a ViewController I had to initiate the following in my startProcess:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        NSInteger tag = cell.tag;
        impact* myScript = self.parentViewController.childViewControllers[1]; // if my script is one of the child view controllers, then this is how you need to access it -- the number might be 0,1 or 2 depending on which one is the impact controller
        [myScript startProcess:tag];
}

Hope this helps!
Happy Coding!


text:
Q: Error while creating a new app in reactjs PS D:\React\counter-app> create-react-app tower
create-react-app : File C:\Users\ee209495\AppData\Roaming\npm\create-react-app.ps1 cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ create-react-app tower
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

A: Try executing the console with admin credentials.
You might not have permissons while trying to execute npm commands.
i would also recommend to use npx create-reaact-app myapp.
This provides a previous check to see if you had already installed react packages, if not, it will install them for you.

A: Try following steps:

*

*Go to Start Menu and search for "Windows PowerShell ISE".

*Right click the x86 version and choose "Run as administrator".

*In the top part, paste Set-ExecutionPolicy RemoteSigned; run the script. Choose "Yes".

*Repeat these steps for the 64-bit version of Powershell ISE too (the non x86 version).

A: this problem because of security feature in your system.
 1. Open powershell as an administrator.
 2. Run the following command set-executionpolicy remotesigned
 3. Try again.

A: The error "create-react-app.ps1 cannot be loaded because running scripts is disabled on this system" occurs when the execution policy does not allow running the specific script on Windows.
Use the Set-ExecutionPolicy -ExecutionPolicy RemoteSigned command to solve the error.
Open your PowerShell as an administrator and set its execution policy with the Set-ExecutionPolicy command.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

The Set-ExecutionPolicy command sets the PowerShell execution policy for the Windows computer.
If you aren't able to run the command as an administrator, try running it with the CurrentUser parameter.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

The RemoteSigned policy still prevents us from running unsigned scripts.
Now, run the Get-ExecutionPolicy command:
Get-ExecutionPolicy

The Get-ExecutionPolicy command should display the effective execution policy for the current PowerShell session (RemoteSigned).


text:
Q: ODataController and Streaming example I have the following requirement. I have a odata contract as follows:
public class videoStreamResponse
{
    public string Id { get; set; }
    public Action<Stream> VideoData { get; set; }
}

List<videoStreamResponse> exportVideo(string[] ids);

My odata service is exposing a list of videoStreamResponse . There will be odata action that returns the list of video stream response.
In the service implementation we call into another service that streams the data. We want to return this to the caller without having to deserialize into memory. Instead I need to stream the contents from the backend video service to the caller directly where by I need to write to the VideoData which is a delegate that returns a stream.
The middle tier service should not deserialize and serialize since that would increase the memory.
Is there any standard patterns or approach to do this with dotnet core and asp.net mvc odata framework.
Thanks


text:
Q: Javascript: Uploading a file... without a file I am trying to fake a file upload without actually using a file input from the user. The file's content will be dynamically generated from a string.
Is this possible? Have anyone ever done this before? Are there examples/theory available?
To clarify, I know how to upload a file using AJAX techniques using a hidden iframe and friends - the problem is uploading a file that is not in the form.
I am using ExtJS, but jQuery is feasible as well since ExtJS can plug into it (ext-jquery-base).

A: A file upload it's just a POST request with that file content properly encoded and with an special multipart/formdata header. You need to use that <input type=file /> because your browser security forbid you to access user disk directly.
As you don't need to read user disk, YES, you can fake it using Javascript. It will be just a XMLHttpRequest. To forge an "authentic" upload request, you can install Fiddler and inspect your outgoing request.
You'll need to encode that file correctly, so this link can be very useful: RFC 2388: Returning Values from Forms:  multipart/form-data

A: Easy way to imitate "fake" file upload with jQuery:
var fd = new FormData();
var file = new Blob(['file contents'], {type: 'plain/text'});

fd.append('formFieldName', file, 'fileName.txt');

$.ajax({
  url: 'http://example.com/yourAddress',
  method: 'post',
  data: fd,
  processData: false,        //this...
  contentType: false         //and this is for formData type
});

A: If you don't need support for older browsers, you can use the FormData Object, which is part of the File API:
const formData = new FormData();
const blob = new Blob(['Lorem ipsum'], { type: 'plain/text' });
formData.append('file', blob, 'readme.txt');

const request = new XMLHttpRequest();
request.open('POST', 'http://example.org/upload');
request.send(formData);

File API is supported by all current browsers (IE10+)

*

*https://developer.mozilla.org/en-US/docs/Web/API/FormData

*http://caniuse.com/#feat=fileapi

A: I just caught this POST_DATA string with the Firefox TamperData addon. I submitted a form with one type="file" field named "myfile" and a submit button named "btn-submit" with value "Upload". The contents of the uploaded file are
Line One
Line Two
Line Three

So here is the POST_DATA string:
-----------------------------192642264827446\r\n
Content-Disposition: form-data;    \n
name="myfile"; filename="local-file-name.txt"\r\n
Content-Type: text/plain\r\n
\r\n
Line \n
One\r\n
Line Two\r\n
Line Three\r\n
\r\n
-----------------------------192642264827446\n
\r\n
Content-Disposition: form-data; name="btn-submit"\r\n
\r\n
Upload\n
\r\n
-----------------------------192642264827446--\r\n

I'm not sure what the number means (192642264827446), but that should not be too hard to find out.

A: Why not just use XMLHttpRequest() with POST?
function beginQuoteFileUnquoteUpload(data)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function ()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
            alert("File uploaded!");
    }
    xhr.send("filedata="+encodeURIComponent(data));
}

The handler script at the server just writes the file data to a file.
EDIT
File upload is still a http post with a different content type.  You can use this content type and separate your content with boundaries:
function beginQuoteFileUnquoteUpload(data)
{
    // Define a boundary, I stole this from IE but you can use any string AFAIK
    var boundary = "---------------------------7da24f2e50046";
    var xhr = new XMLHttpRequest();
    var body = '--' + boundary + '\r\n'
             // Parameter name is "file" and local filename is "temp.txt"
             + 'Content-Disposition: form-data; name="file";'
             + 'filename="temp.txt"\r\n'
             // Add the file's mime-type
             + 'Content-type: plain/text\r\n\r\n'
             + data + '\r\n'
             + boundary + '--';

    xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
    xhr.setRequestHeader(
        "Content-type", "multipart/form-data; boundary="+boundary

    );
    xhr.onreadystatechange = function ()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
            alert("File uploaded!");
    }
    xhr.send(body);
}

If you want to send additional data, you just separate each section with a boundary and describe the content-disposition and content-type headers for each section.  Each header is separated by a newline and the body is separated from the headers by an additional newline.  Naturally, uploading binary data in this fashion would be slightly more difficult :-)
Further edit: forgot to mention, make sure whatever boundary string isn't in the text "file" that you're sending, otherwise it will be treated as a boundary.

A: https://stackoverflow.com/a/2198524/2914587 worked for me, after I added an extra '--' before the final boundary in the payload:
var body = '--' + boundary + '\r\n'
         // Parameter name is "file" and local filename is "temp.txt"
         + 'Content-Disposition: form-data; name="file";'
         + 'filename="temp.txt"\r\n'
         // Add the file's mime-type
         + 'Content-type: plain/text\r\n\r\n'
         + data + '\r\n'
         + '--' + boundary + '--';

A: Just sharing the final result, which works - and has clean way of adding/removing parameters without hardcoding anything.
var boundary = '-----------------------------' +
            Math.floor(Math.random() * Math.pow(10, 8));

    /* Parameters go here */
var params = {
    file: {
        type: 'text/plain',
        filename: Path.utils.basename(currentTab.id),
        content: GET_CONTENT() /* File content goes here */
    },
    action: 'upload',
    overwrite: 'true',
    destination: '/'
};

var content = [];
for(var i in params) {
    content.push('--' + boundary);

    var mimeHeader = 'Content-Disposition: form-data; name="'+i+'"; ';
    if(params[i].filename)
        mimeHeader += 'filename="'+ params[i].filename +'";';
    content.push(mimeHeader);

    if(params[i].type)
        content.push('Content-Type: ' + params[i].type);

    content.push('');
    content.push(params[i].content || params[i]);
};

    /* Use your favorite toolkit here */
    /* it should still work if you can control headers and POST raw data */
Ext.Ajax.request({
    method: 'POST',
    url: 'www.example.com/upload.php',
    jsonData: content.join('\r\n'),
    headers: {
        'Content-Type': 'multipart/form-data; boundary=' + boundary,
        'Content-Length': content.length
    }
});

This was tested to work on all modern browsers, including but not limited to:

*

*IE6+

*FF 1.5+

*Opera 9+

*Chrome 1.0+

*Safari 3.0+


text:
Q: What happens to an open cursor after rolling back the transaction in Postgres using Psycopg2? I am trying to copy a list of CSV files into Postgres using Psycopg2's copy_expert().
I'm opening cursor to execute copy command for each file separately and closing it after the data has been copied.
But, If I get any error for any file in this process, I'm rolling back the transaction.
If I get an error I'm not sure what's going to happen to the cursor that I have opened before copying the CSV file.
Will it be closed automatically after the rollback is done on the connection or will it stay just like that?
I've checked the docs for rollback on psycopg2 http://initd.org/psycopg/docs/connection.html#connection.rollback. But still, I'm unsure of what happens to the cursor that hasn't been closed as they haven't mentioned anything related to the cursor in the docs.
try:
    for tablename, filename in self.mapping:
        cur = self.conn.cursor()
        filename = f"{self.to_db}{wid}-{filename}"
        filename = f"{os.path.join(self.directory, filename)}.csv"
        sql = f"copy {tablename} from stdin with delimiter as ',' csv header;"
        with open(f"{filename}", 'r') as file:
            cur.copy_expert(sql, file)
        cur.close()
    self.conn.commit()
except Exception as e:
    self.conn.rollback()
    return e

A: You could make use the cursor's context manager, when the code leaves the `with´-block, the cursor is closed automatically.
Since you are firing the commit after the for-loop, there is no need to 're-create' the cursor every loop iteration.
class foo():
    def __init__(self):
        self.conn = psycopg2.connect('host=...')

    def whatever(self):
        with self.conn.cursor() as cur:
            try:
                for tablename, filename in self.mapping:
                    filename = f"{self.to_db}{wid}-{filename}"
                    filename = f"{os.path.join(self.directory, filename)}.csv"
                    sql = f"copy {tablename} from stdin with delimiter as ',' csv header;"
                    with open(f"{filename}", 'r') as file:
                        cur.copy_expert(sql, file)
                self.conn.commit()
            except Exception as e:
                self.conn.rollback()
                return e


text:
Q: Mercurial: How to compact/combine specified old revisions into one? I've got a repository. In the middle of its life-cycle I deleted a lot of unnecessary files from it  (I decided to keep  them unversioned).
hg remove
hg commit

The repo grows bigger and bigger.
And I decided to get rid of old revisions the from initial one to the revision where lot of files were removed (let's name it X).
Other words I want combine these revisions (from the initial to the X) into one initial revision.
But same time to keep the history of the following revisions (X+1, etc..) as they are.
I googled for the solution, but failed.
And found nothing clever than do this:
hg init newrepo
cd oldrepo
hg archive -r X newrepo
hg export -r X+1: -o "~/patches/%R-%h.diff"
cd newrepo
hg commit -A -m 'initial release (after archiving)'
hg import ~/patches/*.diff

And damn it, after few successfully applied patches
I receive:
Hunk #1 FAILED at xxx
Hunk #2 FAILED at xxx
2 out of 2 hunks FAILED -- saving rejects to file xxx.rej
abort: patch failed to apply

What I do wrong?
I've got 1 repo without branches (to be more exact to the revision X all branches were merged).
The second solution was
* hg convert to svn
* hg convert to mercurial from revisiob X+1
Failed with python backtrace (probably it was caused by our repo has about 3K files).

A: To filter out files from repository, you want to use hg convert (Mercurial to Mercurial) with --filemap argument (see documentation for more details). Keep in mind the affected changeset IDs (and those of all their descendants) will change.

A: Take a look at the Collapse extension which seems to do what you want.

A: You can fold changesets with MQ, or use histedit extension


text:
Q: m2Eclips plugin: Resolve Workspace Artifacts - is it a good practice Hello I am working on a Maven project that requires me to enable "Resolve Workspace Artifacts" at the time of Maven Build operation. Without which I get build failure as certain dependencies are not resolved.
From this link I understand what "Resolve Workspace Artifacts" does.
To give background: I am starting fresh, with nothing in my local m2 repo. I am cloning a project from Git Lab and while the "mvn clean install" is being run I enable "Resovle Workspace Artifacts".
This is a multi-module maven project.
I want to understand...
1. If this OK (Maven project defined such that it requires us to enable "Resolve Workspace Artifacts")?
2. Could this issue have arised due to incorrect/bad design of Maven project dependencies?
3. If left as it is will there be any issues if I plan towards CI-CD phase?
This is a Spring Boot web project

A: *

*Ideally it should be avoided, but it helps and may be faster if you are concurrently developing multiple projects that are in your workspace, but for whatever reason can't already be installed in a resolvable repo. But really you could just run mvn install on those dependencies to at least get them into your local repo. Though I can see how that might be a 'step too many' when you're just messing around with the code and want to iterate quickly (on the other hand why would you do a full maven build then).

*Perhaps for some reason you haven't pushed/installed another one of your own projects, but that the one with the issue is depending on. Without it being in the local or remote publicly resolvable repo, there is no way for maven to resolve it without "Resolve Workspace Artifacts". But yes, it could be an issue with your dependency tree - difficult to assess without your pom.

*No issue as long as the CI/CD server can fetch the missing dependencies.
If the missing dependencies are hosted in a private repository, the likely solution is to add a <repository> entry in your pom.


text:
Q: using size_t inside for loop throwing error "std::length_error" I had encountered an error inside for loop, if str.size() = 1 then it's throwing error as

terminate called after throwing an instance of 'std::length_error'
what():  basic_string::_M_create

but if str.size() is anything more than 1 then everything goes well.
Also when I changed size_t to int everything goes fine. Why?
for (size_t i = str.size() - 1; i >= 0; i--)
        excess3(str[i]);

Here str is vector of string

A: size_t is an unsigned type, so the condition i >= 0; will always evaluate to true, and the loop never ends.
Either replace i >= 0 with i != 0 (and make sure to never enter the loop with an empty vector), or change the loop variable from size_t to a signed type like int.

A: size_t is unsigned. If str.size() == 1 then i is initialized to 0. the first time through the loop is ok. The second pass decrements i and makes it very large in the unsigned world. On a 32 bit system it would be 0xFFFFFFFF, which is bigger than zero of course. Try ssize_t instead of size_t. It is the signed variant. That's also why int works.


text:
Q: Line break within a wiki link? In Mediawiki, how to insert a line break within a wikilink?
Context: An otherwise nicely balanced table is distorded (one column is very wide while the other columns are narrow) because of a very long wikilink. So I would like this link to be split in two lines.
This breaks the line, but the text is not rendered as a link:
[[Chargoggagoggmanchaugga
goggchaubunagungamaugg]]

A: The problem is that you're using the same text both for link text and link target. The HTML tag can't appear in a link target, so the wiki assumes you didn't mean to generate a link.
You need to specify text and target separately:
 [[Chargoggagoggmanchauggagogg|Chargoggagoggmanchaugga
gogg]]


text:
Q: Gz giving unreadable data I am creating sitemap.xml using php. In which i have to create gz file which contains number of links.
Using following code.
$gzfile = $xmlfile.".gz";
$fp = gzopen ($gzfile, 'w9');
gzwrite ($fp, $photoxmldata);
gzclose($fp);

But when i open created gz file, it gives unreadable data.
Please help.


text:
Q: Get number of items in MySQL database I am using php to create a highscore database for my iPhone Application. However it will only show 100 highscores (that I set). How can I change this to get the count of all of the rows in the database?
Here is part of my code:
$table = "highscores";

// Initialization
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);

// Error checking
if(!$conn) {
    die('Could not connect ' . mysql_error());
}

$type   = isset($_GET['type']) ? $_GET['type'] : "global";
$offset = isset($_GET['offset']) ? $_GET['offset'] : "0";
$count  = isset($_GET['count']) ? $_GET['count'] : "100";
$sort   = isset($_GET['sort']) ? $_GET['sort'] : "score DESC";

A: To get the number of records from a table, you can try following code:
<?php
$query = mysql_query("select count(*) as total from table_name");
$result = mysql_fetch_array($query);
echo $result['total'];
?>

A: SELECT COUNT(*) FROM highscores will give you the number of rows in the highscores table.  But you would also get all the rows, if that's what you want to do, by eliminating the LIMIT clause from your query.  SQL defaults to giving you all of the rows that match.

A: Here's a good article for Getting MySQL Table Size with PHP
Hope that helps.


text:
Q: Para que serve o modo de exibição de compatibilidade do Internet Explorer? Estou com problemas no layout com usuários que usam o browser Internet Explorer em modo de exibição de compatibilidade.
Ao usar o Internet Explorer versão 11.0.21 em modo de exibição de compatibilidade qual será a versão que ele irá assumir? A anterior ou alguma especifica?

A: O Internet Explorer dispõe de vários modos de renderização para as diferentes versões do navegador. Temos desde o 5 (chamado de IE Quirks) até o Edge que é o modo de renderização associado ao IE11 e implementa vários recursos novos de CSS3.
Cada versão possui recursos novos e também torna obsoletos comportamentos/recursos que antes funcionavam. Nesse link, a Microsoft explica as mudanças de compatibilidade do IE por versão.
Quando o IE recebe um HTML, ele fará a renderização da página usando o modo de renderização que ele considerar mais compatível. Mas é possível também especificar no HTML, através da tag Meta, qual versão de renderização do IE é a mais adequada para sua página.
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Vale lembrar que o Microsoft Edge ignora essa tag Meta.

Agora, voltando para a questão, para saber exatamente a versão que o IE está usando para exibir seu site, acesse a ferramenta do desenvolvedor (F12). Na aba de emulador, ele indicará o modo de renderização padrão do seu site e, quando estiver no modo de compatibilidade, a versão do modo de renderização que ele está usando.
Para mais informações, tem o artigo "Como fazer o IE exibir melhor o meu site?".


text:
Q: Reference web component root attribute with CSS Created a web component with a shadow DOM. When the button is clicked it adds the open attribute to the web component.
I would like to show the hidden div in the CSS when the open is added with CSS styling. Is it possible for the shadow DOM styles to reference attributes on the web component root? Otherwise, I have to add a superfluous class or attribute within the shadow DOM.

class CustomComponent extends HTMLElement {
  constructor() {
    super();

    this.element = this.attachShadow({mode: 'open'});
  }

  static get observedAttributes() {
    return ['open'];
  }

  attributeChangedCallback(attrName, oldValue, newValue) {
    if (newValue !== oldValue) {
      this[attrName] = this.hasAttribute(attrName);
    }
  }

  connectedCallback() {
    const template = document.getElementById('custom-component');
    const node = document.importNode(template.content, true);
    this.element.appendChild(node);

    this.element.querySelector('button').addEventListener('click', () => {
      this.setAttribute('open', '');
    });
  }
}

customElements.define('custom-component', CustomComponent);
<template id="custom-component">

  <button>Open</button>

Content

</template>

<custom-component></custom-component>

A: It appears the host CSS pseudo selector is designed to handle this precise situation.

class CustomComponent extends HTMLElement {
  constructor() {
    super();

    this.element = this.attachShadow({mode: 'open'});
  }

  static get observedAttributes() {
    return ['open'];
  }

  attributeChangedCallback(attrName, oldValue, newValue) {
    if (newValue !== oldValue) {
      this[attrName] = this.hasAttribute(attrName);
    }
  }

  connectedCallback() {
    const template = document.getElementById('custom-component');
    const node = document.importNode(template.content, true);
    this.element.appendChild(node);

    this.element.querySelector('button').addEventListener('click', () => {
      this.setAttribute('open', '');
    });
  }
}

customElements.define('custom-component', CustomComponent);
<template id="custom-component">

  <button>Open</button>

Content

</template>

<custom-component></custom-component>


text:
Q: Image not displaying after clicking in lightbokv2.6 I am using lightbox 2.6 my thumbnails are displaying but when i click on image a lightbox appear but it does not display image instead it keep loading the image but does not display it.
my code is-
<!doctype html5>

<link href="css/lightbox.css" rel="stylesheet" />
<link href="css/screen.css" rel="stylesheet" />

A: Use Firefox Firebug or Opera Dragonfly to check if big images are exist and are accessible. Also check error console.
Usage of different extension (jpg and jpeg) is intentional?


text:
Q: Background service only activating when Application is closed Strangely, my service does run in the background, however it only creates the alarm when the application is closed, and not when it is running. Can anyone provide some insight as to why this may be happening. My service class below.
public class TimeDifferenceService extends Service {
DatabaseHelper myDbs;

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

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    myDbs = new DatabaseHelper(this);
    mHandler.postDelayed(mUpdateTimeChecker,100);
   return START_STICKY;
}
Handler mHandler = new Handler();
final Runnable mUpdateTimeChecker = new Runnable() {
    public void run() {
        // do whatever you want to change here, like:

        Cursor res = myDbs.GetFirstTime();
        if (res.getCount() == 0) {
            return;
        }

        while (res.moveToNext()) {
            String booleancheck =res.getString(5);
            notificationCheck = Boolean.parseBoolean(booleancheck);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TimeZone tz = TimeZone.getDefault();

            Calendar c1 = Calendar.getInstance(tz);
            Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

            try {
                c1.setTime(sdf.parse(res.getString(1)));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            c2.getTime();
            long timeDiff = ((c1.getTimeInMillis()-c2.getTimeInMillis())/(1000*60));

            if (timeDiff <= 60 && timeDiff >=0 && !notificationCheck){
                setAlarm();
                String notifDisplay = "true";
                update(res.getInt(0),notifDisplay);
            }else {

            }

            res.close();
        }
        mHandler.postDelayed(this,1000);
    }

};
public void setAlarm(){
    long alertTime = new GregorianCalendar().getTimeInMillis()+1*1000;
    Intent alertIntent = new Intent(this,AlertReciever.class);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.set(AlarmManager.RTC_WAKEUP,alertTime, PendingIntent.getBroadcast(this,1,alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));

}

}


text:
Q: Modem+Router+Switch+Router connection in a LAN What I am trying to do:
I have 2000 users in a region. I have one modem and from that I connect a router now router can only grant access to the IPs between 192.168.0.1-255 BUT my users are 2000 what should I do to achieve this. I need to establish connection between all the device connected to the main router.  Here Communication means to transfer messages and files back and forth.
Approach: To increase number of users, i connect more then 1 router but communication is not being established
I am having the connection as shown in image below,

I am trying to send message(utility is running like IPMessenger on all the PCs) from PC connected to Lynksys to the PC connected to TP-Link.
Problem is that I am not able to do the same.
The IP address of the Lynksys PC is not in the range of 192.168.1.* , it is showing the IP in the range of 192.168.0.*.

A: From your last comment I take it you try to build a WLAN network. With the right equipment (which you should have if you have 2000 users) this would still be only one network. Maybe you would be best served, if you try to build this in a simulated environment with http://www.gns3.net/ or the https://www.netacad.com/web/about-us/cisco-packet-tracer
Anyhow, to execute your chosen solution: Configure the interfaces connected to the switch to be within one network, e.g. 192.168.100.0/24. Now the routers can talk to each other on layer 3. Configure the other interface (or interfaces) to be within another network, e.g. 192.168.200.0/24. Now your clients on this router must be in 192.168.200.0/24 also. Now your clients can talk to your router and to other clients in 192.168.200.0/24 on layer 3. Repeat this step for all routers but choose different networks, e.g. 192.168.201.0/24 and so on. (This is not strictly necessary but I think it makes things easier to grasp.) Set the router as the default gateway for your clients in the respective networks and the traffic from one network can route to the other networks and vice versa. To get internet access configure the router with the WAN connection to be the default gateway of the other routers.
Please note that if you are thinking about providing services from one network for the others, your routers must provide DNAT (ie. port forwarding.)


text:
Q: Remove backslash instances from a file in Python Okay, this may sound like a stupid question, but I can't solve this problem...
I need remove all instances of backslash from downloaded file...  But,
output.replace("\","")

doesn't work. Python considers "\"," a string, rather than "\" one string and "" the other one.
How can I remove backslashes?
EDIT:
New problem...
Originally, downloaded file had to be processed, which I did using:
fn = "result_cache.txt"
f = open(fn)
output = []
for line in f:
    if content in line:
        output.append(line)
f.close()
f = open(fn, "w")
f.writelines(output)
f.close()
output=str(output)
#irrelevant stuff
with open("result_cache.txt", "wt") as out:
    out.write(output.replace("\\n","\n"))

Which worked okay, reducing file's content to only one line...
And finally ended with having this contents only:
Line of text\
Another line of text\
There\\\'s more text here\
Last line of text

I can't use the same thing again, because it would transform every line to a value in a list, leaving brackets and commas... So, I need to have:
out.write(output.replace("\\n","\n"))
out.write(output.replace("\\",""))

in the same line... How? Or is there another way?

A: Just escape the backslash with a backslash:
output.replace("\\","")


text:
Q: Get a list of all files and their attributes on OS X What is the best and fastest way to get a list of every file on OS X including hidden and system files along with their attributes? I'm not afraid of the terminal or scripts, but if there is a wonderful audit-like application out there I'd be interested in comparing that to my options.

A: Depends on what attributes you need, but the standard unix way would be:
find / -type f -print0 | xargs -0 stat

You mention auditing, so something like tripwire may fit your needs better.

A: To list extended attributes and file flags for all files on all devices:
sudo find / -exec ls -ldO@ {} \;

(that's an upper case letter O in the "-ldO@").
To include access control lists (ACLs), the -e option of ls:
sudo find / -exec ls -ldeO@ {} \;

If a device is a Filesytem in Userspace with no allowance for root, then the commands above will not succeed for that device.
For the listing to exclude devices other than the startup volume, the -x option of find:
sudo find -x / -exec ls -ldeO@ {} \;

A: You can use mdfind.

Find files matching a single query.


text:
Q: Does a tool to view Visio documents on Mac exist? Is there an open source (or free) application to view (not necessarily edit) MS Vision 2007/2010 documents on a Mac?

A: As of a few releases ago, LibreOffice (free and open-source) supports not only read, but editing of Visio projects. Pretty sweet. This has been my solution for Visio portability on all my Linux's for some time. I have tested and it works just as well on OSX.
Read more on the added feature.

A: You can open Visio files on a Mac using Lucidchart since it's web-based.  It imports .vsd and .vdx files from Visio.
You can get a read-only view of the Visio files for free; if you want to edit them, then you can use a 14-day free trial or subscribe.

A: check these 3rd-party, it's not bad but not cheap.

*

*ConceptDraw PRO

*OmniGraffle

A: OmniGraffle Professional allows MS Visio imports and exports. However this is not open source or free - but it does have a 14 day free trial version.

A: Both of these apps do not really open Visio files nicely... You will find large sections of the drawing moved, or certain images/objects replaced. It becomes very annoying if you are opening up complex technical drawing.
The best way I have found to solve the problem is to use either a VM of a Windows machine running the full version of office or a slightly cleverer way is to download a program called CrossOver. This then allows you to install PC Applications as if the Mac is running windows. I now have Visio 2007 running successfully on the Mac without having to run a full Windows VM Image. Works really nicely.


text:
Q: How to get Ansible use fail module with arrays? It looks like Ansible can use the debug module with arrays to output multiple lines
- name: debug something
  debug:
    msg:
      - "y"
      - "x"

Output:
TASK [debug something] **********************************************************************************************
ok: [localhost] => {
    "msg": [
        "y",
        "x"
    ]
}

How to get the same behavior with "-fail"?
TASK [Exit on failure] **********************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": ["y", "x"]}

A: Currently not supported by Ansible up to version 2.4.2.


text:
Q: performing multiple word searches in one regular expression python I have a line,"Boy25e6 was angry so he stole a car from girl37b6 and was arrested by cop58c9".
I want a regular expression to obtain the numbers only from boy and girl.
I could do
if re.search("boy([0-9,a-f]+),", line) or re.search("girl([0-9,a-f]+)", line):
Is there anyway to fit these two regular expressions into one?

A: Yes, you can do (boy|girl)([0-9a-f]+)

A: Perhaps a better way to do this is to use finditer from the re module.
>>> import re
>>> s = "Boy25e6 was angry so he stole a car from girl37b6 and was arrested by cop58c9"
>>> f = re.finditer(r'((?:boy|girl)\w+)', s, re.I)
>>> f
<callable-iterator object at 0x7fb3821e3190>
>>> for m in f:
...     print m.group(1)
...
Boy25e6
girl37b6


text:
Q: spacy with joblib library generates _pickle.PicklingError: Could not pickle the task to send it to the workers I have a large list of sentences (~7 millions), and I want to extract the nouns from them.
I used joblib library to parallelize the extracting process, like in the following:
import spacy
from tqdm import tqdm
from joblib import Parallel, delayed
nlp = spacy.load('en_core_web_sm')

class nouns:

    def get_nouns(self, text):
        doc = nlp(u"{}".format(text))
        return [token.text for token in doc if token.tag_ in ['NN', 'NNP', 'NNS', 'NNPS']]

    def parallelize(self, sentences):
        results = Parallel(n_jobs=1)(delayed(self.get_nouns)(sent) for sent in tqdm(sentences))
        return results

if __name__ == '__main__':
    sentences = ['we went to the school yesterday',
                 'The weather is really cold',
                 'Can we catch the dog?',
                 'How old are you John?',
                 'I like diving and swimming',
                 'Can the world become united?']
    obj = nouns()
    print(obj.parallelize(sentences))

when n_jobs in parallelize function is more than 1, I get this long error:
100%|██████████| 6/6 [00:00<00:00, 200.00it/s]
joblib.externals.loky.process_executor._RemoteTraceback:
"""
Traceback (most recent call last):
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\queues.py", line 150, in _feed
    obj_ = dumps(obj, reducers=reducers)
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\reduction.py", line 243, in dumps
    dump(obj, buf, reducers=reducers, protocol=protocol)
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\reduction.py", line 236, in dump
    _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj)
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 267, in dump
    return Pickler.dump(self, obj)
  File "C:\Python35\lib\pickle.py", line 408, in dump
    self.save(obj)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 841, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 770, in save_list
    self._batch_appends(obj)
  File "C:\Python35\lib\pickle.py", line 797, in _batch_appends
    save(tmp[0])
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 725, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 718, in save_instancemethod
    self.save_reduce(types.MethodType, (obj.__func__, obj.__self__), obj=obj)
  File "C:\Python35\lib\pickle.py", line 599, in save_reduce
    save(args)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 725, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 395, in save_function
    self.save_function_tuple(obj)
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 594, in save_function_tuple
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 841, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 599, in save_reduce
    save(args)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 740, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 740, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 495, in save
    rv = reduce(self.proto)
  File "stringsource", line 2, in preshed.maps.PreshMap.__reduce_cython__
TypeError: self.c_map cannot be converted to a Python object for pickling
"""Exception in thread QueueFeederThread:
Traceback (most recent call last):
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\queues.py", line 150, in _feed
    obj_ = dumps(obj, reducers=reducers)
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\reduction.py", line 243, in dumps
    dump(obj, buf, reducers=reducers, protocol=protocol)
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\reduction.py", line 236, in dump
    _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj)
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 267, in dump
    return Pickler.dump(self, obj)
  File "C:\Python35\lib\pickle.py", line 408, in dump
    self.save(obj)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 841, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 770, in save_list
    self._batch_appends(obj)
  File "C:\Python35\lib\pickle.py", line 797, in _batch_appends
    save(tmp[0])
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 725, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 718, in save_instancemethod
    self.save_reduce(types.MethodType, (obj.__func__, obj.__self__), obj=obj)
  File "C:\Python35\lib\pickle.py", line 599, in save_reduce
    save(args)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 725, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 395, in save_function
    self.save_function_tuple(obj)
  File "C:\Python35\lib\site-packages\joblib\externals\cloudpickle\cloudpickle.py", line 594, in save_function_tuple
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 841, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 810, in save_dict
    self._batch_setitems(obj.items())
  File "C:\Python35\lib\pickle.py", line 836, in _batch_setitems
    save(v)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 599, in save_reduce
    save(args)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 740, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 520, in save
    self.save_reduce(obj=obj, *rv)
  File "C:\Python35\lib\pickle.py", line 623, in save_reduce
    save(state)
  File "C:\Python35\lib\pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "C:\Python35\lib\pickle.py", line 740, in save_tuple
    save(element)
  File "C:\Python35\lib\pickle.py", line 495, in save
    rv = reduce(self.proto)
  File "stringsource", line 2, in preshed.maps.PreshMap.__reduce_cython__
TypeError: self.c_map cannot be converted to a Python object for pickling

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python35\lib\threading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:\Python35\lib\threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Python35\lib\site-packages\joblib\externals\loky\backend\queues.py", line 175, in _feed
    onerror(e, obj)
  File "C:\Python35\lib\site-packages\joblib\externals\loky\process_executor.py", line 310, in _on_queue_feeder_error
    self.thread_wakeup.wakeup()
  File "C:\Python35\lib\site-packages\joblib\externals\loky\process_executor.py", line 155, in wakeup
    self._writer.send_bytes(b"")
  File "C:\Python35\lib\multiprocessing\connection.py", line 183, in send_bytes
    self._check_closed()
  File "C:\Python35\lib\multiprocessing\connection.py", line 136, in _check_closed
    raise OSError("handle is closed")
OSError: handle is closed

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".../playground.py", line 43, in <module>
    print(obj.Paralize(sentences))
  File ".../playground.py", line 32, in Paralize
    results = Parallel(n_jobs=2)(delayed(self.get_nouns)(sent) for sent in tqdm(sentences))
  File "C:\Python35\lib\site-packages\joblib\parallel.py", line 934, in __call__
    self.retrieve()
  File "C:\Python35\lib\site-packages\joblib\parallel.py", line 833, in retrieve
    self._output.extend(job.get(timeout=self.timeout))
  File "C:\Python35\lib\site-packages\joblib\_parallel_backends.py", line 521, in wrap_future_result
    return future.result(timeout=timeout)
  File "C:\Python35\lib\concurrent\futures\_base.py", line 405, in result
    return self.__get_result()
  File "C:\Python35\lib\concurrent\futures\_base.py", line 357, in __get_result
    raise self._exception
_pickle.PicklingError: Could not pickle the task to send it to the workers.

What is the problem in my code?

A: In case if you are still not able to find the solution.
I resolved the error by changing
Parallel(n_jobs=8)

to
Parallel(n_jobs=8, prefer="threads")

A: Same issue. I solved by changing the backend from loky to threading in Parallel.

A:
Q: What is the problem in my code?

Well, most probably the issue comes not from the code, but from the "hidden" processing, that appears, once n_jobs directs ( and joblib internally orchestrates ) to prepare that many exact copies of the main process, so as to let them work independently one of each other ( effectively thus escaping from GIL-locking and mapping the multiple process-flows onto physical hardware resources )
This step is responsible for making copies of all pythonic objects and was known to use Pickle for doing this. The Pickle module was known for its historical principal limitations on what can be pickled and what cannot.
The error message confirms this:

TypeError: self.c_map cannot be converted to a Python object for pickling

One may try a trick to supply Mike McKearns dill module instead of Pickle and test, if your "problematic" python objects will get pickled with this module without throwing this error.
dill has the same API signatures, so a pure import dill as pickle may help with leaving all the other code the same.
I had the same problems, with large models to get distributed into and back from multiple processes and the dill was a way to go. Also the performance has increased.

Bonus: dill allows to save / restore the full python interpreter state!

This was a cool side-effect of finding dill, once import dill as pickle was done, pickle.dump_session( <aFile> ) will save ones complete state-full copy of the python interpreter session. This can be restored, if needed ( post-crash restores, trained trained and optimised ML-model state-fully saved / restored, incremental learning ML-model state-fully saved and re-distributed for remote restores for the deployed user-bases, etc. )

A: An additional answer for my question:
I didn't find a solution for Joblib with Spacy, but instead to parallelize the process, I found that Spacy released something called Pipeline, where you can parse large number of documents with multi-threads.
I applied it with the same example above:
class nouns:

    def get_nouns(self, sentences):
        start = time.time()
        docs = nlp.pipe(sentences, n_threads=-1)
        result = [ ' '.join([token.text for token in doc if token.tag_ in ['NN', 'NNP', 'NNS', 'NNPS']]) for doc in docs]
        print('Time Elapsed {} ms'.format((time.time() - start) * 1000))
        print(result)

if __name__ == '__main__':
    sentences = ['we went to the school yesterday',
                 'The weather is really cold',
                 'Can we catch the dog?',
                 'How old are you John?',
                 'I like diving and swimming',
                 'Can the world become united?']
    obj = nouns()
    obj.get_nouns(sentences)

A: I had a similar problem with paralleling lemmatization, but with another library pymystem3.
from pymystem3 import Mystem
mystem = Mystem()

def preprocess_text(text):
   ...
   tokens = mystem.lemmatize(text)
   ...
   text = " ".join(tokens)
   return text

data_set = Parallel(n_jobs=-1)(delayed(preprocess_text)(article) for article in tqdm(articles))

The solution was to put initialization into function.
def preprocess_text(text):
   ...
   mystem = Mystem()
   tokens = mystem.lemmatize(text)
   ...
   text = " ".join(tokens)
   return text

I suspect you could try the same with nlp = spacy.load

A: Just want to add my two cents. Use @staticmethod over your class method and spare the auto-injected self-object to prevent accidentally serializing a whole framework, as happened in my case (flask). As the framework does a lot of behind-the-scenes injections and blow-up the serialization dependencies.

A: Case study on how I fixed this:
Environment

*

*Windows 10 x64

*Python 3.9 or 3.10

*joblib v1.1

Solution
# Examine the stack trace very carefully, you will see a line something like this:
TypeError: self.c_map cannot be converted to a Python object for pickling

This tells you exactly what variable cannot be serialized.
To fix, choose one option:

*

*Remove the variable from the function.

*Initialize the variable in the function from scratch.

In my case, I had to use a mixture of #1 and #2:

*

*Removed a variable that pointed to a class that had a handle to an open file (it cannot pickle anything with an open file).

*A class variable could not be pickled, so I initialized it again inside the function (which removes the need to serialize this class and pass it to the new process).

Example code
# [Bugfix]. Add next line to initialize this again to eliminate pmap pickle error. Stacktrace is your friend!
hdb = HivedbApi(base_dir=hivedb_base_dir, table_name=table_name, partition_type=PartitionType.HiveFilePerDate)
hdb.write(df_trades)

In the example in the OP, I would be hunting for some variable inside get_nouns() that could not be serialized, based on the stack trace (it will tell you exactly what variable it is stumbling over).
Solutions that did not work
Nothing else on this page worked, including changing backend to threading, pickler to dill, annotating the function, changing Python version, etc.
Bottom line:

Sometimes, nothing can serialize a class, especially if it has handles to open files. In this case, the only solution is to (a) remove these variables from the target function, or (b) reinitialize these variables inside the target function.


text:
Q: Share Laravel Session on Subdomains with different guards I'm currently using spatie/permissions and a Subclass of User with constraints to permissions to Login to subdomains in my application.
I now want to be able to share the session between my main domain example.com and the domains some.example.com where some is dynamically loaded from database.
When my logged-in User in example.com accesses the abc.example.com domain and is able to log in there I want to use the current session.
I use different guards on subdomain and domain with the SubUser and User classes as providers.
I already use the database session driver and can see in the logs that the same session id is loaded from database.
As the application is loading the same session from database I'm wondering why my user is not already logged in.
Anyone ever tried this and got a solution for this?

A: So I managed to resolve this issue.
My setup is all subdomains got the user guard and the main domain has the admin guard.
I realised that the Auth::getName() included the guard name and as I logged in using different guards I ended up having two active logins in one session. But these logins had different names and where only valid with the right guard. This guard being different in main domain and subdomains resulted in not really sharing login-state over domain and subdomains.
I managed to resolve this by overriding the default laravel SessionGuard and adding my own driver like so:
In config/auth.php:

'guards' => [
    'user' => [
        'driver' => 'extended_session',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'extended_session',
        'provider' => 'admins',
    ],
]

In AppServiceProvider.php

\Auth::extend('extended_session', function ($app, $name, $config) {
    $providerConfig = $this->app['config']['auth.providers.'.$config['provider']];
    // If you don't use eloquent you need to alter the next line accordingly
    $provider = new EloquentUserProvider($app['hash'], $providerConfig['model']);
    return new SessionGuardExtended('extended_session', $provider, $this->app['session.store']);
});

And add a new Class named SessionGuardExtended like this:
use Illuminate\Auth\SessionGuard;
class SessionGuardExtended extends SessionGuard{}

This results in a shared session with the same auth name for domain and subdomains.

A: Add SESSION_DOMAIN to your .env file and set it to .example.com


text:
Q: Razor Pages .net 6.0 generate Divs on server side I want the program can generate Divs using tagbuilder or any methods in a for loop on theserver side.
For exmaple. In my demo.cshtml.cs
private async Task LoadAsync()
{
   for (int i = 0; i < 15; i++)
       {
          var div = new TagBuilder("div");
          div.AddCssClass("template");
          SOMECODE I DONT KNOW, NEED HELP
       }
}

and in my cshtml, what code should I add to make those Divs appear.

A: You can try to use a html string:
[BindProperty]
        public string htmlString{ get; set; };
private async Task LoadAsync()
{
   for (int i = 0; i < 15; i++)
           {
              var div = "

";
              htmlString+=div;
           }
}

And then if you want to use it in demo.cshtml,try to use @Html.Raw(Model.htmlString)


text:
Q: How can I solve Uncaught TypeError: Cannot read property 'call' of undefined? I implement summernote in my project
My project use laravel 5.3 & vue.js 2
My javascript code like this :
$(function () {
    $('.summernote').summernote({
        height: 200
    });
});

I compile my project use laravel-elixir
If I run : gulp watch and run my form(the textarea use summernote), it's no error
But if I run : gulp --productionand run my form(the textarea use summernote), there exist error :

Uncaught TypeError: Cannot read property 'call' of undefined

How can I solve the error?

A: There is an error on autosize.min.js According to this Post
Try:
autosize.js instead of autosize.min.js.
I post my comment to answer for future reference.


text:
Q: Runing alias or function in background I am connecting to an OpenVPN server from my Linux Mint 19.1 machine. As the Network manager is not setting up routes properly is one uses the GUI to connect I connect by executing:
sudo openvpn --config <config-file.ovpn> &

To make things easier I have stored all my VPN settings in a hidden folder using a specific tree structure. I wanted to define an alias or a function that executes the above command with a particular VPN setting, that I can call from anywhere.
I've added the following to my .bashrc
alias OpenVPN='read -p "VPN name: " VPN_NAME
my_path=~/.openvpn.confs/${VPN_NAME}/OpenVPN
VPN_CONF=${my_path}/vpnconfig.ovpn
sudo openvpn --config $VPN_CONF'

This works well but I have to keep the terminal open as it runs in interactive mode. I wanted to have it spin up and run in the background so I added a "&" to the last command, which works fine if I call that command manually from the terminal. sudo openvpn --config $VPN_CONF & But when I add it to the alias, the system still thinks it is running continuously in the background, but the connection does not work.
I also tried running it as a function, which does not connect either.
OVPN() { sudo openvpn ~/.openvpn.confs/"$@"/OpenVPN/vpnconfig.ovpn & }

Any suggestions for how this might be solved?

A: After seeing this answer about sudo in the background and doing some trial and error, I have solved it by verifying the user privileges separately, before executing the command in the background:
alias OpenVPN='read -p "VPN name: " VPN_NAME
my_path=~/.openvpn.confs/${VPN_NAME}/OpenVPN
VPN_CONF=${my_path}/vpnconfig.ovpn
sudo -v
sudo openvpn --config $VPN_CONF'

Here sudo -v stands for validate, which means that it validates and updates the user sudo timestamp without running a command. Once this is done the following sudo commands do not prompt for a password as this has already been provided.


text:
Q: prisma query change add custom column in select and update field Below is the snippet with comments that, we are planning to achieve with Prisma orm query, which is quite possible in raw SQL.
class User {
  id: number;
  type: 'custom' | 'default' | 'legacy';
  name: string;
  email: string;
  dep?: string;
  createdAt: Date;
  updatedAt: Date

}

prisma.users.findMany({
        where: {
          type: {in : ['custom', 'legacy']},
        },
        select:{
          type: // constant as 'custom'
          dep: true // want to alert it to department
        }
        // add new property, not part of schema
        createdBy: 'System'
      })

Not able to find anything in the doc related to requirements here.

*

*set a constant value for a field here e.g. type to custom

*change filed/column name e.g. dep -> department

*add new filed/column which is not part of table schema