text:
Q: Replacing broken urls (dreamweaver) to new ones in wordpress I am moving an entire site from html and dreamweaver format to wordpress. I imported the content using htlm import plugin that worked well. Now I have to correct all content links as they kept the same variable url format applied by dreamweaver and as I have changed the dite directory structure, most of them are broken now.
Basically, my issue is the following:
1) OLD site internal links urls  (dreamweaver):
page

2)Now, in WP, the correct url for it would be:
page

I am using BrokenLinks and Search&Replace plugins to correct them and my questions are:
Should i replace the old url (1 above) to:
a) page (2 above), or
b) page ( I noticed that even though it is not the final full url (parent page and page), a link with this url works well in WP, probably due any redirect rules.

Even though both will finally work,  I want to know if:
What should be the format (a or b above) I should use to replace the old ones to avoid problem in case I decide to modify the parent page, for example, from "/parentpage/page/" to "/parentpageX/page/"? My doubt is if I use the option "b" to replace the old one, if I change the parent page some time, this link would become broken again?
What is the better option take into account SEO?
Do you suggest any better method to handle this old broken url issue?
Thanks in advance for any help

A: I would use #2 (/parentpage/page/), since that's the 'official' URL WP assigned to it, WP will find the right page faster and it may help you with your SEO.
Yes, if you change slugs it will be a broken link, you could use the Redirection plugin for that (it has the option to add a redirection from the old slug to the new slug, I believe it's activated by default).


text:
Q: Circuit Considerations Note: Can skip all images except last, which is a schematic created using the editor.
I am at a point in the design process where I have created a schematic of the circuit that I want to create. I am using a buck converter to step down a 24V DC battery to 5V and using that battery to power an arduino. This arduino is acting as a speed controller, using PWM and getting input from external switch to set the speed. The input from this switch will be programatically read to set the speed output. The 5V output signal from the arduino then gets run through an op-amp configured as a non-inverting amplifier and drives a motor. The schematic follows: []1
This is the first real circuit I have created, and I don't know where to go from here. It is more than likely that I have made a mistake somewhere or forgotten a part or some heat/power consideration, but I don't have the slightest idea (1) how I could check my circuit for those things or (2) how I would remedy them.
I was wondering how I could go about doing these things and improving my knowledge of electronics in this way. I apologize if this question is somewhat vague; however, I really respect this community and the years of experience you have in the field, and I was hoping that your insights would be valuable in this question, as I don't really know how I could make it more specific. Thanks.
EDIT 1: Ok, after suggestion I am replacing the op-amp with an n-channel MOSFET as follows (Edit 2: added a 10K pull-down resistor on the gate of the MOSFET):

EDIT 3: Added pull down resistor to schematic and flipped MOSFET:

EDIT 4: Adding a full schematic (Edit 5: switched NMOS and Motor position):

simulate this circuit – Schematic created using CircuitLab

A: Your power supply concept makes sense (using a buck converter to make 5 V from 24 V), but your motor driver needs work.
The voltage follower you show in your second schematic won't deliver much voltage to the motor.  The FET will likely need a few volts G-S to turn on enough to allow useful motor current.  With the gate at 5 V, that leaves very little to the motor.  It also uses the 24 V supply very inefficiently.  Most of the power will go into heating the FET, not running the motor.
Your third schematic makes no sense at all.  A flipped N channel MOSFET has a internal diode from source to drain, so the motor will always be on with over 23 V on it, and regardless of what you do with the gate.
I would use a N channel MOSFET as a low side switch.  Connect the motor between its drain and the 24 V supply, and don't forget the Schottky flyback catch diode in reverse across the motor.  Use PWM to set the effective motor voltage.  For example, if the motor is supposed to run from 6 V, then use 25% duty cycle.  This is also much more efficient.
Something like the IRLML0030 can be driven directly from the 5 V PWM output of the microcontroller.  At 40 mΩ, it will only dissipate 40 mW with 1 A thru it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asp.net owin UseCookieAuthentication ExpireTimeSpan I have a Asp.net mvc project that utilizes cookie authentication with auth 0. I have set the following configuration where ExpireTimeSpan is set to 10s.
app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                LoginPath = new PathString("/Account/Login"),

                // Configure SameSite as needed for your app. Lax works well for most scenarios here but
                // you may want to set SameSiteMode.None for HTTPS
                CookieSameSite = SameSiteMode.Lax,
                // More information on why the CookieManager needs to be set can be found here:
                // https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues
                CookieManager = new SameSiteCookieManager(new SystemWebCookieManager()),
                ExpireTimeSpan = TimeSpan.FromSeconds(10)
            });

Looking at the browser, I see the cookie has an expiration of "Session".

My understanding is that this means that the cookie will last until the user closes the browser; however, the ExpireTimeSpan refers to the AuthTicket inside the cookie, and that should expire in 10s.
After about a minute, when I try to make another call to a place that requires authentication, it still allowed me to reach the page, but shouldn't it reject the expired ticket and force me to log back in?
I also saw the cookie value is still xwMhubv...., so I know it's not generating a new cookie value in the background.
Am I misunderstanding something, or am I missing another configuration somewhere?
Thanks.


text:
Q: How to process a set of images in webpack I've been trying to wrap my head around webpack. I have a really hard time digesting it. I can't tell you how many tutorials I've read. I went through nearly all of them on their website. Read the docs section twice. I've watched video tutorials on lynda and youtube. Been struggling with it for nearly a week. I still can't understand most of it.
So just for the heck of it, let's say I want to process a set of images. There's no project, there are no modules, javascript or nothing. I just want to process the images. Why? No reason. Just to get to understand how webpack works and play around with the config file in various ways trying to understand it.
With that said, all I want to do is move a set of images from the 'app/img' folder to the 'build/img' folder, and maybe incorporate the hash in the file name. Eg:
module.exports = {
    entry: {
        entry: ''
    },
    output: {
        path: 'build',
        filename: ''
    },
    module: {
        loaders: [
            {
                test: /\.(png)$/,
                loader: 'file?name=img/[name]-[hash].[ext]',
                include: './app/img/'
            }
        ]
    }
};

Since there's no js file to output (hence I just want to images to be process), there's no entry for 'entry' and 'output' - or at least I'm not sure what to put there.
How would I go about doing this? Because as it stands, this config files is not correct, but I have no idea how to make it work. Thanks.
PS: I have the file-loader package downloaded, which I'm trying to use for this.

A: Webpack is more bundler than task runner like gulp or grunt. You are trying develop simple copy task with rename files - this is not how you should use Webpack.
loaders will be fired only when test scenario will match path in require or import. So since you don't have any importing statements your loader never be used.


text:
Q: How to escape % in a query using python's sqlalchemy's execute() and pymysql? My query is:
result = connection.execute(
         "select id_number from Table where string like '_stringStart%' limit 1;")

gives the error:
query = query % escaped_args
TypeError: not enough arguments for format string

A quick google said to use %% instead of % but that doesn't work either. How do I escape the % or is there another way to query for a string that starts with a random letter then a certain sequence?

A: Since this is a literal string, you're better off using a bound parameter here (illustrated using text()):
from sqlalchemy import text

connection.execute(
    text("select * from table where "
         "string like :string limit 1"),
    string="_stringStart%")

A: Another way to implement bound parameters:
from sqlalchemy import text

connection.execute(
    text("select id_number from Table where string like :string limit 1").\
    bindparams(string="_stringStart%")
)

or even typed strictly:
from sqlalchemy import bindparam, String, text

connection.execute(
    text("select id_number from Table where string like :string limit 1").\
    bindparams(bindparam("string", type_=String)),
    {"string"="_stringStart%"}
)

Bear in mind that text() construct  is deprecated sine SQLAlchemy 1.4 and will be removed in SQLAlchemy 2.0.


text:
Q: How to define an array in C I'm reading the book "Cracking the Coding Interview" which contains several examples of algorithms in C. I'd like to make programs which implement these algorithms and run them as I go along.
One such algorithm is "Min and Max 1" (from the "Big O" chapter):
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int x : array) {
  if (x < min) min = x;
  if (x > max) max = x;
}

I've attempted to 'write a program around this' as follows:
#include<stdio.h>

int array[5] = [1, 3, 2, 5, 4];

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

int main(void):
{
  for (int x : array) {
    if (x < min) min = x;
    if (x > max) max = x;
  }
  printf("The minimum is %i", min)
  printf("The maximum is %i", max)
}

However, if I try to compile and run this I get the error: expected identifier before numeric constant int array[5] = [1, 3, 2, 5, 4];. How would I correctly implement this algorithm for this example input array?

A: What you mean is the following
#include <stdio.h>
#include <limits.h>

#define N   5

int main( void )
{
    int array[N] = { 1, 3, 2, 5, 4 };

    int min = INT_MAX;
    int max = INT_MIN;

    for ( size_t i = 0; i < N; i++ )
    {
        if ( array[i] < min ) min = array[i];
        if ( max < array[i] ) max = array[i];
    }

    printf( "The minimum is %i\n", min );
    printf( "The maximum is %i\n", max );

    return 0;
}

The program output is
The minimum is 1
The maximum is 5

As for your program then it contains invalid constructions according to the C grammar.
In C++ the loop can look the same way as you showed.
#include <iostream>
#include <limits>

int main()
{
    const size_t N = 5;
    int array[N] = { 1, 3, 2, 5, 4 };

    int min = std::numeric_limits<int>::max();
    int max = std::numeric_limits<int>::min();

    for ( int x : array )
    {
        if ( x < min ) min = x;
        if ( max < x ) max = x;
    }

    std::cout << "The minimum is " << min << std::endl;
    std::cout << "The maximum is " << max << std::endl;

    return 0;
}

Take into account that there is no sense to declare the array like global.
As for the array definition in C then you can define it either like
int array[5] = { 1, 3, 2, 5, 4 };

(or using some named constant instead of the number 5)
or like
int array[] = { 1, 3, 2, 5, 4 };

In the last case the number of elements is equal to the number of the initializers. Or even you can use the following initialization
int array[] = { [0] = 1, [1] = 3, [2] = 2, [3] = 5, [4] = 4 };

A: A few issues:

*

*int array[5] = [1, 3, 2, 5, 4]; needs to be int array[] = {1, 3, 2, 5, 4};

*The short form for loop doesn't exist in C. (Are you using a C++11 compiler to compile C code? If so then saving your source file with a .c extension might be a simple way of putting it into C mode.) Use for (size_t i = 0; etc. instead and access the array elements by the index i.

*Using min and max as variable names is to be discouraged as they frequently appear as macro definitions.

A: Use C syntax to implement it in C.

*

*Use {}, not [], to define the initial values of arrays.

*Use INT_MIN and INT_MAX from limits.h to use minimum and maximum values of int.

*Don't place a colon after int main(void).

*for (int x : array) is not supported in C. Use one of the supported forms of loops.

*Semicolons are required after each statements.

Here is an implementation in C99:
#include<stdio.h>
#include<limits.h>

int array[5] = {1, 3, 2, 5, 4};

int min = INT_MAX;
int max = INT_MIN;

int main(void)
{
  for (size_t i = 0; i < sizeof(array) / sizeof(*array); i++) {
    int x = array[i];
    if (x < min) min = x;
    if (x > max) max = x;
  }
  printf("The minimum is %i", min);
  printf("The maximum is %i", max);
}

A: Array is initialized inside {} not []
Looks like you copied it from wrong place or you are a java Programmer.
#include<stdio.h>

int a[5] = {1, 3, 2, 5, 4};

int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

int main(void):
{

  for (int x : array) {
    if (x < min) min = x;
    if (x > max) max = x;
  }
  printf("The minimum is %i", min)
  printf("The maximum is %i", max)
}

This will still give you error if you want i can fix it. I left it so that you can learn this by your own.


text:
Q: Which one is correct "I think he like it" or "I think he likes it?" I am confused if I need to use 3-person verb from with a sentence like "I think he like/likes it."
What is it called in English?

A: The correct usage is "I think he likes it."
For the verb to like the only change is in the the 3rd person singular.


text:
Q: javascript: непонятное поведение при использовании синглтона (в примитивном react компоненте) реализовал синглтон, от которого наследуется другой класс:
class ISingleton
{
    private static _instance?: ISingleton;

    counter: number = 10

    constructor() {
        if (ISingleton._instance)
            return ISingleton._instance;

        ISingleton._instance = this;
    }
}

export class IData extends ISingleton
{
    counter2: number = 10
}

Написал компонент с 2 кнопками - при нажатии на кнопки счетчики увеличиваются и уменьшаются:
class App extends React.Component<any, any> {

  updateCounter = (delta: number) => {

    const data: IData = new IData();
    data.counter += delta;
    data.counter2 += delta;

    console.log(data);
  }

  render() {
    return (
      <div className = "App">
        <button className = "btn" onClick = {() => this.updateCounter(-1)}>Dec</button>
        <button className = "btn" onClick = {() => this.updateCounter(+1)}>Inc</button>
      </div>
    );
  }
}

export default App;

При нажатии несколько раз на кнопку Inc и кнопку Dec наблюдаю следующее:

Объясните мне пожалуйста, почему counter2 уникален для каждой кнопки и меняется только 1 раз для нажатия на каждую кнопку, а counter работает как и ожидается - он общий для всех кнопок и меняется при нажатии на любую кнопку


text:
Q: Getting Shell Syntax error operand expected Hi guys I am gettig a syntax error when I run this small Shell script and can't figure it out :
#!/bin/sh
echo "begin performance logging" > perflog.log
date +"%T.%4N" >> perflog.log
typeset -i startTime=`date +%s`
typeset -i elapse=20
endTime=$(( elapse + startTime ))
while (('date +%s' < endTime)); do
perf top --sort cpu >> perflog.log
done

the error is :
line 7: ((: date +%s < 31555764956: syntax error: operand expected ( error token is "%s < 31555764956")


text:
Q: On an integral inequality involving $L^1(\Omega)$ and bounded functions Let $\Omega$ be an open bounded domain in $\mathbb{R}^N$, let $h\in L^1(\Omega)$ and let $u(t)$ be such that $0<u(t)<R$. Moreover, we set $h_{\mu}(t) =\mu h(t) +(1-\mu)\bar{h}$, with $\bar{h}=\frac{1}{T}\int_0^T h(t) dt$ and $\mu\in [0, 1]$.
I am trying to understand why the inequality
$$\int_0^T h_{\mu}(t) u(t) dt\le (R+T)\|h\|_{L^1}.$$
holds true.
I would proceed in this way:
$$\int_0^T h_{\mu}(t) u(t) dt\le \mu \int_0^T h(t)u(t) dt +(1-\mu)RT\bar{h}\le \mu R\|h\|_{L^1} +(1-\mu)RT\bar{h},$$
but I am stuck in here.
Could someone please help me to obtain the desired result?
Thank you in advance!

A: Can you show that $T\bar{h} \leq ||h||_{L}$ and that $R \leq (T+R)$ ?


text:
Q: SQL Join - Show data if a joined table doesn't hold any data I have a query that joins 3 tables together.
One is a SPAAPPOINTMENTS table - (Spa appointments with price charged in)
The second is SPAAPTADDONS - Addons for the appointments (Nibbles etc), Links between apts and rst
The third is RSTCATALOG table  - Where the addon price is located.
The query:
SELECT        SPAAPPOINTMENTS.APTID, SPAAPPOINTMENTS.SERVICECODE, SPAAPPOINTMENTS.LOCATIONCODE, SPAAPPOINTMENTS.STAFFCODE,
                         SPAAPPOINTMENTS.BLOCKSTARTTIME, SPAAPPOINTMENTS.BLOCKENDTIME, SPAAPPOINTMENTS.I_RECID, SPAAPPOINTMENTS.S_STAYID,
                         SPAAPPOINTMENTS.STATUSCODE, SPAAPPOINTMENTS.BLOCKEDTIME, SPAAPPOINTMENTS.GRATUITY, SPAAPPOINTMENTS.TEMPHOLDID,
                         SPAAPPOINTMENTS.LASTCHGID, SPAAPPOINTMENTS.CANCELID, SPAAPPOINTMENTS.ITEMNO, SPAAPPOINTMENTS.COMMENTS,
                         SPAAPPOINTMENTS.OFFSITELOCATION, SPAAPPOINTMENTS.PRICE, SPAAPPOINTMENTS.PRIORITY, SPAAPPOINTMENTS.SPAPKGCODE,
                         SPAAPPOINTMENTS.ENFORCEGENDER, SPAAPPOINTMENTS.NEWSTATUS, SPAAPPOINTMENTS.RESTNO, SPAAPPOINTMENTS.DONOTMOVE,
                         SPAAPPOINTMENTS.NOSHOW, SPAAPPOINTMENTS.OTHERGENDERREQUESTED, SPAAPPOINTMENTS.MADEBY, SPAAPPOINTMENTS.LINKCODE,
                         SPAAPPOINTMENTS.CONFIRMED, SPAAPPOINTMENTS.CXLNUMBER, SPAAPPOINTMENTS.REQUEST, SPAAPPOINTMENTS.CUSTOMFIELD1,
                         SPAAPPOINTMENTS.CUSTOMFIELD2, SPAAPPOINTMENTS.CUSTOMFIELD3, SPAAPPOINTMENTS.VIP, SPAAPPOINTMENTS.NOPREFERENCE,
                         SPAAPPOINTMENTS.CUSTOMFIELD4, SPAAPPOINTMENTS.CUSTOMFIELD5, SPAAPPOINTMENTS.BOOKID, SPAAPPOINTMENTS.ARTSRESVNO,
                         SPAAPPOINTMENTS.LMSCONFNO, SPAAPPOINTMENTS.ARTSGUESTID, SPAAPPOINTMENTS.CLUBNO, SPAAPPOINTMENTS.MULTIGRPID,
                         SPAAPPOINTMENTS.MAINCONTACT, SPAAPPOINTMENTS.SPABKNAME, SPAAPPOINTMENTS.MULTIGRPAPPTXT, SPAAPPOINTMENTS.CONFCOMMENTS,
                         SPAAPPOINTMENTS.MEMCODE, SPAAPPOINTMENTS.FAMILYMEMTYPE, SPAAPPOINTMENTS.COCOMMENTS, SPAAPPOINTMENTS.GRPMASTERID,
                         SPAAPPOINTMENTS.GUESTTYPE, SPAAPPOINTMENTS.EXTUNIQUEID, SPAAPPOINTMENTS.SETUPTIME, SPAAPPOINTMENTS.BREAKDOWNTIME,
                         SPAAPPOINTMENTS.PSBASEPRICE, SPAAPPOINTMENTS.PSCODE, SPAAPPOINTMENTS.PSCALENDARADJPCT, SPAAPPOINTMENTS.PSDETAILADJ,
                         SPAAPPOINTMENTS.PSPRICE, SPAAPPOINTMENTS.PSDETAILADJSOURCE, SPAAPPOINTMENTS.PSDETAILADJTYPE, SPAAPPOINTMENTS.PSPRICETYPE,
                         RSTCATALOG.C_DPRICE
FROM  SPAAPPOINTMENTS
  INNER JOIN SPAAPPTADDONS ON SPAAPPOINTMENTS.APTID = SPAAPPTADDONS.APTID
  INNER JOIN RSTCATALOG ON SPAAPPTADDONS.ITEMNO = RSTCATALOG.C_ITEM

This returns all data from the appointments table AS LONG AS THEY HAD A ADDON to the Spa Appointment.
If they just had an appointment, and no Add on, it doesn't return the data.
For example, if i use the query and postfix it with: WHERE (SPAAPPOINTMENTS.APTID = 626746)
It doesn't show any data, but there is a line in spaappopintments but NOTHING in the addons table.
If I use anopther AptID, which HAS HAD AN ADDON, it shows the data and is output from the query.
How can I get to show the data if there is NO data in the SPAAPTADDONS table please anyone?

A: Change the below INNER JOIN line
INNER JOIN SPAAPPTADDONS ON SPAAPPOINTMENTS.APTID = SPAAPPTADDONS.APTID
INNER JOIN RSTCATALOG ON SPAAPPTADDONS.ITEMNO = RSTCATALOG.C_ITEM

To an LEFT OUTER JOIN like
LEFT JOIN SPAAPPTADDONS ON SPAAPPOINTMENTS.APTID = SPAAPPTADDONS.APTID
LEFT JOIN RSTCATALOG ON SPAAPPTADDONS.ITEMNO = RSTCATALOG.C_ITEM

A: FROM  SPAAPPOINTMENTS
LEFT JOIN SPAAPPTADDONS ON SPAAPPOINTMENTS.APTID = SPAAPPTADDONS.APTID
LEFT JOIN RSTCATALOG ON SPAAPPTADDONS.ITEMNO = RSTCATALOG.C_ITEM

let all data from SPAAPPOINTMENTS to be in the result.

A: When you join tables together you specify a left and a right table. An inner join will produce a set where the join condition is true for both the left and right side.
What you want is to get a set that has all the data from the left table along with the matching data from the right side. This is a left join.
But, as you also want to get the pricing information for the addons you need to join the third table too. As we can assume that there is a one-to-one matching between the addons and the pricing table it looks like we could use an inner join here, but this won't work as the joins are performed in order, meaning that last join will use the result from the first join as its left side (and that set will have null values for the appointments without any addons) - if we try to do an inner join with the pricing table those rows would be excluded, so you need a left join here too.
In the end you want this:
FROM SPAAPPOINTMENTS
LEFT JOIN SPAAPPTADDONS ON SPAAPPOINTMENTS.APTID = SPAAPPTADDONS.APTID
LEFT JOIN RSTCATALOG    ON SPAAPPTADDONS.ITEMNO  = RSTCATALOG.C_ITEM

On a side note I would encourage you to use table aliases to make the query a bit shorter and more readable. Something like this:
FROM SPAAPPOINTMENTS    apt
LEFT JOIN SPAAPPTADDONS add ON apt.APTID  = add.APTID
LEFT JOIN RSTCATALOG    rst ON add.ITEMNO = rst.C_ITEM


text:
Q: How to fix the there is no attribute "tick" in my code when what everyone else is doing is pygame.time.Clock.tick()? Well , I was trying to make a game with pygame in python ( ver. 3.10.5 ) . I wanted to set Frames Per Seconds , that is FPS for the game by first doing clock = pygame.time.Clock outside the main loop and then doing clock.tick(FPS) , (FPS was another variable before with a value of 27). In every video in Youtube , it works , but in my one it shows "builtin_function_or_method' object has no attribute 'tick' " . I searched a lot but can't find the proper fix or alternative. Please help
import pygame

pygame.init()

window = pygame.display.set_mode((500 , 500))
pygame.display.set_caption("G")

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]
bg = pygame.image.load('bg.jpg')
char = pygame.image.load('standing.png')

clock = pygame.time.Clock

x = 50
y = 50
width = 64
height = 64
vel = 5

FPS = 27

jumping = False
jump_count = 10

left = False
right = False
walkCount = 0

def redrawGameWindow():
    global walkCount

    window.blit(bg , (0, 0))

    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        window.blit(walkLeft[walkCount//3] , (x,y))
    pygame.display.update()

running = True
while running:
    clock.tick(FPS)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if running == False:
            pygame.quit()

    neg = 1

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
        x = x - vel
        left = True
        right = False
    elif keys[pygame.K_RIGHT]:
        x = x + vel
        right = True
        left = False
    else:
        left = False
        right = False
        walkCount = 0
    if not (jumping):
        if keys[pygame.K_UP]:
            y = y - vel
        if keys[pygame.K_DOWN]:
            y = y + vel
        if keys[pygame.K_SPACE]:
            jumping = True
    else:
        if jump_count >= -10:
            neg = 1
            if jump_count < 0:
                neg = -1
            y -= jump_count ** 2 * 0.5 * neg
            jump_count -= 1
        else:
            jumping = False
            jump_count = 10

    redrawGameWindow()

This is what I tried and i cant fix pls help it shows builtin_function_or_method' object has no attribute 'tick'

A: pygame.time.Clock is a class. You have to create an instance object of that class:
clock = pygame.time.Clock
clock = pygame.time.Clock()


text:
Q: Puma don't start after capistrano deploy I have a problem with my capistrano configuration. I have tried to follow severals tutorials without success. When I deploy, everything is good but at the end the deploy finishes without starting puma.
➜  api git:(master) ✗ cap production deploy
roicoeur@51.15.209.247's password:
rvm 1.29.9 (latest) by Michal Papis, Piotr Kuczynski, Wayne E. Seguin [https://rvm.io]
ruby-3.0.0
ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-linux]
00:00 git:wrapper
      01 mkdir -p /tmp
    ✔ 01 roicoeur@51.15.209.247 0.061s
      Uploading /tmp/git-ssh-a0da9a635c16c5f6b69d.sh 100.0%
      02 chmod 700 /tmp/git-ssh-a0da9a635c16c5f6b69d.sh
    ✔ 02 roicoeur@51.15.209.247 0.073s
00:00 git:check
      01 git ls-remote git@gitlab.com:RoiCoeur/roi_coeur_api.git HEAD
      01 15fa8415b1bdebdf2fddc3b3562c9bc6d86be5a9       HEAD
    ✔ 01 roicoeur@51.15.209.247 2.533s
00:02 deploy:check:directories
      01 mkdir -p /data/roi_coeur_api/shared /data/roi_coeur_api/releases
    ✔ 01 roicoeur@51.15.209.247 0.020s
00:02 deploy:check:linked_dirs
      01 mkdir -p /data/roi_coeur_api/shared/public/assets
    ✔ 01 roicoeur@51.15.209.247 0.064s
00:02 deploy:check:make_linked_dirs
      01 mkdir -p /data/roi_coeur_api/shared/config
    ✔ 01 roicoeur@51.15.209.247 0.064s
00:03 git:clone
      The repository mirror is at /data/roi_coeur_api/repo
00:03 git:update
      01 git remote set-url origin git@gitlab.com:RoiCoeur/roi_coeur_api.git
    ✔ 01 roicoeur@51.15.209.247 0.077s
      02 git remote update --prune
      02 Fetching origin
      02 From gitlab.com:RoiCoeur/roi_coeur_api
      02    471f1356..15fa8415  master     -> master
    ✔ 02 roicoeur@51.15.209.247 3.575s
00:07 git:create_release
      01 mkdir -p /data/roi_coeur_api/releases/20210427082855
    ✔ 01 roicoeur@51.15.209.247 0.071s
      02 git archive master | /usr/bin/env tar -x -f - -C /data/roi_coeur_api/releases/20210427082855
    ✔ 02 roicoeur@51.15.209.247 0.954s
00:08 deploy:set_current_revision
      01 echo "15fa8415b1bdebdf2fddc3b3562c9bc6d86be5a9" > REVISION
    ✔ 01 roicoeur@51.15.209.247 0.068s
00:08 deploy:symlink:linked_files
      01 mkdir -p /data/roi_coeur_api/releases/20210427082855/config
    ✔ 01 roicoeur@51.15.209.247 0.066s
      02 ln -s /data/roi_coeur_api/shared/config/database.yml /data/roi_coeur_api/releases/20210427082855/config/database.yml
    ✔ 02 roicoeur@51.15.209.247 0.066s
      03 rm /data/roi_coeur_api/releases/20210427082855/config/secrets.yml
    ✔ 03 roicoeur@51.15.209.247 0.063s
      04 ln -s /data/roi_coeur_api/shared/config/secrets.yml /data/roi_coeur_api/releases/20210427082855/config/secrets.yml
    ✔ 04 roicoeur@51.15.209.247 0.065s
00:09 deploy:symlink:linked_dirs
      01 mkdir -p /data/roi_coeur_api/releases/20210427082855/public
    ✔ 01 roicoeur@51.15.209.247 0.065s
      02 rm -rf /data/roi_coeur_api/releases/20210427082855/public/assets
    ✔ 02 roicoeur@51.15.209.247 0.079s
      03 ln -s /data/roi_coeur_api/shared/public/assets /data/roi_coeur_api/releases/20210427082855/public/assets
    ✔ 03 roicoeur@51.15.209.247 0.049s
00:09 bundler:config
      01 ~/.rvm/bin/rvm default do bundle config --local deployment true
      01 Unknown ruby interpreter version (do not know how to handle): 3.0.0.
    ✔ 01 roicoeur@51.15.209.247 1.043s
      02 ~/.rvm/bin/rvm default do bundle config --local path /data/roi_coeur_api/shared/bundle
      02 Unknown ruby interpreter version (do not know how to handle): 3.0.0.
    ✔ 02 roicoeur@51.15.209.247 0.987s
      03 ~/.rvm/bin/rvm default do bundle config --local without development:test
      03 Unknown ruby interpreter version (do not know how to handle): 3.0.0.
    ✔ 03 roicoeur@51.15.209.247 1.009s
00:13 bundler:install
      The Gemfile's dependencies are satisfied, skipping installation
00:13 deploy:assets:precompile
      01 ~/.rvm/bin/rvm default do bundle exec rake assets:precompile
      01 Unknown ruby interpreter version (do not know how to handle): 3.0.0.
      01 Yarn executable was not detected in the system.
      01 Download Yarn at https://yarnpkg.com/en/docs/install
      01 Yarn executable was not detected in the system.
      01 Download Yarn at https://yarnpkg.com/en/docs/install
    ✔ 01 roicoeur@51.15.209.247 148.221s
02:42 deploy:assets:backup_manifest
      01 mkdir -p /data/roi_coeur_api/releases/20210427082855/assets_manifest_backup
    ✔ 01 roicoeur@51.15.209.247 0.063s
      02 cp /data/roi_coeur_api/releases/20210427082855/public/assets/.sprockets-manifest-8ff059873481df0a51f05274710bdeca.json /data/roi_coeur_api/releases/20210427082855/assets_manifest_backup
    ✔ 02 roicoeur@51.15.209.247 0.071s
02:42 deploy:symlink:release
      01 ln -s /data/roi_coeur_api/releases/20210427082855 /data/roi_coeur_api/releases/current
    ✔ 01 roicoeur@51.15.209.247 0.060s
      02 mv /data/roi_coeur_api/releases/current /data/roi_coeur_api
    ✔ 02 roicoeur@51.15.209.247 0.276s
02:42 deploy:cleanup
      Keeping 5 of 6 deployed releases on 51.15.209.247
      01 rm -rf /data/roi_coeur_api/releases/20210426123044
    ✔ 01 roicoeur@51.15.209.247 0.086s
02:43 deploy:log_revision
      01 echo "Branch master (at 15fa8415b1bdebdf2fddc3b3562c9bc6d86be5a9) deployed as release 20210427082855 by remybeauperin" >> /data/roi_coeur_api/revisions.log
    ✔ 01 roicoeur@51.15.209.247 0.068s
➜  api git:(master)

You can see my capistrano config here:
# puma.rb
threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 }
threads threads_count, threads_count

port        ENV.fetch('PORT') { 3000 }

environment ENV.fetch('RAILS_ENV') { 'development' }

plugin :tmp_restart
####################################################

# deploy.rb
lock "~> 3.16.0"

set :application, 'app'
set :repo_url, 'git@gitlab.com:******/******.git'
set :deploy_to, -> { "/data/#{fetch(:application)}" }

# Default branch is :master
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
set :branch, ENV['BRANCH'].nil? ? :master : ENV['BRANCH']

# set :pty, true

set :ssh_options,
    forward_agent: true,
    keys: [
      File.join(ENV['HOME'], '.ssh', 'id_rsa')
    ]

append :linked_files, 'config/database.yml', 'config/secrets.yml'

after "deploy:updated", "deploy:migrate"
####################################################

# Capfile
require "capistrano/setup"

require "capistrano/deploy"

require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

require 'capistrano/rails'

require "capistrano/rvm"
require "capistrano/bundler"
require "capistrano/rails/assets"
require "capistrano/rails/migrations"

require "capistrano/puma"
install_plugin Capistrano::Puma

Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
####################################################

# Gemfile
ruby '3.0.0'

source 'https://rubygems.org'
...

gem 'puma'

group :development do
  gem 'capistrano',         require: false
  gem 'capistrano-rvm',     require: false
  gem 'capistrano-rails',   require: false
  gem 'capistrano-bundler', require: false
  gem 'capistrano3-puma',   require: false
end
####################################################

I can't explain this problem. Can anyone see what it is?
EDIT
When I try to force the puma:restart in my deploy.rb I have this :
Caused by:
Don't know how to build task 'puma:restart' (See the list of available tasks with `cap --tasks`)

and effectively in cap --tasks i have nothing else for Puma cmd :
...
cap git:wrapper                    # Upload the git wrapper script, this script guarantees that we can script git without getting an interactive prompt
cap install                        # Install Capistrano, cap install STAGES=staging,production
cap puma:config                    # Setup Puma config file
cap rvm:check                      # Prints the RVM and Ruby version on the target host

A: I checked my project and the differences are
## Gemfile
gem 'capistrano3-puma', github: 'seuros/capistrano-puma'

## Capfile
install_plugin Capistrano::Puma, load_hooks: true


text:
Q: One connection for whole of the form hi guys I have this connection and I have to type it every time when I need my db is there any way to type it once and using it in every button by con.open(); and con.close();
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");

A: Yes.  Use a function.
private OleDbConnection GetConnection()
{
    return new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
}

Then when you need a connection, call it:
var con = GetConnection();

Functions promote code re-use.  This code can further be improved by moving the connection string into a configuration file.


text:
Q: How to make MPEG-DASH to stream different qualities based on time slices i am exploring MPEG-DASH technique for video adaptation. As a test case, i have two versions of the same video with different resolutions 400x250(1.mp4) & 640x360(2.mp4) and want to stream it via MPEG DASH. Using GPAC - MP4Box i have generated the mpd using below command:
MP4Box -dash 1000 -rap -bs-switching no -profile live -out manifest.mpd 1.mp4 2.mp4

The Generated MPD is as follows:
<?xml version="1.0"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" minBufferTime="PT1.500S" type="static" mediaPresentationDuration="PT0H4M57.088S" maxSegmentDuration="PT0H0M10.428S" profiles="urn:mpeg:dash:profile:full:2011">
<ProgramInformation moreInformationURL="http://gpac.io">
  <Title>manifest.mpd generated by GPAC</Title>
 </ProgramInformation>
<Period duration="PT0H4M57.088S">
  <AdaptationSet maxWidth="640" maxHeight="360" maxFrameRate="24000/1001" par="16:9" lang="und" startWithSAP="1">
   <Representation id="1" mimeType="video/mp4" codecs="avc1.640015" width="400" height="250" frameRate="24000/1001" sar="10:9" bandwidth="80722">
<SegmentTemplate media="1_dash$Number$.m4s" initialization="1_dashinit.mp4" timescale="24000" startNumber="1" duration="24000"/>
   </Representation>
   <Representation id="2" mimeType="video/mp4" codecs="avc1.64001E" width="640" height="360" frameRate="24000/1001" sar="1:1" bandwidth="137371">
<SegmentTemplate media="2_dash$Number$.m4s" initialization="2_dashinit.mp4" timescale="24000" startNumber="1" duration="24000"/>
   </Representation>
  </AdaptationSet>
 </Period>

What i want exactly is to adopt this video based on time slice i.e. for first 5 seconds, 1.mp4 should be streamed, for next 15 seconds, 2.mp4 should be streamed  and onwards..
Guidance needed on how can i achieve adaptation based on the time slices for streaming different qualities.

A: MPEG DASH is a request and response streaming protocol - the client requests each segment and the streaming server responds with the appropriate segment.
The client decides which bandwidth to request from those available in the manifest, usually based on its view of the network conditions at the time, based on buffering etc, and on the devices capabilities.
Most clients will also allow you manually select a bit rate from those available.
If you want to modify a client to use one bit rate for a given time period and then another bit rate for a different time period, then you will likely want to modify the algorithm in the client that choose the bit rate to request.
Open source players sometimes allow you specify a custom function to do this - some examples:

*

*exoplayer - more info here: https://medium.com/google-exoplayer/exoplayer-2-x-track-selection-2b62ff712cc9

*Dash.js - more info here: https://stackoverflow.com/a/47225096/334402
If you don't want to change anything on the client and want to make the server dictate the stream that is used, the simplest way would be to only provide one bit rate for the first time period and then only the other bit rate for the next period.
MPEG DASH cann support multiple periods - see the diagram below from a DASH overview paper (link  at the time of writing: https://www.nctatechnicalpapers.com/Paper/2012/2012-mpeg-dash-a-technical-deep-dive-and-look-at-what-s-next)

You can see that if you have one period with a single adaption set with a single bit rate or representation, and then the next period also with a single bit rate or representation, you can also achieve what you want. I think it is fair to say, however, that this is not a typical way to use DASH.


text:
Q: declare printf function by myself (using Vistual Studio 2012 and c++) I want to declare printf function by myself, and try if the code can work.
I looked into the <stdio.h> and found it declared as:

_Check_return_opt_ _CRTIMP int __cdecl printf(_In_z_ _Printf_format_string_ const char * _Format, ...);

Then I found
_Check_return_opt_  defined in <crtdefs.h>
_CRTIMP defined in <crtdefs.h>
_In_z_ _Printf_format_string_ defined in <sal.h>
So my code is as:
#include <crtdefs.h>
#include <sal.h>
_Check_return_opt_ _CRTIMP int __cdecl printf(_In_z_ _Printf_format_string_ const char * _Format, ...);
int main()
{
    int a = 100;
    printf("%d\n",a);
}

I guess this will work, but it gets an error:
error LNK2019: unresolved external symbol ...
What's wrong with my code? Are there anything I missed in <stdio.h>?
I have already read a question on stackoverflow.
(https://stackoverflow.com/questions/25155631/microsoft-visual-studio-2012-version-of-printf-function-declaration)
It helps, but doesn't solve my problem.
I also learn to know that an extern "C" function works fine. such as:
extern "C" int printf (const char * __format, ...);

But I think this still not accounts for my doubt.

A: In stdio.h, was the prototype for printf inside an extern "C" {} block?  Note that this block could be large and so you might not have noticed it.  If so, you need to use extern "C" around your prototype.

A: The extern "C" should remove your doubt - without that you are compiling the declaration as C++ which doesn't use a linking convention that's the same as C (which is how printf() is compiled in the library).
You can fix the problem using extern "C" or compiling your program as a C program instead of C++ (change the name of the source file to have a .cextension).


text:
Q: angular server side validation, how to find the form element from the object reference I have a complex form with client and server side validations. lets assume the form is as simple as:
<input type="text" name="name" ng-model="object.name"/>

    <input type="text" name="value{{$index}}" ng-model="order.Value"/>
    <input type="text" name="descr{{$index}}" ng-model="order.Descr"/>

The actual form is much more complex than this and all the client side validation is working, my problem is when the user submits the form via an http ajax request then server returns validation errors in json format, like:
{ errors: [ { desc: "Invalid value", path: "object.Orders[0].Value" } ] }

I can easily get the object reference for the path returned by the server but, how can i get the form element so i can mark it invalid within angular?
I particular i wan't to set the form element $invalid. because the form is complex and i have many of thouse forms i wan't to make an automatic way of finding the form element from the object path object.Orders[0].Value.
Can anyone help me with this

A: Create the new ErrorObjetct and when you get the response assign that error response to that object and use that object like bellow.
<input type="text" name="name" ng-model="object.name"/>

{{ErrorObject.value}}

    <input type="text" name="value{{$index}}" ng-model="order.Value"/>

{{ErrorObject.descr}}
>
    <input type="text" name="descr{{$index}}" ng-model="order.Descr"/>

A: *

*if you want to show errors on form level and not field level, then just have some status bar where you can show these errors. It will be quick and a global solution. read here - at very bottom

*if you want to show errors on field level and not on form level then you will have to change the format of error message, they should include the name of the property which caused the error + error description
then loop thru the form and each model attached to form and push error to $form.$model.$error array, to have tight integration with server side validation. But this solution would be difficult to make global, given that you might have multiple forms being validated same time. so you might need just one line of code for every form where on error of $http you synchronize errors from server with $form. READ HERE
Its too vast topic to provide a working sample, the links should get you going


text:
Q: Contact form is not sending email to my gmail acount I have created a simple form using Visual Studio 2012 but it's not sending email to my gmail account, the page runs fine but when I hit send button I get error:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. j8sm1567623paz.30
Description: An unhanded exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. j8sm1567623paz.30

Source Error:
Line 14:
Line 15:
Line 16:         mailClient.Send(message)
Line 17:
Line 18:

Source File: C:\Website SVN II\test\contact.aspx.vb    Line: 16

Sources:
Imports System.Net.Mail

Partial Class contact
 Inherits System.Web.UI.Page

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    sendMail(txtEmail.Text, txtMessage.Text)
End Sub

Protected Sub sendMail(ByVal From As String, ByVal body As String)
    Dim mailservername As String = "smtp.gmail.com"
    Dim message As MailMessage = New MailMessage(From, "nabeel.f@gmail.com", "feedback", body)
    Dim mailClient As SmtpClient = New SmtpClient

    mailClient.Host = mailservername
    mailClient.Send(message)
    message.Dispose()
End Sub

End Class

HTML.
        first name
        <asp:TextBox ID="txtFName" runat="server"></asp:TextBox>

        last name
        <asp:TextBox ID="txtLName" runat="server"></asp:TextBox>

        email
        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

        message:
        <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"></asp:TextBox>

        <asp:Button ID="Button1" runat="server" Text="Send" />

A: Two things:

*

*You need to use HTTPS.

*You need to provide credentials for your account.

Here's a C# example from here:
using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
           {
               Host = "smtp.gmail.com",
               Port = 587,
               EnableSsl = true,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
           };
using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = body
                     })
{
    smtp.Send(message);
}

vb.net version:
Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    Dim SmtpServer As New SmtpClient()
    SmtpServer.Credentials = New Net.NetworkCredential
                ("xyz@gmail.com", "password")
    SmtpServer.Port = 587
    SmtpServer.Host = "smtp.gmail.com"
    SmtpServer.EnableSsl = True

    mail = New MailMessage()
    Dim addr() As String = TextBox1.Text.Split(",")
    Try
        mail.From = New MailAddress("xyz@gmail.com",
            "Web Developers", System.Text.Encoding.UTF8)

        Dim i As Byte
        For i = 0 To addr.Length - 1
            mail.To.Add(addr(i))
        Next
        mail.Subject = TextBox3.Text
        mail.Body = TextBox4.Text
        If ListBox1.Items.Count <> 0 Then
            For i = 0 To ListBox1.Items.Count - 1
                mail.Attachments.Add(New Attachment
                    (ListBox1.Items.Item(i)))
            Next
        End If
        mail.DeliveryNotificationOptions =
                DeliveryNotificationOptions.OnFailure
        mail.ReplyTo = New MailAddress(TextBox1.Text)
        SmtpServer.Send(mail)
    Catch ex As Exception
        MsgBox(ex.ToString())
    End Try
End Sub


text:
Q: Direct sum of nontrivial vector bundles? When is it true that the direct sum (or whitney sum) of two nontrivial vector bundles is nontrivial? Also, if you have a direct sum of vector bundles, with $a$ and $b$ global sections respectively, does its direct sum have $a+b$ sections?

A: If you know the characteristic classes of your vector bundles, you can compute the characteristic classes of their direct sum, so if any of those don't vanish then the direct sum is nontrivial. Otherwise things are hard. In fact it's known that for any (real or complex) vector bundle $V$ on, say, a compact Hausdorff space, there is another vector bundle $W$ such that $V \oplus W$ is trivial.
Your second question is straightforwardly yes (assuming by "$n$ global sections" you mean "$n$ linearly independent global sections") and the most obvious construction works.


text:
Q: Change Vim swap/backup/undo file name Is it possible to change the way Vim names its swap/backup/undo files?
To avoid clutter, I've set options in my ~/.vimrc to dump these files in ~/.vim/tmp/{swap,backup,undo}; however, as I routinely edit files in different directories with the same name, I often end up with lots of otherwise indistinguishable files and Vim sometimes has trouble recovering.
Ideally, I'd like to use the naming scheme that the persistent undo has (%path%to%file.undo) for all these auxiliary files; there's no obvious way to set it, but can it be done with Buf{Read,Write} macros?

A: I have this in my .vimrc and it names the swap files with full path names and percent signs just as you describe:
" Store swap files in fixed location, not current directory.
set dir=~/.vimswap//,/var/tmp//,/tmp//,.

The key is the // at the end of the directories. See this note from :help dir:

*

*For Unix and Win32, if a directory ends in two path separators "//"
        or "\\", the swap file name will be built from the complete path to
        the file with all path separators substituted to percent '%' signs.
        This will ensure file name uniqueness in the preserve directory.

A: Here's part of my .vimrc from github.
This sets the undodir (and turns it on), sets the backupdir, and directory (used for .swp files). Note that it creates the directories if they don't already exist.
" Save your backup files to a less annoying place than the current directory.
" If you have .vim-backup in the current directory, it'll use that.
" Otherwise it saves it to ~/.vim/backup or .
if isdirectory($HOME . '/.vim/backup') == 0
  :silent !mkdir -p ~/.vim/backup >/dev/null 2>&1
endif
set backupdir-=.
set backupdir+=.
set backupdir-=~/
set backupdir^=~/.vim/backup/
set backupdir^=./.vim-backup/
set backup

" Save your swap files to a less annoying place than the current directory.
" If you have .vim-swap in the current directory, it'll use that.
" Otherwise it saves it to ~/.vim/swap, ~/tmp or .
if isdirectory($HOME . '/.vim/swap') == 0
  :silent !mkdir -p ~/.vim/swap >/dev/null 2>&1
endif
set directory=./.vim-swap//
set directory+=~/.vim/swap//
set directory+=~/tmp//
set directory+=.

" viminfo stores the the state of your previous editing session
set viminfo+=n~/.vim/viminfo

if exists("+undofile")
  " undofile - This allows you to use undos after exiting and restarting
  " This, like swap and backup files, uses .vim-undo first, then ~/.vim/undo
  " :help undo-persistence
  " This is only present in 7.3+
  if isdirectory($HOME . '/.vim/undo') == 0
    :silent !mkdir -p ~/.vim/undo > /dev/null 2>&1
  endif
  set undodir=./.vim-undo//
  set undodir+=~/.vim/undo//
  set undofile
endif

Hopefully, it's commented well enough to understand what's going on. If not, add a comment and I'll fix it.
Ciao!
Update [07/16/2012]
I got an email from Rob Kine asking these questions about the backupdir section that I wanted to answer for everyone:

*

*It looks like you are removing the current directory, and then re-adding it. what does that do?

*What does the ^= operator do?

*How does the order of precedence in the use of folders checked work in Vim? (Like is the last folder added the first one it checks for?)

The first thing is to describe the different operators. These operators have different meanings for non-string-list options, so be warned!

*

*-= removes the value from a string list;

*+= appends the value to a string list;

*^= prepends the value to a string list.

So the backupdir has the following operations applied:

*

*Remove the current directory from the list.

*Append the current directory to the list (this ensures it is the last thing checked).

*Remove the home directory from the list (I don't like stuff being saved there).

*Prepend ~/.vim/backup/.

*Prepend ~/.vim-backup/.

When Vim looks for where to save the backups, it checks from first to last; so it'll check for ~/.vim-backup/, then check for ~/.vim/backup, then check the default list (except for . and ~/ which were removed), and finally check .
You can get help for all these in Vim by using (for example) :help ^= or :help backupdir.

A: Create the directory undo
 $ mkdir ~/.vimundo

Set up your .vimrc file
 set undodir=~/.vimundo


text:
Q: How is it possible to get top comment from all children? I'm able to check whether or not the parent comment is the top comment:
$comment_obj = get_comment( $comment_ID );
$parent_ID = $comment_obj->comment_parent;

But I'd like to be able to get the top comment no matter if I am posting a child or grandchild etc. I can't find much information of retrieving parent/top comments at all?

A: You could adapt get_post_acestors(), and write a similar function for comments. Here is an example that returns the top comment's id or false. Not tested!
function get_root_comment( $comment_id ) {

    $comment = get_comment( $comment_id );

    if ( ! $comment
        || empty( $comment->comment_parent )
        || $comment->comment_parent == $comment_id
    ) {
        return false;
    }

    $ancestors   = [];
    $id          = $comment->comment_parent;
    $ancestors[] = $id;

    while ( $ancestor = get_comment( $id ) ) {

        if ( empty ( $ancestor->comment_parent ) ) {
            return $id;
        }

        // self-reference
        if ( $ancestor->comment_parent == $id ) {
            return $id;
        }

        // loop
        if ( in_array( $ancestor->comment_parent, $ancestors, true ) ) {
            return $id;
        }

        $id          = $ancestor->comment_parent;
        $ancestors[] = $id;
    }
}

Usage in other code with a WP_Comment object:
$root_comment = get_root_comment( $comment_obj->comment_ID );

if ( $root_comment ) {
    // do something with the ID
}


text:
Q: ZXing running (crashes...) on iPod I got a really weird problem with ZXing 2.0 on iPod touch (Version : 5.1.1).
I searched on the Internet and Stackoverflow but i think i just ignore the origin of that issue so i couldn't find anything.
I coded an app which successfully using ZXing running on iPhone Simulator 5.1 and when i try to run on any iPod device (i didn't test other device yet), it compiles and crash at running with no log in console (and i cant type anything on it).
This is the screen that appeared on XCode (i got the developer version 4.3.2) with a green arrow for the last line pasted and "signal SIGABRT" written.
libsystem_kernel.dylib __pthread_kill:
0x35e70324:  mov    r12, #328
0x35e70328:  svc    #128
0x35e7032c:  blo    0x35e70344; __pthread_kill + 32 (arrow for this line)

I think it's related to the libZXingWidget.a static library and I configured the build settings for armv6 armv7 and i386 in two different configurations but didn't work either.
I have no idea anymore, thanks for any suggestion !
EDIT : I forgot to mention that the next thing on the thread stack is GSRegisterPurpleNamedPort.

A: Try rebooting the device. Coring in GSRegisterPurpleNamedPort is pretty common under certain conditions, for example switching between a debug version and an archived ipa. In that case, it's a Mach thing and seems to require a reboot. From what you've said, it doesn't sound like the issue, but it's worth ruling out.
Otherwise:

*

*Have you run any app on your device, i.e., is everything properly provisioned?

*Can you get ScanTest to run on your device?

*Post the whole stacktrace.


text:
Q: How to append text to a log file with WinSCP/C# I'm trying to add text to a text file in a FTP server, but it overwrites it instead of appending, how to solve this ?
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "www.site.com",
    UserName = "name",
    Password = "pass",
    FtpSecure = FtpSecure.Explicit,

    TlsHostCertificateFingerprint = "what ever that is",
};

using (Session session = new Session())
{
    session.Open(sessionOptions);
    TransferOptions options = new TransferOptions();
    options.TransferMode = TransferMode.Ascii;
    options.OverwriteMode = OverwriteMode.Append;

    TransferOperationResult transferResult;
    transferResult = session.PutFiles(@"E:\Up\log.txt", "/log.txt", false, options);
    transferResult.Check();

    foreach (TransferEventArgs transfer in transferResult.Transfers)
    {
        Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
    }
}

Found something similar here, but no solution:
https://winscp.net/forum/viewtopic.php?t=25031
I don't really want to download the file, append to it, then upload it, below code worked but my credentials are visible to WireShark:
byte[] data = Encoding.UTF8.GetBytes(@"Hello World.");
Uri target = new Uri("ftp://site.com/test.txt");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Method = WebRequestMethods.Ftp.AppendFile;
request.ContentLength = data.Length;

request.Credentials = new NetworkCredential("name", "pass");
using (Stream requestStream = request.GetRequestStream())
    requestStream.Write(data, 0, data.Length);

A: You aren't appending text. Try this.
System.IO.StreamWriter sw;
sw = System.IO.File.AppendText(LogFilePath);
sw.WriteLine("Write Something");
sw.Close();

A: WinSCP OverwriteMode.Append is supported with SFTP protocol only.

If you want to use encrypted FTPS with FtpWebRequest, just set FtpWebRequest.EnableSsl.
See FTPS (FTP over SSL) in C#.
Also, as you are setting TlsHostCertificateFingerprint in WinSCP, it seems that your server is using self-signed certificate. Then you might need this with FtpWebRequest:
FtpWebRequest "The remote certificate is invalid according to the validation procedure"


text:
Q: Wordpress - Unable to save values from multiple metaboxes could anybody help me? I cannot save the values of my second meta box (rip_editor_gallery). The values of the first box are saved correctly,
but the image doesn't work. The Upload Button is working, the image appears, but when I update, my image is lost. I attach the code, I really don't know how to resolve this.
This are my two Metaboxes:
add_action( 'add_meta_boxes', 'rip_add_custom_meta_box' );
function rip_add_custom_meta_box() {
    add_meta_box(
    'rip_editor',
    'Portfolio Meta Box',
    'rip_editor_content',
    'rip_portfolio'
    );

    add_meta_box(
        'rip_gallery_metabox',
        'Galerie',
        'rip_editor_gallery',
        'rip_portfolio'
    );
}

The first Metabox is working, the values are saved:
function rip_editor_content( $post ) {

    wp_nonce_field( 'rip_save_meta_box_data', 'rip_meta_box_nonce' );

    $output = '';

    $output = '

                Subline
                <input type="text" name="rip_subline" value="' . esc_html( get_post_meta( $post->ID, 'rip_subline', true ) ) . '" />

                Weitere Infos
                <textarea name="rip_infos" rows="5">' . esc_html( get_post_meta( $post->ID, 'rip_infos', true ) ) . '</textarea>

                Button Text
                <input type="text" name="rip_button_text" value="' . esc_html( get_post_meta( $post->ID, 'rip_button_text', true ) ) . '" />

                Button Link
                <input type="text" name="rip_button_link" value="' . esc_html( get_post_meta( $post->ID, 'rip_button_link', true ) ) . '" />

';
    echo $output;
}

This one makes Problems. After clicking the Update Button the image is lost.
function rip_editor_gallery ($post) {

    $rip_featured_image = ( isset( $meta['rip_featured_image'][0] ) ) ? $meta['rip_featured_image'][0] : '';
    $rip_gallery = ( isset( $meta['rip_gallery'][0] ) ) ? $meta['rip_gallery'][0] : '';
    ?>

        Bild

        <?php if ( '' !== $rip_featured_image ) : ?>
            <img src="<?php echo esc_url( $rip_featured_image ); ?>" />
        <?php endif; ?>

        <input type="text" name="rip_featured_image" value="<?php echo esc_url( $rip_featured_image ); ?>" class="featured_image_upload">
        <input type="button" name="image_upload" value="Hochladen" class="button upload_image_button">
        <input type="button" name="remove_image_upload" value="Entfernen" class="button remove_image_button">

    <?php
}

And that's how I save the values: I tried to echo test, even this doesn't appear, so maybe the variable is empty? I dont't know...
    add_action( 'save_post', 'rip_save' );
function rip_save( $post_id ) {

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    if ( ! isset( $_POST['rip_meta_box_nonce'] ) ) {
        return;
    }

    if ( ! wp_verify_nonce( $_POST['rip_meta_box_nonce'], 'rip_save_meta_box_data' ) ) {
        return;
    }

    if ( 'ritec_portfolio' == $_POST['post_type'] ) {
        if ( !current_user_can( 'edit_page', $post_id ) || !current_user_can( 'edit_post', $post_id ) ) {
            return;
            }
    }

    if( isset( $_POST['rip_subline']) ) {
        update_post_meta( $post_id, 'rip_subline', $_POST['rip_subline'] );
        }

    if( isset( $_POST['rip_infos']) ) {
        update_post_meta( $post_id, 'rip_infos', $_POST['rip_infos'] );
        }
    if( isset( $_POST['rip_button_text']) ) {
        update_post_meta( $post_id, 'rip_button_text', $_POST['rip_button_text'] );
        }

    if( isset( $_POST['rip_button_link']) ) {
        update_post_meta( $post_id, 'rip_button_link', $_POST['rip_button_link'] );
        }

        if ( isset( $_POST['rip_featured_image'] ) ) { // Input var okay.
            echo 'test';
            update_post_meta( $post_id, 'rip_featured_image', sanitize_text_field( wp_unslash( $_POST['rip_featured_image'] ) ) );
        }
}

Thank you very very much :)


text:
Q: Proof for Squeeze Theorem for Sequences Squeeze Theorem: If $a_n$, $b_n$ and $c_n$ are any three sequences with $a_n \lt b_n \lt c_n$ for any $n$ and $\lim_{n \to \infty} a_n = \lim_{n \to \infty} c_n = l$. Then  $\lim_{n \to \infty} b_n = l$.
Proof: Since $\lim_{n \to \infty} a_n = \lim_{n \to \infty} c_n = l$ there are $N_a, N_c \in \mathbb{N}$ so that for any $n \gt N_a$ it holds that $\vert a_n - l \vert \lt \epsilon$ for any $\epsilon \gt 0$. Equaly, if $n \gt N_c$, $\vert c_n - l \vert \lt \epsilon$. We choose $N = max(N_a, N_c)$ so that, when $n \gt N$, both $\vert a_n - l \vert \lt \epsilon$ and $\vert c_n - l \vert \lt \epsilon$ are true.
Now, since $a_n \lt b_n \lt c_n$ it follows, that $\vert b_n - l \vert \le max(\vert a_n - l \vert , \vert c_n - l \vert)$. So, if $n \gt N$, then $\vert b_n - l \vert \lt \epsilon$ has to be true. Thus $\lim_{n \to \infty} b_n = l$. $\blacksquare$
Is this correct?

A: Nice attempt but you should be careful, it's really tricky to keep track of all the logical qualifiers at once! You seem to have the right idea, but you have mistakenly specified your $N_a$ as to hold for all $\epsilon>0$. This would imply that the sequence is eventually constant (equal to $l$), which may not be the case. What we can instead say when we have convergence is that
$$\text{for any }\epsilon >0,\text{we can find some }N_a\text{ such that for}\ldots$$
This is different from
$$\text{we can find some }N_a\text{ such that for any }\epsilon >0\ldots$$
As a silly example, for any positive number $\epsilon$, we can find some smaller positive number, say $\frac{\epsilon}{2}$. But we cannot find a positive number that is smaller than any other given positive number! (I'm obliged to mention that there are models of mathematics where we can, but that is far removed from the point and probably poor pedagogy here.)
I think you are on the right track, so I recommend that you try to "read the mathematical statement out loud" and see what happens to the precise meaning when you permute some of the quantifiers. You should notice a subtle change and after really taking care to follow the definition of convergence you should be able to fix it. Good luck!

A: Thanks for the answer @Cornell Alex Holmes. I think I knew the correct definition. But perhaps I didn't grasp it's subtleties and thus formulated in incorrectly. Here is my second try:
Squeeze Theorem: If $a_n$, $b_n$ and $c_n$ are any three sequences with $a_n \lt b_n \lt c_n$ for any $n$ and $\lim_{n \to \infty} a_n = \lim_{n \to \infty} c_n = l$. Then  $\lim_{n \to \infty} b_n = l$.
Proof: Since $\lim_{n \to \infty} a_n = \lim_{n \to \infty} c_n = l$, for any $\epsilon \gt 0$, there are $N_a, N_c \in \mathbb{N}$ so that if $n \gt N_a$ it follows that $\vert a_n - l \vert \lt \epsilon$ . Equaly, if $n \gt N_c$ then $\vert c_n - l \vert \lt \epsilon$. We choose $N = max(N_a, N_c)$ so that, when $n \gt N$, both $\vert a_n - l \vert \lt \epsilon$ and $\vert c_n - l \vert \lt \epsilon$ are true.
Now, since $a_n \lt b_n \lt c_n$ it follows, that $\vert b_n - l \vert \le max(\vert a_n - l \vert , \vert c_n - l \vert)$. So, if $n \gt N$, then $\vert b_n - l \vert \lt \epsilon$ has to be true.
This means, that for for any $\epsilon \gt 0$ we can find a $N \in \mathbb{N}$ so that $n \gt N \implies \vert b_n - l \vert \lt \epsilon$. Thus $\lim_{n \to \infty} b_n = l$. $\blacksquare$


text:
Q: cx_Oracle.InterfaceError: not connected Al momento de verificar si el usuario existe en la base de datos me sale este error   'cx_Oracle.InterfaceError: not connected'
@staticmethod
        def search_exist(customer):  # Este metodo busca la cedula del cliente que se presente ingresar a la DB
            cursor = connection.cursor()
            cursor.execute("SELECT * FROM customer WHERE cc='{}'".format(customer.cc))

            search = cursor.fetchall()

            connection.commit()

            return search


text:
Q: Will all characters be labelled cheaters once the console is used? Is that is there anyway to create a character, activate the console and not get flagged as a cheater on all of your characters? I mean, if I create a new character and use the console there for testing purposes, if I log in with a different character, will that character be flagged as a cheater too?

A: It flags the character, not the account.
(Source by Runic Staff)


text:
Q: Skipping a line of code if an image isn't selected If a user selects an image it will save the image as per the below code:
PictureBox1.Image.Save(PicFile, System.Drawing.Imaging.ImageFormat.Jpeg)

Now if the user decides not to select an image, is there a way to skip this code? I currently get the following error:

Additional information: Object reference not set to an instance of an object.

This is what I've tried:
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(.jpg;.png;*.gif)|*.jpg;*.png;*.gif"
If opf.ShowDialog = DialogResult.OK Then
    PictureBox1.Image = Image.FromFile(opf.FileName)
End If

Try
    Dim ms As New MemoryStream
    PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
    Dim img As Byte()
    img = ms.ToArray()
    DataGridView1.Rows.Add(img)
Catch ex As Exception
    MessageBox.Show(ex.Message.ToString())
End Try

A:
Now if the user decides not to select an image, is there a way to skip this code?

If by this you mean the user selects Cancel, then yes. Simply place the Try[...]Catch block into your If statement and it will only attempt the code if the user selects Open.
Something like this:
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(.jpg;.png;*.gif)|*.jpg;*.png;*.gif"

If opf.ShowDialog = DialogResult.OK Then
    PictureBox1.Image = Image.FromFile(opf.FileName)

    Try
        Dim ms As New MemoryStream
        PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
        Dim img As Byte()
        img = ms.ToArray()
        DataGridView1.Rows.Add(img)
    Catch ex As Exception
        MessageBox.Show(ex.Message.ToString())
    End Try
End If

If you only wanted to skip certain bits of code you could do a check on opf.FileName. As an example:
If opf.FileName <> "" Then
    PictureBox1.Image = Image.FromFile(opf.FileName)
End If


text:
Q: SVN Repository Newbie Questions I am in my early stages of understanding an SVN repository, and I had a few questions:

*

*What kind of files should I put in a repository? For example, I know PHP, JS, FLA, etc... are  accepted as standard, but what about things liks PSDs (which may be changed in the future), AIs (Adobe Illustrator files), etc...? Should I save those in the repository, or just the exported version?

*Are there files that are considered "too big" to put in a repository? For example, I have a PSD which is 11 mB.

*What is the maxmium recommended file size? If it matters, I am running this repository within my environment, so storage isn't a problem. :)

Thank you for your time.

A: I'll respond to your questions in order.

*

*Any file that you change frequently and would like to have backed up is a good candidate for going in an SVN repository. If you'll ever want to be able to "go back to last Tuesday's version" or something along those lines, you should probably put the file in SVN. To contrast, music and movies are poor candidates for SVN control, since you're not very likely to change them (unless you're a producer or film editor, of course).

*SVN is a differential backup system, meaning it sends only the differences between the new and old files you create. For example, if you add a line to a 3,000-line text file and commit it, only that last line will be sent over the network. So, there is no real limit on file size (apart from those imposed by your bandwidth and host, of course). I've personally tracked a 100 MB file before. Also, keep in mind that the whole differential tracking is great for text files, but not so great on binary files (DOC, PDF, FLA, PSD, etc.) In these cases, you can still use SVN, but you will probably send close to the whole file size every time.

*As I said before, I wouldn't worry about changing the size of your files for SVN's sake; it's pretty versatile.


text:
Q: Celery - how to use multiple queues? I want to create a multiple queues for different tasks. For example emailqueue to sending emails or pipedrive queue to sync tasks with pipedrive API so email does not have to wait until all pipedrives are synced and vice versa.
I'm new in routing and I tried two approaches to create queues but none of them seemes to work.

*

*This is a preferred approach. I tried to define queue inside @task decorator
@task(bind=True,  queue='pipedrivequeue')

def backsync_lead(self,lead_id):

*settings.py
CELERY_ROUTES = { # tried CELERY_TASK_ROUTES too
    'pipedrive.tasks.*': {'queue': 'pipedrivequeue'},
   ...
}

In both cases, when I run celery worker manually, I see only one default celery queue.
(project) milano@milano-PC:~/PycharmProjects/project$ celery -A project.celery worker -l info

 -------------- celery@milano-PC v4.2.2 (windowlicker)
---- **** -----
--- * ***  * -- Linux-4.15.0-47-generic-x86_64-with-Ubuntu-18.04-bionic 2019-04-12 17:17:05
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         project:0x7f3b47f66cf8
- ** ---------- .> transport:   redis://localhost:6379//
- ** ---------- .> results:     redis://localhost/
- *** --- * --- .> concurrency: 12 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

[tasks]
  . project.apps.apis.pipedrive.tasks.backsync_all_stages
  . project.apps.apis.pipedrive.tasks.backsync_lead

As you can see in this line:
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

There is probably just one queue. I want to use this queue only for tasks without queue specified.
Do you know where is the problem?
EDIT
   (project) milano@milano-PC:~/PycharmProjects/peoject$ celery inspect active_queues
Error: No nodes replied within time constraint.

A: You need to run a worker with the queue named explicitly, then django will be able to feed into that queue;
celery worker -A project.celery -l info  # Default queue worker
celery worker -A project.celery -l info -Q pipedrivequeue  # pipedrivequeue worker
celery worker -A project.celery -l info -Q testqueue  # testqueue worker


text:
Q: how to save the result of a loop in JSON? I have created a loop in an asynchronous function that gets data from an external page. I would like the result to be saved in JSON. However, my script doesn't work as expected.
for (let tokenId = 0; tokenId < 5; tokenId++) {
    try{
        let result = await Gateway.tokenURI(tokenId);
        console.log(result);
        fs.writeFileSync("ogUris.json", result)
    }catch(e){
      console.log(e)
    }

  }

A: You are calling fs.writeFileSync() inside your loop where each call to that function will replace/overwrite the previous results.
If you want to save an array of results in your JSON, then you can accumulate the results into an array and then write the array at the end.
const results = [];
for (let tokenId = 0; tokenId < 5; tokenId++) {
    try {
        let result = await Gateway.tokenURI(tokenId);
        results.push(result);
    } catch(e) {
        console.log(e);
    }
 }
 fs.writeFileSync("ogUris.json", JSON.stringify(results));

This will leave you with an array of tokenURIs in JSON format in the file.

A: This is not working because for loop doesn't wait for await Gateway.tokenURI(tokenId) to provide you any response.You can try using promise.all


text:
Q: Azure DevOps API - Set Board Options I'm trying to do few things with Azure DevOps projects through Rest API, but I really quickly got stuck.
For example, I want to use the method "Set Board Options", documentation is here https://learn.microsoft.com/en-us/rest/api/azure/devops/work/boards/set%20board%20options?view=azure-devops-rest-5.1
Does anyone have an idea of how to find out which options (and how exactly) I can use? Is there any way to lookup these values in the Azure DevOps portal or somewhere else?
I was trying to use the .Net library (https://github.com/microsoft/azure-devops-dotnet-samples), but the situation there is the same. Method SetBoardOptions exists but takes Dictionary of strings as the first argument and there is no documentation on how to actually fill up this dictionary, which values are possible to use etc.

A: This API is in preview so I guess this is the reason why the docs so poor:

After a big search and tries, I think you can change 2 options in the board settings:
1) statusBadgeIsPublic - True or False.
2) cardReordering - 0 or 1.
I success to do it with PowerShell:
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"MY-PAT")))
$headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)}

$URI =  "https://dev.azure.com/{org}/{project}/{team}/_apis/work/boards/{board}?api-version=5.1"

$params = @{
 "cardReordering"="1";
} | ConvertTo-Json

Invoke-RestMethod -Method Put -Uri $URI -Headers $headers -Body $params -ContentType 'application/json'


text:
Q: Добавлять (и обновлять) в конце href значение из data-url Есть скрипт, который по клику передает из моих div с классом.atr_donor атрибут data-url и вставляет значение в конец атрибута href ссылок с классом block. Проблема в том, что на  div с классом .atr_donor могут кликать много раз и в href постоянно добавляются значения (с каждым новым кликом). Как добавить атрибут data-url один раз и потом, с последующими кликами, их просто обновлять?
$('.atr_donor').on('click',function(){
    var myurl = $(this).attr('data-url');
    $("a.block").each(function() {
       var $this = $(this);
       var _href = $this.attr("href");
       $this.attr("href", _href + myurl);
    });
})


text:
Q: Распараллеливание стримов Есть у меня самопальный класс BitVector с единственный полем
private boolean[] bits;

Есть в этом же классе небольшой метод, который делает конъюнкцию(логическое "и") для векторов:
public BitVector and(BitVector anotherVector) {

    if (this == anotherVector) return (BitVector) clone();

    if (size() != anotherVector.size())
        throw new IllegalArgumentException("Incompatible sizes: size="+size()+", other.size()="+anotherVector.size());

    BitVector intersectionVector = new BitVector(size());
    for (int i = 0; i < size(); i++){
        if (get(i) & anotherVector.get(i))
            intersectionVector.set(i);
    }

    return intersectionVector;
}

public Object clone() {

    BitVector clone = null;
    try {
        clone = (BitVector) super.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }

    if (this.bits != null) clone.bits = this.bits.clone();
    return clone;
}

public void set(int index){
    bits[index] = true;
}

public boolean get(int index){
    return bits[index];
}

public int size() {
    return this.bits.length;
}

Возможно ли с помощью стримов распараллелить единственный цикл внутри этого метода? Ориентировочные размеры для поля bits - 1 млн

A: А почему нет?
IntStream.range(0, size())
         .parallel()
         .forEach(i -> {
             if(get(i) & anotherVector.get(i)){
                 intersectionVector.set(i);
             }
});

или так, но замеры показали что первый способ чуть быстрее
IntStream.range(0, size())
         .parallel()
         .filter(i -> get(i) & anotherVector.get(i))
         .forEach(i -> intersectionVector.set(i)
);


text:
Q: Replace String in property file in Jenkins I have a properties file where certain string shoudl  be replaced with Jenkins parameter. I ahve tried using the variable directly in the Properties file which did not work.
properties file
DOCKER_TAG_SUFFIX=-REPLACE_RELEASE_VERSION
PROPERTY_FILE_PATH=someproperty

Jenkinsfile snippet
def jboss_parameters = readProperties file: jboss_propfile
jboss_parameters .replaceAll("RELEASE_VERSION",params.RELEASE_VERSION) # try1
jboss_parameters = readFile(jboss_propfile).replaceAll("REPLACE_RELEASE_VERSION",params.RELEASE_VERSION) # try2
# try 3
jboss_parameters.each{k,v ->
     if (v == "REPLACE_RELEASE_VERSION" )
        jboss_parameters.setProperty($k,params.RELEASE_VERSION)
     }
# try 4
def jboss_source_file = new File(jboss_propfile)
def jboss_parameters = jboss_source_file.text.replace("REPLACE_RELEASE_VERSION",params.RELEASE_VERSION)

I am not able to find another way that works for me.
println jboss_parameters output

{DOCKER_TAG_SUFFIX=-REPLACE_RELEASE_VERSION, PROPERTY_FILE_PATH=someproperty}

A: The readProperties step returns a dictionary (map), not a string, that is crated from the properties file.
Your first attempt (# try1) fails because maps in groovy do not have a replaceAll function like strings have and therefore you will get an error.
Your  third attempt (# try3) is failing because you are comparing the map values to REPLACE_RELEASE_VERSION without the - character and therefore the comparison always fails and no values are changed.
I tested the second attempt (# try 2) and it seems to be working, so i am not sure what is your issue, but it is easier to handle properties as a map instead of a string that is retuned from the readFile method.
So if you have only specific properties that need to be updated you can update them directly:
 def jboss_parameters = readProperties file: jboss_propfile
 jboss_parameters.DOCKER_TAG_SUFFIX = params.RELEASE_VERSION // update relevant property

Or if you have multiple properties that should be modified you can iterate and update each value using the collectEntries method. Something like:
 def jboss_parameters = readProperties file: jboss_propfile
 updated_parameters = jboss_parameters.collectEntries { key, value ->
     [key, value.replaceAll("REPLACE_RELEASE_VERSION",params.RELEASE_VERSION)]
 }


text:
Q: flutter - clear the widget cache When I leave a page when I work with flutter and then re-enter it, the old values are saved.
I don't want this to happen.
For example, when I first enter:
int number = 1;

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

bool donus = true;

class _TestPageState extends State<TestPage> {
  List<Todo> sorular = new List<Todo>();

  @override
  void initState() {
    print(donus);
    super.initState();
    getTodos();
  }

  bool pressAttention = true;
  String ileri = "İleri", geri = "Geri";
  @override
  Widget build(BuildContext context) {number++;
   print(number);

output:1
Second entry to the page:
output:2
I do not know how to fix this.

A: The scope of your number variable is outside the scope of your page and its state.
number is essentially static or global, and its lifetime is tied to your application's. Tighten up its scope so that it is declared within your state class and initialise it in your initState method (for private non-final variables).
class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

bool donus = true;

class _TestPageState extends State<TestPage> {
  List<Todo> sorular = new List<Todo>();
  int _number;

  @override
  void initState() {
    _number = 1;
    print(donus);
    super.initState();
    getTodos();
  }

  bool pressAttention = true;
  String ileri = "İleri", geri = "Geri";
  @override
  Widget build(BuildContext context) {
  _number++; // You probably don't want to increment every time you build,
             // but I have no idea what you're using `number` for.
  print(_number);

Your donus variable is also global, which is unlikely to be what you had intended. Dart is an object-oriented language; refer to the language tour for more details on classes, scope, etc.


text:
Q: How to set defcustom variable There is cperl-mode
and the setting I see in source:
(defcustom cperl-indent-parens-as-block nil
  "*Non-nil means that non-block ()-, {}- and []-groups are indented as blocks,
but for trailing \",\" inside the group, which won't increase indentation.
One should tune up `cperl-close-paren-offset' as well."
  :type 'boolean
  :group 'cperl-indentation-details)

I was trying to use (custom-set-variable '(cperl-indent-parens-as-block t)) but that doesn't work so how can I change this to t as global setting?

A: The function is called ...-variables:
(custom-set-variables '(cperl-indent-parens-as-block t))

or you can just use setq, since the variable doesn't have a setter defined:
(setq cperl-indent-parens-as-block t)

A: Easiest way to do it is M-x customize-variable cperl-indent-parens-as-block.
This shows you a nice menu with the possible values etc, and adds the values to your init.el (or emacs.el) afterwards.


text:
Q: Composer autoload Estou com problemas na hr de adicionar uma class ao meu autoload, fica dando Class Routes not found! Alguém poderia me ajuda?

composer.json
"autoload": {
    "psr-4": {
        "App\\Http\\Controllers\\": "app/Http/Controllers/"
    }
},

Routes.php
<?php

namespace App\Http\Controllers;

class Routes {

    public function route() {
        return 'Ola';
    }

}

index.php
<?php

require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use App\Http\Controllers;

$mail = new PHPMailer(true);
$route = new Routes();

dd($route->route());

A: Você só incluiu o namespace Controllers, então para utilizar a classe deste namespace você aind aprecisa referenciá-lo:
use App\Http\Controllers;

$routes = new Controllers\Routes();

Se você quer instanciar a classe sem precisar o namespace precisará incluir a classe ao escopo:
use App\Http\Controllers\Routes;

$routes = new Routes();

Mas esta classe Routes é um controlador? Se está utilizando algo como MVC me parece muito estranho você ter essa classe dentro deste namespace.


text:
Q: How cancel navigation in RichTextBox In my code of RichTextBox in my Windows Phone application I have:
 var link = new Hyperlink();
                        if (!string.IsNullOrEmpty(linkUrl))
                        {
                            link.NavigateUri = new Uri(linkUrl);
                        }
                        link.Foreground = new SolidColorBrush(Colors.Blue);
                        link.TargetName = "_blank";

                        var linkText = new Run() { Text = linkDesc };
                        link.Inlines.Add(linkText);
                        link.Click += new RoutedEventHandler(NavidateTo);

                        paragraph.Inlines.Add(link);

 private static void NavidateTo(object sender, RoutedEventArgs routedEventArgs)
        {

            if (MessageBox.Show(
                             Constants.BrowserNavigating,
                             "",
                              MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
              //cancel Navigation
            }
            else
            {
                StateManager.Set("Browser", "true");
            }
        }

How can I cancel navigation in NavidateTo method?
Update
private static void NavidateTo(object sender, RoutedEventArgs routedEventArgs)
    {
    if (MessageBox.Show(
                     Constants.BrowserNavigating,
                     "",
                      MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
    {
        //cancel Navigation
        var phoneApplicationFrame = Application.Current.RootVisual as PhoneApplicationFrame;
        if (Application.Current.RootVisual as PhoneApplicationFrame != null)
            phoneApplicationFrame.Navigating += new NavigatingCancelEventHandler(NavigationService_Navigating);
    }
    else
    {
        StateManager.Set("Browser", "true");
    }
}

public static void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
{
    {
        e.Cancel = true;
    }
}

This doesn't help

A: Use this.NavigationService.StopLoading();
Also consider this method:
Subscribe to the Navigating event.
void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
{
    // Don't allow refreshing of a static page
    if (DO SOME CHECKS)
        {
            e.Cancel = true;
        }
}

And take a look at this article over at msdn.
http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.navigating.aspx


text:
Q: In which case I need to call finish() method on click back button..? What are the scenarios in which I should call finish() method on back button or it is good to call it on each back button..??

A: it depend on your app requirement, for example:
case 1: when press back, need over your activity, so you need invoke finish, this is default
case 2: in one activity, has 3 step, like a->b->c, if you in the step b or c, you press back just want to back previous step, to b or to a, so you dont need invoke finish method in onBackPressed
so, above just a example, you need make a better choice in your situation.

A: When we came back from the second activity to the first activity in second activity will use this finish() to close the second activity and going back to first activity .

A: Depending upon your requirement... i m using finish()
1) when someone select EXIT option from menu
2) In my login acitity .. so that user doesnt see the login box again on press back button from post login page


text:
Q: IIS not picking up on changes made to my code Why doesn't my iis Server pick up changes to local code? I've changed both css/js files and changed some images but iis just doesn't update anything on the website. I've tried restarting the website and refreshing it on the iis manager but nothing changes.
However when i edit the web.config file it detects it automatically. Why is this? and how can I let the iis server website know that I have changed local files.

A: Are you using any kind of CDN that has the page cached?
If so, you can purge the cache of that URL.
Also test if the changes update when you use Private Browsing/Incognito Mode on your browser.  If this shows the updated page, then it is your browser cache that needs to be cleared.
But to really solve the problem, you'll want to version the JS page.
https://stackoverflow.com/questions/1011605/clear-the-cache-in-javascript

A: I think the problem is your browser cache.
For Chrome and Firefox you can try Ctrl+F5 to force refresh the page.
Failing that press Ctrl+Shift+Del and clear the cache.


text:
Q: Can't login using OAuth2PasswordGrant class I am using https://github.com/p2/OAuth2 library in Swift 3 project. I initialized OAuth2PasswordGrant with settings with username, password, client_id, client_secret, authorize_uri and keychain. And called the authorize function. The error I got was unsupported_grant_type.
self.oAuth = OAuth2PasswordGrant(settings: settings)
self.oAuth.authorize { (json: OAuth2JSON?, error: OAuth2Error?) in
    // did sth here
}

A: Check your settings data structure. My experience was i passed in a URL into authorize_uri instead of a string, and the authorize_uri defaulted to localhost. That was an invalid target and resulted in an unsupported_grant_type error


text:
Q: Please don't welcome spammers and abusers to Stack Exchange I hope I'm not the only one thinking the below is weird and even somewhat disturbing:

Yes. The "New contributor" indicator that ask us to welcome the user showing on a spam post.
I believe there's no need to explain why we better not welcome spammers/abusers to Stack Exchange, so here is what I suggest to do: if a user has a post marked as spam/offensive and approved as such (6 red flags or single binding moderator flag) do not show the New Contributor indicator for that user.
Another alternative is post based: since the indicator is showing based on post trigger it might be even more simple, if the post is marked as spam/offensive (same criteria as showing the "This answer was marked as spam..." message) then remove/ignore the "new user" trigger for that post. This will show it for other posts made by same user, but still better than showing it on obvious spam posts as it is doing now.
Worth also to mention, it's not only for "us", but also to prevent the spammers/abusers themselves feeling welcome. If someone who posted a vulgar/abusive post will see that card when viewing their own (deleted, but it's not really relevant) post, they will feel as if they can just do it again.

A: From my personal opinion any dev time spent implementing a fix to this would not be worth either the expense or added complexity to the feature.
General opinions about the indicator aside, this is a extremely limited use case, considering that:

*

*Most newly created spam accounts never exceed a few posts

*Most destroyed spam is hardly viewed after destruction (and if, then only by veteran users or moderators)

*It would be difficult to find a right "trigger" to hide the indicator

Extrapolating on the third point, I think there wouldn't be a useful way to implement such a limitation, do you

*

*Hide the indicator on posts destroyed as spam?

Now you've restricted the amount of people that this will be useful for (and useful is in quotation marks here, it's at best an optical improvement) to users with the view deleted posts privilege that care about viewing spam deleted posts. That's an incredibly small user group and not an appreciable benefit.

*

*Hide the indicator on further posts when a user has had a post of theirs destroyed as spam?

Most accounts whose first post is spam are either banned by one of the various automatic blocks or outright destroyed by moderators. I'd be very surprised to see that any appreciable contingent of users who have their first post destroyed as spam remain active on the site in such a way where displaying the indicator next to their name would have any effect.

*

*Hide the indicator once a post by an user has recieved a spam flag?

Now maybe more people might be affected by the change, but you still created an UI element with really undocumented functionality. Unless you're also going to show an indicator stating why this is nobody save meta savy users are going to have an earthly clue how exactly the indicator actually behaves (see: added complexity). Still, I think the benefits might be negligible at best.
In conclusion I don't think that any aesthetical benefit for the few users affected by this on any regular basis would be worth the additional complexity. User styles to remove the indicator alltogether exist, and user scripts to remove it conditionally are certainly possible. That seems to be the way to go here.

A:
The "New contributor" indicator that ask us to welcome the user showing on a spam post.

Perhaps that is the problem. The "New contributor" indicator does not "ask us to welcome" them. Neither the indicator itself nor the tooltips on them tell us to welcome them. The most we are asked to do is "be nice". Which ought to go without saying, but that's another matter.
My point is that you're misinterpreting the meaning of the indicator. It merely is there to remind us that the person is a new user.
This is ultimately no different from seeing the "New contributor" indicator on a terrible post. How do you treat a terrible post? You downvote/VTC as appropriate. How do you treat a spam post? You flag it as spam.
The indicator is just there to remind you that the poster is new. Do not allow it to change how you interact with the user's content.
From the post showing off the indicator:

The new indicator doesn't alter functionality.
It's a reminder that how you interact with the person could be extra meaningful (any time we help strangers just out of the love for what we do, it's meaningful). But it's not a magic shield of any kind, it doesn't work like spawn protection (where players can't take damage for the first few seconds after entering) in video games.


text:
Q: How many roots of polynomial in $\mathbb Z[x]$ and $\mathbb Q[x]$ are integers on average? Given $d,B>0$ the number of polynomials in $\mathbb Z[x]$ of degree $d$ and coefficient size at most $B$ have at least one integer roots should be $B^{O(d)}f(d)$ at some function $f$ (from Random Diophantine polynomials: Percent solvable?). So the probability that a uniformly random polynomial in $\mathbb Z[x]$ of degree $d$ and coefficient size at most $B$ has at least one integer root is $\frac{B^{O(d)}f(d)}{(2B+1)^{d+1}}\asymp\frac{f(d)}{2B+1}$ which is close to $0$.

*

*Then what is the average number of integer roots for polynomials in $\mathbb Z[x]$ of degree $d$ and coefficient size at most $B$?

I think it should be $<1$.
However I am not sure of the exact parameterizations.
It might be $\frac1{B^{O(d)}}$ on average.

*What is the average number of integer roots for polynomials in $\mathbb Q[x]$ of degree $d$ and coefficients with numerator of size at most $B$ and denominator of size at most $C$?

A: $$\mathbb{E}[\text{#|roots of P|}]=\mathbb{E}(\sum_{k\in \mathbb{Z}}1_{k \text{ is a root of P}})=\sum_{k\in\mathbb{Z}}\mathbb{P}(P(k)=0)$$
For $k=0$, $\mathbb{P}(P(0)=0)=\frac{1}{(2B+1)}$.
For $k\neq 0$, because the coefficients are independent (if $B$ and $d$ large) $P(k)$ should behave like a Gaussian if $d$ is large of variance $\sigma^2=\sum_{j=0}^d \big(k^{2j}\times\frac{1}{(2B+1)}\sum_{i=-B}^Bi^2\big)\approx  (d+1)\times \frac{B^2}{3}$ if $|k|=1$ and  $\frac{k^{2d+2} -1}{k^2-1} \times \frac{B^2}{3}$ for $|k|>1$. So $$ \mathbb{P}(P(k)=0)\approx \begin{cases} \frac{1}{B\sqrt{2\pi(d+1)/3}}  \text{ for }k=1 \\  \frac{1}{B\sqrt{2 \pi\frac{k^{2d+2} -1}{k^2-1}/3}} \text{for |k|>1}\end{cases}$$ Note that for large $d$, the probability for $|k|>1$ is very small and then
$$\mathbb{E}[\text{#|roots of P|}]\approx \mathbb{P}(P(0)=0)+\mathbb{P}(P(1)=0)+\mathbb{P}(P(-1)=0)\approx\frac{1}{(2B+1)}(1+2\times \frac{\sqrt{6}}{\pi d})
$$(same result as in Random Diophantine polynomials: Percent solvable?)


text:
Q: Are the characteristic functions of bounded random variables infinite times continously derivatable (on the entire real line)? This question was raised to me, and I might need some help with this.
"If $X$ is bounded, meaning $\exists K$, that $|(X)| \le K$ than the characteristic function of $X$ can be derivated infinite times. "
First, I get that if the n-th moment exist, then the characteristic function can be derived n times. So i believe, that if all the moments exist (meaning they are not infinite), then the characteristic function can be derivated infinite times.
However, I can't prove that for a bounded distibution all moments exist. Wikipedia says that "For a distribution of mass or probability on a bounded intervall, the collection of all the moments (of all orders, from 0 to ∞) uniquely determines the distribution (Hausdorff moment problem)", but I cant see whether this means all the moments exist.
Thank you for your help!

A: if by your problem u mean K is a real number then X indeed has all finite moments and E(abs(X^n))<=K^n


text:
Q: Is there a way to get the maximum number of virtual machines that can be created on your Azure account using the Azure Python SDK or the API? I am trying to make a python program that takes the current number of virtual machines from my account and the maximum number of VMs that can be created per account or per region to see how many new VMs I can create.
I used ComputeManagementClient to get the current VMs, but I don't find anything in the documentation (https://learn.microsoft.com/en-us/python/api/overview/azure/?view=azure-python) about a way to take the limit number of VMs. Any tips or ideas?

A: Azure REST API:
You can use the Azure Quota REST API (Preview) to query and manage service limits (quota) for the resources programmatically. The response from the Quota - List API can be leveraged to submit quota update requests as well. Note that apart from support in REST API, quota management is available in several interfaces and languages.
Azure Python SDK:
The same is made available in the Python SDK via the UsageOperations class. The list method gets, for the specified location, the current compute resource usage information as well as the limits for compute resources under the subscription.
So you should be able to do something similar to:
for r in compute_client.usage.list(<location>):
       print(
           f"\nName: {r.name.value}\nCurrent Value: {r.current_value}\nLimit: {r.limit}")

that would yield results like:
Name: availabilitySets
Current Value: 1
Limit: 2500

Name: cores
Current Value: 20
Limit: 100

Name: virtualMachines
Current Value: 11
Limit: 25000

Name: virtualMachineScaleSets
Current Value: 0
Limit: 2500

..
..


text:
Q: Pandas reversing Data Frames giving strange results Let's say I've a df
           value
2023-02-01     a
2023-02-02     b
2023-02-03     c
2023-02-04     d

when I try to reverse df and after doing some operations If i reverse back It not showing complete df Like
import pandas as pd
df = pd.DataFrame(
    {"value": {0: "a", 1: "b", 2: "c", 3: "d"}}
)
df.index = pd.date_range(start='2023-02-01', periods=4,freq='D')
new  = df.loc[::-1] #Reversing 1 time
new2 = new.loc[::-1] # Reversing back again..
print(new2)

Giving me # even though I haven't done any operations on df
2023-02-04     d

Expected
          value
2023-02-01     a
2023-02-02     b
2023-02-03     c
2023-02-04     d

Version Detials
Pandas 1.3.5
Python 3.9