text:
Q: using Paragraphs in Xcode in AppleScriptObjC do shell script "mdfind kMDItemCFBundleIdentifier = com.test.sample > ~/Documents/sampleBuilds.txt"
set homeFolder to (path to home folder)
set sampleFiles to paragraphs of (read POSIX file (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))

if (count of sampleFiles) is 0 then
    display notification "No Sample builds are present on the system"
else
    set sampleFiles to paragraphs of (read POSIX file (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))
    display dialog "You have " & (count of sampleFiles) & " build(s) of Sample on your system. Would you like to remove them all? This cannot be undone"

    repeat with c in SampleFiles
        do shell script "rm -rf " & (quoted form of c)
        display notification "Sample build located at " & c & " has been removed from your system"
    end repeat

    do shell script "rm -rf ~/Documents/SampleBuilds.txt"
end if

When placing script into Xcode with correct sender I get the error:

[AppDelegate testScript:]: Can't make current application into type file. (error -1700) on the line
set sampleFiles to paragraphs of (read POSIX file (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))

Any thoughts on how to get Xcode in AppleScript Application to accept this script?

A: The coercion to POSIX file is not needed which solves the issue.
set sampleFiles to paragraphs of (read (POSIX path of homeFolder & "/Documents/sampleBuilds.txt"))

Basically in AppleScriptObjC POSIX file foo doesn't work, you have to write foo as POSIX file.
Side note:
Reading the text twice is redundant. You can delete the second set sampleFiles to ... line.


text:
Q: WCF Call Result What would be a better approach when providing a wcf client with the call result.
1. Wrapping the result in an object
   public enum DefinedResult : short {
      Success = 0,
      TimeOut = 1,
      ServerFailure = 2,
      UserNotFount = 3,
      Uknown = 4,

      //etc.
   }

   [DataContract]
   public class ServiceResult {

       readonly DefinedResults dResult;

       public ServiceResult(DefinedResult result) {

            this.dResult = result;
      }
      [DataMember]
      public bool IsSuccess
      {
          get {return this.dResult == DefinedResult.Success;}
      }

   }

  //Client:

  WcfClient client = new WcfClient();
  ServiceResult result = client.DoWork();

2. Throwing a custom Exception:
  [Serializable]
  public UserNotFoundException: Exception {

        public UserNotFoundException(string message): base(message) {}

  }

  //client:
  WcfClient client = new WcfClient();
  try {
    result = client.DoWork();
  }
  catch(FaultException<ExceptionDetail> ex) {

      switch(ex.Detail.Type)
      {
          case "MyCompany.Framework.Exceptions.UserNotFound":
             //handle
             break;
          case "MyCompany.Framework.Exceptions.ServerError":
             //handle
             break;
      }
  }

Now, the client can be another .net process (server side) or the same service can be called by java script, hence the question - which one of these (or may be there is something better) is a better approach to let the client know of what happened with the call?

A: First of all, it depends: if you want to return a condition which is not exceptional, then use a result value. Otherwise, use exceptions. In WCF, it goes like this:
Create a custom exception class:
[DataContract]
class MyException : FaultException<mydetails>

Define that your service throws it:
[FaultContract(...)]
void mymethod()...

throw MyException in your service method
Then you can catch your exception in the service method like catch FaultException<mydetails>
This is the nicest way there is.

A: FaultExceptions are swallowed by WebHttpBinding (required for JSON/REST services). In this case, if you want to provide detailed infos to your client, Option 1 is better.
If JSON is not in the way, I would recommend Option 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How are snap applications being protected? How are snap applications being protected when we look at different aspects?

*

*Runtime protections?

*

*Memory protections?

*Differences to ordinary processes?

*Differences to VMs?

*Storage protections?

*

*Protections of application binaries?

*Protections of persistent data?

*Containers

*

*What does the term "container" mean and implicate in respect to application protection and security?

*Differences to ordinary processes?

*Differences to VMs?

*Differences to other containers especially "Docker"?

*Any other relevant protections?

A: snapd developer here.
The word protections seems to imply that snapd contains some sort of DRM system to protect binaries. There's no such thing. Snapd protects your system from possibly untrusted software and various software packages from affecting each other.
Differences from Virtual Machines are simple, there are no virtual machines involved. Running a program in a virtual machine really runs a program, operating system and a hardware emulator as one big process on your system. Snaps don't use anything like that, they instead executed directly on top of the hardware and the kernel provided by the host system.
Differences from ordinary processes are just a few but they make all the difference and magic possible. Snapd uses multiple features of the Linux kernel to give snap processes (processes of started snap applications) different view of the file-system, so that they can run on top of virtually any modern distribution. In addition the interaction of such processes with the kernel and other userspace programs is controlled by a sandbox managed by snapd. The exact behaviour of the sandbox depends on the system used and the set of snap interface connections made between the snaps in the system.
The term container means pretty much nothing today, it is just a marketing buzzword. The linux kernel offers a wide range of tools that allows to segregate various parts of the system and make some of them appear unaffected by changes made by other processes elsewhere. This may range from "it looks like another machine" to "it looks like this machine" and is constantly evolving and expanding in scope of what can be done.
Differences from other "containers" like docker is the set of those primitives used. Specifically snapd uses the device cgroup, the freezer cgroup, the seccomp BPF filter to constrain system calls and a large set of apparmor profiles to constrain access to IPC mechanisms, networking mechanisms, signals, capabilities, read, write and other access to files on the system. Docker or other "containers" typically use different set of such kernel features and configure them differently.
From a purely perception difference snapd is designed to integrate with the host. If you snap install a service it will be directly visible to your machine's service manager (systemd). If you snap install a CLI application you will be able to run it mostly like any other application on your host. If you snap install a graphical application it will integrate with you launcher, panels and other typical controls. This is not the case for docker which is designed to allow you to run, typically, headless network payloads and leave the integration to the user.
As for data protection snapd manages and retains application data between revisions to allow users to revert to a prior working revision as well as contains default permissions that limit access to potentially sensitive access to certain files in the home directory. Still most of the home directory is currently allowed as the mechanisms to mediate access are incomplete or immature. Over time that access will be restricted and only granted through fine-grained mediation.
There's a sophisticated white paper about snapd security model that I could recommend for far more details than those that I presented here: https://developer.ubuntu.com/static/resources/ubuntu-core-16-security-whitepaper.pdf

A: "Still most of the home directory is currently allowed as the mechanisms to mediate access are incomplete or immature. Over time that access will be restricted and only granted through fine-grained mediation."
To provide a little more context for this, by default the snap is only allowed to access its own data and system resources that are considered safe. The snap developer is able to request other resources (known as "interfaces" in snapd) and some are automatically granted and others are granted by the user. Zygmunt is referring to the "home" interface here and snaps do not have it by default, but a snap developer may request it. This home interface is considered a transitional interface to support certain traditional use cases and it is automatically granted on traditional (aka classic) distributions (as opposed to distributions like Ubuntu Core where it is not auto-connected) and the user may choose to revoke it. As Zygmunt points out, over time use of the home interface will be restricted and access to the user's data will only granted through fine-grained mediation.


text:
Q: Why there are many commits messages in PR Why there are many commits messages in my PR?
I am following this way,
I am on main branch then create new branch
1 - git checkout -b feature-abc main
after development finished (with some commit to local branch)
2 - git checkout main
3 - git pull origin main
4 - git checkout -
5 - git merge --no-ff main
add some messages and resolve conflict
6 - git push origin feature-abc
Please below screenshot, I just want to see only the last commit on this PR. How do I do this without any issue?(code missing)

A: A Pull Request is a Github feature that allow Request a branch merge action to another branch.this history of commits are the history of commits performed in that branch.

A: I remove my local main branch
git branch -D main
Then fetch from remote
git fetch
Then create a new branch from the main
git checkout -b new-branch main
After development is done, I again checkout main and pull (ff only)
git pull origin --ff-only main
Then checkout to my dev branch and merge with main (with ff only)
git merge --ff-only main
Final Result


text:
Q: Codeigniter Pagination class limitation I am new to Codeigniter, and I have trouble with the pagination class.
From CI document: (I do studied it carefully and practiced it.)
$this->load->library('pagination');

$config['base_url'] = 'http://example.com/index.php/test/page/';

$config['total_rows'] = '200';

$config['per_page'] = '20';

$this->pagination->initialize($config);

echo $this->pagination->create_links();

It works quite well, when I do practice at local host.
How can I pass more parameters for the base_url value?
Assumed I must pass mypara to page function as below.
$config['base_url'] = 'http://example.com/index.php/test/page/mypara/';

It doesn't work then. How can I joined my parameter (mypara) in the base_url?
It seems it doesn't support passing parameters to base_url.

A: Here's the answer on codeigniter forum. http://codeigniter.com/forums/viewthread/143280/P15T here are many questions that have been answered in there.

A: Here is an excellent tutorial from Nettuts on Pagination with COdeigniter
http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-7-pagination/
You might also change this
$config['uri_segment'] = '2';

to 3 or 4


text:
Q: Getting "Wrong number of arguments or invalid property assignment" when running WScript.Shell.Run() from JavaScript Background:
I am trying to run C:\Windows\System32\Logoff.exe on a local machine from a ASP.NET web application to log off the local user from their terminal services session.
Here is what I have so far:
C#
protected void btnContinueClick(Object sender,
                       EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("WshShell = new ActiveXObject('WScript.Shell');\n");
        sb.Append(@"WshShell.Run('C:\\Windows\\System32\\Logoff.exe " + intSessionID + " /SERVER:" + strServer + "', 1, false);");
        ScriptManager.RegisterStartupScript(Page, GetType(), "RestartSession", sb.ToString(), true);

Running the above with IE's F12 menu open, shows the script gets added to my HTML successfully:
HTML
<script type="text/javascript">
//<![CDATA[
WshShell = new ActiveXObject('WScript.Shell');
WshShell.Run('C:\\Windows\\System32\\Logoff.exe', 1, false);//]]>
</script>
</form>
</body>

However when the Run(...) line executes I get the following error in IE:
Error: WshShell.Run()   Wrong number of arguments or invalid property assignment

What I have tried:

*

*Removing the ", 1, false" optional arguments = same error.

*Moving the ' ' so the line reads (don't know which is correct): sb.Append(@"WshShell.Run('C:\\Windows\\System32\\Logoff.exe " + intSessionID + " /SERVER:" + strServer + ", 1, false);'"); = same error.

*Calling a .bat file with the logoff command inside. (The .bat does actually run, however I get a new error: "logoff is not recognized as an internal or external command, operable program or batch file". Very similar to Call logoff in Ant script.

*Also changed escape characters around in as many possible combinations I can think of, so I don't think it is that.

*Running the command directly from a CMD window does the intended job.

Please help!
Any suitable alternative methods of logging off a user's terminal services session from an internal Intranet web app would also be greatly appreciated!

A: After a lot of variations, I have a working solution. Although the issue was most likely just with variable passing and escape characters (so quite trivial), I'm posting the answer anyway as it could point others towards a work-around when passing variables across multiple platforms.
C#
ScriptManager.RegisterStartupScript(Page, GetType(), "Logoff", $"Logoff(\"{intSessionID}\", \"{strServer}\");", true);

JavaScript
<script type="text/javascript">
    function Logoff(intID, strSvr) {
        WshShell = new ActiveXObject("WScript.Shell");
        WshShell.Run("C:\\Users\\User\\Desktop\\Logoff.vbs" + " \"" + intID + "\" " + " \"" + strSvr + "\"", 1, false);
    }
</script>

The VB script then runs the original Logoff.exe command, along with a couple other audit logging lines.


text:
Q: Cross table with filtered obs on R I'd like to make a crosstable where x is the number of distinct obs of a variable and y is an other variable. With dplyr I can get the information I need with the code below but it obviously does not create a table. What I would like is the number of distinct obs of CODE_UAI.x  for secteur. Below is an example of the data set.

CODE_UAI.x
secteur

0271564D
1

0942344M
2

0271564D
3

0332894S
3

0033082C
2

00381324H
1

0271564D
3

0033082C
2

*

*Code for input dataframe
df1 <- data.frame("CODE_UAI.x" = c("0271564D", "0942344M", "0271564D", "0332894S",
                                   "0033082C", "00381324H", "0271564D", "0033082C"),
                  secteur = c(1, 2, 3, 3, 2, 1, 3, 2))

Ech_final_nom_BSA %>%
  filter(secteur == 3) %>%
  summarise(n=n_distinct(CODE_UAI.x))

I've also tried doing this with the package summarytools with no results.
The results I'm expecting is something like this:

Secteur
# distinct UAI

1
2

2
2

3
2

I hope this makes sense. Feel free to ask further information if needed.

A: Instead of using filter, you can instead do group_by for each secteur and count unique values using n_distinct.
library(dplyr)
df1 %>% group_by(secteur) %>% summarise(n=n_distinct(CODE_UAI.x))

#  secteur     n
#    <dbl> <int>
#1       1     2
#2       2     2
#3       3     2

Or in base R -
aggregate(CODE_UAI.x~ secteur, df1, function(x) length(unique(x)))


text:
Q: ORACLE insertion from other table using TOAD does not align properly (Showing NULL) I have created new table name NEW_TABLE like
Create table NEW_TABLE
(
    Col_1 VARCHAR(50),
    Col_2_ VARCHAR(50),
    Col_3_ VARCHAR(50)
)

I am inserting value from OLD_TABLE like this way
INSERT INTO NEW_TABLE (Col_1)
    SELECT Col_1
    FROM OLD_TABLE_A
    WHERE Col_1 IS NOT NULL;

INSERT INTO NEW_TABLE (Col_2)
    SELECT Col_1
    FROM OLD_TABLE_B
    WHERE Col_1 IS NOT NULL;

When I want to see the NEW_TABLE it show the data like this
Col_1    Col_2
-----    -----
AA
BB
CC
         XX
         MM
         ZZ
         PP
         CC

I am getting NULL value at the start of Col_2.
I want this:
 Col_1    Col_2
 -----    -----
    AA       XX
    BB       MM
    CC       ZZ
             PP
             CC

I have to insert different column in different time separately.while inserting a column I do not want to consider other

A: Since you stated in a comment that there is no relation between the columns, and that there are the same number of columns in old_table_a and old_table_b this will work.  I broke it into steps to make following it easier.
First establish the original table with a WITH clause.  Then with another WITH clause, add an ID column which is the row number.  Finally SELECT, joining on the ID (uncomment the INSERT line at the top when you are satisfied with the results).
Note the "ID" is meaningless as a true ID and serves only to match rows one for one in each table.  If these tables have different numbers of rows you will get unexpected results but it meets your requirements.
SQL> --insert into new_table(col_1, col_2)
SQL> -- Set up the original old table A
SQL> with old_table_a(col_1) as (
     select 'AA' from dual union
     select 'BB' from dual union
     select 'CC' from dual
   ),
   -- Add the id, which is the row_number
   ota_rn(id, col_1) as (
     select row_number() over (order by col_1) as id, col_1
     from old_table_a
   ),
   -- Set up the original old table B
   old_table_b(col_1) as (
     select 'XX' from dual union
     select 'YY' from dual union
     select 'ZZ' from dual
   ),
   -- Add the id, which is the row_number
   otb_rn(id, col_1) as (
     select row_number() over (order by col_1) as id, col_1
     from old_table_b
   )
   -- Now join on the ID (which is really meaningless)
   select a.col_1, b.col_1
   from   ota_rn a
          join otb_rn b
            on (a.id = b.id);

COL_1      COL_1
---------- ----------
AA         XX
BB         YY
CC         ZZ

SQL>

Update before I even post the answer: I see from subsequent comments as I was about to post that you want to allow for adding additional columns with perhaps differing numbers of rows, etc.  That will call for UPDATING, not INSERTING and unless you use the fake row_number ID method I use above really makes no sense in a true relational table. In that case this answer will not meet your needs but I will leave it here in case you want to adapt it for your needs.
I suggest you reconsider your approach to your original problem as this path will take you down a dark hole.  You will have unrelated attributes in a table which violates basic database design and makes selecting this data in the future problematic at best (how will you query results? I'm curious how you will use this table).  Maybe you should take a step back and reconsider your approach and at least start with some properly normalized tables.  What's the real issue your are trying to solve?  I bet there is a better way.

A: insert creates new row. If you want to fill column2 values where column1 is already filled you need to use update or merge. But as mentioned in comments you need to know how to match column2 with column1. You haven't provided any join condition for the data so people are guessing what you need. Please post some sample data from tableA and tableB and how it should look in new_table.
I think you need something like:
step1:
INSERT INTO NEW_TABLE (Col_1)
    SELECT Col_1
    FROM OLD_TABLE_A
    WHERE Col_1 IS NOT NULL;

step2:
merge into NEW_TABLE n
using OLD_TABLE_B b
on (/*HERE PUT JOIN CONDITION*/)
when matched then update set n.col_2_ = b.col_1;

step3:
merge into NEW_TABLE n
using OLD_TABLE_C c
on (/*HERE PUT JOIN CONDITION*/)
when matched then update set n.col_3_ = c.col_1;

A: The second INSERT should be UPDATE, something like:
UPDATE NEW_TABLE
   SET Col_2 = (SELECT Col_2
                  FROM OLD_TABLE
                 WHERE Col_1 = <selection value>
               )
 WHERE Col_1 = <selection value> ;

A: The basic answer is that you should
insert into NEW_TABLE (Col_1, Col_2)
    select OLD_TABLE_A.Col_1, OLD_TABLE_B.Col_2
        from OLD_TABLE_A, OLD_TABLE_B
        where OLD_TABLE_A.Col_1 is not null
            and OLD_TABLE_B.Col_2 is not null;

the problem is that you will then get
Col_1 Col_2
----- -----
AA    XX
AA    YY
AA    ZZ
BB    XX
BB    YY
BB    ZZ
CC    XX
CC    YY
CC    ZZ

now the question you need to answer (that's what Dimitry asked in his comment) is how do you decide that you do not want the AA,YY, AA,ZZ, BB,XX, BB,ZZ, CC,XX and CC,YY ? Once you have an answer to this you can augment the where condition to remove them.

A: select      min (case tab when 'A' then Col_1 end)  as Col_1
           ,min (case tab when 'B' then Col_1 end)  as Col_2

from        (           SELECT 'A' as tab ,rownum as rn ,Col_1 FROM OLD_TABLE_A
            union all   SELECT 'B'        ,rownum       ,Col_1 FROM OLD_TABLE_B
            )

group by    rn

order by    rn
;

OR
select      min (Col_1)  as Col_1
           ,min (Col_2)  as Col_2

from        (           SELECT 'A' as tab,rownum as rn,Col_1 ,null  as Col_2 FROM OLD_TABLE_A
            union all   SELECT 'B'       ,rownum      ,null  ,Col_1          FROM OLD_TABLE_B
            )

group by    rn

order by    rn
;

OR
select      a.Col_1
           ,b.Col_1     as Col_2

from                    (SELECT rownum as rn,Col_1 FROM OLD_TABLE_A) a
            full join   (SELECT rownum as rn,Col_1 FROM OLD_TABLE_B) b
            on          b.rn = a.rn

order by    coalesce (a.rn,b.rn)
;

Results
+-------+-------+
| COL_1 | COL_2 |
+-------+-------+
| AA    | XX    |
+-------+-------+
| BB    | MM    |
+-------+-------+
| CC    | ZZ    |
+-------+-------+
|       | PP    |
+-------+-------+
|       | CC    |
+-------+-------+

A: The problem as I see it is:

*

*Fill any holes in Col_2 with one of each of the values from
OLD_TABLE_B, when you've run out of holes then add new rows.

*Exactly the same technique should to fill Col_3 from OLD_TABLE_C, as so on.  Ideally the initial Col_1 from OLD_TABLE_A should also be able to use the technique although it's a simple insert.

*If you end up with an OLD_TABLE_B_PART_2 this should be able to be run against Col_2 later with the same technique.

The solution needs the following parts:

*

*A MERGE statement as you need to do updates otherwise inserts.

*To use a single MERGE for each pass to update multiple rows, each row with different values, you need a unique way of identifying the row for the ON clause. With no unique column(s) / primary key you need to use the ROWID pseudo-column. This will be very efficient at targeting the row in the table when we get to the UPDATE clause as ROWID encodes the physical location of the row.

*You need all the rows from OLD_TABLE and as many matching rows from NEW_TABLE you can find with holes, so it's a LEFT OUTER JOIN. You could do some sort of UNION then aggregate the rows but this would need an often expensive GROUP BY and you many need to discard an unknown number of surplus rows from NEW_TABLE.

*To match a (potentially non-unique) row in the OLD_TABLE with a unique hole in the NEW_TABLE, both will need a temporary matching IDs. The ROWNUM pseudo-column does this and is cheap.

Given the above, the following statement should work:
MERGE INTO NEW_TABLE
USING
  ( SELECT Col_1, ntid
    FROM
      ( SELECT ROWNUM num, Col_1
        FROM OLD_TABLE_B
        WHERE Col_1 IS NOT NULL
      ) ot
        LEFT OUTER JOIN
      ( SELECT ROWNUM num, ROWID ntid
        FROM NEW_TABLE
        WHERE Col_2 IS NULL
      ) nt ON nt.num=ot.num
  ) sel
ON (NEW_TABLE.ROWID=ntid)
WHEN MATCHED THEN
  UPDATE SET Col_2=sel.Col_1
WHEN NOT MATCHED THEN
  INSERT (Col_2) VALUES (sel.Col_1);

Check the execution plan before using on big data tables. I've seen the optimiser (in Oracle 12c) use a MERGE or HASH join against the target (NEW_TABLE) for the update rather than a plain USER-ROWID access. In this case the workaround I have used was to force NESTED-LOOP joins i.e. add an optimisation hint to the MERGE at the start of the query, so MERGE /*+ use_nl(NEW_TABLE) */. You may also need to check how it does LEFT JOIN depending on your data.

A: Create table NEW_TABLE
(
    Col_1 VARCHAR(5),
    Col_2_ VARCHAR(5),
    Col_3_ VARCHAR(5)
);

Create table OLD_TABLE
(
    Col_1 VARCHAR(5),
    Col_2_ VARCHAR(5),
    Col_3_ VARCHAR(5)
);

insert into old_table values ('AA','XX', null);
insert into old_table values ('BB','MM', null);
insert into old_table values ('CC','ZZ', null);
insert into old_table values (null,'PP', 'YYY');
insert into old_table values (null,'CC', 'XXX');

select * from old_table;

COL_1 COL_2 COL_3

----- ----- -----
AA    XX
BB    MM
CC    ZZ
      PP    YYY
      CC    XXX

alter table new_table add (position number);

.
MERGE INTO new_table D
   USING  (select rownum position, old_table.* from old_table where col_1 is not null) S
   ON (d.position = s.position)
   WHEN MATCHED THEN UPDATE SET D.Col_1 = S.Col_1
   WHEN NOT MATCHED THEN INSERT (d.position, D.Col_1)
     VALUES (s.position, S.Col_1);

MERGE INTO new_table D
   USING  (select rownum position, old_table.* from old_table where col_2_ is not null) S
   ON (d.position = s.position)
   WHEN MATCHED THEN UPDATE SET D.Col_2_ = S.Col_2_
   WHEN NOT MATCHED THEN INSERT (d.position, D.Col_2_)
     VALUES (s.position,S.Col_2_);

MERGE INTO new_table D
   USING  (select rownum position, old_table.* from old_table where col_3_ is not null) S
   ON (d.position = s.position)
   WHEN MATCHED THEN UPDATE SET D.Col_3_ = S.Col_3_
   WHEN NOT MATCHED THEN INSERT (d.position, D.Col_3_)
     VALUES (s.position, S.Col_3_);

select * from new_table order by position;

COL_1 COL_2 COL_3   POSITION
----- ----- ----- ----------
AA    XX    YYY            1
BB    MM    XXX            2
CC    ZZ                   3
      PP                   4
      CC                   5

You can drop POSITION column from new_table after the operation if you wish.

A: run below query
 INSERT INTO NEW_TABLE (Col_1, Col_2)
( SELECT Col_1, Col_2
    FROM OLD_TABLE_A
    WHERE not (Col_1 IS NULL and Col_2 IS NULL))

A: You can't do that like your way.
TRY THIS
INSERT INTO NEW_TABLE (Col_1,COL_2)
    SELECT A.Col_1,B.COL_1
    FROM OLD_TABLE_A A FULL OUTER JOIN OLD_TABLE_B B ON 1=1
    AND A.Col_1 IS NOT NULL
    AND B.Col_1 IS NOT NULL;


text:
Q: How can I stop a thread immediately if have multiple loops, without having multiple if else conditions? Now you may say, to stop a thread just use a global variable like this:
stop_thread = False

for i in range(3):
    if stop_thread:
        break
    else:
        print(i)

    for j in range(10):
        if stop_thread:
            break
        else:
            print(j)

Now the problem with this approach is I need to add multiple if: else statements in each loop I have (to stop the thread immediately), I think If I'm working with a bigger code this approach may not be very readable or not organized. so what will be a better approach?
The condition is: if my code is running and it's inside somewhere in 'j', and suddenly stop_thread = True then should not complete the second loop or in short, the thread should be stopped immediately without using more resources.

A: Exceptions are handy for this because they let you break control flows across any number of levels (even across function calls).  For example:
try:
    for i in range(3):
        print(i)
        for j in range(10):
            if i * j > 5:
                raise StopIteration
            print("   ", j)
except StopIteration:
    print("Stopped!")

0
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
1
    0
    1
    2
    3
    4
    5
Stopped!

Put the try/except at whatever level you want control to return to when the exception is raised; no matter how deeply nested the scope that raises the exception is, the program's execution will jump directly to that except, interrupting everything in between.


text:
Q: Amazon kinesis KCL 1.14.3 - multiple shards and instances issue I have a two instances of my app and two shards in kinesis.
Scenario,

*

*Launching instance 1. Application gets two shards. Everything is ok.

*Launching instance 2 after a few time laters. When Instance 1 processing records from both shards then in the background I have information about shutdown on shard2.
Invoking shutdown() for shard shardId-0000000000XX, concurrencyToken: 07b1aba8-0aa3-48c4-9992-XXXXXXXX, original Shutdown reason: ZOMBIE. childShards:null

I make checkpoint after finishing process records and now I loose lease for second shard then I can't make checkpoint and instance 2 received new records from kinesis immediately.
I try block method shutdown in instance1 to wait to finish records processing but instance2 received records from kinesis at the same time.
How to override any method to keep lease for shard 2 and gracefully finish processing records?


text:
Q: Set filename when exporting report via URL One of my favorite Salesforce reports tricks is that you can automatically download a report by adding URL parameters to the URL.
A link like this will immediately download the indicated report in CSV format:

https://domain.my.salesforce.com/00OA000000xxxxx?export=1&enc=UTF-8&xf=csv

Is there a way to control what the default filename of the downloaded report will be?


text:
Q: Oracle SQL Selecting weekly music rank procedure I'm trying to make procedure to select weekly music rank based on hits and likes.
create or replace procedure select_rank(
  v_title         IN music.title%TYPE,
  v_release_date  IN music.release_date%TYPE,
  v_hit           IN music.hit%TYPE
) is
    v_cnt number := 0;
  BEGIN
    select music.title, music.release_date, count(melon_user.user_idx) as likes, music.hit
    into v_rank, v_title, v_cnt, v_release_date, v_hit
    from melon_user, user_like_music, music
    where melon_user.user_idx = user_like_music.user_idx
      and user_like_music.music_idx = music.music_idx
    group by music.title, music.hit, music.release_date
    order by count(melon_user.user_idx) desc, music.hit desc;

    DBMS_OUTPUT.PUT_LINE('v_title: ' || v_title);
    DBMS_OUTPUT.PUT_LINE('v_cnt: ' || v_cnt);
    DBMS_OUTPUT.PUT_LINE('v_release_date: ' || v_release_date);
    DBMS_OUTPUT.PUT_LINE('v_hit: ' || v_hit);
END select_rank;
/

But I keep getting error says

PLS-00403: expression 'V_RELEASE_DATE' cannot be used as an
INTO-target of a SELECT/FETCH statement
PLS-00403: expression 'V_RELEASE_DATE' cannot be used as an
INTO-target of a SELECT/FETCH statement
PLS-00403: expression 'V_RELEASE_DATE' cannot be used as an
INTO-target of a SELECT/FETCH statement

how do I fix this?

A: In the procedure's signature you have:
v_release_date  IN music.release_date%TYPE,

v_release_date is an IN parameter and will be read only. If you want to assign values to it wthin the procedure and return them then make it an OUT (or IN OUT) parameter.
However, you have also:

*

*Not declared the v_rank variable.

*Your query appears likely to return multiple rows - SELECT .. INTO .. will only work for queries that return a single row. If this is the case then you either want to use BULK COLLECT INTO or return a cursor.


text:
Q: Calculate polynomial using LINQ As a part of a LINQ tutorial I have the following exersise:

You're required to calculate the value of an nth-degree polynomial.
The arguments of the function are:
-int x - the value of x for the polynomial
-IEnumerable coeffs - the polynomial coefficients
Example:
-Input: 2, [3,4,5]
-Output: 25 (calculated as 3*2^2+4*2+5)
Hint: you may need the overload of Aggregate() that takes a seed
value. You may also need to introduce a separate variable for tracking
the index of the element you're processing.

Any ideas?
Thank you so much!

A: As simple as that:
public static int Poly(int x, IEnumerable<int> coeffs)
{
    int idx = 0;
    return coeffs.Reverse().Aggregate(0, (p, q) => p + q * (int)Math.Pow(x, idx++));
}

A: First of all weird choice of IEnumerable coefficients. You could rewrite the below code to "subtract" rather than add to the current coefficient's rank, I guess that's what is expected by whoever designed the problem, since that would require using the overload which takes a seed value, since the first term's value would no longer be coefficient * x^0 (or simply coefficient) in that case. I just think this version is easier to follow and explain, and you should try writing the answer as expected based on this:
IEnumerable<int> coefficients = new int[] { 3, 4, 5 }.Reverse(); //we reverse the coefficients' order for simplicity, in real cases this might not be possible, since IEnumerable does not guarantee it is "replayable"
int x = 2;
int rank = 1; //we start from rank 1 since the first value is x^0 * coefficient, so it's already "added" in Aggregate and correct, we don't need to use the "seed value overload"
var polynomialValue = coefficients.Aggregate((sofar, current) =>
            {
                //we just need to worry about calculating the current value
                int currentValue = current * (int)Math.Pow(x, rank); //you could replace this with a for if you want or use Aggregate here as well, I was just lazy
                Console.WriteLine($"Adding {current} * {x}^{rank} = {currentValue}");
                rank++;

                //and returning the aggregated result which is what we calculated so far plus the current term
                return sofar + currentValue;
            });


text:
Q: How can I set API url such that the API is accessible only to IP whitelisted clients while the web application itself remains accessible to all? I have a web application accessible to the public on a url, say example.com.
Now I want to provide a REST API to some clients to access the data on my server through a protected url, say api.example.com.
I do not want this API link to be accessible to the public and want to keep it protected through a firewall, only requests originating from whitelisted IPs should be able to consume the services.
**Hosting the API as a separate application seems like an overkill
**URL based filtering, say blocking example.com/funnyapi/1 while allowing api.example.com/funnyapi/1 also doesn't seem to be a proper solution.
I am new to REST api.
Please suggest how to go about this.

A: I wouldn't restrict the access based on the hostname, but on the URI path: a web application will usually server the same content, no matter which hostname you use.
Let's say you deployed the Jersey servlet using web.xml at /contextPath/api:
<servlet>
    <servlet-name>ApiServlet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ApiServlet</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

Then you can easily add a Filter to your servlet which will filter according to the remote address. If you are using Tomcat there is already a filter that does that:
<filter>
    <filter-name>AddressFilter</filter-name>
    <filter-class>org.apache.catalina.filters.RemoteAddrFilter</filter-class>
    <init-param>
        <param-name>allow</param-name>
        <param-value>192.168.\d+.\d+</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>AddressFilter</filter-name>
    <servlet-name>ApiServlet</servlet-name>
</filter-mapping>

However, I'll consider adding also some <security-contraint>s:
<security-constraint>
   <web-resource-collection>
      <web-resource-name>Api</web-resource-name>
      <url-pattern>/api/*</url-pattern>
   </web-resource-collection>
     <auth-constraint>
         <role-name>apiUser</role-name>
     </auth-constraint>
     <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
</security-constraint>

Other ways to protect a RESTful API are described in Oracle's documentation.
Edit: If you are using another servlet container, you can create a filter like this:
public class RemoteAddrFilter implements Filter {

   private Pattern allow;

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
      final String pattern = filterConfig.getInitParameter("allow");
      if (pattern != null) {
         allow = Pattern.compile(pattern);
      }
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      if (allow == null) {
         return;
      }
      final String remoteAddr = request.getRemoteAddr();

      if (allow.matcher(remoteAddr).matches()) {
         chain.doFilter(request, response);
      } else {
         if (response instanceof HttpServletResponse) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
         }
      }
   }
}


text:
Q: Can YTD Video Downloader download YouTube playlists having more than 100 videos? I passed the URL https://www.youtube.com/playlist?list=PL8990452B640AD6D5 but it only fetches the first 100 videos.

(FL Studio 11-Time Stretch is the video #100 in the playlist).
I use Windows 7 SP1 x64 Ultimate and YTD Video Downloader.

A: You can download the others manually at sites like http://www.keepvid.com/, but that could be very lengthy depending on how many more videos there are. If there are too many videos, I would recommend using some type of automation software to perform the mouse and keyboard actions for you. For windows 7, I think there's a variety programs that can do this.
To answer your question:
As far as I know, YTD cannot do this.


text:
Q: Proofs of Sets and Subsets I have these proof problems that I need some help on, any direction would be great. Thanks
Let A, B, and C be subsets of some universal set U
(a) Prove the following:
IF $A \cap B$ $\subseteq$ C, and $'A \cap B$ $\subseteq$ C, THEN $B \subseteq C$
(b) Either prove the following or provide a counterexample:
IF $A \cap B$ = $A \cap C$ and $'A \cap B$ = $'A \cap B$ = $'A \cap C$, THEN B = C

A: Hint.  For (a) it is given that
$$A\cap B\subseteq C\ ,\quad A'\cap B\subseteq C$$
and you have to prove $B\subseteq C$.  You should know the basic way of proving a subset statement like this: assume $x$ is in the LHS, and use this assumption (and the given facts) to prove that $x$ is in the RHS.
So, let $x\in B$.  Consider two cases: either $x\in A$ or $x\in A'$.

*

*Case 1, $x\in A$.  Then $x\in A\cap B$, so $x\in C$.

*Case 2, [fill in the details yourself].

In both cases, $x\in C$.  Therefore $B\subseteq C$.
You can use (a) to answer (b).  We have
$$A\cap B=A\cap C\subseteq C\ ,\quad A'\cap B=A'\cap C\subseteq C\ ,$$
so by (a) we get $B\subseteq C$.  See if you can write out a similar argument to show $C\subseteq B$ and thereby prove $B=C$.


text:
Q: String override in whole project using .htaccess I have a string "this is fun".  i want to change to "JUST fun".
Can we change using .htaccess file. I have written this rule
RewriteRule ^this is fun  JUST fun

But nothing happens. I can't change the each file as its huge project and deployed on server already.
Can we do this using .htaccess only.

A: No. .htaccess is for Apache web server configuration, not for performing string replacements in PHP.

A: You can change it on PHP script itself. if you have similar strings in more than one places. then keep it as a variable in config file or the file which includes on those pages and then use that variable. I don't think the way via htaccess


text:
Q: Shortcut Precedence in Ubuntu 20.04 I am advised that I can use the shortcut Ctrl + ; in Google Sheets to insert the current date. However, I have Sogou Input installed on my machine and this shortcut is also bonded to the clipboard functionality in that app, and pressing this shortcut would show me the clipboard, without performing the date insertion in my Google sheet.
I am not able to remove this shortcut from the settings of Sogou Input. I wish to set a priority that Chrome (or whichever browser I use for Google Sheets) > Sogou for this shortcut. Is it possible?

A: This will not be possible. Shortcut keys are defined either global for the desktop, or specific for the application. Global keys take precedence over application specific keys: when you hit a shortcut key, it is first evaluated for global definitions, and if there is none, then it is passed to the application for handling.
The application you installed defined Ctrl+, as a global key, which conflicts with a key you want to use in Google Sheets. The only way to resolve that conflict is to change one of the shortcut definitions. If the application does not expose a way to do so, then it may not be possible without editing source code.


text:
Q: Flag overview in chat should be more detailed and have filters Moderators can look up which posts of a particular user were flagged in chat. This is very useful to quickly get some history on a user when handling a situation in chat. Because chat moderation is global on SE chat, quite often the moderator dealing with the situation is not familiar with the history of the users causing problems. Looking at the chat flags is a quick way to get see if the user has a history of misbehaving.
The problem with the flag report is that it doesn't really distinguish between validated and dismissed flags. So it can also be filled with spurious flags that were dismissed. This makes it harder to find the important flags that were validated and resulted in message deletion and suspension of the user.
The report should ideally indicate

*

*if the flag was validated or declined

*whether a mod was involved

*how many users validated or invalidated the flag

I'd also like to have the ability to filter for validated/invalidated/all flags, with the default on validated flags.


text:
Q: Memory Leak with UIBezierPath in swift I am working on an app that draws waveforms in a window that slides in and out of the main view. I find that if I open the sliding view several times the app begins to slow down. I have discovered that drawing the waveforms with a UIBezierPath is slowing down my app. I'm wondering if there is something that I need to do to terminate the current UIBezierPath and avoid a memory leak. Any suggestions or advice is appreciated I'm not super familiar with using UIBezierPath. Thanks in advance for the help!!!
import UIKit

class WaveView: UIView {
    enum WaveType{
        case sin
        case triangle
        case square
        case noise
        case sawtooth
    }
    var waveType: WaveType = .sin { didSet { setNeedsDisplay() } }
    var color = UIColor.black { didSet { setNeedsDisplay() } }
    let path = UIBezierPath()

    var isSelected = false {
        didSet {
            let tempColor: UIColor = self.backgroundColor!
            self.backgroundColor = color
            color = tempColor
        }
    }

    private var labelColor: UIColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)

    override func draw(_ rect: CGRect) {
        let middle: CGPoint = CGPoint(x: rect.midX, y: rect.midY)
        let width = rect.width
        let height = rect.height
        let graphWidth: CGFloat = 0.6
        let amplitude: CGFloat = 0.2
        let midOrigin = CGPoint(x: width * (1 - graphWidth) / 2, y: height * 0.50)

        switch waveType {
        case .sin:
            path.move(to: midOrigin)
            for angle in stride(from: 5.0, through: 360.0, by: 5.0) {
                let x = midOrigin.x + CGFloat(angle/360.0) * width * graphWidth
                let y = midOrigin.y - CGFloat(sin(angle/180.0 * Double.pi)) * height * amplitude
                path.addLine(to: CGPoint(x: x, y: y))
            }
        case .triangle:
            let d = rect.width * 0.2
            path.move(to: CGPoint(x: middle.x, y: middle.y - d))
            path.addLine(to: CGPoint(x: middle.x + d, y: middle.y + d))
            path.move(to: CGPoint(x: middle.x, y: middle.y - d))
            path.addLine(to: CGPoint(x: middle.x - d, y: middle.y + d))
        case .square:
            let d = rect.width * 0.2
            path.move(to: CGPoint(x: middle.x - d, y: middle.y + d))
            path.addLine(to: CGPoint(x: middle.x - d/3, y: middle.y + d))
            path.addLine(to: CGPoint(x: middle.x - d/3, y: middle.y - d))
            path.addLine(to: CGPoint(x: middle.x + d/3, y: middle.y - d))
            path.addLine(to: CGPoint(x: middle.x + d/3, y: middle.y + d))
            path.addLine(to: CGPoint(x: middle.x + d, y: middle.y + d))
        case.sawtooth:
            let d = rect.width * 0.2
            path.move(to: CGPoint(x: middle.x - d, y: middle.y + d))
            path.addLine(to: CGPoint(x: middle.x + d, y: middle.y - d))
            path.addLine(to: CGPoint(x: middle.x + d, y: middle.y + d))
        case .noise:
            path.move(to: midOrigin)
            for angle in stride(from: 3.0, through: 360.0, by: 3.0) {
                let x = midOrigin.x + CGFloat(angle/360.0) * width * graphWidth
                let y = midOrigin.y - CGFloat(Float.random(in: -1..<1)) * height * amplitude
                path.addLine(to: CGPoint(x: x, y: y))
            }
        }

        color.setStroke()
        path.lineCapStyle = .round
        path.stroke()
    }
}

A: Don't make the path instance a class member variable - just declare a local  UIBezierPath variable in your draw() method.
override func draw(_ rect: CGRect) {
    let path = UIBezierPath()
    // etc.
}

This will ensure the path instructions and data used for one draw() invocation is freed up.


text:
Q: Safe UPDATE JOIN in MySQL TableA and TableB exist in an RDS MySQL DB.
TableB is a temporary table.
I want to achieve: TableA += TableB
I chose to use UPDATE JOIN as follows:
UPDATE TableA
JOIN TableB
ON TableA.id = TableB.id
SET
    TableA.name = TableB.name,
    TableA.anotherid = TableB.someotherid;

But this is an unsafe update, so unless I add something like...
SET SQL_SAFE_UPDATES = 0;

The query fails.
Even if I add...
WHERE id > 0;

Where "id" is an integer primary key, I still get an unsafe update error.
How can I achieve the desired outcome without disabling SQL_SAFE_UPDATES?
Thanks!


text:
Q: Where can I find the offline installer of Google Chrome for the Mac? ..It's easy to find the offline installer for windows machines: http://support.google.com/installer/bin/answer.py?hl=en&answer=126299
However I need to install Chrome on a Mac which has no connection to the Internet.
Can anyone help? It seems like this should be an easy one but I have been surprisingly unsuccessful!
Kind Regards,
Luke

A: Just add ?platform=mac to the end of the Google Chrome download page's URL:
https://www.google.com/intl/en/chrome/browser/?platform=mac
The download is in the form of a DMG file, a disk image containing the Google Chrome app. Installation (as with many Mac apps) merely consists of double-clicking the disk image to mount it and then dragging the app into the system's Applications folder.


text:
Q: Is there a definition for a matrix Gaussian process? Consider this definition of a Gaussian Process:

For any set $$, a Gaussian Process ($\mathcal{GP}$) on $$ is a set of random variables $\{_:\in \}$ such that $\forall \in \mathbb{N}$, $\forall t_1,...,_ \in S$, $\{_{_1},...,_{_}\}$ has a multivariate Gaussian distribution.

What if each random variable $Z_t$ itself has a multivariate Gaussian distribution? Can we easily redefine a Gaussian process to say that "[..] the set $\{Z_{t_1}, ..., Z_{t_n}\}$ has a matrix Gaussian distribution"? Do we run into problems if we use this definition?

A: I found a definition in Sparse matrix-variate Gaussian process blockmodels for network modeling (Feng Yan, Zenglin Xu and Yuan Qi, 2012):

A matrix-variate Gaussian process is a stochastic process whose projection on any    finite   locations $U = [u^⊤_1, . . . , u^⊤_n]^⊤$ follows  a  matrix-variate  normal distribution.    Specically,  given $U$,  the  zero  mean matrix-variate Gaussian process on $M$ has the form: $p(M|U) =\mathcal{GP}_{n,n}(M; 0,K,G)= (2\pi)^{−n^2/2}\text{det}(K)^{−n/2} \text{det}(G)^{−n/2} \text{exp}\{−\frac{1}{2}\text{tr}(K^{−1}MG^{−1}M^⊤)\}$ where $k_{ij}=k(u_i,u_j)$ and $g_{ij}=g(u_i,u_j)$.

No one seems to talk much about matrix-variate Gaussian processes though.


text:
Q: Crystal report fails to load when application is deployed in IIS I  copied the packageTmp over to the inetpub/wwwroot, then added a website and included it as my path.
Installed the crystal report runtime, CRRuntime_32bit_13_0_4 - but still did not work.
I also have crystalreportviewers13 folder in wwwroot/aspnet _client/systemweb/4_0_30319
This is the error I encountered when I go to the page with crystal report.  May i know where the path is defined? This problem occurs when I deploy my application in IIS.
Exception Details: System.Runtime.InteropServices.COMException: Invalid file name.
Source Error:
An unhandled exception was generated during the execution of the current web request.  Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[COMException (0x800001fb): Invalid file name.]
CrystalDecisions.ReportAppServer.ClientDoc.ReportClientDocumentClass.Open(Object& DocumentPath, Int32 Options) +0
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.Open(Object& DocumentPath, Int32 Options) +95
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +270
[CrystalReportsException: Load report failed.]
CrystalDecisions.ReportAppServer.ReportClientDocumentWrapper.EnsureDocumentIsOpened() +333
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename, OpenReportMethod openMethod, Int16 parentJob) +877
CrystalDecisions.CrystalReports.Engine.ReportClass.Load(String reportName, OpenReportMethod openMethod, Int16 parentJob) +1183
CrystalDecisions.CrystalReports.Engine.ReportDocument.EnsureLoadReport() +113
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type) +53
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataTable dataTable)
....
This is the .cs code behind the .aspx code,for reportxx.rpt
m_reportxx = new reportxx();
CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;

DataTable dt = data.GetReport();

reportxx.SetDataSource(dt);

CrystalReportViewer1.ReportSource = m_reportxx;

I tried this and it worked while debugging in the visual studio environment.

A: I know this is an old post. but For anyone still looking for the answer:
You need to register crystal reports in page markup
<% @ Register Assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
    Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

Set the property 'Copy to Output Directory' of the report to 'Copy always'
the path of the file in the crystalreportsource will be ~/bin/YOURFOLDER/YOURFILE
<CR: CrystalReportSource ID ="CrystalReportSource1" runat ="server">
            <Report FileName="~/bin/oilmovement/rptOMDayEnd.rpt">
            </Report>
        </CR: CrystalReportSource>

Now the report should work

A: In my case, I found by 2 days the error and not see nothing wrong...Finally I used Procmon.exe (https://technet.microsoft.com/en-us/sysinternals/processmonitor.aspx?f=255&MSPPError=-2147217396) to trace the error.
I Filter by Result + is not + SUCCESS, I tried to run again the web application and appear the Error: ACCESS DENIED to Folder X.
I give the right permission to X folder and works fine.


text:
Q: Jupyter with ipywidgets and plotly v4? Using Jupyter from Anaconda install on Windows 10; also installed conda install -c plotly plotly, and apparently got Plotly v4.
I just want to start with a simple example - and use ipywidget sliders instead of Plotly ones. So, I've found:
https://moderndata.plot.ly/widgets-in-ipython-notebook-and-plotly/

EXAMPLE 3: interact
A simple example of using the interact decorator from ipywidgets to create a simple set of widgets to control the parameters of a plot.
Link to IPython notebook

Right - so I went to that link, and reorganized the code there into this:
import plotly.graph_objs as go
import numpy as np
from ipywidgets import interact

fig = go.FigureWidget()
scatt = fig.add_scatter()

xs=np.linspace(0, 6, 100)
fig.show()

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        scatt.x=xs
        scatt.y=np.sin(a*xs-b)
        scatt.line.color=color

... and when I run this cell, it draws an empty plot:

... and fails with:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\ipywidgets\widgets\interaction.py in update(self, *args)
    254                     value = widget.get_interact_value()
    255                     self.kwargs[widget._kwarg] = value
--> 256                 self.result = self.f(**self.kwargs)
    257                 show_inline_matplotlib_plots()
    258                 if self.auto_display and self.result is not None:

<ipython-input-21-7dcd6b5f2be1> in update(a, b, color)
     12 def update(a=3.6, b=4.3, color='blue'):
     13     with fig.batch_update():
---> 14         scatt.x=xs
     15         scatt.y=np.sin(a*xs-b)
     16         scatt.line.color=color

C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value)
    349         else:
    350             # Raise error on unknown public properties
--> 351             raise AttributeError(prop)
    352
    353     def __getitem__(self, prop):

AttributeError: x

Apparently, this is because there were enough changes in Plotly v4 to warrant a Version 4 migration guide | plotly; browsing through that, I tried modifying the code like so:
import plotly.graph_objs as go
import numpy as np
from ipywidgets import interact

fig = go.FigureWidget()
scattf = fig.add_scatter()
scatt = scattf.data[-1]

xs=np.linspace(0, 6, 100)
scattf.show()

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        scatt.x=xs
        scatt.y=np.sin(a*xs-b)
        scatt.line.color=color

... and now I don't get the error anymore - but the plot remains empty, and does not update when I drag the sliders.
Can someone let me know, how can I get this example working, so that a plot is drawn, and updated/redrawn when I drag the slider?

EDIT: messed a bit more, and now I have this code:
import plotly.graph_objs as go
import numpy as np
from ipywidgets import interact

fig = go.FigureWidget()
scattf = fig.add_scatter()
scatt = scattf.data[-1]

xs=np.linspace(0, 6, 100)
#scattf.show() # adds extra plot, if there is scattf.show() in update()!

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        scatt.x=xs
        scatt.y=np.sin(a*xs-b)
        scatt.line.color=color
        scattf.show()

update() # update once; so we don't get empty plot at start? not really - still getting empty plot at start, and another one after which is updated

Two problems here:

*

*After running the cell, there is first drawn plot empty, and another one plotted - how can I get it to plot only one plot with the default values? (Without the last update(), there is only one plot, but empty at start - and have to drag a slider to have it start drawing)

*Plot now changes when dragging the sliders - but it flickers a lot; any way to reduce the flicker?

A: Right, so found Interactive Data Analysis with FigureWidget ipywidgets - and rewrote the example accordingly; this has much smoother response, and no double draws - however, I'm still not sure if this is the way to do it; so if anyone knows better, please post ...
import plotly.graph_objs as go
import numpy as np
#from ipywidgets import interact, interactive
from ipywidgets import widgets
from IPython.display import display

aSlider = widgets.FloatSlider(
    value=2.0,
    min=1.0,
    max=4.0,
    step=0.01,
    description='a:',
    continuous_update=False
)

bSlider = widgets.FloatSlider(
    value=1.0,
    min=0.0,
    max=10.0,
    step=0.01,
    description='b:',
    continuous_update=True
)

colorDropdown = widgets.Dropdown(
    description='Color:',
    value='blue',
    options=['red', 'blue', 'green']
)

fig = go.FigureWidget()
#fig.show()
scattf = fig.add_scatter()
scatt = scattf.data[-1]

xs=np.linspace(0, 6, 100)

def response(change):
    with fig.batch_update():
        fig.data[0].x=xs
        fig.data[0].y=np.sin(aSlider.value*xs-bSlider.value)
        fig.data[0].line.color=colorDropdown.value
        fig.layout.xaxis.title = 'whatever'

aSlider.observe(response, names="value")
bSlider.observe(response, names="value")
colorDropdown.observe(response, names="value")

response("doesn't matter what I send here, just triggering") # MUST be before widgets.VBox - if response(x) is last, NOTHING is drawn!

widgets.VBox([aSlider,
              bSlider,
              colorDropdown,
              fig])

A: In Jupyter notebook or JupyterLab environments you can do like this:
import numpy as np
import plotly.graph_objects as go
from ipywidgets import interact

xs=np.linspace(0, 6, 100)

fig = go.FigureWidget()
fig.add_scatter()

@interact(a=(1.0, 4.0, 0.01), b=(0, 10.0, 0.01), color=['red', 'green', 'blue'])
def update(a=3.6, b=4.3, color='blue'):
    with fig.batch_update():
        fig.data[0].x=xs
        fig.data[0].y=np.sin(a*xs-b)
        fig.data[0].line.color=color
fig


text:
Q: Query not using indexes - Is there any way I can use index on REFERENCETYPE column.Below is the table structure and execution plan.
SQL> desc messaginginbox
 Name                                      Null?    Type
 ----------------------------------------- -------- ---------------------------
 MESSAGINGINBOXID                          NOT NULL VARCHAR2(28)
 REFERENCEID                               NOT NULL VARCHAR2(28)
 REFERENCETYPE                                      VARCHAR2(1)
 LISTINGID                                 NOT NULL VARCHAR2(28)
 CREATEDATE                                         DATE
 LASTUPDATED                               NOT NULL DATE
 UPDATEDBY                                 NOT NULL VARCHAR2(28)
 RENTERLISTINGMANAGERID                             VARCHAR2(28)
 OWNERLISTINGMANAGERID                              VARCHAR2(28)
 OCA                                       NOT NULL NUMBER(38)

SQL> create index idx_MESSAGINGIN_REFERENCE on MESSAGINGINBOX( REFERENCETYPE);
Index created.

SQL> analyze table MESSAGINGINBOX compute statistics;

Table analyzed.

SQL> select * from MESSAGINGINBOX where referencetype='B';

55 rows selected.

Execution Plan
-------------------------------------------------------------------------
| Id  | Operation         | Name           | Rows  | Bytes | Cost (%CPU)|
-------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |                | 71354 |     9M|   873   (1)|
|*  1 |  TABLE ACCESS FULL| MESSAGINGINBOX | 71354 |     9M|   873   (1)|
-------------------------------------------------------------------------

SQL> create bitmap index idx_MESSAGINGIN_REFERENCE
     on MESSAGINGINBOX( REFERENCETYPE);

Index created.

SQL> analyze table MESSAGINGINBOX compute statistics;

Table analyzed.

SQL> select * from MESSAGINGINBOX where referencetype='B';

55 rows selected.

Execution Plan
-------------------------------------------------------------------------
| Id  | Operation         | Name           | Rows  | Bytes | Cost (%CPU)|
-------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |                | 71354 |     9M|   873   (1)|
|*  1 |  TABLE ACCESS FULL| MESSAGINGINBOX | 71354 |     9M|   873   (1)|
-------------------------------------------------------------------------

SQL> select count(*) from MESSAGINGINBOX;

  COUNT(*)
----------
    142707

SQL> select distinct referencetype from MESSAGINGINBOX;

REFERENCETYPE
-------------
I
B

SQL> select count(distinct referencetype) from MESSAGINGINBOX;

COUNT(DISTINCTREFERENCETYPE)
----------------------------
                   2

A: One way is to take advantage of the fact that an index will not include entries where the full set of columns is NULL - i.e. create a function-based index that only indexes the 'B' records:
CREATE INDEX just_the_Bs ON messaginginbox
  (CASE WHEN referencetype='B' THEN 'B' END);

To use the index, however, you have to query using the same expression, e.g.:
SELECT * FROM messaginginbox
WHERE (CASE WHEN referencetype='B' THEN 'B' END) = 'B';

I would expect this to most likely use an index range scan followed by table lookup by rowid, given the relatively small volume of data which matches this predicate.
Another way is to use a hint - but note that you may need to add more hints (such as USE_NL) in order to avoid some very poor execution plans:
SELECT /*+INDEX(messaginginbox,idx_MESSAGINGIN_REFERENCE)*/ *
FROM messaginginbox WHERE referencetype='B';

In particular, note the advice here on hints - it can take a lot of hints to force the CBO to use a particular plan: http://jonathanlewis.wordpress.com/2013/05/28/how-to-hint/

A: A regular Btree index should work here, you just need to ensure there is a histogram on the ReferenceType column.
The column data is skewed, and the optimizer appears to know that.  It correctly estimates the distinct count as 2, which is why the rows estimate is almost exactly the number of rows divided by 2.  With the default settings, Oracle creates histograms based on the data distribution and how the columns are used.
Replace the deprecated analyze table with dbms_stats.gather_table_stats and be sure to use all the default options.  You also need to run a query filtering on ReferenceType BEFORE you gather stats.  By default, Oracle will not create a histogram if the column hasn't been used in a predicate.
Run this query to see if the histogram is generated:
select owner, table_name, column_name, histogram
from all_tab_columns
where table_name= 'MESSAGINGINBOX';

A histogram should at least improve the estimated cardinality (rows), which is the first step to fixing an execution plan.


text:
Q: 4 values were expected, but found 33. (near "(" at position 300) 4 values were expected, but found 33. (near "(" at position 300)
SQL query:
-- Transfer the data in the table `city`
INSERT INTO `city` (`id`, `name`, `slug`, `country_id`)
VALUES (1, 'Alor Gajah', 'alor-gajah ', 1),
(2, 'Ampang Jaya', 'ampang-jaya', 1),
(3, 'Alor Gajah', 'alor-gajah', 1),
(4, 'Alor Setar', 'alor- Setar', 1),
(5, 'Ampang', 'ampang', 1),
(6, 'Ampang Jaya', 'ampang-jaya', 1),
(7, 'Ayer Itam', 'ayer-itam' , 1,
(8, 'Ayer Keroh', 'ayer-keroh', 1),
(9, 'Ayer Molek', 'ayer-molek', 1),
(10, 'Ayer Tawar', 'ayer-tawar' , 1),
(11, 'Bagan Serai', 'bagan-serai', 1),
(12, 'Bahau', 'bahau', 1), (13, 'Balakong', 'balakong', 1),
(14, 'Bandar Baru Bangi', 'bandar-baru-bangi', 1),
(15, 'Bandar Baru Salak Tinggi','bandar-baru-salak-tinggi', 1),
(16, 'Bandar Jengka Pusat', 'bandar-jengka-pusat', 1),
(17, 'Bandar Maharani', 'bandar-maharani', 1),
(18, 'Bandar Penggaram', 'bandar-penggaram', 1),
(19, 'Banting', 'banting', 1),
(20, 'Batang Berjuntai', 'batang-berjuntai', 1),
(21, 'Batu Arang', 'batu-arang', 1),
(22, 'Batu Berendam', 'batu-berendam', 1),
(23, 'Batu Caves', 'batu-caves', 1),
(24, 'Batu Delapan Bazaar', 'batu-delapan-bazaar', 1),
(25, 'Batu Gajah', 'batu-gajah', 1),
(26, 'Batu Sembilan Cheras', 'batu-sembilan- Cheras', 1),
(27, 'Bayan Lepas', 'bayan-lepas', 1),
(28, 'Beaufort', 'beaufort', 1),
(29, 'Bedong', 'bedong',1),
(30, 'Bemban', 'bemban', 1),
(31, 'Bentong', 'bentong', 1),
(32, 'Beranang', 'beranang', 1),
(33, 'Bidor ', 'bidor', 1),
(34, 'Bintulu', 'bintulu', 1),
(35, 'Bukit Bakri', 'bukit-bakri', 1),
(36, 'Bukit Baru', 'bukit -baru', 1)

MySQL returns:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 41

this mysql is export from my database...is city SQL
I just key in all the city by manual...anybody can help me fix this?

A: Your issue is here:

 (6, 'Ampang Jaya', 'ampang-jaya', 1),
   (7, 'Ayer Itam', 'ayer-itam' , 1,
   (8, 'Ayer Keroh', 'ayer-keroh', 1),

You have missed out the closing ) on the row 7. Is this a typo?
FIXED:
(6, 'Ampang Jaya', 'ampang-jaya', 1),
(7, 'Ayer Itam', 'ayer-itam' , 1),
(8, 'Ayer Keroh', 'ayer-keroh', 1),


text:
Q: Wordpress : Create independent page for a post Sorry if I am not clear but I am looking for a way to display in an independant template the comment of a given post or something else (of the given post). I don't understand at all the process.

*

*I have a post : website.com/postname

*I want to display only comments of the post here : website.com/postname/comment
If you could give me a beginning of answer...


text:
Q: Get Foreign Key Relationship Information ModelBuilder allows you declare relationships between entities, but we need a way to get all relationship information at runtime. We need to generate JSON to expression our POCO's relationships like so.
relationships = {
            oneToOne: [{
                type: Person,
                hasKey: "id",
                hasOne: "ldapAccount",
                ofType: LdapAccount,
                withKey: "id",
                withForeignKey: "id",
                withOne: "person"
            }],
            oneToMany: [{
                type: Company,
                hasKey: "id",
                hasMany: "agencyRoles",
                ofType: AgencyRole,
                withKey: "id",
                withForeignKey: "companyId",
                withOne: "company"
            }],
            manyToMany: [{
                type: PermissionGroup,
                hasKey: "id",
                hasForeignKey: "permissionId",
                hasMany: "permissions",
                ofType: Permission,
                withKey: "id",
                withForeignKey: "permissionGroupId",
                withMany: "permissionGroups",
                usingMappingType: PermissionGroupToPermission
            }]
        };

Does anyone know how to retrieve relationship information from a context at runtime?


text:
Q: R Shinyapps advanced settings
Here is a screenshot of the shinyapps.io settings. Can someone please explain what these things are and how they relate to each other? There is a limited one liner definitions in the settings area and shiny-server admin guide which doesn't explain much.

*

*To start off with, what is an instance, worker and process?

*What is the difference between the three different timeouts:
'Instance Idle Timeout','Connection Timeout' and 'Idle Timeout'?

*How is any of this related to the number of available cores? How do I even know how many cores are available?

*Does my app use multiple cores if available?

*Do I have to do that explicitly program use of multi-cores or does
shiny automatically distribute tasks?

A: Shiny has a pretty good overview of the concepts here. In part addressing what settings do:

Tuning parameters
The architecture described above uses two load factors to fine tune the performance of your applications.
Worker Load Factor – The threshold percentage after which a new browser connection will trigger the addition of a new worker.
Instance Load Factor – The threshold percentage after which a new connection will trigger the addition of a new Application Instance (limited to the maximum instance limit, free tier is 1)
Each load factor is based on the idea of a threshold percentage, which is the percentage of available connections or processes that are allowed to open before shinyapps.io launches another worker or Application Instance. Both settings are configurable in the Advanced tab within the Settings page for a given application.

...and in part addressing how shiny apps work:

*

*Publisher creates a new application and deploys it to shinyapps.io at https://{someaccount}.shinyapps.io/{appname}

*A request from an end user triggers the start of an Application Instance

*Application Instance will start with at least one worker

*The number of connections to the worker increases as additional end users visit the application. When the Worker Load Factor threshold is exceeded, shinyapps.io adds another worker, so long as the max number of workers per Application Instance has not been reached. New connections are now assigned to the new worker.

*New workers are added when needed as new users continue to visit the application. When the Instance Load factor is exceeded, shinyapps.io will trigger the addition of another Application Instance, so long as the max number of Application Instances has not been reached (the max number may be one).

*Shinyapps.io closes connections as end users close their browsers or are idle for longer than the Idle Timeout.

*Shinyapps.io shuts down each worker once it has no further connections open.

*Shinyapps.io turns off each Application Instance once it has no running workers, or once its workers are idle for longer than the Instance Idle Timeout. This threshold timeout should be increased if you would like to avoid restarting the application. Note: Increasing the timeout will use up more active hours.

*A new request from an end user causes shinyapps.io to turn on an Application Instance, and stages 2-9 repeat.

From these you may be able to piece together what you need. Beyond that, I recommend asking specific questions separately on StackOverflow as they are more likely to be answered that way.


text:
Q: Java WebServer refusing to connect I tried to make a simple java class that runs a server on localhost and just makes a page with the word test as an HTML title and the word test in the body. For some reason, when I run it and try to connect, it refuses to connect. Here's my code:
package Server.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerListenerThread extends Thread{

    private int port;
    private ServerSocket serverSocket;
    public ServerListenerThread(int port) throws IOException {
        this.port = port;
        this.serverSocket = new ServerSocket(port);
    }

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            String html = "<title>Test</title>
test
";
            final String CRLF = "\r\n"; // 13, 10
            String response = "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + html.getBytes().length + CRLF + CRLF + html+ CRLF + CRLF;

            outputStream.write(response.getBytes());

            inputStream.close();
            outputStream.close();
            socket.close();
            serverSocket.close();
        } catch(Exception e) {

        }
    }

}

In my main method, I start a new ServerListenerThread on port 276.

A: you need to keep your thread alive. you can use while for that.
below is the basic modification i did. you can refactor more.
Also create ServerSocket once only.
public class ServerListenerThread extends Thread{
public static void main(String args[]) throws IOException {
    ServerListenerThread s1= new ServerListenerThread(276);
    s1.start();
}

private int port;
private ServerSocket serverSocket;
public ServerListenerThread(int port) throws IOException {
    this.port = port;
    this.serverSocket = new ServerSocket(port);
}

@Override
public void run() {
    while (true) {
        // spin forever

        try {
           // ServerSocket serverSocket = new ServerSocket(port);
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            String html = "<title>Test</title>
test
";
            final String CRLF = "\r\n"; // 13, 10
            String response =
                    "HTTP/1.1 200 OK" + CRLF + "Content-Length: " + html.getBytes().length + CRLF + CRLF + html
                            + CRLF + CRLF;

            outputStream.write(response.getBytes());

            inputStream.close();
            outputStream.close();
            socket.close();
            serverSocket.close();
        } catch (Exception e) {

        }
    }
}

}


text:
Q: iOS 8 sizeThatFits for UITextView text not returning correct height (AutoLayout) I'm trying to vertically center a UITextView using the appropriate height retrieved from sizeThatFits. There are a plethora of other answers that suggest this is the most appropriate way of calculating this.
(Note that I've tried it both with plain and attributed strings, and both exert the same behavior).
No matter what I try (even using attributed strings and setting the font size or line height to something bigger or smaller) it always only shows a certain truncated number of characters of text (in this case, 3 lines, and it's always exactly the same). What am I missing?
_textView.text = [_collectionDescription lowercaseString];
_textView.font = [UIFont fontLight:22];
_textView.textColor = [UIColor whiteColor];
_textView.textAlignment = NSTextAlignmentCenter;
_constraintTextViewHeight.constant = ceilf([_textView sizeThatFits:CGSizeMake(_textView.frame.size.width, FLT_MAX)].height);

[_textView setNeedsDisplay];
[_textView updateConstraints];

A: As always with AutoLayout, you have to do:
[_textInfoView layoutIfNeeded];

(don't even need the setNeedsDisplay at all).
So, fully working:
_textView.text = [_collectionDescription lowercaseString];
_textView.font = [UIFont fontLight:22];
_textView.textColor = [UIColor whiteColor];
_textView.textAlignment = NSTextAlignmentCenter;
_constraintTextViewHeight.constant = ceilf([_textView sizeThatFits:CGSizeMake(_textView.frame.size.width, FLT_MAX)].height);

[_textView layoutIfNeeded];
[_textView updateConstraints];

A: Instead of using sizeThatFits: method, you may use following method:
well you can try this:
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
NSString *text = _textView.text;
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:attributes
                                 context:nil];
_constraintTextViewHeight.constant = CGRectGetHeight(rect)

This method also considers line breaks in string text


text:
Q: Android spinnerStyle not working First excuse me for my english.
Im designing a theme (With HoloEveryWhere) and im trying to style default spinner.
The problem is that the spinnerStyle is not working. I'm testing with this layout.
            <Spinner
                android:id="@+id/spCountry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/etPhone" />

And im using this for my theme.xml..
 <item name="android:spinnerStyle">@style/Coloquium.Spinner.Ruby</item>

and in styles.xml
<style name="Coloquium.Spinner.Ruby" parent="@style/Holo.Spinner.Light">
    <item name="android:background">@drawable/spinner_holo_white</item>
</style>

The problem is that the spinner style is never applied (Others styles like edittextstyle or buttonstyle works fine), the background never change, But i tried this style as spinnerItemStyle and work fine, but spinnerItemStyle is the inner view, and i want to style the outer, the spinner.
If i set background directly in the layout node, the background change fine, but i need to set spinnerStyle for all spinners in the theme, not in layout.
I test a lot of post looking for a solution without success.

A: The solution is:
HoloEveryWhere appear use "spinnerStyle" and not "android:spinnerStyle".
But really... I can't find the HoloEveryWhere documentation about this. :S


text:
Q: gspread spreadsheet not loading, no errors I am writing a python script using gspread. Here is the code:
json_key = json.load(open('<path to json>'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)
gc = gspread.authorize(credentials)

print "0"
worksheet = gc.open("<name of sheet>").get_worksheet(2)
print "1"

The 0 is printed so that means the credentials and everything are loading. But, when I try to load the actual sheet, with the actual name where it says "name of sheet", it doesn't actually work. Nothing happens, and there are no errors, and it never prints 1. Am I doing something wrong? I don't think I am cause I have used this exact code for weeks, and I am suddenly having a problem.

A: gdata spreadsheets API is hanging
https://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3939
https://github.com/burnash/gspread/issues/278
The api is down right now.


text:
Q: AWS AppSync with Firebase Authentication I would like to use Firebase Auth as the Authorization service for AWS AppSync.
In the AppSync settings, I tried to add Firebase Auth as an OpenID Connect provider, but it seems like I'm doing something wrong since I'm getting this error while trying to make a request with a Firebase Auth tokenId:
{
  "errors": [
    {
      "errorType": "UnauthorizedException",
      "message": "Missing authorization header"
    }
  ]
}

In AppSync im using these settings:

*

*Authorization type: OpenID Connect

*OpenID Connect provider domain (Issuer URL): https://securetoken.google.com/<Firebase Project ID>

*Client ID: <Firebase Api Key>

*Issued At TTL: 0

*Auth Time TTL: 0
When performing the query I use the TokenId provided by firebase, and not the ones that come from the federated identity provider(Facebook or Google for example).

A: Apparently, I didn't need to specify the Client ID in the settings. Works fine without it.


text:
Q: Loading a local html file on jar into web engine I'm having a problem in loading an HTML file to my application onto my web engine.
Currently, if I run my application throw IntelliJ IDE. The HTML page is being loaded correctly! But when I make the project and I run the application to my terminal. The HTML file isn't being loaded at all.
My code for loading HTML page to my web engine.
WebEngine we = wv.getEngine();
we.setJavaScriptEnabled(true);
String htmlFile = getClass().getResource("/html/index.html").toExternalForm();
System.out.println(">>>"+htmlFile);
we.load(htmlFile);

Why do I have my println ? To check the path of my HTML page.
It seems that when I run it on my project IntelliJ. The application runs correctly. As shown under:
>>>file:/Developer/Liss-SDE/out/production/liss/html/index.html

But when I do it on my terminal. It prints me something which I don't understand.
>>>jar:file:/Users/damien/Desktop/liss%7cSDE/liss.jar!/html/index.html

Why does it put a jar: at the beginning? Also why is he putting a ! to my program .jar ? And if we compare to the other print, it is totally different!
I extracted the .jar file to check if the directory and the HTML file was missing, but everything is ok.
So what is the problem that I am having?

A: The name of the file, with the jar: and the !, is the URL to the file in the JAR, as defined in JarURLConnection.  Using getResource() on this is showing the file correctly. Use getResourceAsStream() to access the file contents, which should be enough in your case.
You can also get direct access to the contents of your jar using the java jar API. There is a good introduction with a couple of examples at this java2s tutorial page. For jars in your class path (which seems to be the case this time) the jar API is used automatically for you within the getResource() and getResourceAsStream() methods of Class.
From Java 7 onwards, the FileSystem api has been available and hides some of the more awkward details. This Oracle technote gives a concise introduction to the API and how to use it.
Snippet from that page, tweaked to your case:
import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;

public class WhatsInMyJarFile {
    public static void main(String [] args) throws Throwable {
        // locate file system by using the syntax
        // defined in java.net.JarURLConnection
        URI uri = URI.create("jar:file:/Users/damien/Desktop/liss%7cSDE/liss.jar");

       try (FileSystem jarfs = FileSystems.newFileSystem(uri)) {
            Path pathInJarfile = jarfs.getPath("/html/index.html");
            doStuff(Files.newInputStream( pathInJarfile ));
        }
    }
}

A: So I managed in solving this...
And I think this is a weird thing sincerely...
If I collapse all my code into the loading of the web engine everything works correctly...
sigh
I hope that future adventurers will not have this issue as I got...
Simply do that:
we.load(this.getClass().getResource("/html/index.html").toExternalForm());

I don't know if it is a bug or not... Because I didn't changed anything to my project unless putting this line of code...
Thank you to Paul Hicks for trying to help me :)
BUT I found a bug ! XD
So if I click with my mouse to my .jar, the application runs correctly! But if I run the .jar throw my terminal by writing java -jar liss.jar, then it appears that the application doesn't work! xD
I don't know why sincerely...


text:
Q: Create rectangle below a button with CSS only I'm trying to create a CSS based 'button' like this:

The blue is just a background, so it's only about the text "Welkom" and the rectangle displayed below.
Whenever it's active or hovered over it should display a rectangle BELOW the button.
HTML: (This is the button)

Welkom

A: If the below is your HTML:

Welkom

Then you can do this:
li:hover,li:active{
    border-bottom:3px solid blue; /*change blue to the color you want*/
}

See this demo

Fiddle in response to comment: Fiddle 2
The above uses box-align property(http://www.w3schools.com/cssref/css3_pr_box-align.asp) to center the bottom border(without requiring adjustment) but it will not work in IE9 and below

Fiddle 3 : Will work in all browsers but you will have to adjust the bottom at the center using relative positioning for both li and a tag within it.

A: you can do that on :hover with a border-bottom:
But you may and a border already without the hover so avoid jumping.
a {
border-bottom: 5px solid transparent;
}

a:hover {
  border-color: blue
}

The code above is not all you may need.
-Sven
EDIT: as you see the other answer, U ay do that on the list element directly.

A: simple just follow below code:

HTML:

Welkom

CSS:

.link { background-color:#379AE6; width:100%; padding:8px; padding-bottom:16px; }

.link a{ font-family:arial; text-decoration:none; color:#fff;
    }

.link a:hover{ border-bottom:8px solid #6BBBF8; padding-bottom:8px;
    }


text:
Q: Malform query when try to delete bulk records I want to delete bulk records from a custom object.
i am reffering below url:
https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/asynch_api_code_curl_walkthrough.htm
and my batch is
Account obj = new Account(id="0012800000XRdPgAAL");
delete obj;

InvalidBatch : Failed to process query: MALFORMED_QUERY: unexpected
  token: Account

Can any one please help me , how can i delete multiple records from a custom object using API.


text:
Q: Creating a new post returns a NoMethodError: undefined method `summary' for # I have a Post model and Summary model where a post has only one model.
#Post Model
class Post < ActiveRecord::Base
has_one :summary, dependent: :destroy

default_scope { order('rank DESC') }
    scope :visible_to, -> (user) { user ? all : joins(:topic).where('topics.public' => true ) }

    validates :title, length: {minimum: 5}, presence: true
    validates :body, length: {minimum: 20}, presence: true
    validates :topic, presence: true
    validates :user, presence: true

#Summary Model
class Summary < ActiveRecord::Base
belongs_to :post

validates :body, length: { maximum: 100 }, presence: true
end

When I try to create a post with a summary, by clicking save button is a standard form, something in my view causes an error.
undefined method `summary' for #<Post::ActiveRecord_Associations_CollectionProxy:0x007ff7fdcafd80>

<%= markdown @post.title %>

<%= markdown @post.summary.body %>
 ** Its the summary in this line **
      <%= render partial: 'votes/voter', locals: { post: @post } %>

<%= markdown @post.body %>

<%= image_tag @post.image.url(:thumb) if @post.image? %>

Apparently, I'm not able to call summary on my post.
Because summary is its own class, I'm having trouble with my variables in the view above and the corresponding controllers.
class Topics::PostsController < ApplicationController
def create
    @topic = Topic.find(params[:topic_id])
    @post = current_user.posts.build(post_params)
    @post.topic = @topic
    @summary = @post.build(summary_params)
    @summary = @post.summary
    authorize @post

    if @post.save && @summary.save
        @post.create_vote
      flash[:notice] = "Post was saved."
      redirect_to [@topic, @post]
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :new
    end
  end

Do I have the names mixed up? How should I be joining these two models to create and display a summary for for a new post?

A: Try this instead:
def create
  @topic = Topic.find(params[:topic_id])
  @post = current_user.posts.build(post_params)
  @post.topic = @topic
  authorize @post

  if @post.save
    @summary = @post.build_summary(summary_params)
    if @summary.save
      @post.create_vote
      flash[:notice] = "Post was saved."
      redirect_to [@topic, @post]
    end
  else
    flash[:error] = "There was an error saving the post. Please try again."
    render :new
  end
end


text:
Q: c++ perform sequence-for to plain array The c++ sequence-for based on sequence.begin()/end()/++,but the plain array such as int a[10]; can also perform this.Why?Is there some implicit cast from plain array to std::array?

A: For plain arrays range-for uses special handling:

If range_expression is an expression of array type, then begin_expr is __range and end_expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed)


text:
Q: Swift (iOS) TokenAuthenticationStrategy gives me an unresolved identifier error for AlchemyLanguage API I get an error unresolved identifier when I try to follow the steps to use AlchemyLanguage iOS API with Swift. I have imported WatsonDeveloperCloud and have the following two lines:
let token = TokenAuthenticationStrategy(token: "myApiKeyGoesHere")
let alchemyLanguageInstance = AlchemyLanguage(tokenAuthenticationStrategy: token)

A: Here is how to instantiate an AlchemyLanguage object in the most recent version of the Watson Developer Cloud iOS SDK:
let alchemyLanguage = AlchemyLanguage(apiKey: "<api-key>")

Unfortunately, the readme was not updated to reflect a change in December that renamed the TokenAuthenticationStrategy class to APIKeyAuthenticationStrategy and the AlchemyLanguage(tokenAuthenticationStrategy:) init method to AlchemyLanguage(authStrategy:). I opened an issue to track this problem on the Watson Developer Cloud iOS SDK repository.


text:
Q: Identifying dates that falls in the same month, day period across years So I've got a whole list of dates. I need to find out which dates fall within the same range (day and month) as my stipulated "Start Date" and "End Date" for each of the years.
For e.g. for Start Date:2/12/2004, End Date: 31/1/2005, dates falling between 2/12/2000 and 31/1/2001, 2/12/2001 and 31/1/2002, 2/12/2001 and 31/1/2002 etc should be flagged out as "Valid".
Currently I use an upper/lower limit and then test if the Date falling within the range.
Excel Formulas:
Upper: =DATE(YEAR(Date),MONTH(Test),DAY(Test)+Look Back Period)
Lower: =DATE(YEAR(Date),MONTH(Test),DAY(Test)-Look Back Period)
Valid: =IF(AND(Date<=Upper,Date>=Lower),1,0)
Test                    1/1/2005
Look Back Period (Days) 30
Start Date              2/12/2004 (=Test + Look Back Period)
End Date                31/1/2005 (=Test - Look Back Period)

    Date        Upper       Lower       Valid
    04/01/2000  31/1/2000   2/12/1999   1
    05/01/2000  31/1/2000   2/12/1999   1
    06/01/2000  31/1/2000   2/12/1999   1
    07/01/2000  31/1/2000   2/12/1999   1
    10/01/2000  31/1/2000   2/12/1999   1
    11/01/2000  31/1/2000   2/12/1999   1
    12/01/2000  31/1/2000   2/12/1999   1
    13/01/2000  31/1/2000   2/12/1999   1
    14/01/2000  31/1/2000   2/12/1999   1
    17/01/2000  31/1/2000   2/12/1999   1
    18/01/2000  31/1/2000   2/12/1999   1
    19/01/2000  31/1/2000   2/12/1999   1
    20/01/2000  31/1/2000   2/12/1999   1
    21/01/2000  31/1/2000   2/12/1999   1
    24/01/2000  31/1/2000   2/12/1999   1
    25/01/2000  31/1/2000   2/12/1999   1
    26/01/2000  31/1/2000   2/12/1999   1
    27/01/2000  31/1/2000   2/12/1999   1
    28/01/2000  31/1/2000   2/12/1999   1
    31/01/2000  31/1/2000   2/12/1999   1
    01/02/2000  31/1/2000   2/12/1999   0
    02/02/2000  31/1/2000   2/12/1999   0
    03/02/2000  31/1/2000   2/12/1999   0
    04/02/2000  31/1/2000   2/12/1999   0
    07/02/2000  31/1/2000   2/12/1999   0
    .
    .
    .
    30/11/2000  31/1/2000   2/12/1999   0
    01/12/2000  31/1/2000   2/12/1999   0
    04/12/2000  31/1/2000   2/12/1999   0 <-- :(
    05/12/2000  31/1/2000   2/12/1999   0 <-- :(
    06/12/2000  31/1/2000   2/12/1999   0 <-- :(
    07/12/2000  31/1/2000   2/12/1999   0 <-- :(
    08/12/2000  31/1/2000   2/12/1999   0 <-- :(
    11/12/2000  31/1/2000   2/12/1999   0 <-- :(
    12/12/2000  31/1/2000   2/12/1999   0 <-- :(
    13/12/2000  31/1/2000   2/12/1999   0 <-- :(
    14/12/2000  31/1/2000   2/12/1999   0 <-- :(
    15/12/2000  31/1/2000   2/12/1999   0 <-- :(
    18/12/2000  31/1/2000   2/12/1999   0 <-- :(
    19/12/2000  31/1/2000   2/12/1999   0 <-- :(
    20/12/2000  31/1/2000   2/12/1999   0 <-- :(
    21/12/2000  31/1/2000   2/12/1999   0 <-- :(
    22/12/2000  31/1/2000   2/12/1999   0 <-- :(
    25/12/2000  31/1/2000   2/12/1999   0 <-- :(
    26/12/2000  31/1/2000   2/12/1999   0 <-- :(
    27/12/2000  31/1/2000   2/12/1999   0 <-- :(
    28/12/2000  31/1/2000   2/12/1999   0 <-- :(
    29/12/2000  31/1/2000   2/12/1999   0 <-- :(
    01/01/2001  31/1/2001   2/12/2000   1
    02/01/2001  31/1/2001   2/12/2000   1
    03/01/2001  31/1/2001   2/12/2000   1
    04/01/2001  31/1/2001   2/12/2000   1
    05/01/2001  31/1/2001   2/12/2000   1
    08/01/2001  31/1/2001   2/12/2000   1
    09/01/2001  31/1/2001   2/12/2000   1
    10/01/2001  31/1/2001   2/12/2000   1
    11/01/2001  31/1/2001   2/12/2000   1

The formula works fine as long as the periods do not cross between years. However, in the event the Upper and Lower limit cross through between 2 different years, the Valid formula will exclude the previous year's values.
Is there any solution to this?

A: To do this with formulas, set up two more helper columns
lower1: =DATE(YEAR(Date)-1,MONTH(StartDate),DAY(StartDate))
upper1: =C8+2*LookBack
Lower2: =DATE(YEAR(Date),MONTH(StartDate),DAY(StartDate))
Upper2: =Lower2+2*LookBack

valid:  =IF(OR(AND(Date>=lower1,Date<=upper1),AND(Date>=Lower2,Date<=Upper2)),1,0)

All we are doing is setting up two sets of bounds. Relative to Date, one starts with the previous year; the other starts with the current year.  Then check Date to see if it falls within either set.
For appearances, there is no requirement that the bounds columns be visible, or even that they be contiguous with the Date and valid columns.


text:
Q: Reading gscript file with Colab Imagine I got some gscript file sitting in my Google Drive in some Test folder. I can see it from Colab like so:
from google.colab import drive
drive.mount('/content/drive')
import os
files = os.listdir("drive/My Drive/Test")
files
['Test_app.gscript']

However, I tried some options to read Test_app.gscript, but all of them have given me OSError: [Errno 95] Operation not supported: 'drive/My Drive/Test/Test_app.gscript'
Is there a way to read this slippery gscript doc?


text:
Q: Can you Create a Native Vue App with NuxtJS Nuxt is great and I understand clearly the problems it solves.
Where one desires a Nuxt-based SPA as well as native ios/ android versions, does it mean that you have to deal with 2 different code bases and no way to package the resulting SPA as a Vue Native app?

A: You can use Nativescript-vue if you want to work in similar manner as in Nuxt.js.
And if your web app is built in vue, then you can share your code for mobile and web apps simultaneously https://nativescript-vue.org/en/docs/getting-started/code-sharing/

A: I came across the nice article that compares the native options in the Vue ecosystem, which could help you if you are looking for a similar framework: Vue mobile development Frameworks, Mobile Apps with Vue
Alternatively, if you are keen in using Nuxt but limited to android this will help you Android App from Nuxt


text:
Q: Proving that a function is not one to one Can you prove that this functions is not one-to-one?
$f:\Bbb{R} \to \Bbb{R}$, defined by:
$$f(x)=\begin{cases}
x^2&\text{if }x>-1\\
x-4&\text{if }x\le1
\end{cases}$$
I think there is something wrong in my book with this exercise.

A: Stealing lulu's comment so we have an answer:  note that $f(-\frac 12)=\frac 14=f(\frac 12)$ so the function is not one-to-one.


text:
Q: Serialize Steema Tee Chart DrawLine When I serialize a DrawLine (https://www.steema.com/files/public/teechart/java/v1/docs/JavaDoc/com/steema/teechart/tools/DrawLine.html) that contains DrawLineItem's (https://www.steema.com/files/public/teechart/java/v1/docs/JavaDoc/index.html?com/steema/teechart/tools/DrawLines.html) then Java throws a java.io.NotSerializableException: com.steema.teechart.tools.DrawLineItem error.
The objective of DrawLine is to store DrawLineItem's and the Tee Chart documenation states that DrawLine implements java.io.Serializable, but DrawLineItem is not. Please can you assist me to serialize a DrawLine with DrawLineItems or explain why this is has been done like this because I do not see a reason why anyone would need to serialize a DrawLine that did not contain any DrawLineItems?
Alternatively; I can create my own Object with all of the relivant information if you could tell me what information in the DrawLine I need to store/restore the DrawLine and what the code is so that I can draw a DrawLine via code.


text:
Q: How to change MySQL checkpoint interval I've tried changing "progress status update interval" in MySQL Workbench but I'm not sure if the change happened. The interval that I've tried are 1, 4, 20, 200, and 400000.
However, the running time of this query doesn't change much under those different interval settings:
UPDATE trade SET quantity = quantity + 100;

Could anyone help me on change the checkpoint interval? Thanks.

A:
"I've tried changing "progress status update interval" in MySQL
  Workbench but I'm not sure if the change happened. The interval that
  I've tried are 1, 4, 20, 200, and 400000.
However, the running time of this query doesn't change much under
  those different interval settings:"

These settings don't affect the running time of a query at all. They are parameters you might change if you have a long running query and a slow connection. But this parameter has nothing to do with how long your queries will actually take.
That being said, you might be able to speed up this query a bit using an index on your quantity variable. Alternatively, you might try chunking the table into pieces, eg,
UPDATE trade SET quantity = quantity + 100 WHERE trade.id BETWEEN 1 AND 10000;
UPDATE trade SET quantity = quantity + 100 WHERE trade.id BETWEEN 10001 AND 20000;

etc. But just changing progress status update interval in the Workbench... that's not gonna affect your query speed at all. Totally unrelated.


text:
Q: F# idiomatic Try Until I have a function that takes an input and either succeeds and returns Some of the input or returns None. I'll make the example a list of phone numbers that get dialed until someone answers one of the numbers, and then the rest of the numbers should be skipped. And at the end there is a logging of a successful number or of an error message.
My first solution I think is too complicated and also uses a seeding of the failure state on the first try, which seems inelegant:
type PhoneNumber = int

let tryCallNumber phoneNumber =
    if phoneNumber % 2 = 0 then Some phoneNumber
    else None

let nextCall phoneNumberOption nextNumber =
    match phoneNumberOption with
    | Some num -> phoneNumberOption
    | None     -> tryCallNumber nextNumber

let logCall phoneNumberOption =
    match phoneNumberOption with
    | Some num -> printfn "%i" num
    | None     -> printfn "%s" "failed"

let phoneNumbers = [111; 222; 444; 555]

do List.fold (fun state num -> (nextCall state num)) None phoneNumbers
|> logCall

I tightened it up with a better List function, tryPick:
type PhoneNumber = int

let tryCallNumber phoneNumber =
    if phoneNumber % 2 = 0 then Some phoneNumber
    else None

let logCall phoneNumberOption =
    match phoneNumberOption with
    | Some num -> printfn "%i" num
    | None     -> printfn "%s" "failed"

let phoneNumbers = [111; 222; 444; 555]

do List.tryPick (fun num -> tryCallNumber num) phoneNumbers
|> logCall

Does this seem like a good approach? After reading about monadic error handling, I wonder if I should be doing something somehow more in that spirit.

A: Idiomaticity is difficult to measure. I think your approach is close-to-most-idiomatic. And you've got Tomas' sign-off... I would add the function shortcut for logCall, drop the do, pipe phoneNumbers in, eta-reduce the tryCallNumber lambda:
let phoneNumbers = [111; 222; 444; 555]

let tryCallNumber phoneNumber =
    if phoneNumber % 2 = 0 then Some phoneNumber
    else None

let logCall = function
| Some num -> printfn "%i" num
| None     -> printfn "failed"

phoneNumbers
|> List.tryPick tryCallNumber
|> logCall

Personally (unfortunately non-idiomatic in .NET / F# standard-lib), I'd also rename tryCallNumber to just callNumber, as IMO option return types are obvious enough and my code tends to be try-heavy and not reliant on exceptions. Similar to async-by-default libraries where the ...Async suffix is dropped.