text:
Q: Decoding a text file in python What would the syntax look like when decoding a file ,when I try to open the file it shows this #<_io.TextIOWrapper name='DOB.txt' mode='r+' encoding='cp1252'>

A: Your resulting printout is actually your opened file (it's an object).
I suppose you're opening the file like this:
f = open("DOB.txt", "r+", encoding="cp1252")

Directly printing f will result in your current printed string.
To actually retrieve the contents of your file, you need to call the read method.
Example:
f = open("DOB.txt", "r+", encoding="cp1252")
content = f.read()

content will become the contents of your file as a single string whereas newlines are being encoded by a newline character (depending on your OS either \r\n (on Windows) or \n on a UNIX-based OS)


text:
Q: How to use Queues in Laravel Project Code without Artisan commands? I am learning Queues in Laravel I want a practical learning I didnt get exactly what i want still. Please anyone explain me about this.

A: You should take reference from below URL.
https://scotch.io/tutorials/why-laravel-queues-are-awesome

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't scrape the links of different companies from a website using requests I'm trying to get the links of different companies from a webpage but the script I've tried with throws the error below. In chrome dev tools I could see that I can get the ids of different companies using post http requests. However, if I can get the ids then I will be able to make use of this link 'https://angel.co/startups/{}' adding id's in string format to make a full-fledged company link.
Webpage link
I've tried with:
import requests

link = 'https://angel.co/company_filters/search_data'
base = 'https://angel.co/startups/{}'

payload={'sort':'signal','page':'2'}

r = requests.post(link,data=payload,headers={
    'x-requested-with':'XMLHttpRequest'
    'User-Agent":"Mozilla/5.0'
    })
print(r.json())

The above script throws the following error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

How can I get the links of different companies from the aforementioned site using requests?

A: I've made function get_soup(page), which accept page parameter from 1 and returns soup with relevant data. You can put this function in a loop to scrape more pages:
import requests
from bs4 import BeautifulSoup

def get_soup(page=1):
    headers = {
        'Accept-Language'           : 'en-US,en;q=0.5',
        'Host'                      : 'angel.co',
        'User-Agent'                : 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0'
    }

    payload={'sort':'signal','page':str(page)}

    url = 'https://angel.co/company_filters/search_data'

    data = requests.get(url, headers=headers, data=payload).json()

    new_url = 'https://angel.co/companies/startups?' + '&'.join('ids[]={}'.format(_id) for _id in data['ids'])
    new_url += '&sort=' + data['sort']
    new_url += '&total=' + str(data['total'])
    new_url += '&page=' + str(data['page'])
    new_url += '&new=' + str(data['new']).lower()
    new_url += '&hexdigest=' + data['hexdigest']

    data = requests.get(new_url, headers=headers).json()
    return BeautifulSoup(data['html'], 'lxml')

soup = get_soup(1)

rows = []
for company, joined, location, market, website, company_size, stage, raised in zip(soup.select('.column.company'),
                            soup.select('.column.joined .value'),
                            soup.select('.column.location .value'),
                            soup.select('.column.market .value'),
                            soup.select('.column.website .value'),
                            soup.select('.column.company_size .value'),
                            soup.select('.column.stage .value'),
                            soup.select('.column.raised .value')):

    company = company.get_text(strip=True, separator=" ")
    joined = joined.get_text(strip=True)
    location = location.get_text(strip=True)
    market = market.get_text(strip=True)
    website = website.get_text(strip=True)
    company_size = company_size.get_text(strip=True)
    stage = stage.get_text(strip=True)
    raised = raised.get_text(strip=True)

    rows.append([company, joined, location, market, website, company_size, stage, raised])

from textwrap import shorten
print(''.join('{: <25}'.format(shorten(d, 25)) for d in ['Company', 'Joined', 'Location', 'Market', 'Website', 'Company Size', 'Stage', 'Raised']))
print('-' * (25*8))
for row in rows:
    print(''.join('{: <25}'.format(shorten(d, 25)) for d in row))

Prints:
Company                  Joined                   Location                 Market                   Website                  Company Size             Stage                    Raised
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Nutanix Your [...]       May '14                  San Jose                 Virtualization           nutanix.com              1001-5000                IPO                      $312,200,000
EverFi                   Oct '12                  Washington DC            Education                everfi.com               51-200                   Series C                 $61,000,000
Butter Make friends [...]Jun '14                  San Francisco            Messaging                getbutter.me             1-10                     Seed                     $371,500
Fluent The future [...]  Mar '12                  Sydney                   Curated Web              fluent.io                -                        -                        -
Belly                    Sep '12                  Chicago                  Small and Medium [...]   bellycard.com                                     Series B                 $24,975,000
Autotech Ventures [...]  Apr '14                  Menlo Park               Internet of Things       autotechvc.com           1-10                     -                        -
Oscar Health [...]       Jun '14                  Tempe                    Technology               hioscar.com              1001-5000                                         $1,267,500,000
Tovala Smart oven [...]  Feb '16                  Chicago                  Home Automation          tovala.com               11-50                    Series A                 $10,800,000
GiftRocket Online [...]  Mar '16                  San Francisco            Gift Card                giftrocket.com           1-10                     Seed                     $520,000
Elemeno Health B2B [...] Apr '16                  Oakland                  Training                 elemenohealth.com        1-10                     Seed                     $1,635,000
Sudo Technologies [...]  Apr '16                  Menlo Park               -                        sudo.ai                                           -                        -
Stypi                    Sep '16                  -                        -                                                                          Acquired                 -
Amazon Alexa Amazon [...]Sep '16                  Cambridge                Speech Recognition       developer.amazon.com     11-50                    -                        -
Altos Ventures A [...]   Oct '16                  Menlo Park               Technology               altos.vc                 1-10                     -                        -
Flirtey Making [...]     Oct '16                  Reno                     -                        flirtey.com              11-50                    Series A                 $16,000,000
SV Liquidity Fund [...]  Oct '16                  San Francisco            B2B                      svlq.io                  1-10                     -                        -
Princeton Ventures [...] Jan '17                  Princeton                Technology               princetonventures.com    1-10                     -                        -
hulu - Beijing [...]     Jan '17                  Beijing                  TV Production            hulu.com                 -                        -                        -
Distributed Systems [...]Jan '17                  San Francisco            Identity                 pavlov.ai                1-10                     -                        -
Fetch Marketplace [...]  May '17                  Atlanta                  Technology               fetchtruck.com           1-10                     Seed                     -

EDIT: For getting just links, you can do:
soup = get_soup(1)

for a in soup.select('.website a[href]'):
    print(a['href'])

Prints:
http://www.fuelpowered.com
http://www.slide.com
http://www.mparticle.com
http://www.matter.io
http://www.smartling.com
https://stensul.com
https://avametric.com/
https://ledgerinvesting.com

http://www.relativityspace.com
http://teamdom.co
http://www.wonderschool.com
http://www.upcall.com
http://focal.systems
https://asktetra.com
https://www.subdreamstudios.com/
http://www.stedi.com
http://www.magnarapp.com/
http://www.kylie.ai
http://clipboardhealth.com

A: You can use selenium:
from selenium import webdriver
from bs4 import BeautifulSoup as soup
d = webdriver.Chrome('/path/to/chromedriver')
d.get('https://angel.co/companies')
links = [i.a['href'] for i in soup(d.page_source, 'html.parser').find_all('div', {'class':'photo'})]

Output:
['https://angel.co/company/orchestra-one', 'https://angel.co/company/workramp', 'https://angel.co/company/alien-labs', 'https://angel.co/company/teamdom', 'https://angel.co/company/focal-systems', 'https://angel.co/company/ripple-co', 'https://angel.co/company/solugen', 'https://angel.co/company/govpredict', 'https://angel.co/company/ring-6', 'https://angel.co/company/radiopublic', 'https://angel.co/company/function-of-beauty', 'https://angel.co/company/kid-koderz-city', 'https://angel.co/company/united-income', 'https://angel.co/company/volara', 'https://angel.co/company/optimus-ride', 'https://angel.co/company/amplitude-analytics', 'https://angel.co/company/nanonets', 'https://angel.co/company/magnar', 'https://angel.co/company/kylieai', 'https://angel.co/company/clipboardhealth']


text:
Q: WPF DataGrid make new row TabStop I have a DataGrid with CanUserAddRows="True". My table has multiple columns; the user can edit the cells and jump to the next one by pressing Tab. When you are at the last column, Tab will take you to the next row.
However, if you are editing a New Row, when you Tab at the last column, the focus will jump to the next control in the windows BEFORE the new row is created.
What I need to happen is the focus to jump to the new created row in the DataGrid. I honestly have no idea where to begin attacking this problem.
EDIT: I should clarify that the first column of the new row is the one that should get the focus (Imagine someone filling the grid just with the keyboard, using tab).

A: You could handle the PreviewKeyDown event for the DataGrid to intercept the TAB keypress and programmatically press the ENTER key:
<DataGrid x:Name="dg" ... PreviewKeyDown="dg_PreviewKeyDown" />

private void dg_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Tab)
    {
        e.Handled = true;

        var key = Key.Enter;
        var target = Keyboard.FocusedElement;
        var routedEvent = Keyboard.KeyDownEvent;

        dg.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(dg), 0, key)
        {
            RoutedEvent = routedEvent
        });
    }
}


text:
Q: Access denied when trying to navigate to the Authorization url following oauth tutorial I am trying to build an app that brings in and renders Jira data in a unique way. I'm trying to follow the following tutorial: here. I'm at step 1: Direct the user to get an authorization call. I set up my app Permissions and Authorization. The authorization url generator created the following url:
https://auth.atlassian.com/authorize?audience=api.atlassian.com&client_id=1SdMM8pTryWCljI1Awm9drfKvnU2BR2H&scope=read%3Ajira-work%20manage%3Ajira-project%20manage%3Ajira-configuration%20read%3Ajira-user%20write%3Ajira-work%20manage%3Ajira-webhook%20manage%3Ajira-data-provider&redirect_uri=https%3A%2F%2Flocalhost%3A4200%2F&state=${YOUR_USER_BOUND_VALUE}&response_type=code&prompt=consent
(I do get a warning: The Jira Service Management API for your app doesn't have any classic scopes. Add classic scopes to your app.Though I do have 7 Jira Api scopes added.)
This is just a dummy app for now that I will use to connect to localhost. When I try to browse the url I get the following page. Is there something that I'm missing that I need to do?


text:
Q: kexec: relocate_kernel fails I am not able to get kexec to work. For x86_64 relocate_kernel fails to store information for jumping back.
Kexec stops in movq %r9, CP_PA_TABLE_PAGE(%r11).

works fine for kernel 4.4.162, doesn't work for 4.19.2

also works with 4.19.16
How can I find out which change caused this error?

It seems it is a config issue, it works also for 4.19.2 however with defconfig.
Does someone know what the config option breaks kexec?

I forgot to save/restore scratch registers
Really kexec stops in
/* Switch to the identity mapped page tables */
movq    %r9, %cr3

Any idea? What config parameter is wrong?

Must also mention I had to disable loading of fs and gs in load_segments(), otherwise kexec breaks already in load_segments()
Is it EFI issue?


text:
Q: lightning:overlayLibrary popup window closing and opening I am making a related list, that is filterable by certain criteria. I am developing a lightning component that i can use on Lightning Builder. In the component, i use <lightning:overlayLibrary> component to show a popup when users hovers a hoverable record link.
This is the picture of my current popup:

The problem i am facing, is opening and closing the popup correctly. Currently i am triggering a onmousover event on the DIV element and automatically close the event after 3 seconds. The DIV is the "9999999" as link on the left side of the picture.
Problems with that solution:
1) When user is going over the div not intentionally, the popup will show up because onmouseover event was triggered.
2) When user fastly drags the mouse over all the records in the related list, many popup's will show up, i have a check in my javascript that only 1 popup could be shown at once, but i am using setTimeout().
3 When users want to see the popup longer than 3 seconds, they have to reopen it. When i did not close the popup after 3 sec but used onmouseleave event, then when i go on the popup with my mouse, the popup will close, because the triggering div is this number "999999"
What i want to do, is Allow only 1 popup to be open, and if users leave the popup with the mouse, then the popup will be closed. Otherwise the popup will stay open.


text:
Q: SQLite 3 C API Transactions I am using SQLite3 for iPhone development and I'm attempting to wrap a few insert statements into a transaction. Currently I have the below code which is working properly however after reading another question on SO I realized it would be better to have these in one transaction rather than one each. I couldn't find the C API call to begin and commit a transaction. Some of the code is in Objective-C but I don't think that's really relevent to the question.
- (void)saveAnimals {
    //Insert all the animals into the zoo database
    int i;

    const char *sql = "insert into Animal(Zoo_ID, Animal_Num, Animal_Text) Values(?, ?, ?)";
    for (i = 0; i < ([[self animalArray] count] - 1); i++) {

        if(addStmt == nil) {
            if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
                NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
        int animalNum = [[[self animalArray] objectAtIndex:i] animal_Number];
        NSString *animalText = [[NSString alloc] initWithString:[[[self animalArray] objectAtIndex:i] animal_Text]];
        sqlite3_bind_int(addStmt, 1, zoo_ID);
        sqlite3_bind_int(addStmt, 2, animalNum);
        sqlite3_bind_text(addStmt, 3, [animalText UTF8String], -1, SQLITE_TRANSIENT);
        [animalText release];
        if(SQLITE_DONE != sqlite3_step(addStmt)) {
            NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
        }

        //Reset the add statement.
        sqlite3_reset(addStmt);
    }
}

What I think needs to be done would be taking the sqlite3_prepare_v2 command out of the for loop, start the transaction, go through the for loop, commit the transaction. However, I'm not sure what the calls for "start the transaction" and "commit the transaction" are. And would I still use sqlite3_step? Thanks for your help.

A: Start a transaction with: sqlite3_exec(db, "BEGIN", 0, 0, 0);
Commit a transaction with: sqlite3_exec(db, "COMMIT", 0, 0, 0);


text:
Q: Is a value stored in registers/memory an address or the contents? I cannot understand this. My concept just went from 50% to 0.
What does mov eax, 23h do? Does it store the value 23h to eax register or the address 23h (in eax)? Should it not be storing the value of 23 hexadecimal in eax?
if .data contains
value Word 230

and our instructions contain
mov ax, value

What will this do? Store 230 in ax or get the address of value and store it in ax?
Lastly what if we write this code
mov ax, [value]


text:
Q: Involutions on power series $\mathbb{C}[[X_1,\ldots,X_n]]$ For the ring of formal power series $\mathbb{C}[[X_1,\ldots,X_n]]$ over complex numbers,
is it true that any automorphism of order $2$ is after change of co-ordinates
given by $X_i\mapsto  \pm  X_i$?


text:
Q: Is a power set's base set uniquely determined? Is a power set's base set uniquely determined? More precisely, if $\mathcal{P}(S) = \mathcal{P}(T)$, does that imply $S=T$?

A: Since $\bigcup\mathcal{P}(A) =A$, the base is unique.

A: Sure; we can prove the contrapositive. Suppose that $S \neq T$, so that there is (say) $a \in T \backslash S$. Then $\{a\} \in \mathcal{P}(T)$ but $\{a\}\notin \mathcal{P}(S)$, so $\mathcal{P}(S) \neq \mathcal{P}(T)$.


text:
Q: Branch, tag or something else in SVN to indicate overriden functionality? I am writing first project with SVN (Java + frameworks + HTML).  So far only commits, and sometimes update to recent version. I want to change some functionality which works already in my project (this touches several files), and maybe in the future I would like to undo what is done now (if I or customer decided to choose previous implementation/layout of functionality).
How can I achieve this? Something like two versions of functionality in one svn project.

A: If you plan this as a kind of "experimental feature", then you could create a branch for that feature. If you later decide to ignore it, just leave the branch, if you decide to make it the "main" branch, merge it back to your trunk.
If, however, this is a "real" feature and you simply want to remember what the old code looked like than a tag (pre_huge_change_bug1234) might be sufficient.

A: Because you are modifying the functionality i would opt for a branch.
And have 2 branches of the same project.


text:
Q: Java: JDOQL startsWith query, case sensitive I'm using the .startsWith() filter in a JDOQL query but it's case sensitive.
So startsWith("ab") doesn't return "Abc" result and so on.
Will I need to use a SQL query to avoid this ?

A: So combine it with toUpperCase() then perhaps
field.toUpperCase().startsWith("AB")
Edit : fix method names


text:
Q: Out of Bounds Exception in GridView I have 8 Images in the array list and I have to place only 4 of them in the grid and when I press next the next 4 images are to be displayed in the same grid
I am using the for loop as
for (i = 0; i < 4; i++) {
            ItemClassForCategoryImages itemClassForCategoryImages = new MainActivity().new ItemClassForCategoryImages();
            itemClassForCategoryImages.imageId = imgesForCategories[i];
            itemClassForCategoryImages.GridText = GridText[i];
            data.add(itemClassForCategoryImages);
        }

and the other for loop as
textViewForMoreOption.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                data = new ArrayList<MainActivity.ItemClassForCategoryImages>();
                for (j = i; j < i+4; i++) {
                    ItemClassForCategoryImages itemClassForCategoryImages = new MainActivity().new ItemClassForCategoryImages();
                    itemClassForCategoryImages.imageId = imgesForCategories[j];
                    itemClassForCategoryImages.GridText = GridText[j];
                    data.add(itemClassForCategoryImages);
                    i=0;
                }
                CustomAdapteForGrid adapter = new CustomAdapteForGrid(
                        BaseActivity.width, BaseActivity.height, data, ctx, 2);
                gridViewForCategories.setAdapter(adapter);
            }
        });

But this is giving me out of bounds exeption.
Could someone give me an easy method ... ?


text:
Q: Configure SASL_PAINTEXT over multiple Kafka Brokers I am trying to setup a kafka statefulset on Kubernetes scaled up to 3 pods & want to have all kafka brokers to be able to connect with SASL_PLAINTEXT mechanism, however I'm getting the result that only one broker is able to connect & it blocks the rest of brokers. Anyone could please help me make them all able to connect with SASL_PLAINTEXT:
here is the deployment manifest:

java.lang.IllegalArgumentException: requirement failed: Configured end
points xx.x.x.xxx:9094 in advertised listeners are already registered
by broker 2

here is the mounted kafka_jaas.json:
KafkaClient {
    org.apache.kafka.common.security.plain.PlainLoginModule required
    username="kafka-user"
    password="kafka-password"
    user_kafka="kafka-password";
    };
KafkaServer {
    org.apache.kafka.common.security.plain.PlainLoginModule required
    username="kafka-user"
    password="kafka-password"
    user_kafka="kafka-password";
    };

and the listeners config:
    - name: KAFKA_LISTENERS
      value: "INSIDE://:9092,LB://:9094,CONTROLLER://:9093"
    - name: KAFKA_ADVERTISED_LISTENERS
      value: "INSIDE://:9092,LB://xx.x.x.xxx:9094,CONTROLLER://:9093"
    - name: KAFKA_LISTENER_SECURITY_PROTOCOL_MAP
      value: "INSIDE:SASL_PLAINTEXT,LB:SASL_PLAINTEXT,CONTROLLER:SASL_PLAINTEXT"

    - name: KAFKA_INTER_BROKER_LISTENER_NAME
      value: "INSIDE"

    - name: KAFKA_CONTROLLER_LISTENER_NAME
      value: "CONTROLLER"

    - name: KAFKA_CONTROLLER_SHUTDOWN_ENABLE
      value: "false"
    - name: KAFKA_SASL_MECHANISM_CONTROLLER_PROTOCOL
      value: "PLAIN"
    - name: KAFKA_SASL_MECHANISM_INTER_BROKER_PROTOCOL
      value: "PLAIN"
    - name: KAFKA_SASL_ENABLED_MECHANISMS
      value: "PLAIN"

(xx.x.x.xxx is replaced by the external IP address of a load balancer for the kafka service)
& the Kafka image is: wurstmeister/kafka:2.12-2.2.1
zookeeper image: zookeeper:3.5


text:
Q: Is Fiona's collections.OrderedDict immutable? After opening shapefile I want to use all of its attributes (geometry column, crs, etc), but want to delete the contents of the OrderedDict in the 'properties' key. I want to append new data to it, and write it back to a shapefile.
The standard syntax for deleting keys from Python dicts like so
D = {'spam': 2, 'ham': 1, 'eggs': 3}
D.popitem()
('eggs', 3)
D
{'ham': 1, 'spam': 2}

does not apply to the fiona collections object:
How can I manipulate a fiona.collection object? Or are those immutable?

A: Simply use del
import fiona
shape = fiona.open("ashape.shp")
one = shape.next()
print one
{'geometry': {'type': 'Point', 'coordinates': (-0.7989756722151089, 0.5492957746478874)},
'type': 'Feature', 'id': '0',
'properties': OrderedDict([(u'id', 0), (u'test', 5), (u'hello', u'you')])}
# delete one "field"
del one['properties']['hello']
print one
{'geometry': {'type': 'Point', 'coordinates': (-0.7989756722151089, 0.5492957746478874)},
 'type': 'Feature', 'id': '0',
 'properties': OrderedDict([(u'id', 0), (u'test', 5)])}
# add a new "field"
one['properties']['bb']= "hello"
print one
{'geometry': {'type': 'Point', 'coordinates': (-0.58898847631242, 0.17797695262484003)},
'type': 'Feature', 'id': '1',
'properties': OrderedDict([(u'id', 1), (u'test', 5), ('bb', 'hello')])}

If you want to delete all the key/values
 one['properties'].clear()
 print one['properties']
 OrderedDict()
 one['properties']['test'] = 1
 one['properties']
 OrderedDict([('test', 1)])

But be careful, if you modify the properties, you need to modify also the schema of the original shapefile.


text:
Q: PyMongo: unable to list collections of database Below is the piece of the code:
client=MongoClient('localhost',27017)
db1=client.achievements_new
collection=db1.collections

@app.route("/achievements", methods=['GET', 'POST'])
def achievements():
    form = Achievements()
    if form.validate_on_submit():
        uname=request.form['username']

        achievements=request.form['acheivements1']
        db1.collection.insert_one({'user':uname,'achievements':achievements})

        flash('Your achievements have been added successfully!','success')
        return redirect(url_for('home'))
    return render_template('achievements.html', title='Achievements', form=form)

Form is getting submitted successfully,but in python interpreter if i am trying to list collections,it is throwing error; but database is shown in the list;
below is response of python interpreter
from flaskblog import client
print(client.list_database_names())

['achievements', 'achievements_new', 'admin', 'config', 'local', 'mydatabase', 'test']
print(collections.list_collection_names())

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'collections' is not defined
print(db1.list_collection_names())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'db1' is not defined
print(collection.list_collection_names())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'collection' is not defined
print(collections.list_collection_names())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'collections' is not defined

I tried all possible combinations, but got nothing fruitful in return.
Any solution for the same would be of great help.
Thanks!!


text:
Q: Curl batch file I have the following batch file that is executing cURL POST command:
curl -k -X POST -F "upload=@xxx0101.csv" -F "mail=******" -F "pwd=******" -F "orgid=2729" -F "response=JSON" https:************* >> log.txt
SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir %cd%\Backup-%Today%
move %cd%\*.csv %cd%\Backup-%Today%\

I would like the conditional execution of the latter part of the script(after the CURL has been executed) based on success/failure of the cURL POST command/file transfer.
Could you please help me with this.


text:
Q: sending mass email to new employees with PDF attached I have handful of employees joining to the company soon. and i have all of their records ( i.e DOB,F_name, L_name, demographics information)in my SQL database. we usually had HR sending welcome packet to them manually. Now we are trying to automate the task, and send it using a HR email ID to x number (send mass email) of people to their respective emails, with an attached PDF with their name.
Is there a way we could do that using SQL,SSRS or SSIS?
things to be taken in to consideration:
1) it has to be mass email
2) utilize SQL database as a source.
3) update multiple field in PDF for individual person like Name, Email_ID
4) attach PDF to the respective person email and send an email.
any help will be appreciated.

A: If you have the Enterprise Edition of SQL Server, you can use Data Driven Subscriptions to email reports with the Employee as a parameter so each on gets their own information.
You would have a query with the Employees e-mail address to use as the TO: and use their ID as a parameter to pass to the report to filter for that employee's information.
When you run the report, it runs the query to get a separate record for each employee and churns out a separate report.
MSDN - Data Driven Subscriptions


text:
Q: The disjoint cliques problem for complete graphs. There is complete graph $K_{n}$

Find formula for maksimal number of disjoint to each other $k$-cliques in $K_{n}$. Let denote it as $A(n,k)$

I did some research and i computed a formula: $B(n,k)=\lfloor \frac{{n\choose 2}}{{k\choose 2}}\rfloor$.
I thought that equality $A(n,k)=B(n,k)$ holds for every $n,k$, but i was wrong.
For example:

*

*$A(4,3)=1=B(4,3)-1$

*$A(5,3)=2=B(5,3)-1$

*$A(6,3)=4=B(6,3)-1$

*$A(6,4)=1=B(6,4)-1$
Is this true that $A(n,k)=B(n,k)-1$?
Regards


text:
Q: Unable to update an existing schema extension Im trying to add a few properties to an schema Extension with the Microsoft Graph API. Our extension is in development state and I'm obtaining an accesstoken with the same app Id which is owner of the extension.
The problem is that I always get the following error:
{
"error": {
"code": "BadRequest",
"message": "Cannot delete an existing property.",
"innerError": {
  "date": "2020-08-10T15:15:15",
  "request-id": "9344dbe9-084d-4bd9-a690-75fcd32db6bc"
}
}
}

The Following request is used:
PATCH https://graph.microsoft.com/v1.0/schemaExtensions/<OurId>

{
"properties": [
{
  "name":"<name of first property>",
  "type":"String"
},
{
  "name":"<name of second property>",
  "type":"DateTime"
}
]
}

Has anyone an idea?

A: You should mention all properties - existing and new. If "properties" section contains only new properties you will get this error.


text:
Q: How to use KoolReport in Codeigniter? Anyone knows how to integrate KoolReport into Codeigniter? I had followed the guideline from https://www.koolreport.com/ by unzipped the folder and pasted into my project folder and created that three files (SalesByCustomer.php, SalesByCustomer.view.php and index.php). But it didn't work. Kindly tell me the steps clearly. Appreciated.

A: Try to use this instruction for integration Koolreport in Codeigniter.


text:
Q: cant find element by id with selenium and chromedriver in python I keep getting this error.
I am trying to log into my godaddy account in order automatically update my website every day with a new bit of text. It keeps saying it cant find the element by id, but I've tried everyother find_element_by_ method in the PyCharm editor. None of them seem to work. XPath, class, selector, name, etc.
"C:\Users\mperr\PycharmProjects\Selenium Scripts\venv\Scripts\python.exe" "C:/Users/mperr/PycharmProjects/Selenium Scripts/macAndCheeseBar.py"
Traceback (most recent call last):
  File "C:/Users/mperr/PycharmProjects/Selenium Scripts/macAndCheeseBar.py", line 10, in <module>
    user_input = driver.find_element_by_id("username")
  File "C:\Users\mperr\PycharmProjects\Selenium Scripts\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Users\mperr\PycharmProjects\Selenium Scripts\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\mperr\PycharmProjects\Selenium Scripts\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\mperr\PycharmProjects\Selenium Scripts\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
  (Session info: chrome=83.0.4103.61)

here is my code:
from selenium import webdriver

username = "myUsername"
password = "myPassword"

driver = webdriver.Chrome(r"C:\Users\mperr\Downloads\chromedriver_win32\chromedriver.exe")
driver.get("https://sso.godaddy.com/?realm=idp&path=%2Fproducts&app=account")

user_input = driver.find_element_by_id("username")
user_input.send_keys(username)

password_input = driver.find_element_by_id("password")
password_input.send_keys(password)

login_button = driver.find_element_by_id("submit Btn")
login_button.click()

Here is the html:
<input id="username" type="username" aria-labelledby="label-username" aria-required="false" class="username-input ctHidden form-control" value="">

<input id="password" type="password" aria-labelledby="label-password" aria-required="false" class="ctHidden form-control" value="">

<button target="_parent" tabindex="0" class="btn btn-primary btn-purchase btn-block" id="submitBtn" type="button">Sign In</button>

Am I mssing something here?

A: Your code wasn't waiting for the page to load completely.
I tried your code with some changes, here's my code,
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

username = 'your username'
password = 'your password'

driver =webdriver.Chrome(r"C:\Users\mperr\Downloads\chromedriver_win32\chromedriver.exe")
driver.get("https://sso.godaddy.com/")
element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "username"))
    )   #wait for page to load, so element with ID 'username' is visible

user_input = driver.find_element_by_id("username")
user_input.send_keys(username)

password_input = driver.find_element_by_id("password")
password_input.send_keys(password)

login_button = driver.find_element_by_id("submitBtn")
login_button.click()

You can read documentation about selenium waits here.
You can even use python's time module for waits


text:
Q: Making GTK# File Chooser to Select File Only Im using GTK# FileChooserDialog  widget.The problem is that even though the widget is named file chooser you can select folders with it and it returns folder names also.
Is there any way by which i can restrict it to choosing only files? I have checked almost class all properties i could not find any.

A: you can restrict the action by defining its Action-Property in the constructor
private void OpenOFD()
{
    Gtk.FileChooserDialog filechooser =
        new Gtk.FileChooserDialog("Choose the file to open",
            this,
            FileChooserAction.Open,
            "Cancel",ResponseType.Cancel,
            "Open",ResponseType.Accept);

    if (filechooser.Run() == (int)ResponseType.Accept)
    {
        System.IO.FileStream file = System.IO.File.OpenRead(filechooser.Filename);
        file.Close();
    }

    filechooser.Destroy();
}

There are 4 FolderChooserActions:

*

*CreateFolder: Indicates a mode for creating a new folder. The chooser will let the user name an existing or new folder

*Open: Will only pick an existing file

*Save: Will pick an existing file or type in a new filename

*SelectFolder: Pick an existring folder

A: According to the documentation, that behavior depends on the Action property:

*

*If it is set to FileChooserAction.Open or FileChooserAction.Save, only files can selected.

*If it is set to FileChooserAction.SelectFolder or FileChooserAction.CreateFolder, only folders can be selected.


text:
Q: Does Facebook allow CORS headers? How can I discover if Facebook allowes cross domain requests? Can I make a JavaScript which can handle a Cross Domain Request to Facebook?

A: Are you talking about the Facebook API? Anyway:
http://www.test-cors.org


text:
Q: Designing dimension hierarchies: Natural or Unnatural I'm using Analysis Services and when designing dimensions I'm never sure how far to go to build natural hierarchies.
What I mean is I've added in all the genuine attribute relationships. So most hierarchies are natural anyway but the most commonly requested hierarchy is 3 or more levels with a middle level as a slowly changing attribute.
The scenario is tracking jobs. The job has many attributes which are all static but the Debtor attribute (i.e. who's paying the invoice) can change over the course of the job.  So the hierarchies look like this
 - Manager -> Debtor -> Job Name
 - Director -> Debtor -> Job Name
 - Office -> Debtor -> Job Name
 - Office -> Manager -> Debtor -> Job Name

So within the dimension there are many hierarchies that start with static attribute(s) of the job followed by the debtor (which slowly changes) with the job name (dimension key) at the bottom.
So what we do at the moment to "naturalize" these hierarchies is create "fake" attributes for each debtor that appears in a hierarchy that is a combination of the attributes above it. e.g. for the first example above the Debtor level attribute would have a key of Manager and Debtor id's. And for the last example the Manager level would have a key of Manager and Office and the Debtor level attribute would have a key of Office, Manager & Debtor. We then hide all these attributes so they are only used in the hierarchies.
So this makes our dimensions a lot more complicated but we do get the benefit of extra performance on our queries. Often this is a noticeable improvement. Apart from complexity we constantly hit problems because we now have multiple versions of a "Debtor" and the key of the attribute is not the id of the debtor. So this affects Drillthrough and Reporting actions as well as making certain types of calculation more difficult if we want to change behavior for certain levels.
The clients we use are Reporting Services, Excel and Office Web Components.
I've been told that on early versions of SQL 2005 complex queries involving unnatural hierarchies could result in the server getting completely tied in knots which is another reason we've gone to great lengths to avoid unnatural hierarchies.
Also, the exclamation mark design warning is so dramatic in Visual Studio that it seems like a really bad thing to have unnatural hierarchies.
What do other designers do in these situations? How far do you go to avoid unnatural hierarchies?

A: The way to do hierarchies in a slowly changing dimension on a SSAS cube is to synthesize a pseudo-hierarchy with actual keys hidden behind the scenes but just showing the attributes as if they were keys.
Office     Manager    DebtorKey  Debtor      JobKey   Job Name    From        To
Scunthorpe Bloggs     101        Scarper&Co  2001     Fixit       2010-01-01  2010-01-31
Scunthorpe Bloggs     102        Bodgett     2002     Fixit       2010-02-01  9000-01-01

This hierarchy gets constructed over the original slowly changing dimension and is used to do the attribute relationships.  You do want the levels in a hierarchy to have the proper attribute relationships.  IIRC these are necessary for the cube to do the 'Autoexists' optimisation (resolve non-emptiness purely from the dimension before hitting the fact table) - which is why the cube is slow when these relationships are not set up.
You may have to apply the hierarchy to the dimension in SQL before constructing the cube.  Certainly, if you want to load updates, the keys will need to remain static, although if you have time to do a complete refresh this may not be necessary.


text:
Q: "Nosy Neighbor" and the CFQ scheduler I'm trying to understand how does using CFQ affects the "Nosy Neighbor" problem.
I'll ask it a bit naively, can a "Nosy Neighbor" even exist when using CFQ? Isn't that CFQ should make sure all processes(VMs) get fair slices of storage time? If so, how can one VM I/O interfere with another's VM I/O when CFQ is being used?
Environment is CentOS6.5+OpenStack+KVM+Ceph


text:
Q: MongoDB update multiple collections My mongo db contains following collections name like
10.9.40.46
10.9.40.47
10.9.40.48
10.9.40.49
10.9.40.50
10.9.40.51
10.9.40.52

In all collections having N numbers of documents and every documents had common key name as "status" by default all documents had "status" 1, When I update my collections to change "status" 1 to 0 I use following query
 db.getCollection("10.9.40.46").update({"status":1},{$set:{"status":0}},false,true)

The above query work fine but, I want update all my collections then I pass my collections name to query manually, So there is any concepts in MongoDB that I used database and update all collections documents in that database using single query or something like that? I also used looping to read all collections and update documents but I it takes long time because of large number of collections.

A: No, there is no API to perform the same operation on multiple collections with a single command. That's because you normally don't use collections the way you use them. Collections are used to group documents of the same type, not for grouping them based on content and/or key.
The normal way to organize the documents you have would be to put them all in one collection, add a field for the IP address to each document and create an index on the ip-field for faster lookup.

A: you can use  for loop for the same.
var collection='10.9.40.'
var count=46;
var n=46;
var url='';
for(i =0;i<7;i++){
url="";
n=46+i;
url=count+n;
db.getCollection(url).update({"status":1},{$set:
{"status":0}},false,true)
}


text:
Q: Git: Command for cancel a commit When I work, I often meet with this workflow:

*

*Doing something.

*Someone comes to my desk and ask something, I must move to another branch for checking.

*I commit code on this current branch and checkout another branch.

*When I finish, I checkout old branch and continue to work.

This workflow has a disadvantage: it generates a dummy commit in my system. My question is: how can I avoid this situation? For example, when I come back to work, I will cancel previous commit?

A: In addition to the two existing answers (git reset and git stash), I personally just ignore the extra commit (which almost has a commit message of wip...) until I'm ready to push the change somewhere remote, e.g. to github to create a pull request.
At that point, I use git rebase -i to look at all the commits I've got in that branch, and work out which commits I want to push - squashing commits together and rewording commit messages as required.
I've personally found this to be easier to use than git stash, as I typically find I lose track of what stashes are meant to be about. (My fault rather than a flaw in git, but the effect is still bad.) I suspect that git reset would be fine too, but as I often have to rebase anyway before a final merge - e.g. to react to code review comments - I have git rebase as a more mentally efficient part of my workflow.

A: You can use git stash for precisely this. When someone comes to your desk, do a git stash to temporarily "shelve" your current work. Check out the other branch, do your thing, and then, when they leave, switch back to your work branch and do git stash pop.
Make sure you don't have any changes staged, though - git stash, if memory serves, ignores staged changes and untracked files.

A: After you switch back to the old branch, run git reset HEAD^ and you'll get back to your previous state. The latest temporary commit will be discarded. If you've pushed that commit, you'll need to --force a new push.

A: Sounds like you need git stash.  Check out this site for usage.  Your workflow will look something like this:
git stash (stashes your changes for this branch)
git checkout otherBranch (then do your work)
git checkout firstBranch (returning to the original job)
git stash apply (puts your uncommitted changes back)
You can also use git rebase -i to get rid of some of your existing dummy commits, see this.


text:
Q: list out the images of higher resolution using python Im trying to write a python script which will walk through a directory and traverse the all sub directories and if any jpg or png image has higher resolution than 2048*2048 then print out the name of those images. I am not able to traverse the sub-directories. Can anyone plz look into the code
import os
import matplotlib.image as plt

root_path = 'E:\newfolder'
img_list = os.listdir(root_path)

for img_name in img_list:

    if img_name.endswith(('.png', '.jpg')):
        img = plt.imread(root_path+'/'+img_name)

        if img.shape[0] > 2048 and img.shape[1] > 2048:
            print(root_path, img_name)

A: If you're using Python 3.5+, you can use the pathlib module, and then use a recursive glob pattern to find all files in all subdirectories. Then, you filter the paths and retain only those whose suffix is .png or .jpg:
from pathlib import Path

for path in [path for path in Path("dir/to/images").rglob("*.*") if path.suffix.lower() in (".png", ".jpg")]:
    # image = Image(path)
    # if image dimensions greater than 2048 x 2048:
    #     print(path)

print(path) will print out the entire absolute path of the current image, but if you just want to print out the name, you can print(path.name), which will include the suffix (file extension). If you just want the name of the file without the extension, you can print(path.stem).

A: crawl subdirectory using os.walk
import os
import pathlib
from PIL import Image

def crawlImages(directory):
    allowedExtensions = ['.jpg', '.png']
    for root, dirs, files in os.walk(directory):
        for f in files:
            if pathlib.Path(f).suffix in allowedExtensions:
                fileName = os.path.abspath(os.path.join(root, f))
                image = Image.open(fileName)
                width, height = image.size

                # checking minimum image width and height
                if width > 2400 and height > 2400:
                    print(fileName, width, height)

crawlImages('E:\\music')

A: Here's a complete and tested solution that is similar to answers by @Paul and @BrainCity. You'll see that I prefer using small, clear functions, since these encourage reusable code.
You can do the image processing using matplotlib as you do in your question, but you need to install Pillow in order to handle .JPG images, since matplotlib only supports PNG natively. I prefer using Pillow directly unless you're already using matplotlib for other stuff.
from pathlib import Path
from PIL import Image

def print_high_res_images(directory: str):
    root_path = Path(directory).resolve()
    high_res_images = get_high_res_images(root_path)

    if high_res_images:
        print('High resolution images:')
        for file_path in high_res_images:
            print(file_path)

def get_high_res_images(root_path: Path) -> []:
    return [path for path in root_path.rglob("*.*") if is_high_res_image(path)]

def is_high_res_image(file_path: Path) -> bool:
    if is_image(file_path):
        image = Image.open(file_path)
        width, height = image.size
        return width > 2048 and height > 2048

    return False

def is_image(file: Path) -> bool:
    return file.suffix.lower() in ['.png', '.jpg']

# Test our new function:
print_high_res_images(r'E:\newfolder')


text:
Q: How to view DJVU file in UIWebview I am having iOS application in which I want to view data from .djvu file. Is there any way to read .djvu file in Swift or inside UIWebview.
I have also tried following solutions to view djvu file in uiwebview but that doesn't help.
1. Directly open djvu file in uiwebview
 let urlPage : URL! = URL(string: "http://192.168.13.5:13/myData/5451890-OP.djvu")
 webView.loadRequest(URLRequest(url: urlPage))

2. Secondly i have tried to convert djvu file to pdf and the showing that converted pdf file into view.
Reference link: https://github.com/MadhuriMane/ios-djvu-reader
But that gives mirror image with low quality.
3. I have tried to preview file with the help of UIDocumentInteractionController() and it's delegate method but didn't work.
Please suggest any possible ways to do so.

A: Keeping in mind that .djvu files are less popular then similar formats like EPUB, MOBI, PDF and other eBook file formats, I would have following approach to workaround the problem.
1) Create a Web Service to convert djvu files to pdf
ex.: http://example.com/djvuToPdf/djvuFile/outputFile
2) Read the PDF file in UIWebView
To create a Web Service I would assume that you have access to any Linux distributed Server, in my case Ubuntu 16.04.
Step one: Install djvulibre
sudo apt-get install djvulibre-bin ghostscript
Step two: test run $ djvups inputFile.djvu | ps2pdf - outputFile.pdf.
You may also use the ddjvu command. However, files converted with ddjvu command are 10x larger than djvups command. You would want to consider to use --help the explore the settings like mode, quality and so on.
Step three: Creating a Web Service (to keep things simple, I use PHP, use anything at your convenience [Python golang])
<?php

$inputFile = $_GET['input_file'];
$outputFile = $_GET['output_file'];

// use shell exec to execute the command
// keep in mind that the conversion takes quite a long time
shell_exec(sprintf("djvups %s | ps2pdf - %s", $inputFile, $outputFile));

$name = $outputFile;
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;

?>

Final Step: load PDF in App
As Apple advise, consider using WKWebView in place of UIWebView.
if let pdfURL = Bundle.main.url(forResource: "pdfFile", withExtension: "pdf", subdirectory: nil, localization: nil)  {
    do {
        let data = try Data(contentsOf: pdfURL)
        let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
        webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
        view.addSubview(webView)

    }
    catch {
        // catch errors here
    }

}


text:
Q: Unable to parse out EDN in this server request I think I'm doing things right but I can't get my EDN out of the :body input stream. The Ring and Compojure handler is this:
dependencies:
 [ring.middleware.params :as params]
 [ring.middleware.edn :as edn]; https://github.com/tailrecursion/ring-edn

Handler:
(defroutes ajax-example
  (PUT "/ajax-example" r
       (println r)
       {:status 200
        :headers {"Content-Type" "application/edn"}
        :body "yo"}))

I wrap it like:
  (def ajax-wrapped
   (-> ajax-example
      edn/wrap-edn-params
      params/wrap-params))

The println'd response correctly reveals that it is EDN and the content length is correct based on the simple test map I send in, but the map itself is nowhere to be found, it is forever trapped in the input stream of the :body... how to get at it?
Here is the response println:
{:ssl-client-cert nil, :remote-addr 0:0:0:0:0:0:0:1, :params {}, :route-params {}, :headers {origin http://localhost:6542, host localhost:6542, user-agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36, content-type application/edn, cookie _ga=GA1.1.1354518981.1429622648;  content-length 20, referer http://localhost:6542/, connection keep-alive, accept /, accept-language en-US,en;q=0.8,sq;q=0.6, accept-encoding gzip, deflate, sdch, cache-control max-age=0}, :server-port 6542, :content-length 20, :form-params {}, :query-params {}, :content-type application/edn, :character-encoding nil, :uri /ajax-example, :server-name localhost, :query-string nil, :body #, :edn-params nil, :scheme :http, :request-method :put}
The :body is not pasting correctly above, it looks like this:
 [open corner bracket] HttpInput org.eclipse.jetty.server.HttpInput@5d969109 [end corner bracket]

The client-side code sent from the browser using cljs-ajax lib is:
(defn ajax-send
  []
  (let [push {:adder1 2 :add2 3}]
    (PUT "/ajax-example"
         {:format :edn
          :params push
          :handler ajax-result
          :error-handler error-handler})))

Here is the output of a test suggested by one of the answers:
hf.examples> ((-> ajax-example  params/wrap-params edn/wrap-edn-params) (-> (mock/request :put "/ajax-example")
                                                             (mock/content-type "application/edn")
                                                             (mock/body "{:hello \"there\"}")))
{:status 200,
 :headers {"Content-Type" "application/edn"},
 :body
 "{:remote-addr \"localhost\", :params {:hello \"there\"}, :route-params {}, :headers {\"content-length\" \"16\", \"content-type\" \"application/edn\", \"host\" \"localhost\"}, :server-port 80, :content-length 16, :form-params {}, :query-params {}, :content-type \"application/edn\", :uri \"/ajax-example\", :server-name \"localhost\", :query-string nil, :edn-params {:hello \"there\"}, :scheme :http, :request-method :put}"}
hf.examples>

I also tried this:
(defroutes ajax-example
  (PUT "/ajax-example" r
       {:status 200
        :headers {"Content-Type" "application/edn"}
        :body (pr-str (dissoc r :body))}))

Curl result independent of the front end:
curl -X PUT -H "Content-Type: application/edn" -d '{:name :barnabas}' http://localhost:6542/ajax-example
{:ssl-client-cert nil, :remote-addr "0:0:0:0:0:0:0:1", :params {}, :route-params {}, :headers {"host" "localhost:6542", "content-length" "17", "content-type" "application/edn", "user-agent" "curl/7.37.1", "accept" "*/*"}, :server-port 6542, :content-length 17, :content-type "application/edn", :character-encoding nil, :uri "/ajax-example", :server-name "localhost", :query-string nil, :edn-params nil, :scheme :http, :request-method

The content-length of 17 matches the number of characters in the map passed via Curl. But the edn-params is nil! Where is the content?

A: EDIT: As an answer to the updated question, the wrap-edn-params function consumes the body of the request by fully reading the :body InputStream. Compojure routes passes the request to each parameter handler until a non nil value is returned. In this case, whichever handler is passed to routes as the first handler will consume :body and there will be no :body value for the 2nd handler to consume, resulting in a nil body value read by wrap-edn-params.
The request that is being passed to the ring handler probably does not have its content-type set to edn. The wrap-edn-params function will only parse the edn if the request content-type is set to edn.
In addition the parsed edn parameters will only be placed in the :params and :edn-params keys of the request map by the wrap-edn-params function, and therefore :body should not be used to access the parsed edn.
(require '[ring.mock.request :as mock])
(require '[ring.middleware.edn :as edn])

((-> ajax-example  params/wrap-params edn/wrap-edn-params) (-> (mock/request :put "/ajax-example")
                                                             (mock/content-type "application/edn")
                                                             (mock/body "{:hello \"there\"}")))

{:remote-addr "localhost",
 :params {:hello "there"},
 :route-params {},
 :headers
 {"content-length" "16",
  "content-type" "application/edn",
  "host" "localhost"},
 :server-port 80,
 :content-length 16,
 :form-params {},
 :query-params {},
 :content-type "application/edn",
 :uri "/ajax-example",
 :server-name "localhost",
 :query-string nil,
 :body #<ByteArrayInputStream java.io.ByteArrayInputStream@171788d8>,
 :edn-params {:hello "there"},
 :scheme :http,
 :request-method :put}

A: I have fixed this but I do not know why the problem exists.  I had another independent route that also wrapped EDN middle ware. Here is the reproducible example:
(defroutes example-routes2
  (PUT "/test-edn" r
       (println r)
       {:status 200
        :headers {"Content-Type" "application/edn"}
        :body (pr-str (str "request is: " r))}))

(defroutes ajax-example
  (PUT "/ajax-example" r
       (println r)
       {:status 200
        :headers {"Content-Type" "application/edn"}
        :body (pr-str (str "request is: " r))}))

(def edn-routes
  (-> example-routes2
      edn/wrap-edn-params))

(def ajax-wrapped
  (-> ajax-example
      edn/wrap-edn-params))

;;combining all routes on this page into a single handler
(def example-routes (routes example-routes1  ajax-wrapped edn-routes))

Note that these two routes are essentially identical and are being wrapped identically. The one that fails to parse EDN into edn-params is the one listed second in the example-routes def!
curl -X PUT -H "Content-Type: application/edn" -d '{:name :barnabasss}' http://localhost:6542/test-edn
returns:
"request is: {:ssl-client-cert nil, :remote-addr \"0:0:0:0:0:0:0:1\", :params {}, :route-params {}, :headers {\"host\" \"localhost:6542\", \"content-length\" \"19\", \"content-type\" \"application/edn\", \"user-agent\" \"curl/7.37.1\", \"accept\" \"/\"}, :server-port 6542, :content-length 19, :content-type \"application/edn\", :character-encoding nil, :uri \"/test-edn\", :server-name \"localhost\", :query-string nil, :body #, :edn-params nil, :scheme :http, :request-method :put}"
curl -X PUT -H "Content-Type: application/edn" -d '{:name :barnabasss}' http://localhost:6542/ajax-example
returns:
"request is: {:ssl-client-cert nil, :remote-addr \"0:0:0:0:0:0:0:1\", :params {:name :barnabasss}, :route-params {}, :headers {\"host\" \"localhost:6542\", \"content-length\" \"19\", \"content-type\" \"application/edn\", \"user-agent\" \"curl/7.37.1\", \"accept\" \"/\"}, :server-port 6542, :content-length 19, :content-type \"application/edn\", :character-encoding nil, :uri \"/ajax-example\", :server-name \"localhost\", :query-string nil, :body #, :edn-params {:name :barnabasss}, :scheme :http, :request-method :put}"
Switching their order in the example-routes switches which one works. Can anyone explain?


text:
Q: How to get JavaScript to match a regex containing variables and spanning multiple lines? How to get JavaScript to match a regex containing variables and spanning multiple lines?
I am trying to extract string data from a body of text by matching patterns where I know the strings being searched for start and end with certain strings which I pass to the routine. The following line is the heart of the routine:
var aHits = strIn.match(new RegExp(preStr + "(.+?)" + postStr, ignoreCase + "g"));
// ignoreCase equals "i" or "", preStr is leading string, postStr is trailing

This works well until the would-be match contains a line break. Then strIn.match() fails.
I've tried using "(.+?)", "([\\\s\\\S])" and "((.|\\\n|\\\r)+?)" and several other grouping strategies.
I've seen some literal regexes that end with "s" for doing something like this. Can the variables be added to a literal regex? Which pattern is the best, or at least works? Or is it the match method itself that refuses to process a string with newlines? I can't seem to find that stated anywhere.
The newline is contained in the (.+?) portion of the matched string, but would it matter anyway?

A: You were almost there...the dot metacharacter doesn't match newlines, but you were on the right track with [\\\s\\\S]...you just escaped one too many times.  Try this:
var aHits = strIn.match(
    new RegExp(preStr + "([\\s\\S]+?)" + postStr, ignoreCase + "g"));


text:
Q: How do I know if my WP Theme is using infamous TimThumb? Is there a way to know if my current WordPress theme is using the infamous TimThumb plugin?

A: One option is to install a security plugin. Most scan for Tim Thumb throughout your whole file structure, including themes (and will also search for many other types of vulnerabilities if you've been hacked, as your "hacked" tag indicates).
You can also search for files named "timthumb" in your theme directory, or search for the phrase "timthumb" in all files on your site. It helps if you have a local copy and a good editor that will search through files.


text:
Q: Rounding down is not working as expected in Android I am using following code to round down the decimal number
private float roundOffTwoDigits(float number) {
    DecimalFormat toTheFormat = new DecimalFormat("0.0");
    toTheFormat.setRoundingMode(RoundingMode.DOWN);
    number = Float.valueOf(toTheFormat.format(number));
    return number;
}

Now there are the output I am getting
Input Output
2.2   >  2.2
2.21  >   2.2
2.28   >   2.2
2.4    >   2.4
2.6    >   2.5(Why 2.5 it should be 2.6)
2.8     >  2.7(Why 2.7 it should be 2.8)
So even number after decimal place and if it is more than 5 it is decreasing the value which should not happen.
Somebody marked my quesion duplicate with this question here Is floating point math broken?, I am not sure why ?
That question is not at all related to java and android and not having answers and discussion I was expecting.

A: The method has rounded correctly. 2.6 cannot be represented exactly as a float. When you write float a = 2.6F;, a is really
2.599999904632568359375

To do this correctly you should dispense with float completely, and do it using BigDecimal and its String constructor.

A: It sounds like you want to add a Math.floor(). This will make your code always round to the highest value.

A: You can use a workaround, since Paul explained perfectly all the motivations, you cann add a control:
private float roundOffTwoDigits(float number) {
    DecimalFormat toTheFormat = new DecimalFormat("0.0");
    toTheFormat.setRoundingMode(RoundingMode.DOWN);
    float roundedNumber = Float.valueOf(toTheFormat.format(number));
    //add a control to check if the code was wrongly rounded
    if((number - roundedNumber) >= 0,1){
        roundedNumber += 0,1
    }
    return roundedNumber;
}

in this way if the number was rounded to much you will have the correct result.
I know, it's only a workaround but it should work
EDIT i wrote with one more decimal, fixed


text:
Q: Jupiter Notebook not showing titles or axis labels in marplotlib I'm running the following code in the latest version of Jupiter notebook.
x = list(np.linspace(25,55,6))
y = np.random.randint(10000,50000,6)

plt.xlabel = "some random ages"
plt.ylabel = 'some random salaries'
plt.title = 'whatever'

plt.plot(x,y)

plt.show()

However the output does not have any labels or title. I know this question has been asked before but the solution that worked there, of putting everything in the same cell, is not working with me. I am running this in the same cell. Another suggestion from that question, of putting put.show() last, is also not working.


text:
Q: Recursively find all coin combinations that produces a specified amount My apologies in advance. I'm aware that this question has been asked before with answers that have not produced the results I want/need. I am making an attempt to write a function that does the following in Python3:
I need a recursive function that returns all the number of ways (coin combinations) that produce a specified amount. This function can only contain two arguments, amount and coins. I've had a difficult time wrapping my mind around recursion, so explanations would also be greatly appreciated. Thanks.
Here's what I currently have:
COINS = dict(
    USA=[100, 50, 25, 10, 5, 1],
    AUSTRALIA=[200, 100, 50, 20, 10, 5],
    UK=[500, 200, 100, 50, 20, 10, 5, 2, 1]
)

def change(amount, coins):
    """
    >>> change(100, COINS['USA'])
    293
    """
    if amount < 0:
        return 0
    elif amount == 0:
        return 1
    else:
        biggestcoin, *rest = coins[0], coins[1:]
        return change(amount-biggestcoin, coins) + change(amount, rest)

A: biggestcoin, *rest = coins[0], coins[1:]

You want rest here, logically, not *rest, because you have two items on each side. Using *rest here creates an additional layer of list wrapping, which then results in the exception you're presumably seeing.
Once you fix that: think about what happens if you cannot make the desired amount with 1 of each coin. The change(amount, rest) recursive call will eventually occur with amount being greater than zero, and rest being empty. You need to handle that case as well.

A: The idea behind recursion is simple:

Try and reduce the size of the problem, one little step at a time.

If you can do that, you're nearly done! Start with the big problem and just keep reducing the size, little by little, until you end up with a very small problem. You can solve that however you like.

How does this apply to the change making problem? Well, if you're asked to make n, you can reduce the size of the problem a little bit by using just one coin. And if you keep going, eventually you will get to a sufficiently-small problem to solve!


text:
Q: C++ old struct operator overloading syntax changed? I am building my old CPP codes from 20+ years ago, but g++ gives build error.  Can someone explains me what has changed?  Thanks.  (It was fine in turbo C)
error:
t_overload.cpp:8:40: error: no matching constructor for initialization of 'Point'
    Point operator+(Point& v) { return Point(x+v.x, y+v.y); }
                                       ^~~~~~~~~~~~~~~~~~~

cpp file:
#include <stdio.h>

struct Point {
    int x, y;
//    Point(Point& v) {set(v.x, v.y);}     // build okay without this line; error if uncomment
    Point(int a, int b) {set(a,b);}
    void set(int a, int b) {x=a, y=b;}
    Point operator+(Point& v) { return Point(x+v.x, y+v.y); }
};

int main() {
    Point a(1,2);
    Point b(a);

    Point c = a + b;
    printf("%d %d\n", c.x, c.y);
}

A: Point(Point& v)

Copy constructors should take constant parameters, this should be:
Point(const Point& v)

But given what that copy constructor does, it's completely unnecessary. You can get rid of it, completely.
Point operator+(Point& v)

Similarly, the parameter to the overload should be constant:
Point operator+(const Point& v)

See "What are the basic rules and idioms for operator overloading?"
Both of these issues, together with rather nuanced and delicate rules of overloading and how temporaries bind to function parameters, were resulting in your compilation errors.


text:
Q: Using analytics in Angular app only on a specific route using Firebase I have an Angular website which I would like to use Google Analytics with to track the page views. Im using Firebase through @angular/fire to host my website. Therefore, I added the @angular/fire library by ng add @angular/fire and enabled the services I needed, plus analytics.
Now according to the docs I can see how one can inject AngularFireAnalytics in their component to log page views:
import { AngularFireAnalytics } from '@angular/fire/compat/analytics';

constructor(analytics: AngularFireAnalytics) {
  analytics.logEvent('custom_event', { ... });
}

But Im not able to find a way to only enable the whole analytics only on a specific route, and no where else in the website.
I want to set up different paths for the same LandingPageComponent, so that I can visualize the page views from different advertisement funnels. In general I do not want any means of analytics on any other part of the website except for the page view events related to these URLs that end up in the same component after all.

A: I managed to solve my question by defining a custom event and adding a condition to check for the specific route that I wanted in the component by injecting Location service from Angular:
import {Component, OnInit} from '@angular/core';
import {Location} from "@angular/common";
import {AngularFireAnalytics} from "@angular/fire/compat/analytics";

@Component({
  selector: 'app-xxx',
  templateUrl: './xxx.component.html',
  styleUrls: ['./xxx.component.scss'],
})
export class XxxComponent implements OnInit {

   constructor(readonly location: Location,
               readonly analytics: AngularFireAnalytics) { }

   ngOnInit(): void {
      if (this.location.path() === '/myPath') {
         this.analytics.logEvent('custom_event', { ... });
      }
   }

}

According to what I read, it is not possible to disable the default analytics data collection and instead to just send your custom event. Therefore, you either have to have default data collection enabled and send your custom event, or completely turn analytics off. Although, you can turn on and off the analytics from the component, which I'm not sure if its a good practice.
Please let me know if there is an alternative and better solution.


text:
Q: how to retrieve all the styles of a node in tiny mce? I want to retrieve the styles of a node inside the tiny mce instance. With getStyle, I can get only the styles, that I will provide as an argument. But, I don't know which styles will be applied to the node by user. I mean user can apply NUMBER of styles such as font, font color, borders. I simply need to get the whole string inside the style attribute of the node. I tried with the getOuterHTML, but it stripes out the styles.
Thanks in advance.

A: You can get what you want easily using jQuery:
$(tinyMCE.activeEditor.getBody().firstChild).attr('style');


text:
Q: Remove default language in Magento I am in the following bind:
A client wanted 3 languages - English, Russian and Latvian. Naturally, I created 3 store views and changed the language for each. Once I had translated everything via the inline-translate tool, and the client added the products with descriptions in all of the languages,the client had a change of heart, and now wants English to be removed.
Now this is a problem, since it is the default Store view, and can;t be deleted as such. i have thought of just changing the titles and locales of the languages, but that would still leave the product descriptions wrong.
Is there a way to do this, either via DB, or some other way?
TL; DR: How to remove the default store view in Magento?

A: Try to change "Default Storeview" for your default "Store". Go to "System/Manage Stores", choose your store and change "Default storeview" to Russian or Latvian. Then you could be able to delete English storeview.


text:
Q: Changing type of ActiveRecord Class in Rails with Single Table Inheritance I have two types of classes:
BaseUser < ActiveRecord::Base

and
User < BaseUser

which acts_as_authentic using Authlogic's authentication system. This inheritance is implemented using Single Table Inheritance
If a new user registers, I register him as a User. However, if I already have a BaseUser with the same email, I'd like to change that BaseUser to a User in the database without simply copying all the data over to the User from the BaseUser and creating a new User (i.e. with a new id). Is this possible? Thanks.

A: Steve's answer works but since the instance is of class BaseUser when save is called, validations and callbacks defined in User will not run. You'll probably want to convert the instance using the becomes method:
user = BaseUser.where(email: "user@example.com").first_or_initialize
user = user.becomes(User) # convert to instance from BaseUser to User
user.type = "User"
user.save!

A: Based on the other answers, I expected this to work in Rails 4.1:
  def update
    @company = Company.find(params[:id])
    # This separate step is required to change Single Table Inheritance types
    new_type = params[:company][:type]
    if new_type != @company.type && Company::COMPANY_TYPES.include?(new_type)
      @company.becomes!(new_type.constantize)
      @company.type = new_type
      @company.save!
    end

    @company.update(company_params)
    respond_with(@company)
  end

It did not, as the type change would not persist. Instead, I went with this less elegant approach, which works correctly:
  def update
    @company = Company.find(params[:id])
    # This separate step is required to change Single Table Inheritance types
    new_type = params[:company][:type]
    if new_type != @company.type && Company::COMPANY_TYPES.include?(new_type)
      @company.update_column :type, new_type
    end

    @company.update(company_params)
    respond_with(@company)
  end

And here are the controller tests I used to confirm the solution:
  describe 'Single Table Inheritance (STI)' do

    class String
      def articleize
        %w(a e i o u).include?(self[0].to_s.downcase) ? "an #{self}" : "a #{self}"
      end
    end

    Company::COMPANY_TYPES.each do |sti_type|
      it "a newly assigned Company of type #{sti_type} " \
        "should be #{sti_type.articleize}" do
        post :create, { company: attributes_for(:company, type: sti_type) },
             valid_session
        expect(assigns(:company)).to be_a(sti_type.constantize)
      end
    end

    Company::COMPANY_TYPES.each_index do |i|
      sti_type, next_sti_type = Company::COMPANY_TYPES[i - 1],
                                Company::COMPANY_TYPES[i]
      it "#{sti_type.articleize} changed to type #{next_sti_type} " \
        "should be #{next_sti_type.articleize}" do
        company = Company.create! attributes_for(:company, type: sti_type)
        put :update, { id: company.to_param, company: { type: next_sti_type } },
            valid_session
        reloaded_company = Company.find(company.to_param)
        expect(reloaded_company).to be_a(next_sti_type.constantize)
      end
    end
  end

A: You can just set the type field to 'User' and save the record. The in-memory object will still show as a BaseUser but the next time you reload the in-memory object will be a User
>> b=BaseUser.new
>> b.class # = BaseUser

# Set the Type. In-Memory object is still a BaseUser
>> b.type='User'
>> b.class # = BaseUser
>> b.save

# Retrieve the records through both models (Each has the same class)

>> User.find(1).class # = User
>> BaseUser.find(1).class # User


text:
Q: How to show that $\limsup_{n\to \infty}\frac{a_n}{n}\leq \limsup_{n\to\infty}(a_{n}-a_{n-1})$ for any sequence $(a_n)$?
Let $(a_n)$ be a sequence of real numbers. Prove that
  $$\limsup_{n\to \infty}\frac{a_n}{n}\leq \limsup_{n\to\infty}\,
 (a_{n}-a_{n-1}).
$$

If the sequence $(a_n)$ converges, then this is immediate: both sides are $0$. If it is not convergent, how should I approach this problem?

A: First suppose $\limsup\limits_{n\rightarrow\infty} (a_n - a_{n-1}) < \infty$ (otherwise the statement is certainly true), and say it is equal to $M$. Then, intuitively speaking, as we look further along the sequence, each successive term is at most approximately $M$ more than the previous one. Looking further and further along, the worst case scenario is that approximately $M$ is continued to be added to each term. As more terms are added, any aberrant earlier behaviour will be nullified by the increasing $n$ in the denominator, which will make the inequality true.
Let's prove it. First, fix $\varepsilon > 0$. It is my aim to prove that,
$$\limsup_{n\rightarrow \infty} \frac{a_n}{n} \le M + \varepsilon.$$
By the definition of $M$, it follows that we may find some $N \in \mathbb{N}$ such that,
$$n \ge N \implies a_{n+1} \le a_n + M + \varepsilon.$$
It therefore follows by induction that,
\begin{align*}
& a_{N+k} \le a_N + k(M + \varepsilon) \\
\implies& \frac{a_{N+k}}{N+k} \le \frac{a_N}{N + k} + \frac{k}{N + k}(M + \varepsilon).
\end{align*}
Take the limit superior of both sides, as $k \rightarrow \infty$. The left side will simplify to $\limsup\limits_{n\rightarrow\infty} \frac{a_n}{n}$, as we are considering a tail of the full sequence. The right side is convergent as $k \rightarrow \infty$, and converges to $M + \varepsilon$. Thus,
$$\limsup_{n\rightarrow\infty} \frac{a_n}{n} \le M + \varepsilon,$$
as required.

A: Thanks to Theo's answer and Steven's comment, I have a slightly different interpretation of the proof. Let $b_1=a_1$ and $b_n=a_n-a_{n-1}$ for $n>1$. Then it suffices to prove that
$$
\limsup_{n\to\infty}\frac{1}{n}\sum_{k=1}^nb_k\leq \limsup_{n\to\infty}b_n=:M<\infty
$$
Given $\epsilon>0$, there exists $N>0$ such that for all $n\geq N$,
$$
b_n< M+\epsilon
$$
and thus for all $n\geq N$,
$$
\frac1n\sum_{k=1}^n b_k\leq\frac{1}{n}(b_1+\cdots+b_N)+\frac1n\big[M(n-N)+\epsilon(n-N)\big]
$$
It follows that
$$
\limsup_{n\to\infty}\frac1n\sum_{k=1}^n b_k\leq M+\epsilon.
$$
Since $\epsilon$ is arbitrary, we are done.


text:
Q: C++ Template class definition and declaration seperation c++.why can't you separate the definition of your templates class from their declaration and put them inside a .cpp file? is there a workaround to allow the separation.
And could anybody give my a source where I could also get more information with examples.
Thanks


text:
Q: How can I reproduce this magnification effect for my own screen shots? Does anyone know how to make the great-looking magnifying glass, shown in Apple's image, shown below? I really like the shadow! I'd love to know what software Apple uses for this.

A: In Preview you can now add shadowed magnification. I think this was new in El Capitain. But it is not the same shadow. My guess is that effect is produced in Quartz Composer (if they want to "eat their own dog food").
See interface:


text:
Q: Testing dropdown list using WatiN I am using WatiN to test a website and automate a process.  I can successfully open the website, however an issue arises when I am trying to select an option from a select list:
<select id="form:Dropdown" name="form:Dropdown" size="1" title="Select Option"> <option value="0">Select Code</option>
    <option value="234890/NA/1">23FA4890</option>
    <option value="237014/NA/1">23FA7014</option>
</select>

Code:
            Settings.AttachToBrowserTimeOut = 240;
            Settings.WaitUntilExistsTimeOut = 240;
            Settings.WaitForCompleteTimeOut = 240;

            browser = new IE();
            browser.GoTo(url);
            browser.WaitForComplete();
            //Thread.Sleep(10000);
            browser.SelectList(Find.ById("form:Dropdown")).WaitUntilExists(); //ERROR OCCURS HERE
            SelectList dList = browser.SelectList(Find.ById("form:Dropdown"));
            dList.Select("23FA4890");

This looks like it should work, but I keep getting an error "Timeout while waiting 240 seconds for element to show up."

A: I don't believe you need to call WaitUntilExists since WaitForComplete is already going to block until the page is fully loaded.  I know this doesn't answer your question completely, but I wanted to show you an example of some code that I've been using in production for over a year that has never been a problem.
Note, I'm grabbing a frame from within an iframe and selecting the value of "ID" from the drop down list:
Regex regex = new Regex(@"^.*\/globalframeset\.esp.*$");
using (var browser = IE.AttachTo<IE>(Find.ByUrl(regex), 12))
{
    if (browser != null)
    {
        browser.AutoClose = false;

        var iFrame = browser.Frame(Find.ById("GlobalWrapper"));

        if (iFrame != null)
        {
            var frame = iFrame.Frame(Find.ByName("frGlobalNav"));

            if (frame != null)
            {
                frame.TextField(Find.ByName("findtext")).Value = person.MedicalRecordNumber;

                // This code is setting the DDL called "filtertype" to a value of "ID"
                frame.SelectList(Find.ByName("filtertype")).SelectByValue("ID");

                Regex buttonRegex = new Regex(@"^.*\/go_text\.gif.*$");
                frame.Image(Find.BySrc(buttonRegex)).ClickNoWait();
            }
        }

        browser.BringToFront();
    }
}


text:
Q: Let $H\leq G$ where $H$ is max simple. Prove either $G$ is simple or there exists a minimal normal subgroup $N$ of $G$ such that $G/N$ is simple. Question: Let $G$ be a finite group and $H$ a maximal, simple subgroup of $G$.  Prove that either $G$ is simple or there exists a minimal normal subgroup $N$ of $G$ such that $G/N$ is simple.
Thoughts: If $H=G$ or if $H$ is trivial, then $G$ must be simple.   Otherwise, assume that there is a subgroup $N$ of $G$ such that $H\subset N\subseteq G$.  I know that any group that isn't simple can always be split up between a normal subgroup and its corresponding quotient group, but the "maximal" and "minimal" stuff here is throwing me off.
Any help is greatly appreciated!  Thank you!

A: If $H$ is normal, take $N=H$. Otherwise choose any minimal normal subgroup $N$. Then $N\cap H=1$ since $H$ is simple and $G=NH$ since $H$ is maximal. Now $G/N\cong H/H\cap N\cong H$ is simple.


text:
Q: Does the iPhone multi-task while sending email? When I send a message and the progress bar is still "moving", can I simply move along and send another message?
And even before that is completed, if I move along and send another message can I be guaranteed that all messages will be sent?

A: Yes you can. You can even close the Messaging app.

A: Apple's own applications have the capability to do "real" background processing and multitasking. User created applications have "some" capability (and limited time) to perform "certain" background processing and multitasking.
With that said, most apps that need to finish a task, can do so because Apple has provided a way to do such things.


text:
Q: [Vue warn]: Invalid prop: custom validator check failed for prop "time" I have a countdown timer, and is working well, but, in console i have this error: [Vue warn]: Invalid prop: custom validator check failed for prop "time". and i think is someting about datetime output, if i put :time="new Date('03/09/2021 00:00:00').getTime()" the error will be removed and this im trying to achive, but if i do like this: :time="new Date(dataInscrieri.data_inscrieri).getTime()" from mysql datetime the error is present. Some help? Many thanks!
Code:
 <countdown :time="new Date(dataInscrieri.data_inscrieri).getTime() - new Date().getTime()">

            <template slot-scope="props">

                {{ props.days }}
                Zile

                {{ props.hours }}
                Ore

                {{ props.minutes }}
                Minute

                {{ props.seconds }}
                Secunde

            </template>
          </countdown>

export default {
  data () {
    return {
      dataInscrieri: []
    }
  },
  components: {
    'countdown': VueCountdown,
    StatisticsCardLine
  },
  created () {
    //  Data inscrieri eveniment
    this.$http.get('/api/users/data-inscrieri/event')
      .then((response) => { this.dataInscrieri = response.data.results })
      .catch((error)   => { console.log(error) })
  }
}

dataInscrieri.data_inscrieri output from db is:
2020-11-02T22:00:00.000Z

A: Make sure dataInscrieri.data_inscrieri is valid time and I see in VueCountdown  prop -> :time is Number type, when you send other than a number, Vue throws Invalid Prop type type warning.
I think, you can use method to covert the time to number. This will help you to add check before sending time to Countdown component.
<countdown :time="getTime(dataInscrieri.data_inscrieri)">....
...

methods: {
   getTime(date) {
     const datetime = new Date(date)
     return datetime !== 'Invalid Date' ? datetime.getTime() - new Date().getTime() : null
   }
}

A: replace your getTime() function to this:
<countdown :time="getTime(dataInscrieri.data_inscrieri)">....
...


text:
Q: Apache+Nginx+Varnish+APC or ...? I have read some articles about it, but i still dont get some things.

*

*Isnt Varnish and Nginx basically the same thing? I know varnish is not a web server but Nginx in this case is not used as one neither, they both act as a reverse caching proxy.

*Will APC even work in this configuration?
What do you recommend to speed up a Wordpress blog?

A: *

*Varnish is designed from ground-up to be a very fast and scalable web cache solution. Nginx is designed from the ground up to be a very fast, modular and small web server for static content.

*APC is a PHP caching mechanism, you don't run it on nginx, varnish or any other cache/front-end server, you run it on the application server (mod_php, php-fpm etc).
I've not encountered anyone who deploy Varnish and APC at the same time, as it doesnt really help you. Varnish caches the dynamic pages (for example PHP) until you tell it not to.
The trend these days are to design high-performance websites like this:
Load balancers -> Frontends -> Backends (Application servers) -> Databaseservers
                            \- File servers

A: Start off with PHP-APC.  That's a good start for any site.  Override the cache size, and give it like 128M to play with.
Install Memcached, and use that for caching query results.
Install Wordpress's W3 Total Cache plugin, and turn everything on.
Get an Amazon S3 instance with Cloudfront, and configure it as the CDN for your wordpress site.
Configure Varnish as a reverse proxy for your Apache, but remember you'll have to pass any requests containing a wordpress login cookie, or you'll end up with an Identity Crisis, where everyone is served logged-in user content.
That's it.  That's all there really is to it.  It's actually deceptively complicated, but those are the basic main steps.

A: I personally use Internet -> nginx -> Varnish -> Apache simply because I don't want to store images directly in Varnish cache.
I have a couple of blog posts with sample configuration available at - http://syslog.tv if you're interested.

A: Varnish; Apache -or- Nginx; APC/Memcached -or- APC/PHP-FPM.

*

*Varnish caches/serves static content

*Apache/Nginx handles HTTP requests for non-static content

*APC/Memcached / APC/PHP-FPM caches pre-compiled PHP objects

Loadbalancing can be handled at various points

A:
What do you recommend to speed up a Wordpress blog?

I'm not that familiar with WP but don't most people start with WP Super Cache?

A: I run multiple blogs and was having performance issues on EC2 servers so I did the following:
Ubuntu 11.04 -> Varnish -> Apache 2 -> Wordpress Multisite + Domain Mapping Plugin
I run multiple blogs on an EC2 Micro instance.  I tested it with loadimpact.com and it will easily serve 50 concurrent users with multiple requests and no CPU steal problems.
Under this load the CPU is sitting at 0.02% load and the disks are doing nothing.
All you need is Varnish at the front with a good wordpress vcl, it is amazing.


text:
Q: Is there a way to get rid of the (by dot42) using community licence? I have started using the community licence of dot42 to make a small free app for android. I see the string "by dot42" in the app name, is this by design and will remain forever? or is it waiting for me to make modify some setting to remove it?

A: Looking at the changelog of dot42 I read the following:

Apps created with community license always get a "(by dot42.com)"
  postfix in their application name.

Source: https://www.dot42.com/changelog.aspx @ Version 1.0.0.47, released January 15, 2013
So to answer your question, yes with the community edition, it stays because it is by design.

A: As SynerCoder says, this is a restriction of the community licenses. But this will change.
In the week of 5-9 January 2015, we will release the dot42 compiler tools under the GPLv2 license. Note that GPL does not propagate to the output of GPL software. You will be able to build closed source Android applications with dot42 (including commercial). The run-time code is already licensed under Apache License 2.0: https://github.com/dot42/api. As of then, you will no longer need a Professional license to develop commercial applications with dot42. The next update of dot42 will not require activation. Also, the mentioned postfix will no longer be added.

UPDATE: sources are now on https://github.com/dot42


text:
Q: In Editor, splitting really long strings across two or more lines? I am trying to make my script a bit neater, but I have loads of print "str" statements that are really long.
So I might have:
print("Hello, welcome to blah blah blah blah blah blah blah blah blah blah")

However, ideally I'd like this to continue onto a new line, rather than have it trail across the length of the Editor.
It's not hugely important I don't think, but is it possible?

A: In Python, there are numerous possibilities to do this, one is to use """ or alternatively ''' like this:
very_long_string="""Hello,
welcome to
blah blah blah blah
blah blah blah blah
blah blah"""

You can read more on multi-line strings here.

A: You can do that using the triple quotes. Triple quotes in python preserve the formatting of the text that has to be printed. So you can put the string to be printed in like this (if you want it to be like this):
print '''Hello, welcome to
Hello, welcome to blah blah blah
blah blah blah blah blah'''


text:
Q: RedisCacheManager Not Updating keyspace_misses I'm using the spring-boot spring-data-redis 1.8.9.RELEASE RedisCacheManager implementation of CacheManager for caching. One metric that I want visibility into is the cache hit/miss ratio. To get that, I'm extracting the keyspace_hits and keyspace_misses exposed via the redis server which can also be viewed via the redis_cli with INFO STATS. The problem is that RedisCacheManager never registers cache misses, i.e. keyspace_misses never increments even if there is a cache "miss".
Debugging the code, I see that spring-data-redis actually checks to see if the key EXISTS in redis before retrieving it. I see the sense with this approach however when EXISTS is executed against the redis server, it does not register a cache miss.
Is there any way to use RedisCacheManager and register cache misses? I know I can use other redis objects to accomplish this but I was wondering if it could be done with the standard CacheManager implementation?
Edit
The ideal solution won't add a great deal of overhead and I am unable to edit the configuration of the redis server.
Code that RedisCacheManager uses when retrieving an element from cache. Notice Boolean exists:
public RedisCacheElement get(final RedisCacheKey cacheKey) {
    Assert.notNull(cacheKey, "CacheKey must not be null!");
    Boolean exists = (Boolean)this.redisOperations.execute(new RedisCallback<Boolean>() {
        public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            return connection.exists(cacheKey.getKeyBytes());
        }
    });
    return !exists ? null : new RedisCacheElement(cacheKey, this.fromStoreValue(this.lookup(cacheKey)));
}

The above code will execute these commands on redis viewable via MONITOR on a cache miss. Notice again that EXISTS is executed as per the code:

After the above commands are executed, keyspace_misses is not incremented even though there was a cache miss:

A: The code mentioned in the question is part of RedisCache provided by Spring.

*

*Extend and Create a custom implementation of RedisCache class to override the behavior of "get" method to suit your need.

*Extend RedisCacheManager to override the method "createRedisCache" to use your custom RedisCache that you created in first step instead of default cache.


text:
Q: jenkins and artifactory certificates I need to run Jenkins over HTTPS.
I created the certificate and put it into the keystore. Then I launched Jenkins with the following options:
--httpsPort=8443 --httpsKeyStore=/etc/pki/java/cacerts --httpsKeyStorePassword=changeit

So far so good. But I had "peer not authenticated" error when deploying a file in the Artifactory.
According to a solution here I added my artifactory certificate to the keystore.
Now I can deploy files on Artifactory but Jenkins picked up the wrong entry from the keystore (the one of Artifactory). And I have a wrong certificate associated with Jenkins.
I was not able to specify the alias which should be used by Jenkins.
According to Jenkins docs it's possible to run Jenkins with the following options:
--httpsPort=443 --httpsCertificate=path/to/cert --httpsPrivateKey=path/to/privatekey

But in this case I'm not able to use my Artifactory certificate.
How can I run Jenkins with both Jenkins and Artifactory certificates ?

A: Trying different things I came to an idea to rename the alias of jenkins certificate.
The new alias is jenkins.
Strangely enough it solved my problem. For me it looks more like a hack than a solution. Put your real solution here and I'll accept it.


text:
Q: Autocomplete Ajax asp.net MVC, Display text I am using Jquery with Ajax AutoComplete to return some data, but I'm kind of stuck with the display text.
This is what I have:
<script type="text/javascript">
$(document).ready(function () {
    $("#locais").autocomplete({
    source: function (request, response) {
            $.ajax({
                url: '@Url.Action("CreateF")',
                datatype: "json",
                data: {

                    s_localidade: request.term
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.remetente,
                            value: item.ID,
                        }
                    }))
                }
            })
        },
    });
});

And on controller:
   public JsonResult CreateF(string s_localidade)
    {
        var tblOficiosExpedidos = db.tblOficiosExpedidos.Include(t => t.tblLocalidades);
        var local = (from r in db.tblLocalidades
                     where r.Remetente.Contains(s_localidade.ToUpper())
                     select new { remetente = r.Remetente + " - " + r.Cidade, ID = r.LocalidadeID }).ToList();
         return Json(local, JsonRequestBehavior.AllowGet);

    }

On View:
@Html.TextBox("LocalidadeID","", htmlAttributes: new { @class = "form-control", @id="locais"})

It does work, but when i select an item, the text of the text box becomes the key number from my table. Is there a way to when i select something, the text keep as item.remetente but saves the number of item.ID into table?

A: You can do with the help of 'select'
try below approach
Your view
@Html.TextBox("LocalidadeID","", htmlAttributes: new { @class = "form-control", @id="locais"})
@Html.Hidden("hiddenlocais")

In your jquery define  common function that takes both hidden and text box id as parameters
JQuery:
function WireUpAutoComplete(displayControlId, valueControlId)
 {
  $(displayControlId).autocomplete({
    source: function (request, response) {
            $.ajax({
                url: '@Url.Action("CreateF")',
                datatype: "json",
                data: {
                    s_localidade: request.term
                },
                 select: function (event, ui) {
                      $(displayControlId).val(ui.item.Remetente);
                      $(valueControlId).val(ui.item.ID);
                    return false;
               },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.remetente,
                            value: item.ID,
                        }
                    }))
                }
            })
        },
    });

  }

In document ready call above  function
<script type="text/javascript">
$(document).ready(function () {
  WireUpAutoComplete("#locais", "#hiddenlocais");
});

</script>

hope this solve your problem. i haven't tested. let me know if you face any problems


text:
Q: How to know when a menu item has been clicked? I'm using the winsafe crate and want to know when a menu item's been clicked in a window.
flags & MF_MOUSESELECT as u16 should be 1 if so and 0 if not, but it's always 32768 everytime the event is fired, even if it's just from the user hovering a menu item, or even clicking away to make it close.
Why?
self.wnd.on().wm(winsafe::co::WM::MENUSELECT, {
  move |params| {
    let wparam = params.wparam;
    let lparam = params.lparam;
    let flags = (wparam >> 16 & 0xffff) as u16;
    let MF_MOUSESELECT = 0x00008000 as u32;

    println!("{}", flags & MF_MOUSESELECT as u16);
    // always 32768

    0
  }
});

The menu is generated by a resource script which is compiled and embedded in the program:
1 MENU
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
{
  POPUP "&File"
  {
    MENUITEM "&Open",  1
    MENUITEM "&Save",  2
  }
  POPUP "&Help"
  {
    MENUITEM "&About",  3
  }
}

A: You should handle WM_COMMAND. There is actually built in functionality for menus. Simply provide the id you specified in your resource file to check when the correponding menu item is clicked.
Replace your event listener with these:
self.wnd.on().wm_command(co::CMD::Menu, 1, {
  move || {
    println!("Open clicked.")
  }
});

self.wnd.on().wm_command(co::CMD::Menu, 2, {
  move || {
    println!("Save clicked.")
  }
});

self.wnd.on().wm_command(co::CMD::Menu, 3, {
  move || {
    println!("About clicked.")
  }
});


text:
Q: How to compare the rows of two tables and delete only if no matching row I want to be able to delete a row in gridview1 if there are no rows in gridview2 which has exactly the same values as gridview1
What should I put in onRowDeleting?
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    string strConnString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    DataTable dt = new DataTable();

    using (SqlConnection conn = new SqlConnection(strConnString))
    {

      int selectedRow = e.RowIndex;

      GridViewRow theRow = GridView1.Rows[selectedRow];
      string str = ("Delete TDLoanRate where Id=@id");
      SqlCommand insert = new SqlCommand(str, con);

      insert.Parameters.AddWithValue("@id", Convert.ToInt32(theRow.Cells[0].Text));

      using (SqlDataAdapter sda = new SqlDataAdapter())
      {
           insert.Connection = con;
           con.Open();
           sda.SelectCommand = insert;
           sda.Fill(dt);
           GridView1.DataSource = dt;
           GridView1.DataBind();
      }

A: Just compare rows? Normally I would ask things like what have you tried? but its monday, bad enough.
Check this out:
DataGridView dgv = new DataGridView();
DataGridView dgv2 = new DataGridView();

// Iterate on the rowcount
for (int i = 0; i < dgv.RowCount; i++)
{
    // Compare each row and count occurences.
    int occurs = dgv2.Rows.Cast<DataGridViewRow>().Where(row => row == dgv.Rows[i]).Count();
    // If no row is equal
    if (occurs <= 0)
        // Delete it.
        dgv.Rows.RemoveAt(i);
}


text:
Q: Передача переменой из почты Доброго дня! У меня проблема с конструкцией в теле e-mail письма вида:
<img src="site.ru / send_done.php?sended='. $row['id'].'">

Здесь я передаю некое значение id данного адреса своему скрипту, благодаря чему могу отметить факт открытия письма получателем.
Это работает с почтой мэйл.ру и гмэйл точно!
Но яндекс почта почему то на отрез не хочет пересылать так переменную скрипту.
Есть ли какие соображения по этому поводу ?
Может, что-то не так с синтаксисом ?
Спасибо заранее.

A: Cвязался с техподдержкой Яндекс - они извинились даже )) Причем, примерно в это же время переменная начала работать - я ничего не трогал двое суток ... Мистика