text:
Q: .redirect() from mounted middleware with relative destination fails I want to restrict a certain subtree only to authenticated users. The basic setup is as follows (fat removed):
app.use(express.bodyParser())
 .use(express.cookieParser('MY SECRET'))
 .use(express.cookieSession())
 .use('/admin', isAuthenticatedHandler)
 .use('/admin', adminPanelHandler);

Where the handler functions is:
isAuthenticatedHandler = function(req, res, next) {
   if (!req.session.username) {
     res.redirect('login');
   } else {
     next();
   }
};

The problem is that even though I provide the redirect destination as a relative path 'login', it doesn't lead to <mount_point>/login i.e. /admin/login but to /login which of course throws a 404.
From the expressjs API reference:
 This next redirect is relative to the mount point of the application.
 For example if you have a blog application mounted at /blog, ideally
 it has no knowledge of where it was mounted, so where a redirect of
 /admin/post/new would simply give you `http://example.com/admin/post/new`,
 the following mount-relative redirect would give you
 `http://example.com/blog/admin/post/new`:

      res.redirect('admin/post/new');

Am I misreading this?

A: What are you trying to achieve? Why not just redirect to '/admin/login' ?  And the mount point they are talking about is the place where your Express app is located, not necessarily the current URL. So /blog might be setup on your server to be the root of your app while / might be a totally different app. At least that's the way I read this.

A: The issue here is that while you are using your middleware off of /admin, your app itself is not mounted at /admin.  Your app is still off of the root, and your configuration simply says to only use your isAuthenticatedHandler middleware if the request comes in off the /admin path.
I whipped together this gist.  Notice how it uses 2 Express applications, one mounted inside the other (line 23 pulls this off).  That is an example of mounting the application at a different point rather than just putting a given middleware at a given point.  As presently written, that example will give you an endless redirect, since the isAuthenticatedHandler fires for everything off of / in the child application, which equates to /admin overall.  Using 2 separate applications might introduce other issues you're not looking to deal with, and I only include the example to show what Express means when it talks about mounting entire applications.
For your present question, you'll either need to follow what Yashua is saying and redirect to /admin/login or mount your admin interface as a separate Express application.


text:
Q: oracle case or decode? - how to handle no recs How can I make sure in this case statement that if I get now rows selected that I set that my result=1?
I want a value of 1 if I have no records or a count of 0. I would also want a null date to be sysdate by default.
Here is what I have so far. It works with (sysdate-1), but when I tested it with (sysdate-0) or =sysdate (today's date), I
was getting no records. So I want to be able to handle null values too.
How can I change this query to do that? or would I use something like DECODE?
select
     to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD') as mydt,
     case when count(*) = 0 then 1 else 0 end result
from Table1
where
   to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD') >= trunc(sysdate)-1
GROUP BY
    to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD')

Here is my table desc. Perhaps, I should go off of timestamp instead?
There is also a value of counts which may help change this query or not. So what i'm looking for is coming up
with a value of 1 or 0 with a timestamp if that's possible.
SQL> desc Table1
 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 YEAR                           NUMBER
 QUARTER                        NUMBER
 MONTH                          NUMBER
 DAY                            NUMBER
 HOUR                           NUMBER
 TIMESTAMP                      NUMBER
 CNT_N                              NUMBER
 ACTN_N                             NUMBER
 ADDR_C                       VARCHAR2(255)

A: You will never get a count(*) of zero with a group by. If there are no rows, you won't get any groups and if there are rows then any group you get will show the number of rows.
If you have 3 rows for January 1st and another 3 for January 3rd, you will get :
2011/01/01 3
2011/01/03 3

You won't get a row for January 2nd. Are you wanting to generate that row ? Is there a maximum number of rows that you want returned ?

A: I think you can do modify your query like below to assign the sysdate to null values
select
       nvl(to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD') ,sysdate) as mydt
from Table1
where
       nvl(to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD') ,sysdate)
                      >= trunc(sysdate)-1
GROUP BY      nvl(to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD') ,sysdate)

but your second requirement is not very much understood.... please clarify what exectly you want with count(*)
if you want to assign 1 for null date count then you can add following line in select statment
case
when nvl(to_date(year||'/'||month||'/'||day, 'YYYY/MM/DD') ,sysdate) = sysdate then
     1
else
count(*)-- or 0 ???!!!!!

A: It looks like you need to generate the date(s) and then see how may records match each one. Assuming you don't have any data in the future you can do something like:
select trunc(sysdate) + level - (:range + 1) as dt
from dual
connect by level <= (:range + 1);

which with :range set to 1 gives two dates:
DT
---------
19-JUL-11
20-JUL-11

You can then have outer join to that list of dates:
with tmp_dt as (
    select trunc(sysdate) + level - (:range + 1) as dt
    from dual
    connect by level <= (:range + 1)
)
select td.dt as mydt,
    case when count(t.year) = 0 then 1 else 0 end as result
from tmp_dt td
left join table1 t on t.year = extract(year from td.dt)
    and t.month = extract(month from td.dt)
    and t.day = extract(day from td.dt)
group by td.dt
order by td.dt;

If I only have any data in the table for 19-Jul-11, I get:
MYDT          RESULT
--------- ----------
19-JUL-11          0
20-JUL-11          1

If you do have data in the future this won't show it; range is how many days to look in the past. If you know there's a limit of, say, seven days you can use connect by level <= (:range + 1) + 7 or have a second variable, but it rather depends on what you want to see.
I've swapped the join around a bit to avoid doing a date conversion for every row in the table, extracting the relevant part of the generated date instead. I hope you have a reason for storing the date components in separate fields rather than as a date.

If you're only looking for data from today, just change the date generator:
with tmp_dt as (select trunc(sysdate) as dt from dual)
select td.dt as mydt,
     case when count(t.year) = 0 then 1 else 0 end result
from tmp_dt td
left join table1 t on t.year = extract(year from td.dt)
    and t.month = extract(month from td.dt)
    and t.day = extract(day from td.dt)
group by td.dt;

If you always want yesterday, it would be select trunc(sysdate) - 1 as dt from dual, etc.

A: May be you can encapsulate your whole query within the NVL function
like this

SELECT NVL(TO_CHAR((select to_date(year || '/' || month || '/' || day,
                                  'YYYY/MM/DD') as mydt
                     from Table1
                    where to_date(year || '/' || month || '/' || day,
                                  'YYYY/MM/DD') >= trunc(sysdate) - 1
                    GROUP BY to_date(year || '/' || month || '/' || day,
                                     'YYYY/MM/DD')),
                   'DD/MM/YYYY HH:MI:SS AM'),
           '1')
  FROM DUAL

I have removed the case statement from the query
Instead , what this query will do is, in case your query does return any value, it will do so without interference. However, in case the query returns NOTHING, then the NVL function will take over and return 1
I have used the TO_CHAR function to maintain the datatype of both the arguments in the NVL function. Both the date returned and the value for NVL are character based
Hope it helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python: Issues in retaining the exact format of string while uploading data from pipe delimited text to database I have a raw .txt file that contains the following fields and data
ID     MaterialCode    Vendor_Code
1      00033456        1990
2      4455600         02567

I am uploading this data to postgresql using sqlalchemy. I am using the following code:
conn = sqlalchemy.create_engine('conn_strng')
outputdype_app = sqlcol_append_stg(dataframe)
df = pd.read_csv(f,usecols=col_lst,sep='|',converters = \
     {'MaterialCode':'str','Vendor_Code':'str'},engine='python',encoding='iso-8859-1')
df.to_sql(schema=schema_name,name=table_name,con = conn,if_exists = 'append', method = 'multi', index=False,dtype=outputdype_app)

The outputdtype_app is being derived as follows:
def sqlcol_append_stg(dfparam):
    dtypedict_app = {}
    for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "datetime" in str(j):
           dtypedict_app.update({i: sqlalchemy.types.DateTime()})
        else:
           dtypedict_app.update({i: sqlalchemy.types.VARCHAR()})
    return dtypedict_app

When I am seeing the DB, I see the 0 prefixes in MaterialCode and Vendor_Code are gone! I see the following:
ID     MaterialCode    Vendor_Code
1      33456           1990
2      4455600         2567

How can I fix this issue? I want exact same string in DB.


text:
Q: How to access image downloaded from the web I downloaded an image from the web using this code and saved it directly to the application specific internal storage.
is = url.openConnection().getInputStream();
os = LoginActivity.this.openFileOutput(id + ".jpg", Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = is.read(data)) != -1)
    os.write(data, 0, read);

How do I access this stored image using Drawable? I attempted to open it using the following code but the operation resulted in a file not found exception.
File imgPath = new File(id + ".jpg");
profilePic.setImageDrawable(Drawable.createFromPath(imgPath.getPath()));

A: Assuming you call os.close() in the following lines of your code
You need to specify the path when instantiating your File object. Do the following :
File imgPath = new File(yourContext.getFilesDir(), id + ".jpg");

As said in doc of getFilesDir() method :

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.


text:
Q: Jquery draggable: how to make compononent smaller while dragging? I have a dragable image to be dropped on a smaller dropable.
I would like to make the image smaller while dragging to visually fit in the targer,
so on the start event I use:
start: function() {
     $("#primage").css({'width':'80px','height':'auto'});...

The problem is that when the dragging starts, the cursor is positioned according to the initial image size, so it is out of the now smaller image (higher and to the left).
I tried setting the cursorat left option further to the right   to accommodate  the change of width but then the over event of the dropable does not fire when the image is over it but further to the right.
How can I set the cursorat according to the new image size or can you suggest another solution?

A: Perhaps you could position the image at the cursor location instead of trying to position the cursor itself.


text:
Q: Adding a drive and OS to existing system, with full drive encryption Current state:  Laptop with 1 TB encrypted drive running Ubuntu 16.04.
Would like a add a new 2 TB drive that is also encrypted and install 20.04 on it. Would like to keep the 16.04 alive till I have used 20.04 for a few months.
I came across these instructions: https://www.erianna.com/adding-an-secondary-encrypted-drive-with-lvm-to-ubuntu-linux/
Questions:

*

*Would it be good to follow those instructions, especially given that
I intend to install 20.04 on the new drive?

*Or should I remove the 1 TB drive, add the new drive and install
20.04 on it (and verify correctness).  Then put both drives and boot -- and then do what to get an unified view of the two separately encrypted drives?

*Or should I just add the new drive, boot from a 20.04 USB and
install on the new drive, with the installation steps taking care of
whatever would need to be done?  If so, what would be the options to
select during the install?

Boot system is UEFI.  Below are the first few lines from cryptsetup luksDump and the output from lsblk, blkid, and df -h
sudo cryptsetup luksDump /dev/nvme0n1p3
  Version:      1
  Cipher name:  aes
  Cipher mode:  xts-plain64
  Hash spec:    sha256

sudo lsblk
    NAME                      MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
    nvme0n1                   259:0    0 953.9G  0 disk
      nvme0n1p3               259:3    0 952.9G  0 part
        nvme0n1p3_crypt       253:0    0 952.9G  0 crypt
           ubuntu--vg-root    253:1    0 867.5G  0 lvm   /
           ubuntu--vg-swap_1  253:2    0  63.9G  0 lvm   [SWAP]
      nvme0n1p1               259:1    0   512M  0 part  /boot/efi
      nvme0n1p2               259:2    0   488M  0 part  /boot

sudo blkid
    /dev/mapper/nvme0n1p3_crypt: UUID="xyz1" TYPE="LVM2_member"
    /dev/mapper/ubuntu--vg-root: UUID="xyz2" TYPE="ext4"
    /dev/nvme0n1p1: UUID="xyz3" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="xyz10"
    /dev/nvme0n1p2: UUID="xyz4" TYPE="ext2" PARTUUID="xyz8"
    /dev/nvme0n1p3: UUID="xyz5" TYPE="crypto_LUKS" PARTUUID="xyz9"
    /dev/mapper/ubuntu--vg-swap_1: UUID="xyz6" TYPE="swap"
    /dev/nvme0n1: PTUUID="xyz7" PTTYPE="gpt"

df -h
    Filesystem                   Size  Used Avail Use% Mounted on
    udev                          32G     0   32G   0% /dev
    tmpfs                        6.3G   58M  6.3G   1% /run
    /dev/mapper/ubuntu--vg-root  854G  659G  152G  82% /
    tmpfs                         32G  452M   31G   2% /dev/shm
    tmpfs                        5.0M  4.0K  5.0M   1% /run/lock
    tmpfs                         32G     0   32G   0% /sys/fs/cgroup
    /dev/nvme0n1p2               473M  136M  313M  31% /boot
    /dev/nvme0n1p1               511M   24M  488M   5% /boot/efi
    tmpfs                        6.3G  124K  6.3G   1% /run/user/11098


text:
Q: Unoffical upgrade Windows 7 RC Ultimate to Windows 7 RTM Enterprise Anyone here who did this before? I found this Tutorial but it just don't work.
Any help is appreciated,
rAyt

A: Use easy transfer to back up your data and do a clean install
What you're trying to do is unsupported by Microsoft and I'm sure they made it hard to do.
On top of that your changing the software version, which won't go well probably:

Windows 7 Enterprise can only be
activated with a Volume License MAK or
KMS key if it is not activated against
a local KMS server. Enterprise
requires a VL KMS/MAK out of the box
or activation against a local KMS
server. It can be rearmed up to 3
times.

How-To-Geek also wrote a post about doing what you're asking but in the end he notes:

There are a few important things to
keep in mind when you are upgrading to
the final version:
The Windows 7 beta or RC releases were
Ultimate edition, so you'll only be
able to upgrade to the RTM (final) if
you are installing Ultimate Edition.
Whenever possible, you should really
backup your files and do a clean
install. There are less headaches this
way, and you get the benefit of a nice
clean profile.

Note: I know your not asking for this answer, but the worst that can happen is that you loose some settings and have to reinstall some applications. However, everyone using the RC will have to do a clean install

A: An upgrade across "milestones" is not officially supported by Microsoft, so any article you find like this is very risky to use and not recommended. I would just use the built-in Windows Easy Transfer to keep files and settings then do a fresh install as recommended.
Microsoft also stated that upgrades to Windows 7 from the following operating systems are not supported:

*

*Windows 95, Windows 98, Windows Millennium Edition, Windows XP, Windows Vista RTM, Windows Vista Starter, Windows 7 M3, Windows 7 Beta, Windows 7 RC, or Windows 7 IDS

*Windows NT Server 4.0, Windows 2000 Server, Windows Server 2003, Windows Server 2008, or Windows Server 2008 R2

*Cross-architecture in-place upgrades (for example, x86 to x64) are not supported.

*Cross-language in-place upgrades (for example, en-us to de-de) are not supported.

*Cross-SKU upgrades (for example, Windows 7 N to Windows 7 K) are not supported.

*Upgrades from Windows Vista to Windows N, Windows K, Windows KN, or Windows E are not supported.

*Cross-build type in-place upgrades (for example, fre to chk) are not supported.

*Pre-release in-place upgrades across milestones (for example, Windows 7 RC to Windows 7 RTM) are not supported.

Further reading in the Windows 7 Upgrade Paths.


text:
Q: Laravel:How to fix SQLSTATE[23000]: Integrity constraint violation? I'm trying to populate a database using seeder.
I get an error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (forge.projects, CONSTRAINT projects_status_id_foreign FOREIGN
  KEY (status_id) REFERENCES status_projects (id))

Here are my migrations:
public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('subtitle');
        $table->longText('main_data');
        $table->string('budget_description');
        $table->integer('owner_id')->unsigned();
        $table->integer('category_id')->unsigned();
        $table->integer('deadline_id')->unsigned();
        $table->integer('city_id')->unsigned();
        $table->string('website')->nullable()->default('null');  //reference
        $table->decimal('budget', 18, 4);
        $table->integer('status_id')->unsigned()->default('1');
        $table->dateTime('started_at')->nullable();
        $table->integer('account_id')->unsigned()->default(1);
        $table->timestamps();
        $table->softDeletes();
    });
}

This is a migration for Status:
public function up()
{
    Schema::create('status_projects', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
    });
}

Several people are working on this project, so I created an additional migration:
public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->unsignedInteger('status_id');
        $table->foreign('status_id')
            ->references('id')->on('status_projects')
            ->onDelete('cascade');
    });
}

Now when I try to execute the command
php artisan migrate

I get error:

SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'status_id' (SQL: alter table projects add status_id int unsigned null)

How can I fix this?

A: This should solve the problem: you have to refresh your database (ps: you are going to re-insert your rows)
php artisan migrate refresh

A: im think your id type is TYNYINT. you must your id type change to INT


text:
Q: Google US Holidays Calendar Feed Forbidden I was pulling in US holidays using this google calendar feed...
https://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/full?alt=json-in-script&callback=jQuery18204341156887821853_1416248123466&start-min=2014-10-26T00%3A00%3A00Z&start-max=2014-12-07T00%3A00%3A00Z&singleevents=true&max-results=9999&_=1416248372436
It now returns Forbidden Error 403.  I'm assuming this has to do with v2 being shutdown today: https://developers.google.com/google-apps/calendar/v2/developers_guide_protocol
I can't find how to get this feed with v3.  Does anyone know?
UPDATE: It appears I am not using the URL above, I am actually using this URL: https://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic
And it appears to work.  The bug seems to be with the "fullcalendar" jQuery plugin I am using.  It is taking this URL that works and turning it into the initial one I posted that does not work.  I will investigate further and see if the fullcalendar has a patch or new version.

A: To make this work with v3, just register for a developer key at https://console.developers.google.com and then do:
GET https://www.googleapis.com/calendar/v3/calendars/usa__en%40holiday.calendar.google.com/events?key={YOUR_API_KEY}

A: I went through the same problem today.My client has been using fullcalendar for a while now. The problem seems to be that Google shut down the API (v1, v2)
http://googleappsupdates.blogspot.ca/2014/06/calendar-gdata-api-google-calendar.html
I have been working on making it compatible with the v3. I uploaded the files you may need here:
http://dev.radicalwerks.com/RadicalCalendar/rwCal/fullcalendar.js
and
http://dev.radicalwerks.com/RadicalCalendar/rwCal/gcal.js
Here you can see the example working:
http://dev.radicalwerks.com/RadicalCalendar/my_fgcalendar.html
There is a few steps you need to do in order to enable the API and make it work.
First of all create a client ID and get a Key from the developer console of google:
https://console.developers.google.com/project
In order to do that, create project, go to credentials under APIs & Auth etc. When you get the client ID, keep the AUTHORIZED REDIRECT URIS textarea blank. Add the domain where you need to run the API under JAVASCRIPT ORIGINS (you can use several domains adding one per line). You might know all of this but could help to others who does not have a clear idea of how it works.
Once you get the client ID and Key you have to add them into the variables located in the fullcalendar.js file. They are on top:
var clientId

var apiKey

Keep the scope value. Finally you need to get the calendar ID (located beside the XML badge under calendar settings / Calendar Details / Calendar Address. You have to add it in the object we usually use to add the url. You will not need the url anymore. You need to add a new property called "calendarId". If you check the live example under http://dev.radicalwerks.com/RadicalCalendar/my_fgcalendar.html you can see how I added mine.
One last thing you need to load the API by adding on the head:
<script src="https://apis.google.com/js/client.js"></script>

All the additions I did in those 2 files are between comments: /* New update by Yared */
I have to improve the code, it is just a quick fix to make it work. Now it is time to sleep :) I will probably update the code soon. Basically, so you know, I interrupted the AJAX call if is detecting the property CalendarID and then I am making a request using the API v3 and adjusting the events object according to the new format.
I think I am not missing anything. I hope all of this helps.

A: Not sure if this is equivalent since I can't see the original, but try: https://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic?alt=json-in-script&callback=jQuery18204341156887821853_1416248123466&start-min=2014-10-26T00%3A00%3A00Z&start-max=2014-12-07T00%3A00%3A00Z&singleevents=true&max-results=9999&_=1416248372436


text:
Q: JMeter doesn't launches the Chrome or Firefox browser JMeter V5.3
Though JMeter lib and lib/ext has all the required selenium web driver plug-ins, when I triggered the Run button it's not launching the browser and throws the below error.
Not sure where am i doing wrong.

21-07-18 00:34:58,484 INFO o.a.j.e.StandardJMeterEngine: Thread will continue on error
2021-07-18 00:34:58,484 INFO o.a.j.t.ThreadGroup: Starting thread group... number=1 threads=1 ramp-up=1 delayedStart=false
2021-07-18 00:34:58,489 INFO o.a.j.t.ThreadGroup: Started thread group number 1
2021-07-18 00:34:58,489 INFO o.a.j.e.StandardJMeterEngine: All thread groups have been started
2021-07-18 00:34:58,491 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1
2021-07-18 00:34:58,500 INFO o.a.j.t.JMeterThread: Thread finished: Thread Group 1-1
2021-07-18 00:34:58,500 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[Thread Group 1-1,6,main]
java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkState(ZLjava/lang/String;Ljava/lang/Object;)V
    at org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:137) ~[selenium-remote-driver-3.14.0.jar:?]
    at org.openqa.selenium.remote.service.DriverService$Builder.usingDriverExecutable(DriverService.java:272) ~[selenium-remote-driver-3.14.0.jar:?]
    at com.googlecode.jmeter.plugins.webdriver.config.ChromeDriverConfig.getThreadService(ChromeDriverConfig.java:101) ~[jmeter-plugins-webdriver-3.3.jar:?]
    at com.googlecode.jmeter.plugins.webdriver.config.ChromeDriverConfig.createBrowser(ChromeDriverConfig.java:82) ~[jmeter-plugins-webdriver-3.3.jar:?]
    at com.googlecode.jmeter.plugins.webdriver.config.ChromeDriverConfig.createBrowser(ChromeDriverConfig.java:21) ~[jmeter-plugins-webdriver-3.3.jar:?]
    at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.getPreparedBrowser(WebDriverConfig.java:234) ~[jmeter-plugins-webdriver-3.3.jar:?]
    at com.googlecode.jmeter.plugins.webdriver.config.WebDriverConfig.threadStarted(WebDriverConfig.java:221) ~[jmeter-plugins-webdriver-3.3.jar:?]
    at org.apache.jmeter.threads.JMeterThread$ThreadListenerTraverser.addNode(JMeterThread.java:769) ~[ApacheJMeter_core.jar:5.3]
    at org.apache.jorphan.collections.HashTree.traverseInto(HashTree.java:993) ~[jorphan.jar:5.3]
    at org.apache.jorphan.collections.HashTree.traverse(HashTree.java:976) ~[jorphan.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.threadStarted(JMeterThread.java:737) ~[ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.initRun(JMeterThread.java:725) ~[ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:252) ~[ApacheJMeter_core.jar:5.3]
    at java.lang.Thread.run(Unknown Source) [?:1.8.0_291]
2021-07-18 00:34:58,505 INFO o.a.j.e.StandardJMeterEngine: Notifying test listeners of end of test
2021-07-18 00:34:58,509 INFO o.a.j.g.u.JMeterMenuBar: setRunning(false, *local*)

A: You need to upgrade to guava version 20.0
Download guava-20.0.jar and copy to JMeter's lib folder
If you have guava-19.0.0.jar (or older), you need to remove it

A: Sounds like you don't have all the necessary .jar files under JMeter Classpath (or suffering from a form of a Jar Hell)

*

*According to JMeter Best Practices you should always be using the latest version of JMeter so consider upgrading to JMeter 5.4.1 (or whatever is the latest JMeter stable version which is available at JMeter Downloads page)

*Install Selenium/WebDriver Support plugin using JMeter Plugins Manager - it will download and install the WebDriver Sampler and all its dependencies

*You should be able to use the WebDriver Sampler normally now


text:
Q: How to sort an NSArray of strings in date format @"Aug 2013" in ascending order..? I have an array of NSString objects in the format... @"Aug 2013" @"July 2013" and so on...
I want to sort this array in ascending order.. Is getting the date first for individual value a good idea..?

A: An other solution in one block
NSArray* array = [NSArray arrayWithObjects:@"Janvier 2012",@"Mars 2013", @"Juin 2013", @"Octobre 2012", nil];

NSArray* result = [array sortedArrayUsingComparator:^(id a, id b) {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM YYYY"];

    NSDate* datea = [dateFormat dateFromString:a];
    NSDate* dateb = [dateFormat dateFromString:b];

    return [datea compare:dateb];
}];

A: I see you prefer "stringly" (not a typo) typed variables. They often end up giving you error like this. What you really should do is to store dates as dates. They compare nicely agains each other and you can do fancy date calculations with them. The same is true for numbers.
Then if you want to present them like "Aug 2013" or "July 2013" in the user interface: use a date formatter to format the dates into appropriate strings for display only.

For this case the two main classes that you should look into (read the documentation and such) are: NSDate and NSDateFormatter. NSCalendar and NSDateComponents should also prove useful.

A: I address this kind of problem by using a category to switch back and forth between NSDate and NSString.   I would solve this problem by converting to dates using the category, sorting, and then converting back.
My category looks like the following (you'd need to add similar methods to manage the month/year format that your strings have)
    #import "NSDate+Utils.h"

    @implementation NSDate (NSDate_Utils)

    + (NSDate *)dateFromI18NString:(NSString *)dateString
    {
        if (dateString == nil)
            return nil;
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
        NSDate *d = [dateFormatter dateFromString:dateString];
        return d;
    }

    - (NSString *)dateToI18NString
    {
        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";

        return [dateFormatter stringFromDate:self];

    }

A: I would use NSArray of NSDate objects instead and format it's content where needed.

A: You can sort your array by implement below code.
-(void)somemethod{
   NSArray *sortedArray = [[NSArray alloc]initWithArray:YOURARRAY];
   sortedArray = [sortedArray sortedArrayUsingFunction:dateSort context:nil];
  }

Call below function as above to sort your array.(Update formater as per your date format of array )
NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM yyyy"];

NSDate *d1 = [formatter dateFromString:s1];
NSDate *d2 = [formatter dateFromString:s2];

return [d1 compare:d2]; // ascending order
return [d2 compare:d1]; // descending order
}

I hope, It may help you.

A: Try this
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *unsortedArray =[[NSArray alloc]initWithObjects:@"July 2013",@"Aug 2013",@"Jun 2012", nil];
NSMutableArray *arrSorted = [NSMutableArray arrayWithArray:unsortedArray];
for(int i=0;i<[arrSorted count];i++)
{

    for(int j=i+1;j<[arrSorted count];j++)
    {
        NSDateFormatter *df=[[NSDateFormatter alloc] init];
        df.dateFormat=@"MMM yyyy";
        NSDate *date1=[df dateFromString:[arrSorted objectAtIndex:i]];
        NSDate *date2=[df dateFromString:[arrSorted objectAtIndex:j]];
        if([date1 compare:date2]== NSOrderedAscending)
        {
            [arrSorted exchangeObjectAtIndex:i withObjectAtIndex:j];
        }
    }
}
// ORDER_DESCEND
NSLog(@"%@",arrSorted);

arrSorted = [NSMutableArray arrayWithArray:[[arrSorted reverseObjectEnumerator] allObjects]];
// ORDER_ASCEND
NSLog(@"%@",arrSorted);

}

A: - (NSArray *)sortedDateArrayWithExistedArray:(NSMutableArray *) setExistedArray acending:(BOOL)ascendingBoolvalue
{

    NSArray *sortedArray = [setExistedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"dd MMM, yyyy"];

            NSDate *d1 = [formatter dateFromString:obj1[@"displayDate"]];
            NSDate *d2 = [formatter dateFromString:obj2[@"displayDate"]];
       // id =  [d1 compare:d2];
        if (ascendingBoolvalue)
        {
            return [d1 compare:d2];
        }
        else
        {
            return [d2 compare:d1];
        }
    }];

     return sortedArray;
}

set setExistedArray == yourArray
set ascending parameter as yes or no based upon your requirement yes for ascending order no for descending order.
how to access this function
self.sortedArray = [[self sortedDateArrayWithExistedArray:self.yourArray Acending:NO] mutableCopy];
if yourArray is mutable place call mutable copy method otherwise no need


text: Q: Hosting Asp .Net MVC3 Web Application in IIS 7.5 We have developed an application using Asp .Net MVC3 for our Organization.we want to host that Application to Access the Same using a Link from other systems.I did publish the web Application by right clicking on its properties and used web deploy option.Now i can see that Application in IIS under Default website and when i give browse i can view the Application running Properly.but when i try to access the same from another computer using the same link with my system's Ip Address i couldn't Access the Same.It would be great if we get any assistence on this issue.we r struggling on this for past 2 days


text:
Q: Cannot read property 'get' of undefined when uploading image in wordpress Cannot read property 'get' of undefined
When uploading in the editor
When uploading at media library, the upload is very slow and eventually cannot get this:
"The webpage might be temporarily down or it may have moved permanently to a new web address."
Theme name      i   Newsmag
PHP Version       i   7.3.11-1+ubuntu
18.04.1+deb.sury.org+1
max_execution_time          300
max_input_vars          5000
WP Memory Limit         256 MB/request
WP version      i   5.4


text:
Q: In firefox, how do I create a bookmark and pin it to the taskbar as an icon, without it getting pinned to the firefox jump list I have managed to successfully set this up by following a guide before, but that seems to have since disappeared from the internet.
If I recall correctly, it involved something as silly as creating shortcuts to shortcuts, or something along those lines.
I'm trying to make give myself an icon I can launch from the taskbar that will take me to a specific URL. If I create a normal shortcut and attempt to pin that, it instead gets pinned to the firefox jump list, which is not what I want.

A: Nevermind, found my own answer
http://www.intowindows.com/how-to-pin-a-website-link-to-windows-7-taskbar/


text:
Q: UPDATE nested array field BigQuery I have two table Order and Person, where i am trying to update name in Order  table from Person table by matching id.
Could anyone help on to frame the update query.
Tables
Order
Person

A: UPDATE `projectID.dataset.order` o
SET o.product.items.customer.name =
(SELECT name FROM `projectID.dataset.person` p
WHERE o.product.items.customer.id = p.id )
WHERE  TRUE;


text:
Q: Sinatra success stories Have you used Sinatra successfully? What kind of a project was it? In what situations would you recommend using Sinatra instead of Rails or Merb?

A: I've dabbled with Sinatra, but haven't really written anything serious with it.
As you said above, there's a list at http://www.sinatrarb.com/wild.html, although a lot of the applications listed there seem to link to GitHub pages, which I assume are often people experimenting with Sinatra and publishing their results online. Then, there's also the Sinatra mailing list, where you might find links to some interesting projects.[*]
As for your question on when to use Sinatra, I personally would answer "for smaller projects." When you want something up and running very quickly, it seems like Sinatra is an excellent choice. It's also great for people who like Ruby. With that I mean, when you're doing something in Rails, you have to do it "The Rails Way". Rails is the framework upon which you're building your application, and you have to adhere to its customs and conventions. Sinatra, on the other hand, feels like a library. You feel like you're writing Ruby, if you want to connect to a database, you use the library you like/think is appropriate for the job, if you want to output HTML you choose the templating library you like, and if you want a simple web framework, you choose Sinatra. Sinatra is not something upon which you build your whole application, it's something you use beside the rest of your application.
So, as you may have gathered, I'm quite fond of Sinatra, and I would use it for personal (or small-scale) projects. It's easy to set up and easy to use, as long as you know what you're doing. Looking through http://www.sinatrarb.com/wild.html, it seems like that's what most people are using it for, see for example Is Lost on yet? and Calendar About Nothing.
[*] Edit: I found a thread here, with people linking to their projects. There seem both larger and smaller projects. Very interesting stuff.

A: There is a list at http://www.sinatrarb.com/wild.html.
Still, I'd like to hear a bit more about them. I also suspect that there are lots of successful Sinatra projects outside that list.

A: I just released TweepDiff (http://tweepdiff.com) written in Sinatra. Anything else would have been overkill but I would use Sinatra for bigger projects too.

A: I think sinatra is best suited for micro-applications development (no big surprise, it's a micro-framework)
Sinatra provides you with a sufficient level of abstraction to build almost everything you want quickly. And what I like about sinatra is that the framework gives you tight control over what your app is actually doing, you can really "feel" what you are writing. So, I would say Sinatra is a subtly balanced framework.
I also think Sinatra is attractive for "people who likes writing Ruby" as said before. You start writing ruby class before implementing a sinatra interface. (good exemple of this kind of workflow here : http://dev-logger.blogspot.com/2009/01/ric-rac-roe-in-soup-of-technologies.html)

A: I wanted to be able to run succinct self-contained Ruby scripts from my web server.  As far as functionality goes, it would be similar to a CGI library.  Sinatra was perfect.  One sinatra app later and I have a collection of scripts accessed through simple sinatra style routes.
Whenever I need to write a web application that doesn't depend on a database, I suspect sinatra will be my first port of call.

A: I'd have to echo most of the above comments.  We're in the process of implementing a Sinatra/HAML stack for browsing and basic reporting on data.
I really like the combination of simplicity and direct connection to Ruby.  If something isn't working in the browser, it's pretty easy to port it out to a straight Ruby program for debugging.
There's definitely a feeling of building a dog house with Sinatra versus the Taj Mahal with Rails.  It's easy to comprehend (it's also helping me understand the need for MVC and Rails).
Altogether very cool stuff and very fast.  I haven't stressed it yet, so I can't say how well it'll behave in the real world.

A: I made http://istay.com using sinatra, all I can say is that it is a fantastic little framework for any site that doesn't directly use or doesn't have a database.
Though I do feel sinatra has reach it's limit with the current site, and any extensions will be written using Rails or other framework.

A: I use Sinatra for small 'one function' kinds of apps (My current blogging engine might be a good example). I think the simplicity of Sinatra works best for little utilities and basic API front-ends (Twitter apps, etc).
For larger scale apps there is even the Sinatra-based Padrino Framework with some of the niceties that you would usually reach for Rails to provide.


text:
Q: Android XML How to set background gradient inside a custom shape button I am creating a button shape look like WWTBAM game show:

I have created the shape for it but don't know how to put the gradient in it.
This is my styles.xml file I created:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="ButtonShapeArrow">
        <item name="cornerFamily">cut</item>
        <item name="cornerSize">50%</item>
    </style>
</resources>

And button in layout_main.xml:
<com.google.android.material.button.MaterialButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Start"
    app:shapeAppearance="@style/ButtonShapeArrow"/>

How do I set gradient for that button?

A: Create a custom background, you can change angle to change to position of the gradient
bg_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
     <gradient
         android:angle="270"
         android:endColor="@android:color/transparent"
         android:startColor="#802BC0E4" />
</shape>


text:
Q: How can I get better-looking fonts in my terminal (URxvt)? I've noticed that the fonts in URxvt look a little bit low-res compared to fonts that I see in my browser, for example.
I was wondering how could I fix my .Xdefaults file to make the fonts have a little bit more detail and be sharper.
It might not be visible in this picture, but I can definitely notice the difference when looking myself:

Here is my current .Xdefaults:
URxvt*background: Black
URxvt*foreground: White
URxvt*geometry: 80x30
URxvt*scrollBar: false

"URxvt.font: 9x15

!-- Xft settings -- !
Xft.dpi:        96
Xft.antialias:  true
Xft.rgba:       rgb
Xft.hinting:    true
Xft.hintstyle:  hintfull

! -- Fonts -- !
URxvt.font:xft:Monospace:pixelsize=15
URxvt.boldfont:xft:Monospace-Bold:pixelsize=15

A: There are a couple of good resources available for font configuration. The first I would recommend is the Arch wiki page, it has details on how to manually configure your fonts.conf or how to install and use the various patchsets (like infinality—which are distro agnostic).
There is also a long thread on the Gentoo boards that has a lot of good tips, but requires some wading through.
Ultimately, font appearance is quite subjective.
The settings that you have in your .Xresources look fine, but if you are dissatisfied with how your fonts appear, you will have to configure the settings you are after in your files in$XDG_CONFIG_HOME/fontconfig/conf.d until you achieve what you are looking for.
You are also setting your DPI at 96: check what your monitor's optimum DPI is and set it accordingly.

A: In ~/.Xresources, put, for example, the below config. (There are some other configurations of urxvt that might interest you here
(note that this is a plain text file, posted on the web;
you may want to use "View Source" to read it).
There you also find another color scheme, that might be better if you ever experience eye problems because of too bright lights emitting from a monitor.
More colors stuff.)
Then, in ~/.xinitrc, put xrdb ~/.Xresources.
For testing, an alias like alias xup="xrdb ~/.Xresources" could be useful, then simply start a new instance of urxvt.
URxvt.font:     xft:bitstream vera sans mono:size=16:antialias=true
URxvt.boldFont: xft:bitstream vera sans mono:bold:size=16:antialias=true

URxvt*color0:  #000000 // black
URxvt*color1:  #B40000 // red
URxvt*color2:  #00AA00 // green
URxvt*color3:  #AAAA00 // yellow
URxvt*color4:  #5555AA // blue
URxvt*color5:  #AA00AA // magenta
URxvt*color6:  #00AAAA // cyan
URxvt*color7:  #AAAAAA // white
URxvt*color8:  #555555 // black (now and below: bright)
URxvt*color9:  #FF0000 // red
URxvt*color10: #00FF00 // green
URxvt*color11: #FFFF00 // yellow
URxvt*color12: #6464FF // blue
URxvt*color13: #FF00FF // magenta
URxvt*color14: #00FFFF // cyan
URxvt*color15: #FFFFFF // white

Here is what it looks like:

urxvt:


text:
Q: Simulate Mouse Drag Programatically in Java Is there a way to simulate mouse drag events in Java.  I can simulate mouse clicks and mouse movements using the java.awt.Robot.  However, I cannot simulate the action of a mouse drag.
I tried having the robot class keep the mouse button depressed using, robot.mousePress(), and moving the mouse location while pausing several times during the mouse move before calling robot.mouseRelase.  However, all this does is simulate the mouse cursor moving and does not simulate a mouse drag event.
I will include a snippet of the code I am using; however, all it does is just what I mentioned above, click the mouse and move the mouse cursor.
I am running this applications on Windows 7.
Thanks in advance.
   public void click() throws AWTException, InterruptedException {
  int numberOfMoveIterations = 15;

  Robot bot = new Robot();
  Thread.sleep(mouseDownDelayClickTime + this.delayTime);
  bot.mouseMove((int) (mouseClickDownXLocation * this.widthEventOffset), (int) (mouseClickDownYLocation * this.heightEventOffset));
  bot.mousePress(InputEvent.BUTTON1_MASK);
  if (mouseClickDownXLocation != mouseClickUpXLocation || mouseClickDownYLocation != mouseClickUpYLocation) {
     int xAmountToMove = mouseClickUpXLocation - mouseClickDownXLocation;
     int yAmountToMove = mouseClickUpYLocation - mouseClickDownYLocation;
     int xAmountPerIteration = xAmountToMove / numberOfMoveIterations;
     int yAmountPerIteration = yAmountToMove / numberOfMoveIterations;

     int currentXLocation = mouseClickDownXLocation;
     int currentYLocation = mouseClickDownYLocation;

     while (currentXLocation < mouseClickUpXLocation + xAmountToMove
          && currentYLocation < mouseClickUpYLocation + yAmountToMove) {
        currentXLocation += xAmountPerIteration;
        currentYLocation += yAmountPerIteration;

        bot.mouseMove(currentXLocation, currentYLocation);
        Thread.sleep(mouseUpDelayClickTime);

     }
  }
  bot.mouseRelease(InputEvent.BUTTON1_MASK);

}

A: I had a similar problem as before. Here is the link for the other question I have answered :
https://stackoverflow.com/a/45063135/
Adding the thread.sleep(); is the right solution for making a drag motion. But you add it to the wrong place. You need to make sure the cursor is moving while the mouse is pressed. In order to suspend the thread mousePressed, you will have to add thread.sleep between mousePressed and mouseMoved.
See the codes as below:
public void click() throws AWTException, InterruptedException {
int numberOfMoveIterations = 15;

Robot bot = new Robot();
thread.sleep(mouseDownDelayClickTime + this.delayTime);
bot.mouseMove((int) (mouseClickDownXLocation * this.widthEventOffset), (int) (mouseClickDownYLocation * this.heightEventOffset));
bot.mousePress(InputEvent.BUTTON1_MASK);

/* suspend the current thread here */
thread.sleep(mouse pressed thread suspended time);

if (mouseClickDownXLocation != mouseClickUpXLocation || mouseClickDownYLocation != mouseClickUpYLocation) {
  int xAmountToMove = mouseClickUpXLocation - mouseClickDownXLocation;
  int yAmountToMove = mouseClickUpYLocation - mouseClickDownYLocation;
  int xAmountPerIteration = xAmountToMove / numberOfMoveIterations;
  int yAmountPerIteration = yAmountToMove / numberOfMoveIterations;

  int currentXLocation = mouseClickDownXLocation;
  int currentYLocation = mouseClickDownYLocation;

  while (currentXLocation < mouseClickUpXLocation + xAmountToMove
      && currentYLocation < mouseClickUpYLocation + yAmountToMove) {
    currentXLocation += xAmountPerIteration;
    currentYLocation += yAmountPerIteration;

    bot.mouseMove(currentXLocation, currentYLocation);

 }
}
bot.mouseRelease(InputEvent.BUTTON1_MASK);


text:
Q: PayPal Payouts with encoded user id I need some help with Paypal Payouts. I am currently using Java SDK and working in sandbox environment.
I am trying to implement a button in my webapp that will enable users to receive monetary awards in their paypal accounts. My first idea was to ask for their email and then - using the SDK create a payout item and send that. All works well, except that when someone types (unintentionally I assume) wrong email, then money are not going to be transferred. That is why I decided that asking the user to login with paypal and then using their paypal id will be much more error-proof.
So I followed the steps described here.
I am successfully able to exchange the authorization code and receive access and refresh tokens. Then I use those to load user info that contains only user_id (login scope is openid).
When I try to create a PayoutItem with recipient type PAYPAL_ID and value - user_id from Userinfo object - the operation is unsuccessful (no error - just the batch result is null).
We do not have and we do not expect to have any transactions from this user - so there is no way to use getTransactionDetails in order to retrieve payer id.
I suspect that user_id is not the correct property to use. However, I cannot find any information on how I can integrate payouts with recipient type PAYPAL_ID combined with paypal login.
Help, please!


text:
Q: Get the js script from a rest api hit and execute it on browser I need to get user details behind the scene when he is accessing our browser based application. So a plug and play JavaScript component need to be created which can be easily embedded in the header of the web page. The logic of capturing the data points should sit on server side. So an API can be invoked from this component and then "User-Agent" header can be leveraged in that API to get the data points.
However, not all data points can be Identified from User-Agent such as language, screen resolution, color depth, etc. Capturing these attributes need an execution of JavaScript on client side.
Two approaches:

*

*With Redirect(If allowed and component is an iFrame so that parent page is not reloaded)

When the component loads initially, redirect it to another page which will contain the JavaScript that will capture these details and it will be auto submitted and sent to the API which will use the data points and then redirect to the component with a flag to not perform the capture activity again.

*Without redirect

So, The approach am thinking is to have a component in which, during onLoad event, an API will be invoked and the JavaScript code (To capture the data points from client) will be returned as response. Then this returned JavaScript will be executed on client and result will be saved in a hidden field. There will be an Allow button(part of requirement to take user consent) in this component, which when clicked, the data from the hidden field will be submitted to the API.
Please review the approach and let me know if it sounds good and viable.

A: I bet that the second approach would be better. And even better, you don't actually need to write a dedicated API to generate the JS file s required for tracking.
Now, write a simple JavaScript file which will collect the required data. I'll name this as track.js.
function collectAndSubmit(){
  var data = {};

  // Then collect the required data
  data.screenWidth = window.innerWidth;
  data.screenHeight = window.innerHeight;
  data.preferredLanguages = navigator.languages; // In the form of an array

  // Submit the data through XHR
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "https://example.com/track.php");
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); // Note that we're sending a JSON request
  xhr.send(JSON.stringify(data));
}

The last 6 lines of code will send all of the collected data in JSON format to a server. However, I don't know which server are you using (e.g. PHP, Node.js) since they have different ways to parse the JSON data. For example, PHP you can use $data = json_decode(file_get_contents('php://input')); to obtain the requested data or var data = req.body; if you're using Node.js with Express and the body-parser module.
The best part here is that track.js doesn't have to be generated by an api, e.g. by performing a GET request to /gettrackingscript. Instead, you can serve this as a static file, putting it on your CDN and so on.
And now, what is the best way to download this track.js file? Well, it depends on how would you use it. You can simply include a <script src="track.js"> tag when the page loads and call the collectAndSubmit() method when you would like to send the data. Or by getting the script through another XMLHttpRequest and execute them with eval().
Since you're planning to redirect the user after all of the data has been sent, you don't have to refresh the page unless if you're sticking to the MVC (mode-view-controller) pattern when building the site. After the xhr.send(), you can set your backend server to send additional data back to the browser by sending a HTTP response, which you can parse it here by using:
xhr.onreadystatechange = function() {
  if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
    // Assuming that you're using JSON
    var additionalData = JSON.parse(xhr.responseText);
  }
}


text:
Q: How to toggle elements? I have this in template:

Zahtjev / Stavka  <input *ngIf="showFilter==='1'" type="text">

Usluga <input *ngIf="showFilter==='2'" type="text">

Broj telefona <input *ngIf="showFilter==='3'" type="text">

In ts i have this:
filter(filterNumb){
    this.showFilter = filterNumb;
}

Now what i want is also when user click again on same icon to close this input. Any suggestion how can i do that?

A: This might solve it. If not I need more info.
filter(filterNumb){
  if(this.showFilter !== filterNumb) {
    this.showFilter = filterNumb;
  }
  else { this.showFilter = '0'; }
}


text:
Q: How to auto replicate data in cassandra I am very new to cassandra and currently in early stage of project where i am studying cassandra.
Now since cassandra says to de-normalize data and replicate it. So, i have a following scenario :
I have table, user_master, for users. A user has

*

*subject [type text]

*hobbies [type list]

*uid [type int]

*around 40 more attributes

Now, a user wants to search for another user. This search should look for all user who matches the subject and hobbies provided by user. For this reason i am planning to make a different table user_discovery which will have following attribute only for every user

*

*subject [type text]

*hobbies [type list]

*uid [type int]

*other irrelevant attributes won't be part of this table.
Now my question is:

*

*Do i need to write on both tables for every insert/update in user_master? Can updation of user_discovery be automated when their is any insert/update in user_master.

*Even after studying a bit, i am still not so much sure that making a separate table would increase the performance.Since, number of users would be same in both table (yes, number of column would be very less in user_discovery). Any comment on this would be highly appreciated.
Thanks

A: The idea of separate tables for queries is to have the key of the table contain what you are looking for.
You don't say what the key of your second table looks like, but your wording "the following attributes for every user" looks like you plan to have the user (Id?) as key. This would indeed have no performance advantage.
If you want to find users by their hobby make a table having the hobby as key, and the user id (or whatever it is you use to look up users) as columns. Write one row per hobby, listing all users having that hobby. Write the user into every row matching one of his hobbies.
Do the same for the subject (i.e. separate table, subject as key, user ids as columns).
Then, if you want to find a user having a list of specific hobbies, make one query per hobby, creating the intersection of the users.
To use these kind of lookup-tables you would have indeed to update all table every time you update a user.
Disclaimer: I used this kind of approach rather successfully in a relative complex setting managing a few hundred thousand users. However, this was two years ago, on a Cassandra 1.5 system. I haven't really looked into the new features of Cassandra 2.0, so I have no idea whether it would be possible to use a more elegant approach today.


text:
Q: Drawing a tangent plane to the torus I'm trying to draw a torus and a plane tangent to it. Here is my code so far:
F[x_, y_] := {Cos[x] (3 + Cos[y]), Sin[x] (3 + Cos[y]), Sin[y]}
dxF[x_, y_] := D[F[a, b], a] /. {a -> x, b -> y}
dyF[x_, y_] := D[F[a, b], b] /. {a -> x, b -> y}
normal[x_, y_] := Cross[dxF[x, y], dyF[x, y]]
Manipulate[
 Show[Plot3D[(normal[px, py][[1]] (x - F[px, py][[1]]) +
       normal[px, py][[2]] (y - F[px, py][[2]]))/normal[px, py][[3]] +
     F[px, py][[3]], {x, -4, 4}, {y, -4, 4}],
  ParametricPlot3D[F[u, t], {t, 0, 2 Pi}, {u, 0, 2 Pi}]], {px, 0,
  Pi}, {py, 0.1, Pi/2 - 0.1}]

Not sure how to include the output here. This basically draws a torus and a plane but the plane intersects the torus. For some reason the order of the the arguments of SHOW also makes a big difference in output.
Mathematically this should be pretty simple. I find the normal vector to the torus by taking directional derivatives. Then their cross product is the normal vector $(a,b,c)$ to the tangent plane and the equation $z=\frac{1}{c}(a(x-x_0)+b(y-y_0))+z_0$ defines the plane.
What am I doing wrong?
Edit: Just in case somebody comes looking for something like this here is the code I ended up using. I used it as an example in paper to illustrate the concept of tangent spaces.
Manipulate[
 Show[ParametricPlot3D[F[u, t], {t, 0, 2 Pi}, {u, 0, 2 Pi},
   AxesEdge -> {{-10, 10}, {-10, 10}, {-10, 10}}],
  ContourPlot3D[
   normal[px, py][[1]] (x - F[px, py][[1]]) +
     normal[px, py][[2]] (y - F[px, py][[2]]) +
     normal[px, py][[3]] (z - F[px, py][[3]]) == 0, {x, xmin,
    xmax}, {y, ymin, ymax}, {z, zmin, zmax},
   ContourStyle -> {Opacity[0.5], Blue}],
  Graphics3D[{Arrow[{F[px, py], F[px, py] + dxF[px, py]}],
    Arrow[{F[px, py], F[px, py] + dyF[px, py]}]}], Boxed -> False,
  Axes -> False, PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}}], {px, 0,
  Pi}, {{py, 0.5}, 0.2, Pi/2 - 0.1}, {{xmin, -5}, -10,
  0}, {{ymin, -5}, -10, 0}, {{zmin, -5}, -10, 0}, {{zmax, 3}, 0,
  10}, {{ymax, 3}, 0, 10}, {{xmax, 5}, 0, 10}]

A: There are just some little mistakes. First your parametric equation of the plane should be $z=-\frac{1}{c}(a(x-x_0)+b(y-y_0))+z_0$. Also, you can adjust AspectRatio and PlotRange for better visibility:
F[x_, y_] := {Cos[x] (3 + Cos[y]), Sin[x] (3 + Cos[y]), Sin[y]}
dxF[x_, y_] := D[F[a, b], a] /. {a -> x, b -> y}
dyF[x_, y_] := D[F[a, b], b] /. {a -> x, b -> y}
normal[x_, y_] := Cross[dxF[x, y], dyF[x, y]]
Manipulate[
 Show[Plot3D[-(normal[px, py][[1]] (x - F[px, py][[1]]) +
        normal[px, py][[2]] (y - F[px, py][[2]]))/
     normal[px, py][[3]] + F[px, py][[3]], {x, -10, 10}, {y, -10, 10},
    PlotRange -> {{-5, 5}, {-5, 5}, {-5, 5}}, AspectRatio -> 1,
   ClippingStyle -> None],
  ParametricPlot3D[F[u, t], {t, 0, 2 Pi}, {u, 0, 2 Pi}]], {px, 0,
  2 Pi}, {py, -\[Pi]/2, \[Pi]/2}]


text:
Q: 'list::list' names the constructor, not the type I get this error while compiling my class linked list with constructors. I wanted to do a copy assignment operator, but i get this error 'list::list' names the constructor, not the type.
the line is:
list::list& operator= (const list &l)

list is my the name of my class

A: If you are defining your operator= function inside your class definition, declare it thus:
class list {
  ...
  list& operator=(const list&) { ... return *this; }
};

If you are defining your operator= function outside your class definition, declare it as in this complete and correct example:
class list {
  public:
  list& operator=(const list&);
};
list& list::operator=(const list&) {
  return *this;
}
int main() {}

A: This error is pretty self-explanatory.
Use this code:
list& operator= (const list &l)

Outside a class declaration, you have to precise in which scope belongs the function:
list& list::operator= (const list &l)
//    ^^^^^^


text:
Q: Как убрать баннер debug на экране Flutter-приложения Я пытаюсь сделать скриншот с помощью команды
flutter screenshot

И мне хотелось бы чтобы на нем не было баннера debug в правом верхнем углу, чтобы его(скриншот) можно было разместить в портфолио и магазине приложений.
Сейчас он присутствует на скриншоте.
Какие можно убрать данный баннер?

A:
Для начала: данный баннер автоматически убирается при сборке билда для релиза приложения.

Если же вы хотите, чтобы он Вас не смущал во время процесса разработки и отладки, Вы можете проделать следующее:
При создании экземпляра MaterialApp (или ScaffoldApp) Вам необходимо установить флаг debugShowCheckedModeBanner в значение false
MaterialApp(
  debugShowCheckedModeBanner: false,
)

Либо тоже самое можно сделать и при инициализации CupertinoApp
CupertinoApp(
  debugShowCheckedModeBanner: false
)

Их (одного из них) как правило можно найти в файле main.dart

После этого данный баннер исчезнет


text:
Q: limpiar tabla HTML por cada llamada GET utilizando jQuery tengo una aplicación MVC ASP.NET C# que consume un servicio Web Api via jQuery para obtener todos los registros de una tabla especifica y funciona bien, mi unico problema es: presiono el boton para obtener los datos y los muestra en una tabla pero si vuelvo a presionar el boton me muestra nuevamente los datos pero junto con los anteriormente recuperados, es decir, muestro dos veces los mismos datos en la tabla y si presiono una tercera vez muestro tres veces los datos.
este es mi codigo javascript, el $("#Table").empty() me funciona para no mostrar dos veces los registros pero me borra los encabezados de las columnas
$("#boton_de_pabletoreto").click(function () {

    $.ajax({
        type: "GET",
        url: "http://localhost:55987/api/Empleados",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            //$("#Table").empty();
            $.each(data, function (i, item) {
                var rows = "
" +
                    "" + item.id + "	" +
                    "" + item.Nombres + "	" +
                    "" + item.Cargo + "	" +
                    "" + item.Dpto + "	" +
                    "
";
                $('#Table').append(rows);
            });
            console.log(data);
        },

        failure: function (data) {
            alert(data.responseText);
        },
        error: function (data) {
            alert(data.responseText);
        }

    });
});

y el codigo HTML de la tabla

                ID
                Nombre
                Departamento
                Cargo

me pueden indicar como mostrar los datos solamente una vez por favor.

A: En tu html, a la tabla la segmentas en header y body. Asi:

            ID
            Nombre
            Departamento
            Cargo

Y en el success del ajax, haces referencia al tbody de la tabla. Asi:
$('#Table > tbody').empty();
$.each(data, function (i, item) {
    var rows = "
" +
        "" + item.id + "	" +
        "" + item.Nombres + "	" +
        "" + item.Cargo + "	" +
        "" + item.Dpto + "	" +
        "
";
    $('#Table > tbody').append(rows);
});
console.log(data);

A: 0
si no deseas borrar los encabezados debes separarlos del contenido de la tabla con las etiquetas y así:

$("#boton_de_pabletoreto").click(function () {

$.ajax({
    type: "GET",
    url: "http://localhost:55987/api/Empleados",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $("#Table > tbody").empty();//limpia solo los registros del body
        $.each(data, function (i, item) {
            var rows = "
" +
                "" + item.id + "	" +
                "" + item.Nombres + "	" +
                "" + item.Cargo + "	" +
                "" + item.Dpto + "	" +
                "
";
            $('#Table tbody').append(rows);
        });
        console.log(data);
    },

    failure: function (data) {
        alert(data.responseText);
    },
    error: function (data) {
        alert(data.responseText);
    }

});
});

y el codigo HTML de la tabla

        ID
        Nombre
        Departamento
        Cargo

A: Prueba con $('#Table').remove(rows); antes de insertar las nuevas rows, no se si te eliminará los encabezados.

A: Lo que hace la función append() es generar un elemento e insertarlo como último hijo del elemento que hayas usado en el selector. Lo que tú necesitas es que se machaque el contenido de tu tabla.
Puedes usar:
$('#Table').html(rows);

En vez de:
$('#Table').append(rows);

De esta manera la tabla será rellenada con el contenido de la variable rows machacando lo que la tabla tuviese dentro antes.


text:
Q: Entity Framework 6 Update where foreign key references NULL I have a table DivorceCases which has many fields and it's model is like:
    [Key]
    [Required]
    public string case_id { get; set; }
    public string user_id { get; set; }
    public DateTime case_date { get; set; }
    public virtual Transactions t { get; set; }

I am trying to add transaction details to an existing row but I am getting a [NullReferenceException: Object reference not set to an instance of an object.] error. In the DivorceCases table EF6 has created a column t_id for foreign key reference of Transactions Table.

I used :
public static void UpdatePayment(string cid,string txnno)
  {
 DivorceCasesContext db = new DivorceCasesContext();
            DivorceCases dc = db.DivorceCase.Where(x => x.case_id == cid).Include(x => x.t).SingleOrDefault();
            if (dc.t == null || dc.t.txn_id1 == null || dc.t.txn_id1 == "")
            {
                dc.t.txn_id1 = txnno;
                dc.t.amount1 = amount.ToString();
                dc.t.date1 = DateTime.Now.ToString();
            }
            else
            {
                dc.t.txn_id2 = txnno;
                dc.t.amount2 = amount.ToString();
                dc.t.date2 = DateTime.Now.ToString();
            }
            db.Set<DivorceCases>().Attach(dc);
            db.Entry(dc).State = EntityState.Modified;
            db.SaveChanges();
        }
}

The Error I'm getting is:
    [NullReferenceException: Object reference not set to an instance of an object.]
   gonylaw.Helpers.Amounts.UpdatePayment(String cid, String txnno) +425
   gonylaw.Controllers.PaymentController.PaymentProcessor(CreditCard c) +461
   lambda_method(Closure , ControllerBase , Object[] ) +104
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9644037
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

A: You are accessing properties of dc.t without ensuring dc.t is not null.  If the if statement short circuits on the first condition, dc.t is null, yet you attempt to assign a value to dc.t.txn_id:
if( dc.t == null || ... )
{
    dc.t.txn_id1 = txnno; // null ref exception here
}

Asside from that, there are other improvements I suggest:
public static void UpdatePayment(string cid,string txnno)
{
    // add using block to dispose of DbContext after you're done with it
    using( DivorceCasesContext db = new DivorceCasesContext() )
    {
        DivorceCases dc = db.DivorceCase.Include(x => x.t)
            .Where( x => x.case_id == cid )
            .SingleOrDefault();

            // take care of your null ref problem
            if( dc.t == null )
            {
                dc.t = new Transactions();
            }

            // simplify null/empty string check
            if( string.IsNullOrEmpty( dc.t.txn_id1 ) )
            {
                dc.t.txn_id1 = txnno;
                dc.t.amount1 = amount.ToString();
                dc.t.date1 = DateTime.Now.ToString();
            }
            else
            {
                dc.t.txn_id2 = txnno;
                dc.t.amount2 = amount.ToString();
                dc.t.date2 = DateTime.Now.ToString();
            }

            // this is not needed - dc is already attached to the context
            //  (unless you're doing something nonstandard by default
            //   within your DbContext)
            //db.Set<DivorceCases>().Attach(dc);
            //db.Entry(dc).State = EntityState.Modified;

            db.SaveChanges();
        }
    }
}


text:
Q: Arguments of different types in a same Fortran subroutine I want to define a subroutine in modern fortran (90 or newer) to print a matrix (with integer or real numbers) or vectors (with integer o numbers).
SUBROUTINE print_matrix_vector( A )

! WHAT TYPE CAN I WRITE TO A ???

END SUBROUTINE

Of course, I wanted to call a subrutine
CALL print_matrix_vector( A )

independent if A is a matrix of real or integer numbers, and if A is a vector of real or integer numbers.
Thanks in advance for your comments. I think this is something very usual, but I did not find nothing clear.

A: So Fortran uses interface statements to declare overloads to functions. I have done the exact same thing recently.  The key is to create an interface, I call show which is used as an alias for all the separate functions needed.
interface show
    procedure show_vector_i, show_vector_r, show_vector_d
    procedure show_matrix_i, show_matrix_r, show_matrix_d
end interface

Here is the output first.
 Display Matrices/Vectors

 vector=
    1
    2
    3
    4

 matrix=
    1    5    9   13
    2    6   10   14
    3    7   11   15
    4    8   12   16

 A=
 4.47723     3.36660     1.48809    -.752551
 6.36660     7.19091     6.67333     5.54482
 7.48809     9.67333     10.1187     9.77902
 8.24745     11.5448     12.7790     13.0861

 u=
 6.36660
 7.19091
 6.67333
 5.54482

 v=
 3.36660
 7.19091
 9.67333
 11.5448

and the code
program FortranConsole1
use, intrinsic :: iso_fortran_env
implicit none

interface show
    procedure show_matrix_i, show_matrix_r, show_matrix_d
    procedure show_vector_r, show_vector_d
end interface

integer :: row(16), matrix(4,4), i
real(real64), allocatable, target :: A(:,:)
real(real64), pointer :: B(:,:)
real(real64), allocatable :: v(:), u(:)

row = [(i,i=1,16)]
matrix = reshape( row, [4, 4])

print *, "Display Matrices/Vectors"
print *, ""

print *, "vector="
call show(row(1:4))

print *, "matrix="
call show(matrix)

A = dble(matrix)

A = sqrt( matmul( transpose(A), A) ) - A

print *, "A="
call show(A)

v = A(:,2)
u = A(2,:)

print *, "u="
call show(u)
print *, "v="
call show(v)

contains

subroutine show_vector_i(v, w)
! Display the vector 'v' in a single column
!   v : the array of real numbers
!   w : the column width. default = 5
!   s : sig. figures w-5 (calculated)
    integer, intent(in) :: v(:)
    integer, intent(in), optional :: w
    integer :: i,n,wt
    character(len=16) :: fmt
    if(present(w)) then
        wt = w
    else
        wt = 5
    end if
    n = size(v)
    write( fmt, "(a,g0,a)") "(*(g",wt,".0))"
    write( * , fmt ) ( v(i), new_line("A"), i=1,n )
end subroutine

subroutine show_vector_r(v, w)
! Display the vector 'v' in a single column
!   v : the array of real numbers
!   w : the column width. deafult = 12
!   s : sig. figures w-5 (calculated)
    real(real32), intent(in) :: v(:)
    integer, intent(in), optional :: w
    integer :: i,n,dg,wt
    character(len=16) :: fmt
    if(present(w)) then
        wt = w
    else
        wt = 12
    end if
    dg = wt - 6
    n = size(v)
    write( fmt, "(a,g0,a,g0,a)") "(*(g",wt,".",dg,"))"
    write( * , fmt ) ( v(i), new_line("A"), i=1,n )
end subroutine

subroutine show_vector_d(v, w)
! Display the vector 'v' in a single column
!   v : the array of real numbers
!   w : the column width. deafult = 12
!   s : sig. figures w-5 (calculated)
    real(real64), intent(in) :: v(:)
    integer, intent(in), optional :: w
    call show_vector_r(real(v),w)
end subroutine

subroutine show_matrix_i(A, w)
! Display the matrix 'A' in columns
!   A : the array of integers
!   w : the column width. Default = 5
    integer, intent(in) :: A(:,:)
    integer, intent(in), optional :: w
    integer :: i,j,n,m, wt
    character(len=16) :: fmt
    if(present(w)) then
        wt = w
    else
        wt = 5
    end if
    n = size(A,1)
    m = size(A,2)
    write( fmt, "(a,g0,a)") "(*(g",wt,".0))"
    write( * , fmt ) ( (A(i,j),j=1,m), new_line("A"), i=1,n )
end subroutine

subroutine show_matrix_r(A, w)
! Display the matrix 'A' in columns
!   A : the array of real numbers
!   w : the column width. deafult = 12
!   s : sig. figures w-5 (calculated)
    real(real32), intent(in) :: A(:,:)
    integer, intent(in), optional :: w
    integer :: i,j,n,m,dg,wt
    character(len=16) :: fmt
    if(present(w)) then
        wt = w
    else
        wt = 12
    end if
    dg = wt - 6
    n = size(A,1)
    m = size(A,2)
    write( fmt, "(a,g0,a,g0,a)") "(*(g",wt,".",dg,"))"
    write( * , fmt ) ( (A(i,j),j=1,m), new_line("A"), i=1,n )
end subroutine

subroutine show_matrix_d(A,w)
! Display the matrix 'A' in columns
!   A : the array of dble numbers
!   w : the column width. default = 12
! Converts 'A' into single precision and calls `show_matrix_r`
    real(real64), intent(in) :: A(:,:)
    integer, intent(in), optional :: w
    call show_matrix_r(real(A),w)
end subroutine

end program FortranConsole1

In reality, the functions should be in a module file in order to be reused again and again in different programs.


text:
Q: Downloading encrypted binary file using C# Windows Phone is missing data I need to download an encrypted xml binary file from a url which has been encrypted using JAVA. I have managed to encrypt the file in JAVA, then add the file in my WP7 project and decrypt using c# and read the file into my app succesfully.
I need to now store the file on a web server so the app can access it and I'm finding that the file is not complete or in the incorrect format when I download it and the decryption does not work.
I have tried using both WebClient and HttpWebRequest and both give me the same result. The xml encoded file is approximately 17000 bytes but the file downloaded from both of these methods return a file about 16000 bytes long. I think the downloaded file is missing end of line characters but I can't verify this. The code I'm using at the moment to download the file is pretty simple and is as follows:
private void GetFile()
    {
        WebClient client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        String url = "http://url/encodedfile.txt";
        client.DownloadStringAsync(new Uri(url));

     }

    void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {

        string s = e.Result;

        byte[] encodedFile = System.Text.Encoding.UTF8.GetBytes(e.result);

        //decrypt file....

Looking at the encrypted data they look very similar but the length of encodedFile is not the correct length of the original encrypted file.I've debugged this and copied the characters in encodedFile to TextPad its all on one line. I'm not sure if that's the issue or not but I've looked everywhere on how to download a binary file and most suggestions are to use HttpWebRequest but I get the exact same result so I don't think that is the issue.
Any help appreaciated.

A: DownloadString will try to read the data as an unicode string. Since you're downloading binary data, it's no wonder the output isn't correct. Try using WebClient.OpenReadAsync instead:
private void GetFile()
{
    var webClient = new WebClient();

    webClient.OpenReadCompleted += OpenReadCompleted;

    string url = "http://url/encodedfile.txt";

    webClient.OpenReadAsync(new Uri(url));
}

private void OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    // Decrypt the contents of e.Result
}


text:
Q: Partitions and the mounting points An extract from a book-

Linux organizes attached storage as block devices, you can move to
the /sys/block/ directory and list its contents. Among the contents
will be a directory called sda/. (Remember that sda stands for
Storage Drive A.) That's the first drive used by your system on boot:
Change to the sda/ directory and run ls. Among its contents,
you'll probably see files with names like sda1, sda2, and sda5.
Each of these represents one of the partitions created by Linux to
better organize the data on your drive.

On my Ubuntu machine, the below partitions are shown for sda-

Running df -h | grep sda gives

As seen, /dev/sda5 is mounted on '/' and /dev/sda1 on /boot/efi.
Why is there no mounting point for partition sda2?

A: sda2 is an extended partition, which is a partition used with the MBR partitioning scheme to store other partitions. It contains sda5. It serves no purpose other than to store other partitions and is therefore not a candidate for mounting.
See What mount points exist on a typical Linux system? for details.


text:
Q: How to plot (ggplot) two charts in the same plot R I need to compare 2 spectras by putting two charts in the same plot.
I cannot use the Melted function because my two data sets are 2 FTIR spectra with x numbers (wavenumber) not being quite the same.
I'm using this to plot the charts individually:
sacola57 <-read_excel("57.xlsx", sheet=1)

ggplot(sacola57, aes(x=Wavenumber,
                 y=Absorbance)) +
geom_line() +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

and
PADRAO <-read_excel("padrao.xlsx", sheet=1)
ggplot(PADRAO, aes(x=Wavenumber,
               y=Absorbance)) +
geom_line() +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

sacola57:

padrao:

I've tried this:
sacola58 <- read_excel("58.xlsx", sheet=1)
padrao <-read_excel("padrao.xlsx", sheet=1)
head(sacolas58)
head(padrao)

sacolas = merge(sacola58, padrao, by="Wavenumber")

sacolasMelted <- reshape2::melt(sacolas, id.var='Wavenumber')
head(sacolasMelted)

ggplot(sacolasMelted, aes(x=Wavenumber, y=value, col=variable,)) + geom_line() + theme_bw() +
labs( x = "Comprimento de onda (cm-1)", y = "Absorbância", color = "Amostra")+
scale_color_manual(labels = c("sacola branca", "sacola transparente", "sacola verde"), values = c("palevioletred2", "paleturquoise4", "red"))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

And return that:
1 Wavenumber   Absorbance.x Absorbance.y
<0 row> ( row.names lenght 0)
head(sacola58
 +      )
# A tibble: 6 × 2
 Wavenumber Absorbance
   <dbl>      <dbl>
 1       650.     0.0341
 2       652.     0.0316
 3       654.     0.0285
 4       656.     0.0288
 5       658.     0.0306
 6       660.     0.0341
> head(padrao)
# A tibble: 6 × 2
 Wavenumber Absorbance
   <dbl>      <dbl>
1       650.      0.176
2       653.      0.180
3       656.      0.178
4       659.      0.171
5       662.      0.179
6       665.      0.173

A: Does this work for you? I don't think you need to reshape your data, you can just stack the rows, provided you make a column to distinguish which spectra each row relates to.
sacola58 <- read_excel("58.xlsx", sheet=1)
sacola58$Src = "sacola58"
padrao <-read_excel("padrao.xlsx", sheet=1)
padrao$Src = "padrao"
combo <- rbind(sacola58, padrao)

I expect that will make something like this:
data.frame(
  stringsAsFactors = FALSE,
               Src = c("sacola58","sacola58",
                       "sacola58","sacola58","sacola58","sacola58","padrao",
                       "padrao","padrao","padrao","padrao","padrao"),
        Wavenumber = c(650L,652L,654L,656L,658L,
                       660L,650L,653L,656L,659L,662L,665L),
        Absorbance = c(0.0341,0.0316,0.0285,0.0288,
                       0.0306,0.0341,0.176,0.18,0.178,0.171,0.179,0.173)
) -> combo

Which you can plot like this:
ggplot(combo, aes(x=Wavenumber, y=Absorbance, col=Src))) +
  geom_line()


text:
Q: Size issue with embedding layer in Keras Problem:
The Keras embedding layers I've defined appear to be the incorrect size, as suggested by the error I'm getting.
InvalidArgumentError: indices[19,0] = 99 is not in [0, 31)

Code:
Kaggle notebook - https://www.kaggle.com/benseto/tf-ffnnregressor
Not sure if you need an account to access the code. If so, I'll look at exporting this outside.
Summary of Problem:
I'm using the old "Bluebook for Bulldozers" Kaggle competition for learning. I'm attempting to train a feed-forward neural network for this regression exercise (price prediction). Because the categorical features have many unique features, the strategy I'm taking is to train a Keras embedding layer for each of these categorical features, rather than one-hot encoding (which blows dataframe to an unwieldy size).
I've managed to almost get this working, but believe there's an error in the size of the embedding layers:
Error during fit():
InvalidArgumentError: indices[19,0] = 99 is not in [0, 31)

Through searching stackoverflow, people have concluded this is due to an incorrect size for the Embedding layer, typically the input dimension needs to be vocab_size + 1.
To generate a separate Keras embedding layer for each categorical feature, cell #25 of the linked notebook defines each embedding layer:
# Build layer to ingest each categorical features vector
def build_embedding_layer(num_categories, inputs, concats, name = 'categorical'):
    categories = num_categories + 1             # Per Keras docs, embedding input dim should be input_size + 1
    dimensions = min(50, categories // 2 + 1)

    input = keras.layers.Input(shape = (1,), name = name)
    embedding = keras.layers.Embedding(categories, dimensions, input_length = 1)(input)
    embedding = keras.layers.Reshape(target_shape = (dimensions,))(embedding)

    inputs.append(input)
    concats.append(embedding)

In the above function, num_categories is the number of unique records for each feature vector, while inputs and concats represent arrays holding the final input tensors for each feature.
What have I tried:
I've tried to manually increase the size of the embeddings layer to a large number but still run into the stated issue when calling fit().
At this point, I'm stuck and any suggestions and/or insights into this issue is appreciated.

A: As a follow-up, I've lifted this code into a different environment (Google Colab) and it's working there. Therefore, there must be a bug in the original runtime environment (Kaggle) and nothing wrong with the code itself.


text:
Q: What is the fastest way to unlock iPhone X to the homescreen? (rather than double tap, Face ID, swipe up) Needless to say every 0.1 second counts, I want to stay in the flow as much as possible.
Current method of unlocking iPhone X pisses me off is really annoying - it requires 3 independent interactions.
Related: Is there a way to unlock to Home screen without swiping up?

A: You can raise the phone or press the side-button and then swipe up. You do not have to wait for Face ID to complete in between.
This is much faster compared to double-tap, wait for Face ID and swipe.
There's no way currently to access the home screen faster, for example without having to swipe up.


text:
Q: How find this $\lim_{n\to\infty}a_{n}$ let sequence $\{a_{n}\}$,such  $a_{1}=2\pi-6$,
and
$$a_{n}=\left\lceil\dfrac{2\pi}{a_{n-1}}\right\rceil\cdot a_{n-1}-2\pi$$
Find the
$$\lim_{n\to\infty}a_{n}$$
where $\left\lceil\dfrac{2\pi}{a_{n-1}}\right\rceil$is the smallest integer not less than $\dfrac{2\pi}{a_{n-1}}$
My try: since
$$a_{n}>0,\dfrac{a_{n}}{a_{n-1}}=\lceil\dfrac{2\pi}{a_{n-1}}\rceil-\dfrac{2\pi}{a_{n-1}}\le 1$$
and then I can't Find this limit,and maybe other nice methods,
Thank you  very much

A: $a_1 > 0$ and $\bigg\lceil\frac{2\pi}{a_n}\bigg\rceil \ge \frac{2\pi}{a_n}$. By induction you can easily prove that $a_n >0 \, \forall \, n \in \mathbb N$.
As you proved, if $a_n >0$, then the sequence is strictly decreasing.
Remains to show that the actual limit is $0$, a reasonable guess.
Using the fact that the sequence is strictly decreasing and strictly positive, you know that the sequence has a unique limit.
The limit will solve the equation $a = \big\lceil\frac{2\pi}{a}\big\rceil a - 2\pi$ which can be rewritten as : $$\bigg\lceil\frac{2\pi}{a}\bigg\rceil - \frac{2\pi}{a} = 1$$
This has no solution for any $a_1 > a > 0$ therefore the limit is not strictly positive.
So the limit is $0$.
Perhaps easier (just thought about it), $$\lim_{a_n\to0} \bigg\lceil\frac{2\pi}{a_n}\bigg\rceil a_n  - 2\pi= 0$$
therefore $0$ is a limit. Since the limit is unique, it is $\underline{\text{the}}$ limit.
Another way I thought of doing this is to use the squeeze theorem. I'm sure there's a way to do it.

A: If there is a (nonzero) limit, it should satisfy
$$a = \lceil\frac{2\pi}{a}\rceil a - 2\pi,$$ which should have a solution (which I am having some trouble finding).


text:
Q: Toggle GeoJSON layers using an html button instead of links with Mapbox GL JS I am working on a web map that involves toggling two GeoJSON layers on and off. I previously used Mapbox JS to do this by removing layers and adding them on click with a custom HTML button, but am having an issue accomplishing this with Mapbox GL JS. All I am trying to do is toggle two layers on and off (show and hide) using HTML buttons instead of the links appended to the created CSS menu:
var layers = document.getElementById('menu');
layers.appendChild(link);

I figured I could bind the function to the button element, but cannot get it to work properly:
document.getElementById("toggle-layer-one").onclick = function() {};

HTML:
<button data-balloon="Campsite" data-balloon-pos="right" id="toggle-layer-one"></button>

CSS
#toggle-layer-one {
background-image: url("../Assets/Campsite.svg");
background-size: 70px 70px;
height: 70px;
width: 70px;
border-top: 1px solid #fff;
}

JS
map.on('style.load', function () {
map.addSource("sample", {
    type: "geojson",
    data: "https://raw.githubusercontent.com/aarontaveras/Sample-GeoJSON-Data/master/sample.geojson"
});

map.addLayer({
    "id": "sample-point-one",
    "type": "symbol",
    "source": "sample",
    "filter": ["==", "$type", "Point"],
    "layout": {
        "icon-image": "circle-15",
        "icon-size": 1,
        "icon-anchor": "center",
    }
});

map.setFilter('sample-point-one', ['==', 'region', 'Africa']);

map.addLayer({
    "id": "sample-point-two",
    "type": "symbol",
    "source": "sample",
    "filter": ["==", "$type", "Point"],
    "layout": {
        "icon-image": "circle-15",
        "icon-size": 1,
        "icon-anchor": "center",
    }
});

map.setFilter('sample-point-two', ['==', 'region', 'Asia']);

});

// Toggle layers
var toggleableLayerIds = ["sample-point-one", "sample-point-two"];

for (var i = 0; i < toggleableLayerIds.length; i++) {
var id = toggleableLayerIds[i];

var link = document.createElement('a');
link.href = '#';
link.className = 'active';
link.textContent = id;

link.onclick = function (e) {
    var clickedLayer = this.textContent;
    e.preventDefault();
    e.stopPropagation();

    var visibility = map.getLayoutProperty(clickedLayer, 'visibility');

    if (visibility === 'visible') {
        map.setLayoutProperty(clickedLayer, 'visibility', 'none');
        this.className = '';
    } else {
        this.className = 'active';
        map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
    }
};

var layers = document.getElementById('menu');
layers.appendChild(link);
}

Thanks!

A: I ended up figuring it out.
HTML:
TEST

JS:
var toggleLayerId = ["sample-point-one"];

document.getElementById("test").onclick = function (e){
for (var index in toggleLayerId) {
    var clickedLayer = toggleLayerId[index];
    e.preventDefault();
    e.stopPropagation();

    var visibility = map.getLayoutProperty(clickedLayer, 'visibility');

    if (visibility === 'visible') {
        map.setLayoutProperty(clickedLayer, 'visibility', 'none');
        this.className = '';
    } else {
        this.className = 'active';
        map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
    }
}
};


text:
Q: How to make image from BufferImage I am trying to make image from BufferImage, but it's not working. here is my code ...
This code is not working, can anyone please help me ...
try {

       BufferedImage bimage = (BufferedImage)(new ImageIcon("str")).getImage();

       BufferedImage image = new BufferedImage(500, 500, bimage.TYPE_BYTE_GRAY);
       File outputfile = new File("saved.png");
       ImageIO.write(image, "png", outputfile);
       Image image_1  = ImageIO.read(new File("saved.png"));

       lp2_2.setIcon(new ImageIcon(image_1));

   } catch (IOException e) {}

A: Hopefully this will work better, I have tried it many times.
public void writeImage(String output, String fileName, BufferedImage img) throws IOException {
        File file = new File(output + "\\HE\\" + fileName + ".bmp");
        ImageIO.write(img, "bmp", file);
}

=================================================================================
If you want to use this image in any JPanel then here is code for it, it is already working fine,
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class ShowImage {

    public ShowImage(final String filename) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame editorFrame = new JFrame("My Frame " +filename);
                editorFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                BufferedImage image = null;
                try {
                    image = ImageIO.read(new File(filename));
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
                ImageIcon imageIcon = new ImageIcon(image);
                JLabel jLabel = new JLabel();
                jLabel.setIcon(imageIcon);
                editorFrame.getContentPane().add(jLabel, BorderLayout.CENTER);

                editorFrame.pack();
                editorFrame.setLocationRelativeTo(null);
                editorFrame.setVisible(true);
            }
        });
    }
}

A: Maybe your way of converting IconImage to BufferedImageis not right.
So you can try the following snippet
BufferedImage bi = new BufferedImage(icon.getIconWidth(),icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
icon.paintIcon(null, g, 0,0);
g.dispose();

After this you can use BufferdImage as you are already using.
Or you can look this question Java converting Image to BufferedImage
if you want to see how to convert Image to 'BifferedImage' because as given in this post you can't just cast Image to BufferedImage.
Although i would request you to add more information like what error or exception you are getting and may be if there is an exception add the stacktrace .

A: here is my new code and its working properly ... thank you all for your kind support ...
try{
       BufferedImage cat = ImageIO.read(new File(str));

       for (int w = 0; w < cat.getWidth(); w++) {
       for (int h = 0; h < cat.getHeight(); h++) {
           Color color = new Color(cat.getRGB(w, h));
           //int averageColor = ((color.getRed() + color.getGreen() + color.getBlue()) / 3);
           //int averageColor = int((color.getRed())*0.21 +(color.getGreen())*0.71+(color.getBlue())*0.07);

           double r =color.getRed()*0.21;
           double g =color.getGreen()*0.71;
           double b =color.getBlue()*0.07;
           int averageColor = (int)(r+g+b);

           Color avg = new Color(averageColor, averageColor, averageColor);
           cat.setRGB(w, h, avg.getRGB());
                                               }
                                               }
           ImageIO.write(cat, "jpg", new File("image_greyscale.jpg"));
           lp2_2.setIcon(new ImageIcon((new ImageIcon("image_greyscale.jpg")).getImage().getScaledInstance( 600, 600,  java.awt.Image.SCALE_SMOOTH )));

       }catch(IOException e){
                e.printStackTrace();
                System.exit(1);}

A: Everyone here missed the point.  A BufferedImage is an Image.


text:
Q: What does this tail and head mean in performance's network panel?
I'm trying to improve the performance of my website with chrome devtools, with the performance panel, I saw the network sequence with line in the front and in the end of request, what does these lines mean? Or any document could also help.


text:
Q: Parse nbd.Key(urlsafe=string) externally I am a bit further. I am getting the key representatation in Google Apps Script of a key created with nbd.Key() in python.
When I decode this key, I get an incomplete set of data:
agxzfm92ZXItc2lnaHRyJwsSCEN1c3RvbWVyIghzeXNhZG1pbgwLEglDb25kaXRpb24YpJwBDA

When I convert that back, I get readable entities, but I miss the ID. This is base64decoded:
"js~over-sightr'Customer"sysadmin   Condition��"

Is there a way to get everything back without needing Python?
Old post:

In Google Datastore, a set of scores is saved to the DataStore as
  nbd.jsonProperty.
I can parse this in Google Apps Script, and I get a set of data. Now I
  find for each element the following structure:
[
 {"not_applicable":false,
  "key":"aghxxxxxxxxxxIUXVlc3Rpb24YgICAgPjChAoM",
  "given_score":0
 },
 ...
]

The key here, I can base64decode. I see that I find the related
  question information (the key points to another entity).  It shows a
char+datastoreId+char+kind+?I expect the key here?
Exept, how can I get that last part? The base64 decoder gives stange
  characters for that last part, but I suspect there is the ID as a
  number in there.
I am using Google Apps Script. Can I get this ID from this encoded
  string? I cannot post the whole string, but the last part of the byte
  array is [-128, -128, -128, -8, -62, -124, 10, 12] and I suspect this
  represents the ID.
Any ideas or experience?

A: The URLSafe keys (specific to the Python client library) is a Base64 encoded version of an internal protobuf v1 representation of the Entity Key. It was not designed to be decoded externally.
I don't think Apps Script has an easy way to consume protobuf messages, however you could theoretically implement it by looking at the NDB implementation combined with an understanding of how Protocol Buffers encodes data.