Q: MYSQL Query matching column names to rows in another table I have two tables in MYSQL, one contain a list of options a customer can pick from and the other has the cost of the options. I would like a view that returns the cost of each customers option set. For my example I'll use the analogy of buying a new car.
Customers table
customer - sunroof - mag_wheels - spoiler
--------------------------------------------------
John     - true    - true       - false
Steve    - false   - true       - false
Lucy     - false   - false      - false

Options table
option      - price
-----------------
sunroof     - 100
mag_wheels  - 150
spoiler     -  75

Desired results
customer   - cost
-----------------
John       - 250
Steve      - 150
Lucy       - 0

or this would do, as I good easily multiply selected by price and then group by customer
customer   - option     - selected - price
------------------------------------------
John       - sunroof    - true     - 100
John       - mag_wheels - true     - 150
John       - spoiler    - false    -  75
Steve      - sunroof    - false    - 100
Steve      - mag_wheels - true     - 150
Steve      - spoiler    - false    -  75
Lucy       - sunroof    - false    - 100
Lucy       - mag_wheels - false    - 150
Lucy       - spoiler    - false    -  75

I've been puzzling over this for hours now and I can't even figure out where to start, a join seems out of the question as there are no common elements to match. I wonder if using UNION is the answer but I can't figure out how to combine row values with column headings.
If anyone could point me in the right direction I'd be ever so grateful, double points if you come up with a solution that dynamically picks up the different options so I could add more in the future without rewriting the query.
Many thanks in advance.
The reason I wanted to have all the options as a single row is I was hoping to use Access to make a form for picking the options and I couldn't figure out how a single form could create multiple rows.

A: This is a horrible data layout.  You should have an association table, with one row per customer and option.
But, you can do it:
select c.customer, sum(o.cost) as cost
from customers c left outer join
     options o
     on (c.sunroof = true and o.option = 'sunroof' or
         c.mag_wheels = true and o.option = 'mag_wheels' or
         c.spoiler = true and o.option = 'spoiler'
        )
group by c.customer;

EDIT:
You do not want all options in a single record.  Instead, you need an association table:
create table customer_options (
    customer_optionid unsigned auto_increment,
    customer varchar(255) references customer(name),
    option varchar(255) references option(option)
);

Actually you should really have integer primary keys for all the tables, and use them for the foreign key references.  If you need data in the output in the question, then just write a query to return it in that format.

A: Looking at the table structure, even I think it will not be possible to write joins because as you mentioned, the table structure doesn't have a relation between them.
I am assume you have just started the project, so it's time you first re-visit your DB structure and correct it.
Ideally, you should have a customer table with a customer id.
Then you should have products table with product id.
One table which will have data on what products customers have purchased - something like customer_products. This will be a one to many relation. So customer 1 can have product 1,3 and 5. Which would means in customer_product there will be three entries.
And then when you want to do a sum total, you can first join the table customer, product based on customer_product and then do a sum of the price also to get the total amount for individual customer.

A: Bad design.  You must a have a customers table like this:
custumer_id
customer_name
other fileds...

On the other hand you should have an accesories table,  where you usually describe each item-
accesory_id
accesory_name
supplier_id
country_of_origin
other stuff

Also an accesory_price table,  where prices are added due the fact that prices change.
accesory_id
price
active_price
date_price_added

An finally you should relate all in a customer_accesory table:
customer_id
accesory_id

By having this,  you can join tables and select both customer basket size and customer preferences of accesories.  Basket size,  or the amount purchased by each customer can be summarized  SUM,  AVG,  COUNT or you can pivot data using GROUP_CONCAT in order to generate high quality reports.


Q: Cakephp MYSQL query: SELECT where date is greater than I have to run a MYSQL select query where the query returns all values that have the beginning date 10 days after today. I have tried these two methods none of which seem to work, where do I need to make a change?
$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(['month(date_from)' => 03])
    ->andWhere(['date_from' >= date("Y-m-d",strtotime("+10 days"))])
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

$fix_d_table = TableRegistry::get('fixed_departures');
$f_dates_march = $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(['month(date_from)' => 03])
    ->andWhere(['date(date_from)' >= date("Y-m-d",strtotime("+10 days"))])
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

A: Try below one
$fix_d_table = TableRegistry::get('fixed_departures'); $f_dates_march
= $fix_d_table   ->find("all")
    ->where(['trek_id' => 3])
    ->andWhere(
        function ($exp) {
            return $exp->or_([
                'date_from <=' => date('Y-m-d', strtotime("+10 days")),
                'date_from >=' => date('Y-m-d')
            ]);
    })
    ->order(['date_from'=>'asc'])
    ->select(['date_from', 'date_to', 'seats_available','id'])
    ->toArray();

A: should be
'date_from >=' => date("Y-m-d",strtotime("+10 days"))

if you can rely on mysql server date you can use NOW() inside your query
 ->where(function($exp, $q) {
        return $exp->gte($q->func()->dateDiff([
            'date_from ' => 'identifier',
            $q->func()->now() ]),  10);
    });

this will give you the following SQL condition
WHERE
(
  DATEDIFF(date_from , NOW())
)  >= 10


Q: How to use subqueries in MySQL I have two tables.
Table user:
CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(20) NOT NULL AUTO_INCREMENT,
  `ud_id` varchar(50) NOT NULL,
  `name` text NOT NULL,
  `password` text NOT NULL,
  `email` varchar(200) NOT NULL,
  `image` varchar(150) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB

and mycatch:
CREATE TABLE IF NOT EXISTS `mycatch` (
  `catch_id` int(11) NOT NULL AUTO_INCREMENT,
  `catch_name` text NOT NULL,
  `catch_details` text NOT NULL,
  `longitude` float(10,6) NOT NULL,
  `latitude` float(10,6) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `image` varchar(150) NOT NULL,
  `user_id` int(20) NOT NULL,
  PRIMARY KEY (`catch_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB;
ALTER TABLE `mycatch`
  ADD CONSTRAINT `mycatch_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

My goal is: I want to retrieve longitude and latitude from mycatch against given ud_id (from user) and catch_id (from mycatch) where ud_id = given ud_id and catch_id > given catch_id.
I used the query but fail to retrieve
SELECT ud_id=$ud_id FROM user
WHERE user_id =
(
SELECT user_id,longitude,latitude from mycatch
WHERE catch_id>'$catch_id'
)

The error is:

#1241 - Operand should contain 1 column(s)

A: First, try not to use subqueries at all, they're very slow in MySQL.
Second, a subquery wouldn't even help here.  This is a regular join (no, Mr Singh, not an inner join):
SELECT ud_id FROM user, mycatch
WHERE catch_id>'$catch_id'
AND user.user_id = mycatch.user_id

A:  Select m.longitude,m.latitude from user u left join mycatch m
on u.user_id =m.user_id
where u.ud_id=$ud_id and
m.catch_id >$catch_id


Q: I don't know what to do because an error occurs --> Uncaught TypeError: Cannot read property 'getContext' of null window.onload=function() {
    c=document.getElementById('gc');
    cc=c.getContext('2d')
    setInterval(update,1000/30);
    c.addEventListener('mousemove',function(e) {
        p1y=e.clientY-ph/2;
    });
}

I am creating a pingpong game but as am fixing it an error occurs and I can't solve it. I have an onload but it doesn't work..

A: HTML
Add below code in HTML body
 <body>
        <canvas id="gc"></canvas>
</body>

JS
 <script>
    window.onload=function() {
    c=document.getElementById('gc');
    cc=c.getContext('2d')
    setInterval(update,1000/30);
    c.addEventListener('mousemove',function(e) {
        p1y=e.clientY-ph/2;
    });
   }
</script>


Q: Update grouped records with sequence in sql I have following structure of data in sql table
COL1    COL2    COL2   GRP_ID
A       A       B      100
A       A       B      100
A       A       C      101
A       A       B      100
A       D       E      102
A       D       E      102
F       G       H      103
F       G       H      103

i have the code same this one but it is for oracle,  in sql it is not possible to define a function for next value for. How to change this code for sql?
CREATE FUNCTION NEXT
      RETURN NUMBER IS
      v_nextval NUMBER;
    BEGIN
      v_nextval := NEW_SEQUENCE.nextval;

      RETURN(v_nextval);
   END;
/

UPDATE EXAMPLE
SET EXAMPLE.GroupID =
  (
   SELECT G.GroupID FROM
   (
     SELECT B.Column1, B.Column2, B.Column3, MY_SCHEMA.NEXT() AS GroupID
     FROM EXAMPLE B
     GROUP BY B.Column1, B.Column2, B.Column3
   ) G
   Where G.Column1 = EXAMPLE.Column1 AND G.Column2 = EXAMPLE.Column2
   AND G.Column3 = EXAMPLE.Column3);

SELECT *
FROM EXAMPLE

A: The GRP_ID can be calculated using DENSE_RANK():
select col1, col2, col3,
       dense_rank() over (order by col1, col2, col3) as grp_id
from t;

If you want to update the value, one method is:
update t
    set grp_id = (select count(distinct col1, col2, col3) + 1
                  from t t2
                  where t2.col1 < t.col1 or
                        (t2.col1 = t.col1 and t2.col2 < t.col2) or
                        (t2.col1 = t.col1 and t2.col2 = t.col2 and t2.col3 <= t.col3)
                 );

Note that not all database support count(distinct) on multiple columns.  In those databases, you can concatenate the values together.


Q: flash video smoothing I have a short flv I want to play on my website. I use the below actionscript 2 code to play the video, but the anti-aliasing of text is really poor quality. I added a line to introduce "smoothing" to the video, but it appears to have no visible effect.
var my_video:Video;
var my_nc:NetConnection = new NetConnection();
my_nc.connect(null);
var my_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(my_ns);
my_ns.setBufferTime(2);
my_ns.play("thevideo.flv");
my_video.smoothing = true; //does nothing

Incidentally, I am exporting the flv video from aftereffects, and when I export the movie as a (larger) "lossless" quicktime movie, the movie looks perfect when played in quicktime, but has the same poor anti-aliasing when viewed in adobe media player, VLC, or mplayer.
Any clue on what the problem is, or if there's a better way for me to go about doing this?

A: The smoothing attribute only affects how the video is scaled - that is, whether or not the video is smoothed if you play it at double size or the like. If your Video component is scaled the same size as the source video, this attribute won't do anything.
With that said, please understand that there's no such thing as anti-aliasing going on at the player end of things. Assuming that everything is the right size (so your video isn't being scaled up to 103% or anything), what you see in the Flash player is exactly the data in the source FLV. So any aliasing you see happened when the video was encoded, not at runtime.
So assuming your sizes are right, my guess would be that you should look at the encoding end of things to solve the problem. Is your FLV of a comparable size as the lossless quicktime? If it's a lot smaller, then you're probably compressing it a lot, and increasing the quality settings might help. Likewise, what codec did you use? If you're using the newest codec (H264), the quality ought to be very similar to a quicktime movie of similar size. But the older codecs can have significantly less quality. Especially the old Sorenson Sparc codecs (the ones that require player 6/7 or better to view) are pretty sad by today's standards. And especially the Sorenson codec was heavily customized for low-bandwidths, so even if you encode with very high quality settings you tend to get big increases in file size but very little increase in quality. For these reasons it's highly recommended to make sure you're using the newest codec available for the player version you're targeting.
If none of that helps, please update with some details about what codecs and encode settings you're using.


Q: Retain colour but change transparency in photoshop How can I retain a specific colour of an object (or layer) but change the transparency?
I have 2 objects which I want to have a specific colour but currently the opacity is 100%. I need to maintain the current colours but with a opacity of 50%.
Obviously if I change the opacity the colours change (dependent on the background). I need to know how to get an original colour at 100% opacity to make my desired colour at 50% opacity.

A: Okay so couldn't find a specific way to do it with photoshop so I worked out the math based off the RGB values and came up with a formula to do the job.
For each colour channel I used this formula:
Colour value = Desired Colour + (Background Colour - Desired Colour)*(1-1/Desired Opacity)
eg. 30 = 120 + (255-120)*(1-1/0.6)
Obvious only values between 0-255 are applicable and you may need to round values. This also needs to be done 3 times for red, green and blue.


Q: Multiple iterations of vector with structs "cannot move out of borrowed content" I need to iterate a vector with structs in each iteration in a loop. It works fine as long as the vector doesn't contain structs. I have tried many different solutions but always get some kind of ownership problem.
What am I doing wrong?
struct Element {
    title: String,
}

impl Element {
    pub fn get_title(self) -> String {
        self.title
    }
}

fn main() {
    let mut items: Vec<Element> = Vec::new();
    items.push(Element {
        title: "Random".to_string(),
    });
    items.push(Element {
        title: "Gregor".to_string(),
    });

    let mut i = 0;
    while i < 10 {
        for item in &items {
            println!("Loop {} item {}", i, item.get_title());
        }
        i = i + 1;
    }
}

playground
error[E0507]: cannot move out of borrowed content
  --> src/main.rs:23:44
   |
23 |             println!("Loop {} item {}", i, item.get_title());
   |                                            ^^^^ cannot move out of borrowed content

A: The problem is, that your get_title method consumes the Element and therefore can only be called once.
You have to accept &self as parameter instead and can do the following:
Either return a &str instead of String:
pub fn get_title(&self) -> &str {
    &self.title
}

or clone the String if you really want to return a String struct.
pub fn get_title(&self) -> String {
    self.title.clone()
}

Also have a look at these questions for further clarification:

*

*What are the differences between Rust's `String` and `str`?

*What types are valid for the `self` parameter of a method?

A: Here is a solution to the problem, it required borrowing self object and lifetime specifications.
Moving from &String to &str is only for following better practices, thanks @hellow Playground 2
struct Element<'a> {
    title: &'a str
}

impl <'a>Element<'a> {
    pub fn get_title(&self) -> &'a str {
        &self.title
    }
}

fn main() {
    let mut items: Vec<Element> = Vec::new();
    items.push(Element { title: "Random" });
    items.push(Element { title: "Gregor" });

    let mut i = 0;
    while i < 10 {
        for item in &items {
            println!("Loop {} item {}", i, item.get_title());
        }
        i = i + 1;
    }
}


Q: Ant  and  sqlcmd - Different Outputs I have one .sql file that is execute using ant, when I execute it with the  tag I recived a different output as when i used  calling "sqlcmd".
sql tag output:
  [sql] Executing resource: C:\SqlTesting\TestScriptDependencies\Executor.sql
  [sql] Failed to execute:  Use Library Exec CallSelectSP
  [sql] com.microsoft.sqlserver.jdbc.SQLServerException: Invalid object name'Libraty.dbo.libraryDocumentType'.
  [sql] 0 of 1 SQL statements executed successfully

exec tag output:
 [exec] First SP
 [exec] Msg 208, Level 16, State 1, Server MyPC-PC, Procedure getFirstDocumentType, Line 3
 [exec] Invalid object name 'Libraty.dbo.libraryDocumentType'.
 [exec] Second SP
 [exec] Msg 208, Level 16, State 1, Server MyPC-PC, Procedure badSP, Line 3
 [exec] Invalid object name 'Libraty.dbo.libraryDocumentType'.

And this is the .sql file.
Print 'First SP'
Exec getFirstDocumentType
Print 'Second SP'
Exec badSP
Go

I wonder if it is a way of the SQL tag reproduce the same output as the EXEC tag.
Thanks.

A: Looks like the first one is submitting the whole script as a single batch via jdbc. Whereas the second appears to be sending each sql statement via sqlcmd - hence the print statements succeed (and result in synchronized output - which is not always guaranteed with print - raiserror(str, 10, 1) with nowait; is the only guarantee of timely messaging) and both sp calls are attempted, each producing their own (sql) error.


Q: log4j.properties file disappears in the project/Classes location I'm configuring log4j in my standalone Java project. I created the property file under project/classes folder but everyday when I run the my application I get errors like
log4j:WARN No appenders could be found for logger (cafcontroller.CAFController).
log4j:WARN Please initialize the log4j system properly.

Then when I check the project/classes folder I find the log4j.properties file missing. Then I create one manually in it. I don't understand why it goes missing.
Please help me to fix this .

A: Whenever you rebuild your project, classes folder gets completely refreshed, deleting and recreating all the class files. Put your log4j.properties file inside your project/src folder. It will be copied to your classes folder on rebuild.


Q: List available library - SQL Linked Server AS400 I'm using SQL server 2005 (64bit version) and have successfully connect to as400 using IBM DB2 UDB for iSeries IBMDA400 OLE DB Provider.
Anyone know how to list available library/table and get the field name & description?
already looking around, and have tried this query, but still no luck
select * from OpenQuery(AS400, 'select * from QSYS.qadbxatr');

A: The information is available through the catalog views in the SYSIBM schema.
Schema (library) information is available in SQLSCHEMAS.
Table (file) information is available in SQLTABLES.
Column (field) information is available in SQLCOLUMNS.

*

*V7R1: IBM i catalog tables and views

*V5R4: ODBC and JDBC catalog views


Q: Using sqlite how can i update or insert to a table using a condition? Having a blank table with three columns
CREATE TABLE AssyData    ( AID int NOT NULL PRIMARY KEY UNIQUE , MaxDef float  , MaxDefLC int  , MaxDefNID int , Comps text , SubAssys text )

I would like to Update or insert new values if the new MaxMag is larger than the current one and if the AID is the same. AID is a unique Primary key. Assuming an AID of 100 I have tried the following, but with no success:
INSERT INTO AssyData
(AID  , MaxDef  , MaxDefLC  , MaxDefNID , Comps  , SubAssys)
VALUES( 100 , 101 , 202 , 203 , "" , "")
ON CONFLICT(AID)
DO UPDATE
SET
MaxDef = excluded.MaxDef ,
MaxDefNID = excluded.MaxDefNID ,
MaxDefLC = excluded.MaxDefLC ,
Comps = excluded.Comps ,
SubAssys = excluded.SubAssys
WHERE excluded.MaxDef > 100

I get the error "near "ON": syntax error"
What is wrong with my statement?
Thanks Shawn for the Approach.

A: Assuming you're using a somewhat recent (3.24 or newer) version of sqlite, you can use what's known as UPSERT:
INSERT INTO AssyData(AID, MaxMag, MaxDefNID) VALUES (?, ?, ?)
ON CONFLICT(AID) DO UPDATE SET MaxMag = excluded.MaxMag
                             , MaxDefNID = excluded.MaxDefNID
                    WHERE excluded.MaxMag > MaxMag;

A: In case your vesrsion of SQLite does not allow the use of UPSERT you can achieve what you need in 2 steps:
INSERT OR IGNORE INTO AssyData
(AID, MaxDef, MaxDefLC, MaxDefNID, Comps, SubAssys)
VALUES(100, 111, 202, 203, '', '');

This INSERT OR IGNORE will fail without an error if you try to insert a row with an AID that already exists in the table.
Then:
UPDATE AssyData
SET
  MaxDef = 111,
  MaxDefLC = 202,
  MaxDefNID = 203,
  Comps = '',
  SubAssys = ''
WHERE AID = 100 AND MaxDef < 111;

This will fail if the row to be updated contains MaxDef equal or greater than the value 111.
See the demo.
In general such code needs special care when implemented, because as you can see the value  of MaxDef (111 in this example) must be set 3 times.


Q: Adding new server to Farm not firing event receivers Experts-
We have deployed WSP (with features and feature activation event receivers) in farm environment. Event receivers creates timer jobs to perform few changes to all servers in farm.
Issue:
When new server is added to farm, WSP is getting deployed automatically(can see deployed files), but event receivers are not being fired on newly added server. Hence missing our project related configuration changes in new server.
Please suggest .
Bala


Q: Oracle Apex Office Print: cannot generate excel report when source query returns null value I have a query very similar to this test query:
select
'file1' as "filename",
cursor (
    select
        cursor (
            select
                cursor (
                    select
                        'Test Customer' as CUSTOMER,
                        'Test Country' as COUNTRY,
                        'Test Port' as PORT
                    from
                        dual
                    where
                        1 = 2
                ) as "table_without_rows",
                cursor (
                    select
                        'Test Customer' as CUSTOMER,
                        'Test Country' as COUNTRY,
                        'Test Port' as PORT
                    from
                        dual
                    where
                        1 = 1
                ) as "table_with_rows"
            from
                DUAL
        ) as "list"
    from
        DUAL
    ) as "data"
from
    DUAL

Using AOP PLSQL api I am able to generating a report but with no data in it. If all the cursors return rows it works correctly. As its not throwing any errors I am not sure what is causing this behavior.
The template structure for excel file is given below:
{#list}{#table_without_rows}..(Column names)..{/table_without_rows}
... Some text and styles ...
{#table_with_rows}..(Column names)..{/table_with_rows}{/list}

(edited)
Apex Version: 5.1.3.00.05
AOP Version: 3.0

A: which version of AOP are you using? does the error occur if you set the AOP url to apexofficeprint.com/api?
if you set the debugging to local from the AOP components settings, you should receive a JSON, if you send it to support@apexofficeprint.com we would gladly help you out with this issue.
EDIT: Bug on version 3.0, issue was fixed from version 3.1.


Q: macOS terminal asking for password every time I run copy command I'm running a bash command on mac that moves a file to private/etc/app_name/.
sudo cp my_file.cpp private/etc/app_name/

Every time the I want to run the bash file, the OS asks for my system password.
> ./run_copy.sh
Password: *******

Is there a way to by-pass this or configure in such way that I only have to enter the password once.

A: Apparently, on my Macbook, I see /etc directory having symlinks with the /private/etc directory which is owned by the wheel group & root is part of that group. So, you would need to use sudo to copy to that directory.
With that said on a Linux machine, you can work around this by adding your group to a new file in the /etc/sudoers.d/<group-name> path.
<grp-name> ALL=(ALL) NOPASSWD:ALL

I've just tried this on my mac, I could copy files onto /private/etc directory without entering the sudo password prompt.
Unfortunately, this comes up with some risks as users of your group get privileged access without entering any password prompt. You might accidentally delete important system files etc.,
A more niche approach could be to allow selectively like <group> ALL = (ALL) NOPASSWD: /usr/local/bin/copy-script. This way, they can't run all scripts/commands with sudo privileges.


Q: MS-DOS delete with wildcards on ends What I want is a wildcard that means "contains"
So if I have a directory with
a.txt
b.param
b.param.config

I would like to delete only b.param and b.param.config
I have tried del *.param*, del *param* ... but nothing seems to match anything for the beginning and end of the file but containing param.
I am running the command from a batch file, so if the solution is in batch that will work as well.

A: I think del *param* should work for this...
c:\test>dir /w
 Volume in drive C is HP
 Volume Serial Number is 0EBF-B242

 Directory of c:\test

[.]              [..]             a.txt            b.param
b.param.config
               3 File(s)             29 bytes
               2 Dir(s)  185,518,833,664 bytes free

c:\test>dir /w *param*
 Volume in drive C is HP
 Volume Serial Number is 0EBF-B242

 Directory of c:\test

b.param          b.param.config
               2 File(s)             20 bytes
               0 Dir(s)  185,518,833,664 bytes free

c:\test>del *param*

c:\test>dir /w
 Volume in drive C is HP
 Volume Serial Number is 0EBF-B242

 Directory of c:\test

[.]     [..]    a.txt
               1 File(s)              9 bytes
               2 Dir(s)  185,518,833,664 bytes free

What happened when you tried this? What version of MS-DOS are you running?


Q: How can I allow multiple users to access the same amazon instance at the same time? I am new to Amazon Cloud, and trying to create an EC2 instance that can allow multiple users to access at the same time.
While there are plenty of documentations, I haven't found an answer to my question. Whenever those documentations say "user", it refers me. But I want to have an application installed in the instance, and allow more than one of my users to access it simultaneously.
How can I achieve this? Thank you very much!

A: The same way you would add multiple users to a normal instance. I am going to assume you are using linux and can login to the instance, if not, see this post. Now you just need to add a user, and setup the ssh keys.


Q: Get substring with code from different strings I'm working on a web scraper. Among the fields it scrapes there is a Description tag like this one, different for each product:

Black Tshirt

REF.: V23T87C88EC

COMPOSIÇÃO:

90% Poliamida

I can get the content of the description tag without problems, but I also need to get the value of REF inside the description (V23T87C88EC for this example).
The problem is this description is always different for all products, HOWEVER there is ALWAYS a "REF.: XXXXXXXXX" substring in there.
The length of the REF id can change, and it can be anywhere in the string.
What's the best way to always get the REF id?

A: Possible solution is the following:
html = """

Black Tshirt

REF.: V23T87C88EC

COMPOSIÇÃO:

90% Poliamida

"""

import re

pattern = re.compile(r'REF\.: (.+?)$')

found = pattern.findall(html)

Returns ['V23T87C88EC']

REGEX DEMO

A: You can do this with a regex (read more about regex: https://docs.python.org/3/howto/regex.html) :
html = '''

Black Tshirt

REF.: V23T87C88EC

COMPOSIÇÃO:

90% Poliamida

'''

import re

myref = re.search (r"(?<=REF.: )\w+", html)[0]

print(myref)

# V23T87C88EC


Q: Using VBS Script in AAE and getting 1024 Expect Statement I am new to coding in VBS and all the time I am getting 1024 Expect Statement Error in my VBScript. If anyone could point me where is a mistake I would be gratefull.
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
objExcel.Visible = True
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

Till filtering part everything goes correct. When I try to run filtering part as a Macro in Excel it works but when I am implementing it into Script it throws me an error.

A: In VBScript, you don't have to mention the name of the parameters while calling a function/method. You just need to pass the values. The parameters names are required in excel-vba, not in VBScript.
So, try replaying,
Worksheets("PO Buy Update").Range("H3").AutoFilter Field:=8, Criteria1:="<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter Field:=17, Criteria1:="<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter Field:=16, Criteria1:=">=" & BeginDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

with
Worksheets("PO Buy Update").Range("H3").AutoFilter 8,"<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17,"<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16,">=" & BeginDate,1,"<=" & EndDate

Reference to the Autofilter Method
Reference to the enumerated constant xlAnd

A: VBScript can't handle named parameters. Change the last lines to
Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"
Worksheets("PO Buy Update").Range("Q3").AutoFilter 17, "<>"
Worksheets("PO Buy Update").Range("P3").AutoFilter 16, ">=" & BeginDate, xlAnd, "<=" & EndDate

and it'll hopefully get you a step closer. You might need to define xlAnd and other constants as well.

A: VBScript, as the other answers state, does not handle the named parameters.
Therefore it doesn't know what you mean by Worksheets.  They will need to be fully qualified as references belonging to the parent objWorkbook object.
objWorkbook.Worksheets("PO Buy Update").Range("H3").AutoFilter 8, "<>"

will work just fine.  You will need to replace any and all excel named values (such as xlAnd) with the enumerated value equivalent, or declare them as constants and set the value to match the enumerated value if you want to use the named parameter.

A: Thanks for your answers and pointing me, my mistakes. My final solution is below
Dim Path
Dim BeginDate
Dim EndDate
Path = WScript.Arguments.Item(0)
BeginDate = WScript.Arguments.Item(1)
EndDate = WScript.Arguments.Item(2)
Set objExcel = CreateObject("Excel.Application")
Set objWorkBook = objExcel.Workbooks.Open(Path)
Set c=objWorkBook.Worksheets("PO Buy Update") // Attached WorkbookSheet(name) into variable and then specified which row, column is a header
objExcel.Visible = True
c.cells(3,8).AutoFilter 8, "<>"
c.cells(3,17).AutoFilter 17, "<>"
c.cells(3,16).AutoFilter 16, ">=" & BeginDate, 1, "<=" & EndDate

I believe my main problem was that I have header in third row and when I did not specified that Script was searching for filtering option in first row.
Once again thanks for your time !


Q: Find certain value/element in two-dimensional ArrayList I have a two dimensional arraylist
List<List<String>> movies_info = new ArrayList<>();

which I populate creating new rows
movies_info.add(new ArrayList<String>());

and adding elements
movies_info.get(i).add(title);

.
I would like to be able to check if the element I'm adding already exist in the entire ArrayList. Is it possible to achieve this result without using the following for.loop?
boolean found = false;
for (int i = 0; i < movies_info.size(); i++) {
    if(movies_info.get(i).contain(title)) {
    found = true;
}
if (!found) {
    movies_info.add(new ArrayList<String>());
    movies_info.get(i).add(title);
}

A: You can replace your second ArrayList by a HashMap  and check if it is already there.
movies_info.add(new HashMap<String,String>());

if (!movies_info.get(i).containsKey(title)){
    movies_info.get(i).put(title,title);
}

Both the search for a key in the HashMap and also adding a new element have constant time complexity O(1)
To get the values afterwards you can use this code
for (String title : movie_info.get(i).keySet()){
      // Use title
}

A: I would suggest a different approach. Instead of creating a list of lists of String-s, you can have a class called Movie and create a list of Movie objects. Then you can directly query the list by calling the contains method.
Note: you need to override two methods in the Movie class, hashCode and equals, for the contains method to work. By overriding these two methods, you will tell the list object how to compare two Movie objects.
UPDATE: you don't have to manually write the equals and hashCode methods (at least not if you are using the Eclipse IDE). You can just right-click anywhere inside the class's body and choose Source -> Generate hashCode and equals ..., it will prompt you on which fields of the class you want to compare two objects, select the fields, hit OK and off you go, these two methods will be automatically generated for you.
Here's a simple example:
public class Movie
{
    String title;

    public Movie(String t)
    {
        this.title = t;
    }

    public String getTitle()
    {
        return title;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Movie other = (Movie) obj;
        if (title == null)
        {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        return true;
    }
}

You can test it like this:
import java.util.ArrayList;
import java.util.List;

public class Test
{
    public static void main(String[] args)
    {
        List<Movie> movies = new ArrayList<Movie>();
        movies.add(new Movie("Movie 1"));
        movies.add(new Movie("Movie 2"));

        System.out.println(movies.contains(new Movie("Movie 1")));
    }
}

A: Something like this? it simplifies a bit..
for(List<String> mInfo : movies_info) {
   if(!mInfo.contains(title)) {
      //do stuff
   }
}


Q: Is it possible to make fast big circular buffer arrays for stream recording in Haskell? I'm considering converting a C# app to Haskell as my first "real" Haskell project.  However I want to make sure it's a project that makes sense.  The app collects data packets from ~15 serial streams that come at around 1 kHz, loads those values into the corresponding circular buffers on my "context" object, each with ~25000 elements, and then at 60 Hz sends those arrays out to OpenGL for waveform display.  (Thus it has to be stored as an array, or at least converted to an array every 16 ms).  There are also about 70 fields on my context object that I only maintain the current (latest) value, not the stream waveform.
There are several aspects of this project that map well to Haskell, but the thing I worry about is the performance.  If for each new datapoint in any of the streams, I'm having to clone the entire context object with 70 fields and 15 25000-element arrays, obviously there's going to be performance issues.
Would I get around this by putting everything in the IO-monad?  But then that seems to somewhat defeat the purpose of using Haskell, right?  Also all my code in C# is event-driven; is there an idiom for that in Haskell?  It seems like adding a listener creates a "side effect" and I'm not sure how exactly that would be done.

A: Look at this link, under the section "The ST monad":
http://book.realworldhaskell.org/read/advanced-library-design-building-a-bloom-filter.html

Back in the section called “Modifying array elements”, we mentioned
  that modifying an immutable array is prohibitively expensive, as it
  requires copying the entire array. Using a UArray does not change
  this, so what can we do to reduce the cost to bearable levels?
In an imperative language, we would simply modify the elements of the
  array in place; this will be our approach in Haskell, too.
Haskell provides a special monad, named ST, which lets us work
  safely with mutable state. Compared to the State monad, it has some
  powerful added capabilities.
We can thaw an immutable array to give a mutable array; modify the
  mutable array in place; and freeze a new immutable array when we are
  done.

...

The IO monad also provides these capabilities. The major difference between the two is that the ST monad is intentionally designed so that we can escape from it back into pure Haskell code.

So should be possible to modify in-place, and it won't defeat the purpose of using Haskell after all.

A: Yes, you would probably want to use the IO monad for mutable data.  I don't believe the ST monad is a good fit for this problem space because the data updates are interleaved with actual IO actions (reading input streams).  As you would need to perform the IO within ST by using unsafeIOToST, I find it preferable to just use IO directly.  The other approach with ST is to continually thaw and freeze an array; this is messy because you need to guarantee that old copies of the data are never used.
Although evidence shows that a pure solution (in the form of Data.Sequence.Seq) is often faster than using mutable data, given your requirement that data be pushed out to OpenGL, you'll possible get better performance from working with the array directly.  I would use the functions from Data.Vector.Storable.Mutable (from the vector package), as then you have access to the ForeignPtr for export.
You can look at arrows (Yampa) for one very common approach to event-driven code.  Another area is Functional Reactivity (FRP).  There are starting to be some reasonably mature libraries in this domain, such as Netwire or reactive-banana.  I don't know if they'd provide adequate performance for your requirements though; I've mostly used them for gui-type programming.


Q: FileNotFoundException when calling C# dll from C++/CLI I have a C# dll, with some methods, which I am trying to access in my native project with /CLR support.
I reference this DLL using a #using directive, and the DLL is recognized and the project compiles.
However, during runtime, I get a FileNotFoundException, which is pretty weird since the DLL is present in the source directory of the project.
TheDLL is compiled inVS 2015 with .NET Version 4.5.2. Since I have CLR support on my C++ mixed, I have edited the project file to make TargetFrameworkVersion as 4.5.2, but still the runtime does not work.
Kindly advise on what could be the issue?
EIDT - ADDED SOME CODE
C#
namespace TestManagedLibrary
{
    public class Class1
    {
        public int i;
        public Class1()
        {
            i = 5;
        }

        public int returnValue()
        {
            return i;
        }
    }
}

C++/CLI
#using <TestManagedLibrary.dll>

using namespace System;
using namespace System::Runtime::InteropServices; // Marshal
using namespace TestManagedLibrary;

ref class ManagedFoo
{
public:
    ManagedFoo()
    {
        Console::WriteLine(_T("Constructing ManagedFoo"));
        Class1 ^testObject = gcnew Class1();
        int a = testObject->returnValue();
    }
};

A: First of all you need to ensure that the TestManagedLibrary.dll file is located in a place where Fusion could find it. Your first try should be the location of the executable you are running.
One way to handle this is via the reference properties. If the reference to your TestManagedLibrary.dll is set with the copy local flag than during the build the referenced library is going to be copied from the referenced location to the output directory.
You can enable the internal fusion logging to find out the details:

*

*Run Developer Command Prompt with administrative privileges.

*Run fuslogvw

*In the Assembly Binding Log Viewer hit settings and set either Log bind failures to disk or Log all binds to disk.

*Start your service

*Hit Refresh in the Assembly Binding Log Viewer, pick your executable and hit View Log

A: The compiled DLL should have been in the same location as the executable for the CLR to search for it. In my case, the .NET compiled DLL was in the solution folder and not searchable.


Q: Getting Index of an Object from NSArray? i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for testing purposes i am having an array with values {57,56,58..} to get an index of lets say 56,
NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger Aindex = [myArray indexOfObject:num];
NSLog(@" %d",Aindex);

the value i get is something like 2323421. what am i possibly doing wrong??

A: NSNumber *num1 = [NSNumber numberWithInt:56];
    NSNumber *num2 = [NSNumber numberWithInt:57];
    NSNumber *num3 = [NSNumber numberWithInt:58];
    NSMutableArray *myArray = [NSMutableArray arrayWithObjects:num1,num2,num3,nil];
    NSNumber *num=[NSNumber numberWithInteger:58];

    NSInteger Aindex=[myArray indexOfObject:num];

    NSLog(@" %d",Aindex);

Its giving the correct output, may be u have done something wrong with storing objects in ur array.

A: Try this:
NSArray's indexOfObject: method. Such as the following:
NSUInteger fooIndex = [someArray indexOfObject: someObject];

A: Folks,
When an object is not found in the array the indexOfObject method does NOT return a 'garbage' value. Many systems return an index of -1 if the item is not found.
However, on IOS - because the indexOfObject returns an UNSIGNED int (aka NSUInteger) the returned index must be greater than or equal to zero. Since 'zero' is a valid index there is no way to indicate to the caller that the object was not found -- except by returning an agreed upon constant value that we all can test upon. This constant agreed upon value is called NSNotFound.
The method:
- (NSUInteger)indexOfObject:(id)anObject;

will return NSNotFound if the object was not in the array. NSNotFound is a very large POSITIVE integer (usually 1 minus the maximum int on the platform).

A: The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
The garbage value you get is probably equal to NSNotFound.
Try testing anIndex against it. The number you are looking for isn't probably in your array :
NSNumber *num=[NSNumber numberWithInteger:56];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
    NSLog(@"not found");
}

or log the content of the array to be sure :
NSLog(@"%@", myArray);

A: If you're using Swift and optionals make sure they are unwrapped.  You cannot search the index of objects that are optionals.

A: I just checked. Its working fine for me. Check if your array has the particular number. It will return such garbage values if element is not present.

A: indexOfObject methord will get the index of the corresponding string in that array if the string is like @"Test" and you find like @"TEST" Now this will retun an index like a long number


Q: MKMapView zoom User Location and Annotation I want my MKMapView to zoom 'User Location' and the Annotation as close as possible.
The map already show both, but is zoomed out to the whole country.
How can I do that?
And I don’t know why the Annotation and Pin are not animated.
My Code:
//Coords User
CLLocationCoordinate2D user_location;
user_location.latitude = mapView.userLocation.location.coordinate.latitude;
user_location.longitude = mapView.userLocation.location.coordinate.longitude;
//Coords Annotation
CLLocationCoordinate2D club_location;
club_location.latitude = [self.clubInfo.latitude doubleValue];
club_location.longitude = [self.clubInfo.longitude doubleValue];

MKMapPoint userPoint = MKMapPointForCoordinate(user_location);
MKMapPoint annotationPoint = MKMapPointForCoordinate(club_location);

MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);

MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);

MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];

// Add an annotation
MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
annotation.coordinate = club_location;
annotation.title = self.clubInfo.clubName;
annotation.subtitle = @"Pin!";
[mapView addAnnotation:annotation]; // This was missing
[mapView selectAnnotation:annotation animated:YES];

Logs:
userRect: {{134217728.0, 134217728.0}, {0.0, 0.0}}
annotationRect: {{99775488.0, 152579328.0}, {0.0, 0.0}}

unionRect: {{99775488.0, 134217728.0}, {34442240.0, 18361600.0}}

mapView.visibleMapRect: {{96025087.6, 116070015.1}, {41943040.7, 54657025.8}}

A: If I understand well, you want those two annotations to be visible with maximum possible zoom. I found this solution that does not reqire any calculations.
// You have coordinates
CLLocationCoordinate2D user = ...;
CLLocationCoordinate2D annotation = ...;
// Make map points
MKMapPoint userPoint = MKMapPointForCoordinate(user);
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation);
// Make map rects with 0 size
MKMapRect userRect = MKMapRectMake(userPoint.x, userPoint.y, 0, 0);
MKMapRect annotationRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0);
// Make union of those two rects
MKMapRect unionRect = MKMapRectUnion(userRect, annotationRect);
// You have the smallest possible rect containing both locations
MKMapRect unionRectThatFits = [mapView mapRectThatFits:unionRect];
[mapView setVisibleMapRect:unionRectThatFits animated:YES];

CoreLocation and MapKit structures are hell.

A: For anyone coming here later: The shortest way of doing this is (iOS7+) this:
Assuming you have a @property MKMapView *mapView, and an MKPointAnnotation *theAnnotation, call:
[self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO];

Now this could cause some problems if called too early (i.e. when self.mapView.userLocation is not yet set). If so, you can call in viewWillAppear:
[self.mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL];

Then, implement:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"location"]) {
        [self.mapView showAnnotations:@[theAnnotation, self.mapView.userLocation] animated:NO];
    }
}

That way you're sure it's set. Don't forget to remove the observer at viewWillDisappear:
[self.mapView.userLocation removeObserver:self forKeyPath:@"location"];

A: Use these 4 classes - it works like a charm!
//MapViewController.h file

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController <CLLocationManagerDelegate>  {
    IBOutlet UIButton *buttonBack;
    IBOutlet MKMapView *mapView;
    IBOutlet UILabel *labelTitle;
    NSString *lon,*lat,*nickName;
    BOOL isFirstLaunch;
}
@property(nonatomic,retain) NSString *lon,*lat,*nickName;
@property(nonatomic,retain) IBOutlet UIButton *buttonBack;
@property(nonatomic,retain) IBOutlet UILabel *labelTitle;
@property(nonatomic,retain) IBOutlet MKMapView *mapView;
-(IBAction)buttonBackAction:(UIButton *)_btn;
-(void)zoomToFitMapAnnotations;
@end

//
//  MapViewController.m
//
#import "MapViewController.h"
#import "Annotation.h"

@implementation MapViewController
@synthesize buttonBack,mapView,labelTitle;
@synthesize lon,lat,nickName;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */
-(IBAction)buttonBackAction:(UIButton *)_btn{
    [self.navigationController popViewControllerAnimated:1];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    CLLocationManager* locationManager = [[CLLocationManager alloc] init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [locationManager startUpdatingLocation];
    NSLog(@"MapViewController");
    labelTitle.text = @"anscacorona.blogspot.in"
    CLLocationCoordinate2D location;
    location.latitude = [self.lat floatValue];
    location.longitude = [self.lon floatValue];

    Annotation *annotation = [[Annotation alloc] init];
    annotation.theCoordinate = location;
    annotation.theTitle = [NSString stringWithFormat:@"%@",labelTitle.text];

    [mapView addAnnotation:annotation];
    [annotation release];
    mapView.showsUserLocation = 1;

    [self zoomToFitMapAnnotations];
    [super viewDidLoad];
}

// Shows the location of both users. called when the device location changes to move the map accordinly. necessary ONLY once when the window is opened. afterwards the user can move the map as he choises.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    if (isFirstLaunch) {
        CLLocationCoordinate2D topLeftCoord;
        CLLocationCoordinate2D bottomRightCoord;

        topLeftCoord.longitude = fmin([self.lon floatValue], newLocation.coordinate.longitude);
        topLeftCoord.latitude = fmax([self.lat floatValue], newLocation.coordinate.latitude);

        bottomRightCoord.longitude = fmax([self.lon floatValue], newLocation.coordinate.longitude);
        bottomRightCoord.latitude = fmin([self.lat floatValue], newLocation.coordinate.latitude);

        MKCoordinateRegion region;
        region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
        region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
        region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5; // Add a little extra space on the sides
        region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5;  // Add a little extra space on the sides

        region = [mapView regionThatFits:region];
        [mapView setRegion:region animated:YES];
        isFirstLaunch = NO;
    }

}

-(void)zoomToFitMapAnnotations
{
    if([mapView.annotations count] == 0)
        return;

    CLLocationCoordinate2D topLeftCoord;
    CLLocationCoordinate2D bottomRightCoord;
    topLeftCoord.longitude = fmin(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
    topLeftCoord.latitude = fmax(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);

    bottomRightCoord.longitude = fmax(mapView.userLocation.location.coordinate.longitude, [self.lon floatValue]);
    bottomRightCoord.latitude = fmin(mapView.userLocation.location.coordinate.latitude, [self.lat floatValue]);

    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };

    CLLocationCoordinate2D userCoord = {[self.lat floatValue],[self.lon floatValue]};
    region.center = userCoord;
    region.span.latitudeDelta = 0.05f;//fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = 0.05f;//fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;  // Add a little extra space on the sides

    [mapView setRegion:region animated:YES];
    [mapView regionThatFits:region];
}
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc. that aren't in use.
}
#pragma mark - View Lifecycle

-(void)viewWillAppear:(BOOL)animated{
    isFirstLaunch=YES;
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {

    [super dealloc];
}

@end

//anotation classes- Annotation.h
#import <MapKit/MapKit.h>

@interface Annotation : NSObject  <MKAnnotation>{
    CLLocationCoordinate2D theCoordinate;
    NSString *theTitle;
    NSString *restId;
    NSString *theSubtitle;
}
@property(nonatomic,retain) NSString *restId;
@property(nonatomic,retain) NSString *theTitle;
@property(nonatomic,retain) NSString *theSubtitle;
@property CLLocationCoordinate2D theCoordinate;
@end

//Annotation.m
#import "Annotation.h"

@implementation Annotation
@synthesize theCoordinate,theTitle,theSubtitle,restId;
- (CLLocationCoordinate2D)coordinate;
{
    return theCoordinate;
}

// required if you set the MKPinAnnotationView's "canShowCallout" property to YES
- (NSString *)title
{
    return theTitle;
}

// optional
- (NSString *)subtitle
{
    return theSubtitle;
}

- (void)dealloc
{
    [super dealloc];
}

@end


Q: Datadog: How to automate configuring Log Archives How can I automate configuring Log Archives on GCP?
I can do it manually by following steps
https://docs.datadoghq.com/logs/archives/?tab=googlecloudstorage
I guess selenium can help this
but I looking for a more programmatic way like Terraform or REST API
Thank you.

A: I’m not sure if it is a recent addition, but the Datadog public API supports configuring Log Archives: https://docs.datadoghq.com/api/latest/logs-archives/
You can also use tools like Terraform to configure them: https://registry.terraform.io/providers/DataDog/datadog/latest/docs/resources/logs_archive (it uses the Datadog API internally)


Q: JComboBox - out of bounds exception i have a small problem. I'm trying to import logins from my database to a vector and then to use that vector for JComboBox. My method for downloading logins :
public void loginReader (Vector<String> loginy, String tableName)
{
    String query = "select login from " + tableName;

    try {

        Statement statement = mConnection.createStatement();
        ResultSet rs = statement.executeQuery(query);
        while (rs.next())
            {
             Vector<String> vstring = new Vector<String>();

                vstring.add(rs.getString("login"));

                loginy.addAll(vstring);
            }
        } catch (SQLException e)
            {
                e.printStackTrace();

            }
}

That's in class DatabaseManagement. I made another class (GUI) and there's that JComboBox. Why it doesn't work ?
package DataBase_Hospital;

 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.SQLException;
 import java.text.ParseException;
 import java.util.Properties;
 import java.util.Vector;

 import javax.swing.ImageIcon;
 import javax.swing.JButton;
 import javax.swing.JComboBox;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JScrollPane;
 import javax.swing.JTextArea;
 import javax.swing.JTextField;

 public class Message extends JFrame implements ActionListener {

JButton SEND_MESSAGE;
JButton READ_MESSAGE;
public JLabel background;

JLabel NAME_LABEL;

JTextField NAME_FIELD;

JTextArea DATABASE_FIELD;
static Vector<String> loginy = new Vector<String>();

private static DatabaseManagement DATABASE;

public Message() {

    setSize(290, 500);
    setTitle("Message Panel");

    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    JLabel background=new JLabel(new ImageIcon("/Users/Dominik/Desktop/messageFrame.png"));
    add(background);

    DATABASE_FIELD = new JTextArea(3,3);
    JScrollPane scrollPane = new JScrollPane(DATABASE_FIELD);
    scrollPane.setBounds(45, 50, 200, 200);
    background.add(scrollPane);
    DATABASE_FIELD.setEditable(true);

    NAME_LABEL = new JLabel("Odbiorca :");
    NAME_LABEL.setBounds(40, 380, 140, 20);
    background.add(NAME_LABEL);

    SEND_MESSAGE = new JButton();
    SEND_MESSAGE.setIcon(new ImageIcon("/Users/Dominik/Desktop/sendMail.jpg"));
    SEND_MESSAGE.setBounds(75, 270, 60, 60);
    background.add(SEND_MESSAGE);
    SEND_MESSAGE.addActionListener(this);
    SEND_MESSAGE.setToolTipText("Send message");

    READ_MESSAGE = new JButton();
    READ_MESSAGE.setIcon(new ImageIcon("/Users/Dominik/Desktop/jwj.png"));
    READ_MESSAGE.setBounds(150, 270, 60, 60);
    background.add(READ_MESSAGE);
    READ_MESSAGE.addActionListener(this);
    READ_MESSAGE.setToolTipText("Read message");

  JComboBox loginList = new JComboBox(loginy);
  loginList.setSelectedIndex(loginy.capacity());
  loginList.addActionListener(this);
  loginList.setBounds(145, 380, 100, 20);
  background.add(loginList);

}

public static void main(String[] args) {

    Message window = new Message();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    DATABASE.loginReader(loginy,"uzytkownicy");
}

public void actionPerformed(ActionEvent e)
{
    Object EVENT_SOURCE = e.getSource();
    DATABASE = new DatabaseManagement("pacjent");

    if (EVENT_SOURCE == SEND_MESSAGE)
    {
        DATABASE.sendMessage(DATABASE_FIELD.getText(), "uzytkownicy", NAME_FIELD.getText()) ;
    }

}
}

A: After creating your JComboBox with your empty Vector, you set the selectedIndex to loginy.capacity (). The problem is that while the capacity of your Vector is 10 (as stated in the JavaDoc for the default constructor), it's actual size is 0. Hence the ArrayOutOfBoundsException. You should check for the size of your Vector before setting the selected index of your JComboBox.

A: I suspect the problem is you are trying to set the selected index of your combo box to the capacity of your vector.
loginList.setSelectedIndex(loginy.capacity());

From the docs .capacity():

Returns the current capacity of this vector.
  Returns:
  the current capacity (the length of its internal data array, kept in the field elementData of this vector)

This is not the size i.e. the number of logins in your database. this is the capacity of internal datastructure which will always be >= the number of elements in the vector.
Try using Vector#size() but you will still need to subtract one (provided there is actually data in the vector) from this so your code should be:
loginList.setSelectedIndex(loginy.size() - 1);

And this will set the last login in the comboBox. Which is not required in your case as you are populating the vector after creating the combobox so you could just remove this line from your code until you populate the vector.

Edit as per comments
All you should need to do to have the logins is reorder the execution order. I.e populate your vector then create your combo box, Change your main method to something like this:
public static void main(String[] args) {
    //First initialise your database (dont do this in the action performed method)
    //  you should only need one and not need to create a new one on each action
    DATABASE = new DatabaseManagement("pacjent");
    // Read logins (I assume this is the method that does it)
    DATABASE.loginReader(loginy,"uzytkownicy");
    // Then create your message window...
    Message window = new Message();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
}


Q: problems with cookies i'm using restful-authentication plugin with rails 2.3.8
i've problems with cookies store
i've put a logger instruction in this function for check the cookie:
 def send_remember_cookie!
      cookies[:auth_token] = {
        :value   => @current_user.remember_token,
        :expires => @current_user.remember_token_expires_at }
      logger.error "--------------#{cookies[:auth_token].keys}"
    end

But when i launch the program i receive this error:
undefined method `keys' for nil:NilClass

why?
How can i set the cookie?
thanks

A: The cookies object is an instance ApplicationController::CookieJar. It's almost like a Hash but the behavior of the [] and []= methods are not symmetric. The setter sets the cookie value for sending to the browser. The getter retrieves the value which comes back form the browser. Hence when you access it in your code having just set the outgoing value the incoming value will be unset. There some more info on this here
Also did you intentionally mean to say cookie[:auth_token].keys or did you mean cookie.keys?


Q: Column not found: 1054 Field Field 'email' unknown in where I have 3 rubrics for now.

When, I login in the rubric Studentwith the email test.gmail.com I can see my informations private

Then, I LOGIN in the rubric Feedback always with the email test.gmail.com I have like error message:
SQLSTATE [42S22]: Column not found: 1054 Field Field 'email' unknown in where (SQL: select count (*) as aggregate fromreturnswhere email= test@gmail.com)
my fields on the table Feedbacks are:
protected  $fillable = ['user_id','instruction', 'description', 'fk_eleve'];
My function index() is the following:
public function index(Request $request)

{
    $user = $request->user();

    $feedbacks = Feedback::query()
    ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
        $query->where('email', $user->email);
    })
    ->when($request->has('search'), function (Builder $query) use ($request) {
     $query->join('eleves', 'feedbacks.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->where('eleves.nom','like','%'.$request->input('search').'%');
     })
    ->paginate(5);

    return view('admin.feedbacks.index', compact('feedbacks'))
        ->with('display_search', $user->hasRole('admin'));
}

Thank you for your help.

A: You most likely need to add the email column to your fillable array:
protected $fillable = ['user_id','instruction', 'description', 'fk_eleve', 'email'];

Did you further create a proper migration for this, like does the table have the column email?


Q: I want to use this. $ axios with Vuex constants What I want to come true
I use this.$axios many times, so I tried to put it in a constant, but it doesn't work.
I read the official docs but didn't understand.
Is it because this isn't available in the Nuxt.js lifecycle?
Code
url.js
export const AXIOS_POST = this.$axios.$post

export const POST_API = '/api/v1/'

export const POST_ITEMS_API = '/api/v1/post_items/'

Vuex
import * as api from './constants/url.js'  // url.js in this.

export const state = () => ({
  list: [],
  hidden: false
})

export const mutations = {

  add (state, response) {
    state.list.push({
      content: response.content,
      status: response.status
    })
  },

  remove (state, todo) {
    state.list.splice(state.list.indexOf(todo), 1)
  },

  edit (state, { todo, text }) {
    state.list.splice(state.list.indexOf(todo), 1, { text })
  },

  toggle (state, todo) {
    todo.status = !todo.status
  },

  cancel (state, todo) {
    todo.status = false
  },

  // アクション登録パネルフラグ
  switching (state) {
    state.hidden = !state.hidden
  }
}

export const actions = {

  post ({ commit }, text) {

//I want to use it here

    this.$axios.$post(api.POST_ITEMS_API + 'posts', {
      post_items: {
        content: text,
        status: false
      }
    })
      .then((response) => {
        commit('add', response)
      })
  }
}

Error

Uncaught TypeError: Cannot read property '$axios' of undefined

A: Since your file is located into a constants directory, you should probably use some .env file.
Here is a guide on how to achieve this in Nuxt: https://stackoverflow.com/a/67705541/8816585

If you really want to have access to it into a non .vue file, you can import it as usual with something like this
/constants/url.js
import store from '~/store/index'

export const test = () => {
  // the line below depends of your store of course
  return store.modules['@me'].state.email
}

PS: getters, dispatch and everything alike is available here.
Then call it in a page or .vue component like this
<script>
import { test } from '~/constants/url'

export default {
  mounted() {
    console.log('call the store here', test())
  },
}
</script>

As for the lifecyle question, since the url.js file is not in a .vue file but a regular JS one, it has no idea about any Vue/Nuxt lifecycles.


Q: how to upload an image to aws s3 bucket and get the saved url in Android studio using java I need to upload the image to the AWS s3 bucket in android. I implemented that the user has taken a photo from the gallery after having the image path I need to save that in a bucket and get the url from bucket in android.
I HAVE access key and secret key and bucket name. I am not clear how to implement this in android. Please help me out.
// This is the code of taking an image from the gallary
private void selectImage() {
        final CharSequence[] options = {"Choose from Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Upload Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Choose from Gallery")) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @SuppressLint("LongLogTag")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                thumbnail = getResizedBitmap(thumbnail, 400);
                Log.w("path of image from gallery......******************.........", picturePath + "");
                imageView.setImageBitmap(thumbnail);
                BitMapToString(thumbnail);
            }
        }
    }

    private void BitMapToString(Bitmap userImage1) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        userImage1.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        Document_img1 = Base64.encodeToString(b, Base64.DEFAULT);
        System.out.println(Document_img1 + "........IMAGE");
    }

    private Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

A: Please check out the Storage category in the AWS Amplify library.
There's some setup/configuration to do (as noted in that guide), but the actual upload will look like this:
Amplify.Storage.uploadFile(
    "remoteS3Key",
    localFile,
    result -> Log.i("Demo", "Successfully uploaded: " + result.getKey()),
    failure -> Log.e("Demo", "Upload failed", failure)
);


Q: Configuring ASP.NET MVC app's IIS 7.5 Application Pool identity as login on SQL Server 2008 R2 I am trying to use IIS 7.5 Application Pool identity as login on SQL Server 2008 R2 so that my ASP.NET web app can connect to the database...
Using this approach worked fine on my local dev machine (IIS 7.5 and SQL Server 2008 R2 on same machine).
However, when I try to set up the same on production (IIS and SQL servers are separate) I am unable to add "IIS APPPOOL\MyAppAppPool" login to SQL Server 2008 R2.
Notice that in either case you cannot use "Browse..." when creating a login in SQL Server since "IIS APPPOOL\MyAppAppPool" user identity is dynamic (or "special")...
Any ideas?
Update:
For more info on Application Pool Identities see here.
From article:

Whenever a new Application Pool is
  created, the IIS management process
  creates a security identifier (SID)
  that represents the name of the
  Application Pool itself. For example,
  if you create an Application Pool with
  the name "MyNewAppPool," a security
  identifier with the name
  "MyNewAppPool" is created in the
  Windows Security system. From this
  point on, resources can be secured by
  using this identity. However, the
  identity is not a real user account;
  it will not show up as a user in the
  Windows User Management Console.

A: That articles states (under "Accessing the Network") you still use the <domainname>\<machinename>$ aka machine account in the domain.
So if both servers are in "foobar" domain, and the web box is "bicycle", the login used to the SQL Server Instance is foobar\bicycle$
If you aren't in a domain, then there is no common directory to authenticate against. Use a SQL login with username and password for simplicity
Edit, after comment
If the domains are trusted then you can use the machien account still (use domain local groups for SQL Server, into which add a global groups etc)
As for using app pool identities, they are local to your web server only as per article. They have no meaning to SQL Server. If you need to differentiate sites, then use proper domain accounts for the App Pools.
You can't have it both ways...


Q: Django include template tag alternative in python class I know there is a Django template tag that allows to include other templates like so:
{% include 'template.html' %}

I am wondering if I could do the same, but in a separate python class (not in  the HTML template)?
I know that for example the url tag has an equivalent, like so:
{% url 'some_url_name' %} -> reverse('some_url_name')

A: I think you might be looking for render_to_string.
from django.template.loader import render_to_string
context = {'foo': 'bar'}
rendered_template = render_to_string('template.html', context)


Q: How to clear a window in PySimpleGUI I am using PySimpleGUI to build a GUI. How do you clear all the widgets on the window? In tkinter you have the code:
widget.destroy()

If you attempt this in PySimpleGUI you get the error:
NameError: name 'RWG' is not defined

if my widget is called RWG. I tried making RWG a global variable but I got the same error. Can I have some help?
My code that gets the error:
def oof():
    RWG.destroy()

import PySimpleGUI as sg
sg.theme("DarkAmber")
layout = [[sg.Text("Don't Even Try!!!")],
          [sg.Button("RWG")]]

window = sg.Window("Don't Even Try It", layout).Finalize()
window.Maximize()

while True:
    event, values = window.read()

    if event == "RWG":
        oof()

I would appreciate any help

A: You can clear elements with:
window.FindElement(key).Update('')

Have you tried this?


Q: Rails 4: From which step in the boot process can I check the ActiveRecord::Base class? I would like to perform some checking on the database resources only when the app starts/restarts (if any new migrations happen in between) by calling:
resources = ActiveRecord::Base.send(:subclasses).map { |subclass| subclass.name }

I tried inserting this code at different steps of the initialization process without any success (getting an empty array as a result).  Why? And where should I insert it?
If I perform this checking in the ApplicationController , it will be always be executed.  I only need to run it once after boot.
Where can I insert it?

A: Compiling the gist of answers other people have given before:
In the development environment your model classes will not be eager loaded.
Only when you invoke some code that references a model class, the corresponding file will be loaded. (Read up on 'autoloading' for further detail.)
So if you need to do some checks upon startup of the rails server, you can manually invoke
Rails.application.eager_load!

and after that get a list of all model classes with
model_classes = ActiveRecord::Base.descendants

For a list of model names associated with their database tables, you might use
model_classes.map{ |clazz| [clazz.model_name.human, clazz.table_name] }.sort

You can put your code in an arbitrarily named file in the config/initializers directory. All ruby files in that directory will get loaded at startup in alphabethical order.
The eager loading will of course take some time and thus slow down server and console start-up in the development environment a bit.
Other approaches such as parsing a list of filenames in the app/models directory are not reliable in more complex Rails applications.
If in a Rake task, make sure your Application is properly initialized before you send eager_load!. To that end, let your rake task depend on :environment.
HTH!


Q: HTTPHandler for all files in directory I have created an HTTPHandler to handle all files within a certain folder ("Files"). When i run it locally from Visual Studio it works fine. However when i deploy it on the server (IIS 7, Classic Mode), the handler is not firing for files of types such as pdf, jpg, gif...etc (although requests for files with extensions .aspx, .axd...etc do work).
How exactly should i configure web.config to handle these files as well. I placed a web.config file inside the Files folder with the following:
<configuration>
    <system.web>
      <httpHandlers>
        <add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
      </httpHandlers>
    </system.web>
</configuration>

Please help...

A: add one more element in your HTTPHandler tag for specific file type for example
<configuration>
<system.web>
  <httpHandlers>
    <add verb="*" path="*.*" type="MyProject.Web.FileSecurityHandler, MyProject.Web"/>
   <add path="*.jpg,*.jpeg,*.bmp,*.tif,*.tiff" verb="*" type="NameofYourHandler" />
  </httpHandlers>
</system.web>
</configuration>


Q: Integrating Angular 4 into ASP.NET Core MVC app - how to mix routing I'm trying to integrate my Angular 4 app into asp.net mvc core project. And I'd like to have Angular app available within my Core MVC project with this Url - mydomain.com/ngx.
Here's how I do it now (and it doesn't work):
I build Angular app with angular-cli and use ng build ... --base-href /ngx (notice the slash). Then I copy everything from dist folder (where the build is placed by CLI) and copy it into wwwroot/ngx folder into my Core MVC project. But when I open localhost/ngx/index.html I get 404 errors for main.bundle.js and other js files. I checked the requests and for some reason it tries to get it as localhost://main.bundle.js - why from root?
now, if I build it with --base-href ngx (no slash) and open the site, it gets redirected to /ngx/ngx (doubles the ngx). so... wtf? :)
Core MVC routing doesn't have anything special, I haven't touched that part.
So how can I make it work as localhost/ngx ASP.NET Core MVC project?

A: Works fine here with
ng build --base-href /ngx/ --output-path dist/ngx,

running http-server from the dist directory, and going to http://localhost:8080/ngx/index.html


Q: typing effect in Arabic language appear disconnected So I used this tutorial to make a typing effect and it appears great in English, I tried
to use Arabic text (which is a connected letter language) and it appears good on my device.
when I sent the app prototype for the client to test it, the Arabic language letters appear disconnected in his device! so weird as I couldn't debug it because it does not happen on my laptop and mobile phone!
I found this library which has a test demo at the bottom of the page, I asked him to test Arabic words on it, it appears like this on his device (iPhone xs max, chrome browser):

but it appears like this on my device (Linux, chrome browser):

any idea why this happens and how to solve it?


Q: How to safely create a file if it doesn't exist from concurrently-running processes without using locking? Suppose two (or more) concurrently-running Java processes need to check for the existence of a file, create it if it doesn't exist, and then potentially read from that file over the course of their runs. We want to protect ourselves against the possibility of multiple writer processes clobbering each other and/or reader processes reading an incomplete or inconsistent version of the file.
What we're currently doing to arbitrate this situation is to use Java NIO FileLocks. One process manages to acquire an exclusive lock on the file to be created using FileChannel.tryLock() and creates it, while the other concurrently-running processes fail to acquire a lock and fall back to using an in-memory version of the file for their runs.
Locking is causing various problems for us on our compute farm, however, so we're exploring alternatives. So my question to you is: is there a way to do this safely without using file locks?
Could, eg., the processes write to independent temporary files when they find a file doesn't exist, and then more or less "atomically" move the temp file(s) into place after they've been written? In this scenario, we might end up with multiple writer processes, but that would be ok provided that any processes reading from the file always read one version or another, and not a mix of two or more versions. However, I don't think all operating systems guarantee that if you have a file open for reading, you'll continue reading from the original version of the file even if it's overwritten mid-way through the read.
Any suggestions would be much appreciated!

A:
Suppose two (or more) concurrently-running Java processes need to check for the existence of a file, create it if it doesn't exist, and then potentially read from that file over the course of their runs.

I don't quite understand the create and read part of the question.  If you are looking to make sure that you have a unique file then you could use new File(...).createNewFile() and check to make sure that it returns true.  To quote from the Javadocs:

Atomically creates a new, empty file named by this abstract pathname if
  and only if a file with this name does not yet exist.  The check for the
  existence of the file and the creation of the file if it does not exist
  are a single operation that is atomic with respect to all other
  filesystem activities that might affect the file.

This would give you a unique file that only that process (or thread) would then "own".  I'm not sure how you were planning on letting the writer know which file to write to however.
If you are talking about creating a unique file that you write do and then moved into a write directory to be consumed then the above should work.  You would need to create a unique name in the write directory once you were done as well.
You could use something like the following:
private File getUniqueFile(File dir, String prefix) {
    long suffix = System.currentTimeMillis();
    while (true) {
        File file = new File(dir, prefix + suffix);
        // try creating this file, if true then it is unique
        if (file.createNewFile()) {
           return file;
        }
        // someone already has that suffix so ++ and try again
        suffix++;
    }
}

As an alternative, you could also create a unique filename using UUID.randomUUID() or something to generate a unique name.


Q: Wrong file input I have to enter string x in reverse order, but it outputs null. Why and how to fix it?
Sorry in advance for the name of the variables, but also for the double loop (I know it's bad, but this is the only thing that came to my mind)
The main question is why null is entered in the file
public static void OutputOfFile(char[] x)throws IOException {
        File file = new File("test");
        PrintWriter out = new PrintWriter(file.getAbsoluteFile());

        out.print(x);
        out.close();
    }

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String x = reader.readLine();
        char[] x1 = x.toCharArray();
        char[] x2 = new char[x1.length];
        for(int i = x1.length - 1; i < -1; i--) {
            for (int k = 0; k > x1.length; k++) {
                x2[i] = x1[k];
            }
        }
        OutputOfFile(x2);
    }

A: the problem is with your loop, you need to iterate in one loop instead of an inner loop:
public static void OutputOfFile(char[] x) throws IOException {
    File file = new File(""test"");
    PrintWriter out = new PrintWriter(file.getAbsoluteFile());

    out.print(x);
    out.close();
}

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String x = reader.readLine();
    char[] x1 = x.toCharArray();
    char[] x2 = new char[x1.length];

    for (int i = x1.length - 1, k = 0; i >= 0; i--, k++) {
        x2[k] = x1[i];
    }

    OutputOfFile(x2);
}


Q: pymssql (python module) losing item when fetching data I have a database named "sina2013",and the columus is Title,Content
Now I want to use pymssql module to get the data.At the same time ,using the Title as the filename of a txt file,the Content as the content of the txt file.
The strange thing is the number of files is less than the items in database.
where is the error?
the code i have tried is:
import pymssql
conn = pymssql.connect(...)
cur = conn.cursor()
cur.execute('SELECT Title,Content FROM sina2013')
count=len(cur.fetchall()) #Will return the right number :5913
for Title,Content in cur:
    filename=file(str(Title)+r'.txt',r'w')
    filename.write(Content )
    filename.close()
cur.close()

The number of txt file is less than it should be.
what is the reason?

A: Perhaps changing your for loop into this:
# cursor fetchall() method returns all rows from a query
for Title,Content in cur.fetchall():

... will fix the issue?


Q: How do I get arrayMaxConsecutiveSum from CodeSignal more efficient? I am working through some problems on CodeSignal. I came across this one, arrayMaxConsecutiveSum. I got it to pass almost all tests, but it is timing out on the last one. If I move the test into custom tests, it passes there, so I'm not sure what to do. How do I code it better so that it doesn't time out?
Problem:

Given array of integers, find the maximal possible sum of some of its k consecutive elements.
Example: For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be
arrayMaxConsecutiveSum(inputArray, k) = 8. All possible sums of 2 consecutive elements are:
2 + 3 = 5;
3 + 5 = 8;
5 + 1 = 6;
1 + 6 = 7.
Thus, the answer is 8.

function arrayMaxConsecutiveSum(inputArray, k) {
    let max = 0;

    for(let i = 0; i < inputArray.length; i++){
        let sum = 0;
        let newArr = inputArray.slice(i, i + k);
        sum = newArr.reduce((accumulator, currentVal) => accumulator + currentVal);
        if(sum > max){
            max = sum;
        }
    }

    return max;
}

Error: Tests passed: 19/20. Execution time limit exceeded on test 20: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input.

A: Your current algorithm is O(n ^ 2) because it requires a nested loop.
You can make it O(n) by using a rolling sum instead. Start with the sum of elements 0 to k, then on each iteration, subtract the earliest element that makes up the sum and add the next element not included in the sum yet.
For example, with a k of 2:

*

*start out with the sum of elements [0] and [1]

*subtract [0], add [2], compare the new sum

*subtract [1], add [3], compare the new sum

and so on.

function arrayMaxConsecutiveSum(inputArray, k) {
    let rollingSum = inputArray.slice(0, k).reduce((a, b) => a + b);
    let max = rollingSum;
    for(let i = 0; i < inputArray.length - k; i++){
        rollingSum += inputArray[i + k] - inputArray[i];
        max = Math.max(max, rollingSum);
    }
    return max;
}

console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));

A:

function arrayMaxConsecutiveSum(inputArray, k) {

    var max = inputArray.slice(0,k).reduce((a,b)=>a+b);
    var cur = max;
    for(var i = k; i < inputArray.length; i++) {
        cur = cur + inputArray[i] - inputArray[i-k];
        if(cur>max)
            max = cur
    }
        return max

}

console.log(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2));


Q: Make SliverAppBar have an image as a background instead of a color I have a SliverAppBar with a background image.
When collapsed it has a blue color as a background:

But instead of the blue color I want it to show the background image when collapsed:

How can I achieve this?
I've already tried to give the app bar a transparent background color,
but it did not work.
Code:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  var scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Home());
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: DefaultTabController(
          length: 2,
          child: NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverAppBar(
                  expandedHeight: 200.0,
                  floating: false,
                  pinned: true,
                  flexibleSpace: FlexibleSpaceBar(
                      centerTitle: true,
                      title: Text("Collapsing Toolbar",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.0,
                          )),
                      background: Image.network(
                        "https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350",
                        fit: BoxFit.cover,
                      )),
                ),
                SliverPadding(
                  padding: new EdgeInsets.all(16.0),
                  sliver: new SliverList(
                    delegate: new SliverChildListDelegate([
                      TabBar(
                        labelColor: Colors.black87,
                        unselectedLabelColor: Colors.grey,
                        tabs: [
                          new Tab(icon: new Icon(Icons.info), text: "Tab 1"),
                          new Tab(
                              icon: new Icon(Icons.lightbulb_outline),
                              text: "Tab 2"),
                        ],
                      ),
                    ]),
                  ),
                ),
              ];
            },
            body: Center(
              child: Text("Sample text"),
            ),
          ),
        ));
  }
}

A: Please check below code :
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  var scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Home());
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: DefaultTabController(
      length: 2,
      child: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              expandedHeight: 200.0,
              floating: true,
              pinned: true,
              snap: true,
              actionsIconTheme: IconThemeData(opacity: 0.0),
              flexibleSpace: Stack(
                children: <Widget>[
                  Positioned.fill(
                      child: Image.network(
                    "https://images.pexels.com/photos/396547/pexels-photo-396547.jpeg?auto=compress&cs=tinysrgb&h=350",
                    fit: BoxFit.cover,
                  ))
                ],
              ),
            ),
            SliverPadding(
              padding: new EdgeInsets.all(16.0),
              sliver: new SliverList(
                delegate: new SliverChildListDelegate([
                  TabBar(
                    labelColor: Colors.black87,
                    unselectedLabelColor: Colors.grey,
                    tabs: [
                      new Tab(icon: new Icon(Icons.info), text: "Tab 1"),
                      new Tab(
                          icon: new Icon(Icons.lightbulb_outline),
                          text: "Tab 2"),
                    ],
                  ),
                ]),
              ),
            ),
          ];
        },
        body: Center(
          child: Text("Sample text"),
        ),
      ),
    ));
  }
}


Q: SSE (Server Sent Events) Client library for Clojure? I would like to handle a Server Sent Events stream in Clojure.
Does anyone know a small client library to just do that please ?
I was expecting to find something like https://github.com/stalefruits/gniazdo, which is for Websockets, but for SSE.
I could not find anything though and the only lib that may have been a good candidate is not maintained anymore https://github.com/clojurewerkz/ssese
thanks in advance ...

A: Here are some overviews on the topic:

*

*https://sweetcode.io/using-html5-server-sent-events/

*https://juxt.pro/blog/posts/course-notes.html

*https://www.lucagrulla.com/posts/server-sent-events-with-ring-and-compojure/

*Server push of data from Clojure to ClojureScript

*https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
Here is a highly voted comparison on StackOverflow between Server Sent Events and WebSockets (my favorite):

*

*WebSockets vs. Server-Sent events/EventSource
And here is a nice comparison from IBM (2017):

*

*https://www.ibm.com/developerworks/library/wa-http-server-push-with-websocket-sse/index.html

A: immutant.web has support for SSE built in: http://immutant.org/documentation/current/apidoc/guide-web.html#h3155
There is also this middleware for other web servers: https://github.com/kumarshantanu/ring-sse-middleware, although I have not tried it myself.


Q: How to provide tunnel between my own app and my own server? I have implemented an Android App which connects my home server.  I want  to implement a tunnel between my app and the server. when ever app connects to server it will be connected through the secure tunnel. Tunnel might be anything. Is  there any suggestion???
P.S.: I want to create tunnel just for this particular app not for all.


Q: Symfony2 using jsroutingbundle and got login error I am using Jsroutingbundle and I add these two lines in my base.html.twig and it works fine.
<script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
<script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>

But when I login next time, it jumped to a page like this:
fos.Router.setData({"base_url":"\/Symfony\/web\/app_dev.php","routes":[],"prefix":"","host":"localhost","scheme":"http"});

And the url is:
http://localhost/Symfony/web/app_dev.php/My/Test/js/routing?callback=fos.Router.setData

I am actually logged in because I can jump to other pages. But it is just unfriendly. How should I handle this problem?

A: In the access_control of your security add:
    - { path: ^/js/, role: IS_AUTHENTICATED_ANONYMOUSLY }


Q: Hi everyone! My question is about the Charles-proxy certificate My question is about the Charles-proxy certificate. I've already installed Charles on my laptop. The real problem is when I tried to install it on my mobile. I have a Xiaomi with the android 11 version, with this one is impossible. I did everything I could. I have another mobile a Moto G. When I try to link the mobile with Charles I couldn't see the connection between the mobile and the laptop. Can somebody help me?
Thanks in advance!


Q: Why does isEqualToString not work for NSString? I am trying to code the login process for an iPhone app in XCode. The problem is with the NSString serverOutput below. When I print it using printf(serverOutput.UTF8String); it prints 'Yes' to the console. However when I compare serverOutput to "Yes" it doesn't work. Any help would be appreciated. Here's my code:
- (IBAction) loginButton: (id) sender
{
    // TODO: spawn a login thread

    indicator.hidden = FALSE;
    [indicator startAnimating];
    NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",userName.text, password.text];

    NSString *hostStr = @"http://10.243.1.184/connectDB.php?";
    hostStr = [hostStr stringByAppendingString:post];
    NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
    printf(serverOutput.UTF8String);

    if([serverOutput isEqualToString:@"Yes"]){

        UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized"
        delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

        [alertsuccess show];
        [alertsuccess release];

    }
    else {
        UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect"
        delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
        [alertsuccess show];
        [alertsuccess release];
        //[self.navigationController pushViewController:DashboardViewController animated:YES];
        loginbutton.enabled = TRUE;

    }

    loginbutton.enabled = FALSE;
}

A: Based on helping others with similar situations I would say the problem is that the response from the server isn't just the string "Yes". Most likely there is some whitespace before and/or after the text. Perhaps a stray newline or two.
Try this:
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(@"Result = '%@'", serverOutput); // look for space between quotes
serverOutput = [serverOutput stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


Q: php limit mail () this might be easy but I don´t see the way. I have a shopping cart at my side where user can buy things. for this the buyer can  imput his email-adress into an input-form. the order is sent with php mail() to the shopowner and the buyer.
I´m looking for a way to limit mail to sent only two email, this for preventing spam.
I see the risk that spammers could input a semicolon string like this:
email@examplecom;email@xxyz.com;hans@jdkdl.com

A: Y can't you validate using .
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
  $headers .= "Reply-to: $validemail\r\n";
}else
{
//redirect.
}

considering your actual question .
<?php
$emails = explode(';',$emailList);
if(count ($emails)<3)
{
if(filter_var_array($emails, FILTER_VALIDATE_EMAIL))
    {
    mail();
    }
  else
    {
    //die
    }
}
?>

A: You could check the number of email in the string like this:
if(count(explode(';',$emailList))<3)
{
    // send email
}
else
{
    // Oh no, jumbo!
}

This code will explode your email string based on the ; characters into an array while at the same time use a count function on the array and execute one of two scenarios based on the number.

A: This should work to only pick maximum two emails (the first two):
$emailString = "email@examplecom;email@xxyz.com;hans@jdkdl.com";
$emails = explode(";", $emailString);
$emails = array_slice($emails, 0, 2);
$emailString = implode(";", $emails);
var_dump($emailString);

Outputs:
string(31) "email@examplecom;email@xxyz.com"


Q: Kinect Html5 Stream to web in existing C# Application For our university project we need the kinect video Stream accessible from another Device in the network. Preferable as a HTML5 Webserver. The Microsoft.Samples Webserver works only with the kinect1 and we need it for kinect 2. Another interesting solution is the one from intrael but we need to implement it in our own application.
Are there any solutions I didn't find or could anyone give us a working example or hint how to proceed?

A: If someone stumbles across this we solved this now with using a simple TCP Listener which listens for a connection:
 TcpListener srv = new TcpListener(IPAddress.Any, 51530);
        srv.Start(1);

        client = srv.AcceptTcpClient();

Then we changed the Kinectpicture into a Bitmap and on every new picture we send the bitmap to the connected device:
NetworkStream ns = client.GetStream();

            Graphics g = Graphics.FromImage(bitmap);

            MemoryStream imageStream = new MemoryStream();

            using (var ms = new MemoryStream())
            {
                Bitmap bmp = new Bitmap(bitmap);
                bmp.Save(imageStream, ImageFormat.Bmp);
            }

           // bitmap.Save(imageStream, ImageFormat.Bmp);
            Console.WriteLine("Bild wird über Socket geschickt");
            //reset the memory stream to start of stream
            imageStream.Position = 0;
            //copy memory stream to network stream
            imageStream.CopyTo(ns);
            //make sure copy is completed
            imageStream.Flush();
            imageStream.Close();

            //Makes sure everything is sent before closing it
            ns.Flush();

on the other side there is an android device which gets the network stream and translates it into a bitmap and shows it in an imageview.
Feel free to ask additional questions for needed clarification.