text:
Q: Unable to update view - The target table of the UPDATE is not updateable I have a view (v_licence_data) that is constructed like so:
SELECT "licences"."user_id"             AS "user_id",
       "licences"."licence_id"          AS "licence_id",
       "licences"."licence_created"     AS "licence_created",
       "licences"."licence_expiry"      AS "licence_expiry",
       "licences"."licence_key"         AS "licence_key",
       "licences"."machine_id"          AS "machine_id",
       "users"."email"                  AS "email",
       "users"."first_name"             AS "first_name",
       "users"."last_name"              AS "last_name",
       "users"."date_created"           AS "date_created",
       "machines"."machine_fingerprint" AS "machine_fingerprint",
       "licences"."id"                  AS "id"
FROM   (("licences"
         LEFT JOIN "users"
                ON(( "licences"."user_id" = "users"."id" )))
        LEFT JOIN "machines"
               ON(( "licences"."machine_id" = "machines"."id" )))

I am trying to do an UPDATE on the view:
UPDATE v_licence_data
SET email = 'test'
WHERE licence_id = '6787C1-07B5F5-CDC649-28D156-A8706B-V3'

However I get the following error: The target table v_licence_data of the UPDATE is not updatable
I have read the Updatable and Insertable Views documentation, and I believe that my view meets all the conditions to be an updateable view.
How can I resolve this? Thanks in advance.

A: The Updatable and Selectable Views documentation states that multi-table views can only be updated if they exclusively use INNER JOINS:

It is sometimes possible for a multiple-table view to be updatable, assuming that it can be processed with the MERGE algorithm. For this to work, the view must use an inner join (not an outer join or a UNION). Also, only a single table in the view definition can be updated, so the SET clause must name only columns from one of the tables in the view.

So unless you're able to change your view, the only option you have is directly updating the table. This will allow you to use a LEFT JOIN:
   UPDATE licenses l
LEFT JOIN users u
       ON l.user_id = u.id
      SET u.email = 'test'
    WHERE l.license_id = '6787C1-07B5F5-CDC649-28D156-A8706B-V3'

See db<>fiddle.


text:
Q: When appending a font awesome icon in a button using jQuery the icon disappears when I click another button I am making a to do list web app using jQuery. I have a grey bootstrap button with an empty box icon (from font awesome) to show an item is incomplete. When the user completes the task I want the button to become green and the icon to change into a checked box icon (from font awesome also). I can get the button to become green by changing the class and the icon to change for one item however when I click another item to mark as complete the previous button stays green however the checked box icon disappears.
Essentially the code for the icon which is  gets removed from the code of the first button that is clicked once the second button is clicked however the previous button still stays green. The same thing happens to the second button when I click a third button. How can I get  to stay? Thanks in advance for any help.
var checked = $("").addClass("fa fa-check-square-o");

  $("table").on("click", ".btn-default", function(){
    $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-success").append(checked));
  });

A: simply put the checked element into click scope
  $(document).on("click", ".btn-default", function(){
      checked = $("").addClass("fa fa-check-square-o");
      $(this).replaceWith($("<button>").attr("type", "button").addClass("btn btn-success").append(checked));
  });

otherwise it will always reference the same  element and append it to the next clicked button

A: try simplifying this line
$(this).replaceWith("<button type='button' class='btn btn-success'>

</button");

A: Move the declaration of var checked into the click handler. The reason is that you're creating a single element and moving it around each time you call .append.
From the .append docs
http://api.jquery.com/append/
"If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Button within Angular Material Table not working I have the following Angular Material Table setup:

      <ng-container matColumnDef="delete">

          <button type="button" mat-button color="primary" (click)="test()">Delete</button>

      </ng-container>

      ...

  test() {
    console.log('test');
  }

If I click on the delete button the test() method isn't called. If I remove the 'mat-button' directive the button suddenly works.
I have other material design buttons on the form so it isn't a module import issue.
What is happening here?
StackBlitz to show the problem: https://stackblitz.com/edit/angular-fgkduw?file=src%2Fapp%2Fapp.component.html

A: Changing [dataSource] to an array instead of a function solves the problem.
https://stackblitz.com/edit/angular-ezanza?embed=1&file=src/app/app.component.html
It may be a strange behaviour caused by using mat-table in an inappropriate way.
Angular Material Table expects [dataSource] to be an array or, for more complex applications, a DataSource instance.
https://material.angular.io/components/table/overview#1-write-your-mat-table-and-provide-data

A: In the mat-table , you can use button like this
                    <button
                        mat-icon-button
                        color="accent"
                        (click)="delete(row.id)"
                      >
                        <mat-icon aria-label="delete" class="md-20"
                            >delete</mat-icon
                        >
                    </button>

A: I had a similar problem in the past as well. Button inside an *ngFor wasn't working for me like in your example.
The not working example, where the buttons behave similarly to yours:

https://stackblitz.com/edit/angular-form-array-example-hq5tud

This was when it was solved:

https://stackblitz.com/edit/angular-form-array-example-test123-2jzdij

Maybe this will help:

*

*Mat-Button click inside a *ngFor with let index = index does not react/fire action

*Problems with *ngFor and MatDialog in Angular


text:
Q: Determine project type ( ProjectTypeGuids ) in VS2010 programmatically for Sharepoint Projects I use VS2010 and Sharepoint 2010 projects.
I have an VS 2010 Addin, and I need detect type project programmatically.
I edit my csproj (for Sharepoint Project), and I have seen this ProjectTypeGuids:
{BB1F664B-9266-4fd6-B973-E1E44974B511};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}

Any FULL list of known project type Guids, included Sharepoint projects?
How can I get ProjectTypeGuids  programmatically  for my EnvDTE.Project in C# ?
References:
List of known project type Guids
http://www.mztools.com/articles/2008/mz2008017.aspx
What is the significance of ProjectTypeGuids tag in the visual studio project file
http://social.msdn.microsoft.com/Forums/en/vsx/thread/d9d05cdc-96a1-4044-95d8-a4f8885a660a
What is the significance of ProjectTypeGuids tag in the visual studio project file
http://www.mztools.com/articles/2007/MZ2007016.aspx

A: Carlos J.Quintero:
See:
HOWTO: Get the project flavor (subtype) of a Visual Studio project from an add-in
http://www.mztools.com/Articles/2007/MZ2007016.aspx
There is no full list since everyone can create new project types, that's the reason GUIDs are used.
You can create SharePoint 2010 projects and get the Guids, that's how I got that list.
Mathias Herbaux:
If you can get IVsSolution instance, you can have all GUID that compose your project:
  public bool IsTypedProject(IVsSolution solution, EnvDTE.Project project)
        {
            IVsHierarchy hierarchy;
            solution.GetProjectOfUniqueName(project.UniqueName, out hierarchy);
            IVsAggregatableProjectCorrected AP;
            AP = hierarchy as IVsAggregatableProjectCorrected;
            string projTypeGuids = string.Empty;
            if (AP != null)
            {
                AP.GetAggregateProjectTypeGuids(out projTypeGuids);
                if (projTypeGuids.ToUpper().Contains("YOUR_GUID".ToUpper()))
                {
                    return true;
                }
            }

            return false;
        }

Maybe you can can request service like this :
(IVsSolution)ServiceProvider.GetService(typeof(SVsSolution))

References:
http://social.msdn.microsoft.com/Forums/da-DK/vsx/thread/bf18037e-479a-4ca8-ae64-81ee39652d73


text:
Q: Open an Android Studio project in a new desktop Am using the latest version of Android Studio, so am working on project A but want to open a different project B in a in a new desktop using Windows + Tabs and switching between the desktops using CTRL + WIN + Right Arrow - for quick reusing of code.
Why won't my android studio app open in the second desktop? When i click the launcher it only loads but doesn't open. Is there a setting or a correct way to do it?

A: Navigate to File>Settings>Appearance & Behavior>System Setting then change Project Opening setting according to your need.


text:
Q: How to choose LUKS encryption when installing RHEL 6? With the default RHEL 6 installer, how can I choose the LUKS encryption?
Afaik if I prepare the disk like
cryptsetup luksFormat -c cast5-cbc-plain -s 128 /dev/$DEVICE

could be the "fastest" encryption, but the installer only prompts for password, then later, at the partitioning it recognizes it as "unknown" partition.
UPDATE: so in short, I just want to speed up io with using the mentioned faster encryption (? are there faster/but still ""secure""?) with the default install. How can I don it?
UPDATE#2: what would be the fastest encryption that can be still used in the default GUI install??

A: You might be stuck using a kickstart to define the partition with the encryption type instead of using the graphical install interface.

A: I think if you just tell it to format the 'unknown' partition that it will format it and leave the encryption just as you specified. So the strategy of using luksFormat to create a partition that uses a particular encryption scheme that you think will be faster will work.


text:
Q: JavaScript/jQuery working with Date and Time Objects? I need to implement a simple "seconds" counter.
Want to do something like this:
var start = new Date();
var sectionEnd = new Date();

var startTime = start.getTime();
var sectionEndTime = sectionEnd.getTime();

$('#next').on('click', function()){
  // set start time if NOT set or use set startTime
  $('#start-time').text().length < 1 ? startTime : $(this).text();

  // set or update section end time
  $('#section-end-time').html(sectionEndTime)

  // calculate the difference from startTime to current sectionEndTime
  var elapsedTime = startTime - sectionEndTime;

  // alert elapsed time in seconds..
  alert(elapsedTime);
}

So obviously the above is pseudo code and I just wrote to illustrate what I am trying to accomplish. Is there a simple jQuery solution to this? Perhaps 3-4 lines of code without using an external plugin?

A: use $.now(), like that:
HTML:
<button id="startDate">Date</button>

Jquery:
 $("#startDate").on("click",function()
 {
  DateDifference();
 });

 function DateDifference()
 {
    var date1 = new Date($.now());
    setInterval(function()
    {
      var date2 = new Date($.now());
      var seconds = (date2 - date1)/1000;
      $("p").html(seconds+" seconds of differrence between date1 and date2");
    }, 1000);
 }

JSFIDDLE:
http://jsfiddle.net/56ojwos5/


text:
Q: Trying to damp transformer output ringing of Flyback Converter when primary FET turns on I have a flyback regulator with some output ringing spike problems. It is a 70-130V input with 6V regulated output and 75V unregulated output based on the LM5021 flyback IC.
When going from no load to 3W load on the regulated 6V output, the transformer output pin on the 75V output (basically the voltage across the output rectifier) has a huge negative spike. The load transient momentarily causes the duty cycle to jump to about 70%. This negative spike only happens during transient load on the 6V. I haven't been able to test high load on both outputs yet so maybe it will happen there as well. Right now the spike is getting dangerously close to the limit of my 600V output rectifier.
The yellow trace is the voltage across the output rectifier and the blue trace is the gate drive of the switching FET. The transformer doesn't like being put back into charging state while in continuous mode it seems. I have since added 500pF with 200Ω across the output rectifier and it helped a little bit by getting rid of higher frequency ringing but not the main negative going spike.

Here is the output stage. The 6V feeds back to an opto feedback network. The 18V is used to self power the power supply. I measured about 16μH of leakage inductance in the transformer. It is meant to operate in continuous mode when up to 70W is drawn from the 75V output. When there is little to no load it will run DCM and do pulse skipping.
I would really love to figure out how to knock down that negative voltage transient. Maybe I should just go to a 1kV output diode. With 80V on the primary side (afraid to go to full 130V input yet) and 75V on the output I don't understand how I get 400V spikes across the output diode. Transformer step-down is 36:25 for the 75V output and 36:2 on the regulated 6V output.
Thanks for your help!

Here is a more complete representative schematic of this supply from my simulation file:


text:
Q: How to read self closing tag's attribute in xml? I have this type of xml:
<trace>
    <string key="id" value="1"/>
    <event>
        <string key="Hello" value="1"/>
        <string key="World" value="2"/>
    </event>
    <event>
        <string key="Stack" value="3"/>
        <string key="Overflow" value="4"/>
    </event>
</trace>

I want to read the key attributes here.
I already wrote this code:
    try {

        File fXmlFile = new File("C:\\sampleXml.xes");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile.toString());

        doc.getDocumentElement().normalize();

        NodeList nListTrace = doc.getElementsByTagName("trace");

        for (int j = 0; j < nListTrace.getLength(); j++) {

            Node nNode = nListTrace.item(j);

            NodeList nListEvent = doc.getElementsByTagName("event");

            for(int i = 0 ; i < nListEvent.getLength(); i++){

                Node nNodeEvent = nListEvent.item(i);

                Element eElement = (Element) nNodeEvent;

                System.out.println("\nCurrent Element :" + nNodeEvent.getNodeName());

            }
        }

    } catch(Exception e){
        e.printStackTrace();
    }

How can i get all elements in events? How can i get access to attributes in element which has self closing tag?

A: If you want to iterate the structure of the XML, don't use doc.getElementsByTagName() in a nested loop. That method basically ignore the XML structure and locates all elements of the given name, regardless of where the element is located.
So, first, why use getElementsByTagName("trace") if <trace> is the root element. Just call doc.getDocumentElement() to get the root element.
Also, whether a tag is given as <string key="id"/> or <string key="id"></string>, the result DOM tree will be exactly the same, so there is no special consideration for handling self-closing tags, when using DOM.
If you want to iterate the content of an <event> element, you can:

*

*Iterate child nodes using elem.getFirstChild() and elem.getNextSibling().

*Iterate child nodes using elem.getChildNodes().

*Iterate descendant elements using elem.getElementsByTagName("...").

Note that option 3 only returns elements, but searches all descendants, while options 1 and 2 returns all node type, but only direct children.

A: Access the attributes as following:
            Element traceElem = doc.getDocumentElement();
            Element elem = (Element) traceElem.getElementsByTagName( "string" ).item( 0 );
            System.out.println( elem.getAttribute( "key" ));
            System.out.println( elem.getAttribute( "value" ));


text:
Q: Wordpress api not allowing rejecting server-side connection I'm trying to connect to our wordpress api in our asp.net mvc application, using the following code
 public static string GetLifespeakBlogListings()
    {
      WebClient client = new WebClient();
      string url = "https://lifespeak.com/wp-json/wp/v2/posts?categories=6";
      string listings = client.DownloadString(url);

      return listings;

    }

however I'm getting the following exception :
System.Security.SecurityException Failed to negotiate HTTPS connection with server.fiddler.network.https> HTTPS handshake to lifespeak.com (for #1) failed. System.IO.IOException Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

If I access this feed from a browser, it works fine https://lifespeak.com/wp-json/wp/v2/posts?categories=6
However, if I try from fiddler, I get the same exception:

I'm assuming that something on our wordpress site is blocking this request for some reason. Is there something I can configure to prevent this? How can I determine the cause?

A: The issue was that the version of System.Net I was using in my application was attempting to make the request to the wordpress API using TLS 1.0, and was getting rejected, similar to the issue with fiddler that dave pointed out above.  I fixed this by adding the following line of code in the method, as specified in How to specify SSL protocol to use for WebClient class
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Note that the value has to be added manually and cast as a SecurityProtocolType, as .net 4.0 (the version I was using) doesn't support tls1.2


text:
Q: What does Google index after a mod-rewrite? I know if you do a 301 redirect Google indexes the final page you end up at.But what happens if you redirect with a mod_rewrite?  Does Google know where it ends up and index the final page?

A: Google knows nothing about it because mod_rewrite doesn't change anything the user can see. mod_rewrite sits at the front of your webserver, modifying the URLs that it serves. The URLs provided by the client do not change though.


text:
Q: Kafka multiple Logstash integration issue I have a 6 node cluster running kafka broker on 3 machines and a topic with 18 partitions.
I started logstash process on 3 out of six nodes with a common consumer group subscribing to this topic.
But when I describe consumer-group:
/bin/kafka-consumer-groups.sh --bootstrap-server : --group --describe

It shows a same logstash owner for all 18 partitions. Shouldn't I see the partitions divided among 3 logstash processes that I have running on 2 nodes. Rightnow looks like only one logstash consumer is working.
Plus from
    zkCli.sh ls /consumers doesn't show
Restarting ZK and kafka doesn't help.
Here is my logstash input section:
input {
  kafka {
    bootstrap_servers => "ip-...internal:6667,ip-.internal:6667"
    group_id => "my-group"
    topics => ["input"]
    consumer_threads => 2
  }
}


text:
Q: Is it possible do serialize/deserialize multilevel json objects? When I have a simple json it is easy, take
{"type":"simple","content":"i love apples"}

I just create a pojo:
public class Example {
    public Object type;
    public Object content;
}

Then doing:
ObjectMapper mapper = new ObjectMapper();
Example ex = mapper.readValue(getInputStream(),Example.class)

will do the job.
But now suppose I have something more complicated, a multilevel json
{
    "type": "complicated",
    "params": [
        {
            "type": "simple",
            "content": "i still love apples"
        },
        {
            "type": "simple",
            "content":"i love spam too"
        }
    ]
}

As you can see the "params" field of this new Object is a json array, and each element of this array could be mapped to my Example pojo class.
Is there a way to do this? Sorry if it could seem trivial, but I can't find any good documentation about jackson... it just talks about simple cases.

A: Here you go!
NOTE: no setters in the class, which is why I have to use @JsonCreator. Habit of mine, I don't do beans ;)
If you have setters for the different fields you can do without @JsonCreator at all.
public final class Jackson
{
    private static final String JSONCONTENT
        = "{" +
            "\"type\":\"complicated\"," +
            "\"params\":[" +
            "{\"type\":\"simple\"," + "\"content\":\"i still love apples\"}," +
            "{\"type\":\"simple\",\"content\":\"i love spam too\"}" +
            "]" +
        "}";
    public static void main(final String... args)
        throws IOException
    {
        final ObjectMapper mapper = new ObjectMapper();
        final Complicated complicated
            = mapper.readValue(JSONCONTENT, Complicated.class);
        System.out.println("Deserialization done");
        System.out.println("Serializing");
        System.out.println(mapper.writeValueAsString(complicated));
    }
}

class Complicated
{
    private final String type;
    private final List<Simple> params;

    @JsonCreator
    Complicated(@JsonProperty("type") final String type,
        @JsonProperty("params") final List<Simple> params)
    {
        this.type = type;
        this.params = new ArrayList<Simple>(params);
    }

    public String getType()
    {
        return type;
    }

    public List<Simple> getParams()
    {
        return Collections.unmodifiableList(params);
    }
}

class Simple
{
    private final String type;
    private final String content;

    @JsonCreator
    Simple(@JsonProperty("type") final String type,
        @JsonProperty("content") final String content)
    {
        this.type = type;
        this.content = content;
    }

    public String getType()
    {
        return type;
    }

    public String getContent()
    {
        return content;
    }
}

A: For your case you can use google gson : https://code.google.com/p/google-gson/
Using that library the following simple code produces the output you want :
@Test
public void testGson() {
    Gson gson = new Gson();
    Param param = new Param("simple", "i still love apples");
    Enclosure enclosure = new Enclosure("complex", param);
    String json = gson.toJson(enclosure);
    System.out.println(json);
}
output : {"type":"complex","param":{"type":"simple","content":"i still love apples"}}

You can also do more complex serializations using Gson so it should fit your needs as you expand in serialization.

A: Yes it is possible, I don't know how it is with Jackson but in many JSON libraries it works when you have a List of Objects in your Example class.

A: it's possible. Here is an example with flexjson:

*

*I have a list of groups, in that every groups has a list of users

*The relevant code sequence:
try (
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos );
        FileOutputStream fos = new FileOutputStream( outputFileName ); )
{
    oos.writeObject( groupList );
    fos.write( baos.toByteArray() );
}


text:
Q: TypeError: "NoneType" object is unsubscriptable I have this error when running this code with Python:

TypeError: "NoneType" object is unsubscriptable".

Code:
number = 0

with open('playlist.txt') as read_number_lines:
    for line in read_number_lines:
        if line.strip():
            number += 1

number = number - 1
print 'number: ', number

for i in range(number):
    author_ = raw_input('author: ')
    line = input('line: ')
    file = open('playlist.txt','a').writelines(' - ' + author_)[line]

How do I fix it?

A: You've got a few problems in
file = open('playlist.txt','a').writelines(' - ' + author_)[line]

The immediate source of your error is that .writelines() doesn't return anything (so it returns None) which you're trying to index using [line]. That produces your error.
Also, you shouldn't be calling that method on the open() call directly.
The entire second for loop is mysterious to me. You're opening that file again during each iteration of the loop (which you don't want to do; it probably wouldn't even work).
Perhaps you wanted to do something like
with open('playlist.txt','a') as file:
    for i in range(number):
        author_ = raw_input('author: ')
        line = raw_input('line: ')
        file.write(author + " - " + line)

but it's still hard to see the point of this...


text:
Q: Error to open Custom Camera (Objective-c) I try to make a custom camera but it doesn't work. Also I need add a overlay but I don't know how. Somebody can help me?
    - (IBAction)AbrirCamara:(id)sender {
UIImagePickerController *picker = [UIImagePickerController new];
                                                   picker.delegate = self;

                                                   if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
                                                   {

                                                       picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
                                                       picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
                                                       picker.showsCameraControls = NO;
                                                       picker.navigationBarHidden = YES;
                                                       picker.toolbarHidden = YES;
                                                       picker.wantsFullScreenLayout = YES;

                                                       picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                                                       [self presentViewController:picker animated:YES completion:nil];
                                                   }}

This is the error.
      Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Source type must be UIImagePickerControllerSourceTypeCamera'
*** First throw call stack:
(0x2ed43f0b 0x394dace7 0x317cf6d9 0x317cf551 0xdc7e7 0x315a86c7 0x315a8663 0x315a8633 0x31593d7b 0x315a807b 0x3156b541 0x315a3325 0x315a2c4b 0x31577e75 0x31576541 0x2ed0efef 0x2ed0e4b7 0x2ed0cca7 0x2ec77769 0x2ec7754b 0x33be46d3 0x315d6891 0xde565 0x399d8ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException

A: UIImagePickerController *picker = [UIImagePickerController new];
picker.delegate = self;

if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{

    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = YES;
    picker.toolbarHidden = YES;
    picker.wantsFullScreenLayout = YES;

    [self presentViewController:picker animated:YES completion:nil];
}

your problem is you are write sourceType below that error occur.
First Set SourceType after you other controller set.

A: set picker.sourceType = UIImagePickerControllerSourceTypeCamera after allocating you imagepicker controller and make other setups outside if condition like cameraDevice, mode etc. just present that picker inside if.
And make sure that you have set UIImagePickerControllerSourceTypeCamera as sourcetype as your error seems that you are setting wrong source type.


text:
Q: maven release:prepare FAILS due to 1.7 svn working copy (expects 1.6) I have had it up to HERE with maven! I finally get things working and running, and then I have attempted to do my first maven release:prepare using an external maven runtime THROUGH m2eclipse.
Here is the issue I am experiencing:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.0:prepare (default-cli) on project scs-global-parent: Unable to commit files
[ERROR] Provider message:
The svn command failed.
Command output:
svn: The path 'C:\Users\Sam\MyProj\model\scs-global-parent' appears to be part of a Subversion 1.7 or greater working copy.  Please upgrade your Subversion client to use this working copy.
I am using Subclipse 1.8.x - which supports 1.7 working copies? There must be a workaround ... what am I missing here?? Do I need to add an "experimental" version of the maven-release-plugin? Currently I am using the "default" in that I don't have a version specified in my pom or settings.xml. Thank you!!
Which "subversion client" is the plugin yelling at me about?

A: Maven will be using whatever subversion you have on your system accessible from the command line.
Check that the version of Subversion that runs from command line.  (use svn --version from a command prompt or shell).  Upgrade that particular version of Subversion on your system and it should work.

A: you can use svnjava provider it supports 1.7 see http://code.google.com/a/apache-extras.org/p/maven-scm-provider-svnjava/
More details: http://code.google.com/a/apache-extras.org/p/maven-scm-provider-svnjava/wiki/UsingWithReleasePlugin


text:
Q: Update value for the same table using parent, child condition in DB2 I have one table in DB2 which having parent & child relation on same table, how can I update child  column using parent relation.
Example:
update table1
set    col1 = (select col2 from table2 where id='14')
where  table1.id=table2.parent

A: It looks like you may have specified your conditions jumbled around. I'm assuming you want to change the value of col1 on row 14, and you want it to have the value from col2 of its parent.
So the outer statement, the UPDATE, should have a WHERE clause specifying which row to update -- the one with id = 14.  When we refer to this reference to the table, we'll use a nickname for it. I chose a single letter nickname, 'u', to mean the row we're going to update.
I'm guessing the id column is numeric, in which case it should not be quoted. (The u qualifier there on id is optional, since there is no ambiguity in the WHERE clause of the UPDATE statement. I merely added it for clarity.)
The value that will be put in col1, comes from col2 in the subquery. We want to get it from the row whose id matches the parent column in the row to be updated. This record is also in table1, but to distinguish this table reference from the other, I'll give it a nickname of 'p', to mean parent row.
update table1 as u
  set col1 = (select col2
                from table1 as p
                where p.id = u.parent
             )
  where u.id = 14

( I've used the word "nickname", but the proper term is "correlation name". )


text:
Q: Transitivity on relations I have a question concerning proving properties of Relations.
The question is this:
How would I go about proving that, if R and S (R and S both being different Relations) are transitive, then R union S is transitive?
The answer is actually FALSE, and then a counter example is given as a solution in the book.
I understand how the counterexample works as explained in the book, but what I don't understand is, how exactly they arrive to the conclusion that the statement is actually false.
Basically I can see myself giving a proof that if that for all values (x,y,z) in R and S, if (x,y) is in R and (y,z) is in R, (x, z) is in R since R is transitive. And if (x,y) is in S and (y,z) is in S, (x,z) is in S since S is transitive. Since (x,z) is in both R and S, the intersection is true. But why wouldn't the union of R and S be true as well?
Is it because that the proof cannot be ended with "since (x,z) is in both R and S, (x,z) can be in R or S"? Basically, that a proof can't be ended with an OR statement at the end?

A:
I understand how the counterexample works as explained in the book, but what I don't understand is, how exactly they arrive to the conclusion that the statement is actually false.

Given that there's a (presumably valid) counterexample, the statement has to be false. Trying to apply your proof to the counterexample can help reveal the error.
That's not to say that it's never the case that the union of two transitive relations is itself transitive. Indeed, there are obvious examples such as the union of a transitive relation with itself or the union of less-than and less-than-or-equal-to (which is equal to less-than-or-equal-to for any reasonable definition). But the original statement asserts that this is the case for any two transitive relations. A single counterexample disproves it. If you could provide a (valid) proof of the statement, you'd have discovered a paradox. This usually causes mathematicians to reevaluate the system's axioms to remove the paradox. In this case there is no paradox.
Let T be the union of R and S (for the sake of simplicity, let's assume domain equals range and that it's the same set for both). What you are trying to prove is that if xTy and yTz, then it must be the case that xTz. As part of your proof outline, you state the following:

if (x,y) is in R and (y,z) is in R, (x, z) is in R since R is transitive

This is clearly true as it's just the definition of transitivity. As you point out, it can be used to prove the transitivity of the intersection of two transitive relations. However, since T is the union, there's no reason to assume that xRy; it might be that xSy only. Since you can't prove the antecedent (that xRy and yRz), the consequent (that xRz) is irrelevant. Similarly, you can't show that xSz. If you can't show that xRz or xSz, there's no reason to believe that xTz.
This implies the sort of situation that gives a counter example to the statement: when one half of the transitive pair comes only from R and the other comes only from S. As a simple, contrived, example, define the relations over the set {1,2,3}:
R={(1,2)}
S={(2,3)}
Clearly, both R and S are transitive (as there are no x, y, z such that xRy and yRz or xSy and ySz). On the other hand,
T={(1,2),(2,3)}
is not transitive. While 1T2 (since 1R2) and 2T3 (since 2S3), it is not the case that 1T3. Your textbook probably gives a more natural counterexample, but I feel that this gives a good understanding of what can cause the assertion to fail.


text:
Q: Posting instagram carousel with python I want to post a carousel of n images using python. I have found various sources on how to upload a single picture with a caption by using libraries like InstaBot, but I could not find any source on how to do this with a carousel, if it is at all possible.
I have all the files stored locally and know how to get the filenames and everything within my script. I want to be able to set the order of the images as well. There tend to be 5 images, so the maximum of 10 will never be surpassed.
Anybody know if this is possible and if yes, how do I achieve it?

A: as far as my knoledge no library has this option,But it is possible if u use API on your own
update: check instagrapi library
guys come on why -2 reputation, i am just trying to help as far as i know, i need reputation to comment on answers guys


text:
Q: Calculating audio gain on Android I'm trying to calculate audio gain for different Android samples in real-time. Are there any libraries that can actually achieve what GainNode in Javascript does
(https://developer.mozilla.org/de/docs/Web/API/GainNode)?
I'm working with the Android visualizer so I have time domain as well as frequency domain samples available.


text:
Q: Простое шифрование файла на C# У меня простая windows form. Две кнопки: одна шифрует файл любым способом, сохраняет файл и в конце расширения дописывает .crypt; другая расшифровывает.
Поиск в интернете дал только шифровку string строк.
Помогите в реализации кода.

A: Для самого простого случая можно использовать шифр XOR. Для шифрования и дешифрирования будет использоваться одна и та же кнопка button1.
Функция шифрования и дешифрования:
byte[] Crypt(byte[] bytes)
    {
        for (int i = 0; i < bytes.Length; i++)
            bytes[i] ^= 1;
        return bytes;
    }

Функция получения нового имени файла:
string GetNewFileName(string FileName)
    {
        return FileName.EndsWith(".crypt") ? FileName.Remove(FileName.LastIndexOf(".crypt")) : FileName + ".crypt";
    }

Пример использования в программе:
private void button1_Click(object sender, EventArgs e)
        {
            byte[] MyFile = File.ReadAllBytes(MyFilePath);
            byte[] NewFile = Crypt(MyFile);
            string NewFileName = GetNewFileName(MyFileName);
            File.WriteAllBytes(NewFileName, NewFile);
        }


text:
Q: Record mywebsite.com link with query in LSApplicationQueriesSchemes My iOS 11.0+ app is trying to open a URL of the following format, where DATANAME1, DATANAME2, USERNAME vary depending upon the user looking at different data:
http://www.mywebsite.com/Topic.html?topic=DATANAME1-USERNAME-DATANAME2

However, the command 'canOpenURL' I use before calling this link returns false. I believe this is due to not having whitelisted this link.
Consider that any html page within mywebiste.com (for example: http://www.mywebsite.com/Help.html) can instead be opened without any issue.
Questions:

*

*Since I cannot whitelist every possible combination of USERNAME, DATANAME1, DATANAME2 obviously, is there a way to whitelist the link under the key LSApplicationQueriesSchemes in info.plist?

*Do I need to add a URLScheme (under Info->URL Types) as well? What would be the right string to add in this case?
Thanks.


text:
Q: Trouble Adding DatePicker to Modal - Displays in backdrop I am trying to insert a DatePicker I found here: http://www.eyecon.ro/bootstrap-datepicker/ but I cannot get it to display in front of my modal. (I can see it in the backdrop of the modal)
I am not sure if I either implemented it incorrectly, or if I need to rig it to be on top of the modal's display.
Here is my Bundle.config where I added the datepicker.css and bootstrap-datapicker.js files.
public class BundleConfig
{
    // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        // Use the development version of Modernizr to develop with and learn from. Then, when you're
        // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/datepicker.css",
                  "~/Content/site.css"));

        bundles.Add(new ScriptBundle("~/bundles/myscript").Include(
                  "~/Scripts/MyScripts.js", "~/Scripts/bootstrap-datepicker.js"));
    }
}

And here is my modal

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Create

Title

                     <input type="text" name="createName" style="text-align: center; height: 35px; font-size: 20px; width: 100%" placeholder="Title" />

Release Date

                     <input type="text" name="createRelease" id="datepicker" style="text-align:center; height:35px; font-size:20px; width:100%" placeholder="Date (mm/dd/yyyy)" />

Description

                     <input type="text" name="createDescription" style="text-align:center; height:35px; font-size:20px; width:100%" placeholder="Description" />

            <button type="button" onclick="createFunction(this)" class="btn btn-success">Create</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

So it "seems" to be working fine, except that I cannot click anything in the calendar as it is appearing in the backdrop.
Here is an image for reference

Any and all help apprecaited!
I am new to a lot of this, so if the solution is a little tricky a detailed explanation would be welcomed! :)

A: It's a css problem :
The modal datepicker is behind the modal so :
CSS :
.datepicker{
    z-index: 1100 !important;
}

If the datepicker widget is well .ui-datepicker


text:
Q: elasticsearch tire gem exact match I'm currently using Tire to access my ES data however I've not been able to get it to do an exact match, for instance
User.search :per_page => 10 do
 query do
    boolean do
       must { match :first_name, 'tom'}
       must { match :last_name, 'smith'}
       end
   end
end

However that returns firstnames that are tom, tomas, tommy and tomiena.. when I'd like it to only match tom.

A: Try the match_phrase query,
User.search :per_page => 10 do
 query do
    boolean do
       must { match :first_name, 'tom', :type => :phrase}
       must { match :last_name, 'smith', :type => :phrase}
       end
   end
end

A: You can try with a query_string query :
User.search :per_page => 10 do
 query do
    boolean do
       must { string 'first_name:tom'}
       must { string 'last_name:smith'}
       end
   end
end
If that doesn't work it means that you'd have to check on your analyser.


text:
Q: the comparative ... , the comparative ... and predication I know people have asked about the correlative comparative construction, but none of the previous posts concerns its specific analysis.
How would you analyze the boldfaced part of #2 below?

*

*The more you buy, the greater the discounts you receive.

*The more you buy, the greater discounts you receive.

In #1, "greater" stands in a predicative relation to "the discounts you receive"; it's paraphrasable as "The discounts you receive are (the) greater the more you buy.
The copular verb "are" can be treated as omitted in #1.
Does the same predicative relation hold in #2? What about an alternative analysis whereby "greater discounts" stands in a verb-object relation to "receive"? In this connection, consider #3:

*The longer you work, the more money you earn.

Which kind of relation holds in #3? A predicative or verb-object relation?


text:
Q: Properly Discontinuous Group Actions Let $G$ be a group acting on a topological space $X$. We say the action of $G$ on $X$ is properly discontinuous (or $G$ acts properly discontinuously on $X$)
if one of the following two equivalent conditions is satisfied:

*

*for every $x \in X$ and every compact subset $K$ of $X$ we have that the set $\{T \in G : T(x) \in K\}$ is finite.

*for every compact subset $K$ of $X$ we have that the set $\{T \in G : T(K) \cap K \neq \phi \}$ is finite.

The question is how to prove the equivalence of these two conditions.


text:
Q: How to format "if" statement (conditional) on multiple lines in bash? I have a Bash shell function that takes an argument and performs something on it if needed.
do_something() {
  if [need to do something on $1]
  then
    do it
    return 0
  else
    return 1
  fi
}

I want to call this method with several arguments and check if at least one of them succeeded.
I tried something like:
if [ do_something "arg1" ||
     do_something "arg2" ||
     do_something "arg3" ]
then
  echo "OK"
else
  echo "NOT OK"
fi

Also, I want to make sure that even if the first condition is true all other conditions will still be evaluated.
What is the correct syntax for that?

A: Run the commands first, then check if at least one of them succeeded.
#!/bin/bash

success=0
do_something arg1 && success=1
do_something arg2 && success=1
do_something arg3 && success=1

if ((success)); then
    printf 'Success! At least one of the three commands succeeded\n'
fi

A: The correct syntax is:
if  do_something "arg1" || \
    do_something "arg2" || \
    do_something "arg3"
then
  echo "OK"
else
  echo "NOT OK"
fi

\ is used to tell the shell a command continues in the next line.
EDIT: I think this should do what you want:
#!/bin/bash

do_something() {
  if [need to do something on $1]
  then
    do it
    echo "OK"
  else
    echo "NOT OK"
  fi
}

do_something "arg1"
do_something "arg2"
do_something "arg3"

A: Use backslashes.
if [ $(do_something "arg1") ] || \
   [ $(do_something "arg2") ] || \
   [ $(do_something "arg3") ]
then
  echo "OK"
else
  echo "NOT OK"
fi

EDIT
Also - I want to make sure that even if the first condition is true all other conditions will still be evaluated.
That's not possible in only one if statement. Instead you can use a for loop that iterates over the arguments and evaluates them separately. Something like:
do_something() {
  for x in "$@"
  do
    if [need to do something on $x]
    then
      do it
    else
      echo "no action required on $x"
    fi
  done
}

A: I prefer:
if {
    do_something "arg1" ||
    do_something "arg2" ||
    do_something "arg3"
}; then
    echo "OK"
else
    echo "NOT OK"
fi


text:
Q: Create a confusion matrix First note: I am creating a recommender system. This should later suggest articles to the user that they might also like.

I'm in the process of creating a confusion matrix. Unfortunately I am not able to make it. I'm getting an error. I have attached an example below, unfortunately I don't know how to rebuild my code.

*

*How do I create a confusion matrix based on my existing data?

How do I have to rebuild it to get such a "nice" confusion matrix like in the example?
Dataframe:
d = {'purchaseid': [0, 0, 0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 8, 9, 9, 9, 9],
     'itemid': [ 3, 8, 2, 10, 3, 10, 4, 12, 3, 12, 3, 4, 8, 6, 3, 0, 5, 12, 9, 9, 13, 1, 7, 11, 11]}
df = pd.DataFrame(data=d)

   purchaseid  itemid
0           0       3
1           0       8
2           0       2
3           1      10
4           2       3
...         ...    ...

Code:
PERCENTAGE_SPLIT = 20
    NUM_NEGATIVES = 4
    def splitter(df):
      df_ = pd.DataFrame()
      sum_purchase = df['purchaseid'].nunique()
      amount = round((sum_purchase / 100) * PERCENTAGE_SPLIT)

      random_list = random.sample(df['purchaseid'].unique().tolist(), amount)
      df_ = df.loc[df['purchaseid'].isin(random_list)]
      df_reduced = df.loc[~df['purchaseid'].isin(random_list)]
      return [df_reduced, df_]

    def generate_matrix(df_main, dataframe, name):

      mat = sp.dok_matrix((df_main.shape[0], len(df_main['itemid'].unique())), dtype=np.float32)
      for purchaseid, itemid in zip(dataframe['purchaseid'], dataframe['itemid']):
        mat[purchaseid, itemid] = 1.0

      return mat

dfs = splitter(df)
df_tr = dfs[0].copy(deep=True)
df_val = dfs[1].copy(deep=True)

train_mat = generate_matrix(df, df_tr, 'train')
val_mat = generate_matrix(df, df_val, 'val')
num_users, num_items = train_mat.shape

def get_train_samples(train_mat, num_negatives):
    user_input, item_input, labels = [], [], []
    num_user, num_item = train_mat.shape
    for (u, i) in train_mat.keys():
        user_input.append(u)
        item_input.append(i)
        labels.append(1)
        # negative instances
        for t in range(num_negatives):
            j = np.random.randint(num_item)
            while (u, j) in train_mat.keys():
                j = np.random.randint(num_item)
            user_input.append(u)
            item_input.append(j)
            labels.append(0)
    return user_input, item_input, labels

user_input, item_input, labels = get_train_samples(train_mat, NUM_NEGATIVES)
val_user_input, val_item_input, val_labels = get_train_samples(val_mat, NUM_NEGATIVES)

hist = model.fit([np.array(user_input), np.array(item_input)], np.array(labels),
                 validation_data=([np.array(val_user_input), np.array(val_item_input)], np.array(val_labels)))

from sklearn.metrics import classification_report
x_train = user_input, item_input
y_train = labels
x_test = val_user_input, val_item_input
y_test = val_labels

y_pred = model.predict(([np.array(val_user_input), np.array(val_item_input)], np.array(val_labels)), batch_size=64, verbose=1)
y_pred_bool = np.argmax(y_pred, axis=1)

print(classification_report(y_test, y_pred_bool))

Example:
import numpy as np
import matplotlib.pyplot as plt

from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import plot_confusion_matrix

# import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
class_names = iris.target_names

# Split the data into a training set and a test set
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

# Run classifier, using a model that is too regularized (C too low) to see
# the impact on the results
classifier = svm.SVC(kernel='linear', C=0.01).fit(X_train, y_train)

np.set_printoptions(precision=2)

# Plot non-normalized confusion matrix
title = ("Confusion matrix, without normalization")

disp = plot_confusion_matrix(classifier, X_test, y_test, display_labels=class_names, cmap=plt.cm.Blues,)
disp.ax_.set_title(title)
print(title)
print(disp.confusion_matrix)

plt.show()

Try:
import seaborn as sns
from sklearn.metrics import precision_recall_fscore_support, confusion_matrix, roc_curve, auc
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True)

[OUT] ValueError: Classification metrics can't handle a mix of binary and continuous targets

EDIT:
I'm using the NCF model

The architecture of a Neural Collaborative Filtering model. Taken from the Neural Collaborative Filtering paper.
# full NCF model
def get_model(num_users, num_items, latent_dim=8, dense_layers=[64, 32, 16, 8],
              reg_layers=[0, 0, 0, 0], reg_mf=0):

    # input layer
    input_user = Input(shape=(1,), dtype='int32', name='user_input')
    input_item = Input(shape=(1,), dtype='int32', name='item_input')

    # embedding layer
    mf_user_embedding = Embedding(input_dim=num_users, output_dim=latent_dim,
                        name='mf_user_embedding',
                        embeddings_initializer='RandomNormal',
                        embeddings_regularizer=l2(reg_mf), input_length=1)
    mf_item_embedding = Embedding(input_dim=num_items, output_dim=latent_dim,
                        name='mf_item_embedding',
                        embeddings_initializer='RandomNormal',
                        embeddings_regularizer=l2(reg_mf), input_length=1)
    mlp_user_embedding = Embedding(input_dim=num_users, output_dim=int(dense_layers[0]/2),
                         name='mlp_user_embedding',
                         embeddings_initializer='RandomNormal',
                         embeddings_regularizer=l2(reg_layers[0]),
                         input_length=1)
    mlp_item_embedding = Embedding(input_dim=num_items, output_dim=int(dense_layers[0]/2),
                         name='mlp_item_embedding',
                         embeddings_initializer='RandomNormal',
                         embeddings_regularizer=l2(reg_layers[0]),
                         input_length=1)

    # MF latent vector
    mf_user_latent = Flatten()(mf_user_embedding(input_user))
    mf_item_latent = Flatten()(mf_item_embedding(input_item))
    mf_cat_latent = Multiply()([mf_user_latent, mf_item_latent])

    # MLP latent vector
    mlp_user_latent = Flatten()(mlp_user_embedding(input_user))
    mlp_item_latent = Flatten()(mlp_item_embedding(input_item))
    mlp_cat_latent = Concatenate()([mlp_user_latent, mlp_item_latent])

    mlp_vector = mlp_cat_latent

    # build dense layer for model
    for i in range(1,len(dense_layers)):
        layer = Dense(dense_layers[i],
                      activity_regularizer=l2(reg_layers[i]),
                      activation='relu',
                      name='layer%d' % i)
        mlp_vector = layer(mlp_vector)

    predict_layer = Concatenate()([mf_cat_latent, mlp_vector])
    result = Dense(1, activation='sigmoid',
                   kernel_initializer='lecun_uniform',name='result')

    model = Model(inputs=[input_user,input_item], outputs=result(predict_layer))

    return model

A: The output of your model, y_pred are not class values, but (as a softmax layer with one neuron is used), can be interpreted as class probabilities. Particularly, the is not one confusion matrix to compute, you first have to select a discrimination threshold, that is, a value between 0 and 1 which defines which of the continuous  values in your prediction should assigned to which class.
Assume you found out that 0.8 is a good threshold, that is, every entry in y_pred larger as 0.8 is assigned to class 1, every entry smaller is assigned to class 0, then the following should compute the confusion matrix for that particular threshold:
import seaborn as sns
import numpy as np
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_test, (y_pred > 0.8).astype(np.int))
sns.heatmap(cm, annot=True)


text:
Q: TypeScript - declare type of a React component class constructor with a certain static method I got this to work with regular classes, including classes that extend the target class as you can see below:
interface ALike {
  a: () => boolean
}

interface ALikeConstructor {
  new (): ALike
  aStatic: () => boolean
}

function acceptsALike(ctr: ALikeConstructor) { }

class A {
  public a() {
      return true;
  }

  public static aStatic(): boolean {
      return true;
  }
}

class AB extends A {
  public b() {
      return true;
  }
}

class ANoStatic {
  public a() {
    return true;
  }
}

acceptsALike(A); // ok
acceptsALike(AB); // ok
acceptsALike(ANoStatic); // ok (error shows)

Playground
However, for whatever reason it does not work with React components and TypeScript does not give much of an explanation.
import React from 'react'

type Props = {
  test: true
}

interface CLike extends React.Component<Props> {
  c(): boolean
}

interface CLikeConstructor {
  new(): CLike
  cStatic(): boolean
}

class C extends React.Component<Props> implements CLike {
  public c() {
    return true;
  }

  public static cStatic() {
    return true;
  }
}

function acceptsCLike(ctr: CLikeConstructor) { }

acceptsCLike(C); // Argument of type 'typeof C' is not assingable to parameter of type 'CLikeConstructor' - no further explanation.

Playground
I understand that something about React.Component makes it incompatible, but what is it and is there a way to work around it?

A: The problem is that your constructor signature (in CLikeConstructor) describes a constructor with no arguments. The react class has a constructor with one argument (the props).
You can defined the constructor signature to not care about the number of args:
interface CLikeConstructor {
  new(...a: any[]): CLike
  cStatic(): boolean
}

Playground Link
You could also make it accept just one param (the props) like this: new(props: any): CLike


text:
Q: For Comparing two Excel columns in VBA, is it best to use Union, Intersect, or CountIf? I have two worksheets in Excel. One, ("List") has a list of 2000 or so rows. The other ("Library") has a large array of 2000 or so columns, each with 150 rows. I want to delete each column in "Library" that has nothing in it appear in "List".
What I have so far (using the CountIf function) is:
Sub DeleteLibrary()

Dim Rng As Range
Dim Keyword As Range
Dim Library As Worksheet
Dim List As Worksheet
Dim Chunk As Range
Dim X As Long

X = 1
Application.ScreenUpdating = True

Set Library = Sheets("Library")
Set List = Sheets("List")
Set Keyword = List.Range("A1:A2000")
Set Chunk = Library.Range("A1:A150").Offset(0, X)

   Do While X <= 1500
   If Application.WorksheetFunction.CountIf(Keyword, Chunk) >= 1 Then
    X = X + 1
    ElseIf Application.WorksheetFunction.CountIf(Keyword, Chunk) = 0 Then
    Chunk.Delete Shift:=xlLeft
    Else: Stop
    End If

    Loop
    End
End Sub

However, this gives me a type mismatch for the first CountIf line. Am I taking the right approach? Would Union or Intersect be a better route?
Thanks


text:
Q: DRF testing - create object with a many-to-many relation I have the following model Project:
class Project(models.Model):
    name = models.CharField(max_length=128)
    slug = models.SlugField(blank=True)
    assigned_to = models.ManyToManyField(
        User, blank=True, related_name="assignees")
    created_date = models.DateField(auto_now_add=True)
    updated_date = models.DateField(auto_now_add=False, auto_now=True)

If I need to create a new project, all I need to do is supply the name alone. This works for both the Admin dashboard and DRF APIVIEW. But when I try to test the functionality with DRF with an API call, I get the error: [b'{"assigned_to":["This field is required."]}'] Although the field is not required.
My test code below
import datetime
from marshmallow import pprint

from rest_framework.test import APITestCase, APIClient
from freezegun import freeze_time

from accounts.models import User
from .models import Project

@freeze_time("2021-11-14")
class ProjectTests(APITestCase):

    client = APIClient()
    project = None

    name = 'IOT on Blockchain'
    dead_line = datetime.date(2021, 11, 21)
    data = {
        'name': name,
        'dead_line': dead_line,
    }

    def create_user(self):
        username = 'test_user1'
        email = 'test.user1@gmail.com'
        password = '@1234xyz@'
        user_type = 'regular'
        data = {'username': username,
                'email': email,
                'password': password,
                'user_type': user_type,
                }
        return User.objects.create_user(**data)

    def create_project(self):
        project = Project.objects.create(**self.data)
        user = self.create_user()
        project.assigned_to.add(user)
        return project

    def test_create_project_without_api(self):
        """
        Ensure we can create a new project object.
        """
        self.project = self.create_project()
        self.assertEqual(Project.objects.count(), 1)
        self.assertEqual(self.project.name, 'IOT on Blockchain')
        self.assertEqual(self.project.dead_line,
                        datetime.date(2021, 11, 21))
        self.assertFalse(self.project.reached_deadline)
        self.assertEqual(self.project.days_to_deadline, 7)
        # runs successfully

    def test_create_project_with_api(self):
        """
        Ensure we can create a new project object with an
        API call.
        """
        url = 'http://127.0.0.1:8000/api/projects'
        project = self.client.post(url, self.data, format='json')
        # project.data.assigned_to.set(self.create_user())
        pprint(project.__dict__)
        self.assertEqual(Project.objects.count(), 1)
        self.assertEqual(self.project.name, 'IOT on Blockchain')
        self.assertEqual(self.project.slug, 'iot-on-blockchain')
        # does not run successfully (error mentioned in text body)

    def test_delete_project(self):
        """
        We can delete a user
        """
        self.project = self.create_project()
        self.project.delete()
        self.assertEqual(Project.objects.count(), 0)

Edit: Added serializer code
class ProjectWriteSerializer(serializers.ModelSerializer):
    """
    This serializer is used for CREATE, UPDATE operations on the Project model.
    """

    # We receive list of user ids (ids[int] <= 0) by which we assign
    # users to a project
    assigned_to = serializers.PrimaryKeyRelatedField(
        queryset=User.objects.all(), many=True)

    class Meta:
        model = Project
        fields = ('id', 'name', 'slug', 'assigned_to')

Any insights and help is very appreciated.

A: You have specified your own serializer field. As a result, it will no longer look at the blank=True part, and by default serializer fields are required. You can make these optional with:
class ProjectWriteSerializer(serializers.ModelSerializer):
    assigned_to = serializers.PrimaryKeyRelatedField(
        queryset=User.objects.all(),
        many=True,
        required=True
    )

    class Meta:
        model = Project
        fields = ('id', 'name', 'slug', 'assigned_to')


text:
Q: How to search for APT packages with a specific substring in their names only? In the past I used to search for a package specifying a part of its name in Synaptic, as far as I can remember. Now it searches in package descriptions too and this is very inconvenient as it gives a huge lot of irrelevant results. I have tried using console aptitude and apt-cache search but both of them do the same. So how do I search in the names only (ignoring the descriptions)?

A: With apt-cache, you can use the --names-only switch with your search term, and/or use some regex to narrow the searches down. Some examples I have used are listed below.
1) Using --names-only with a simple search of the word launcher cuts out a lot of results:
apt-cache search launcher --names-only

Often when using regex in your searches, --names-only isn't necessary as well, since you narrow the results down much further anyway, as these examples below demonstrate.
2) You could use regex to find all available desktop environments available:
apt-cache search -- '-desktop$'

3) or to find dev files that you don't know the name of:
apt-cache search 'jpeg*-dev'

The methods shown in the examples above are very useful when using apt-cache to search for packages for which you only partially know the name.


text:
Q: Intellij: What's the difference between 'Run' and 'Run...'
I'm trying to change the default Run keyboard shortcut to ⌘R. - Because I dont want to reach for the trackpad everytime and my fingers are not long enough to do ⌥⇧F10 at once. What's the difference between 'Run' and 'Run...'?

A: ... is used in menus to indicate that it will lead to a dialog box.


text:
Q: Topological space representing anti-periodic boundary conditions It is well-known that we often use the circle $\mathbb{S}^1$ to represent boundary conditions, i.e., if $f$ is $2\pi$-periodic, then we can define it on the circle. In analogy, what if $f$ is $2\pi$-anti-periodic, i.e., $f(x+2\pi) = -f(x)$, is there a natural topological space to define $f$ on?

A: A function with "anti-period" $2\pi$ is also periodic with period $4\pi$, since we have $$f(x+4\pi)=f((x+2\pi)+2\pi)=-f(x+2\pi)=-(-f(x))=f(x).$$ So we can still view $f$ as defined on the unit circle, just "scaled" appropriately.

A: It sounds like your background is physics so I don't know how much of the relevant mathematical background you have here. There are these things called vector bundles over a topological space $X$: you can think of them as being like a "continuous family" $V_x, x \in X$ of vector spaces; the $V_x$ are called the fibers of the bundle. Given a vector bundle you can also consider "sections" of it, which are like a continuous choice $f_x \in V_x, x \in X$ of vector in each of these vector spaces; these generalize continuous functions on $X$. For example, any smooth manifold has a tangent bundle whose sections are vector fields.
Vector bundles are formally defined by defining their total space $E$, which looks like the disjoint union $\bigsqcup_{x \in X} V_x$ of all the fibers but with a particular topology, and then a projection map $\pi : E \to X$ sending $V_x$ to $x$. The fibers of the vector bundle are then given by the fibers $\pi^{-1}(x) \cong V_x$ of the projection map $\pi$, and sections of the bundle can be defined as right inverses to $\pi$: that is, as maps $f : X \to E$ such that $\pi \circ f = \text{id}_X$. You can check that this condition is equivalent to requiring $f(x) \in V_x$ as expected.

All of that was background for the following construction. $S^1$ admits a nontrivial real line bundle (a vector bundle whose fibers are $1$-dimensional real vector spaces) which "twists by $-1$" as you go around the circle. You can visualize its  as the (open) Mobius strip; somewhat more explicitly, you can define it as the quotient of the space $\mathbb{R} \times [0, 2\pi]$ by the equivalence relation
$$(x, 0) \sim (-x, 2\pi).$$
The projection map to $S^1$ is given by projecting to the second coordinate, thinking of $S^1$ as $[0, 2\pi]$ with the endpoints identified. Now you can check that a (continuous) section of this line bundle is basically the same thing as a (continuous) antiperiodic function. Similarly, if we had taken the trivial line bundle $\mathbb{R} \times S^1$, its (continuous) sections would just be (continuous) functions on $S^1$, or $2\pi$-periodic (continuous) functions.


text:
Q: MySQL: как получить все строки без повторов? есть такие записи:
(колонки: Date,Val,Name)
2016-02-01 350 A
2016-02-01 360 B
2016-02-02 351 A
2016-02-02 350 B
2016-02-02 350 B
...

нужно получить все строки без повторов (когда для каждой даты имя будет уникальным, только 1 раз для каждой даты)... т.е.:
2016-02-01 350 A
2016-02-01 360 B
2016-02-02 351 A
2016-02-02 350 B

Мой запрос работает не верно:
SELECT * FROM myTable WHERE Date>='2016-01-01' group by Name ORDER BY Date asc, Name asc

A: Определите, что должно выдаваться в поле Val при такой выборке. Группируйте по дате и имени. Применяйте соответствующую агрегацию к Val. Например, с min:
select date, min(val), name from mytable group by date, name


text:
Q: ShareActionProvider is null I have been searching for 3 or 4 days about a solution on this. I have tried:
Null Pointer exception in using support library share action provider
or
why MenuItemCompat.getActionProvider returns null? and some others
but still I get null on ShareActionProvider. I am pretty new on developing android apps so I really need some help.
My xml menu file is:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_share"
    android:title="@string/action_share"
    app:showAsAction="always"
    android:icon="@android:drawable/ic_menu_share"
    android:actionProviderClass="android.support.v7.widget.ShareActionProvider"/></menu>

and my fragment is:
public static class DailyActivityFragment extends Fragment {
    private static final String LOG_TAG = "Dailyshare";
    private ShareActionProvider mShareActionProvider;

    public DailyActivityFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
        return rootView;
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
        inflater.inflate(R.menu.detailfragment, menu);
        MenuItem item = menu.findItem(R.id.action_share);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
        if (mShareActionProvider != null) {
            mShareActionProvider.setShareIntent(createShareIntent());
        }else{
            Log.i(LOG_TAG, "is null");
        }
    }

    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT,
                "this text will be shared");
        return shareIntent;
    }
}

as an import I have:
import android.support.v7.widget.ShareActionProvider;

A: You could just create a ShareActionProvider and assign it.
mShareActionProvider = new ShareActionProvider();
mShareActionProvider.setShareIntent(createShareIntent())
MenuItemCompat.setActionProvider(item, mShareActionProvider);

A: You have wrong namespace usage in XML:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:actionProviderClass="android.support.v7.widget.ShareActionProvider"

should be app:actionProviderClass (the provider class is from apk resources, not native android classes).
See https://stackoverflow.com/a/32602896/907576


text:
Q: IFTTT - Download a list of files from a URL I have a CSV with a list of file names in the first column
filename1
filename2 etc
The actual files are sitting on website.com/< filename >.pdf
How do I write an applet to download all the files from the URL into maybe Dropbox?
Thanks heaps

A: Its easy in Zapier
create a Zap that is triggered for new rows in a google sheet, and when triggered reads a cell in the row (which is the file url) and uploads it to dropbox.
Once you have set this up you paste your CSV into google sheets and voila!


text:
Q: Find and count odd numbers in a array with using an if So i´ve been tryng to count the odd numbers in an array without the help of an if. Any Master coders out there (i am a novice).
public static void main(String[] args) {

      int array[] = {1,4,5,9,0,-1,5,7};
      int count = 0;
        for (int i = 0; i <array.length ; i++) {
            if (array[i] %2 != 0){
                count ++;
            }
        }

        System.out.println("Odds " + count);

}

A: Even better, not even a for needed ;)
public static void main(String[] args) {
        int array[] = { 1, 4, 5, 9, 0, -1, 5, 7 };
        long count = Arrays.stream(array).filter(it -> (it & 1) == 1).count();
        System.out.println("Odds " + count);
    }

A: Okay all you need to do is build the int array into a String using StringBuilder...
Then you need to split it into two arrays by evens and odds!  Now you have an array of evens and an array odds! As Strings! You find the number of odds by taking the length of the array after.  You also can then parse them back into int or leave them as String and just print them:
      int array[] = {1,4,5,9,0,-1,5,7};

      StringBuilder sb = new StringBuilder();

        for (int i = 0; i <array.length ; i++)
        {
            sb.append(array[i]);
            sb.append(",");
        }
        String str = sb.toString();

        //You can split and them parse them back into an integer!  And then print them anyway!
        String[] odds = str.split("\\,*\\-*\\s*[24680]*\\,");
        //This is the number of odds!
        System.out.println(odds.length);
        for (String odd : odds) {
            int oddNum = Integer.parseInt(odd);
            System.out.print(oddNum + " ");
        }

        System.out.println();

        //Or just print them!
        String[] evens = str.split("\\,*\\-*\\s*[13579]*\\,");
        for (String even : evens) {
            System.out.print(even + " ");
        }

Note: My regex is not the best and this can be improved to remove whitespace/empty characters better
PS.  No if statements were harmed in the making of this code.  Also this code is clearly not meant to be use in a real setting, and I did it mess around with regex but it does what was required.


text:
Q: Having difficulties with Jekyll / Liquid I'm tring to do a loop for Nav links below my posts. This is going into the _layout of posts.html
I can't get the link to not show if the post is the last or the first. Any help would be awesome.

{% for post in site.posts %}

    {% if post.previous != forloop.last %}
        ← Last
    {% elsif post.next != forloop.first %}
        Next →
    {% endif %}

{% endfor %}

A: I had better luck using page.next/previous
    {% if page.previous %}
        ← Older
    {% endif %}
    {% if page.next %}
        Newer →
    {% endif %}

A: Change your if statements to just check if post.previous exists.
{% if post.previous %}

    ← View previous article

{% endif %}
{% if post.next %}

    View next article →

{% endif %}

A: Add images to your link background.
 For images to show up just add image: [image location] in your YAML front matter

    {% if page.previous.url %}
      « {{ page.previous.title }}
      {% if page.previous.image %}

      {% endif %}

    {% endif %}
    {% if page.next.url %}
      {{ page.next.title }} »
      {% if page.next.image %}

      {% endif %}

        {% endif %}


text:
Q: ElasticSearch Script Fields accessable in sort Is it possible to access a script_field inside a sort?
I have
search_body["script_fields"] = {
    "test": {
        "script": {
            "lang": "painless",
            "inline": skill_rating_algorithm.replace("\n", ""),
            "params" : {
                "param1": {....}
            }
        }
    }
}

And as sort:
search_body["sort"] = {
    "_script": {
        "type": "string",
        "order": "desc",
        "script": {
            "lang": "painless",
            "inline": "def c = params._fields['test']; return c;",
        }
    },
    "number_of_years_of_experience": {"order": "desc"},
    "value.raw": {"order": "asc"},
}

But this only return errors.
I could do a sorting script but i need the value returned in the document as a separate key.
My questions is:
Can i access the script_field "test" inside the sort? (More script_fields will come and i will need different ordering)


text:
Q: Scroll to section navigation issues I am building a single page website and need a 'scroll to section navigation', I'm using this jsfiddle as a basic template. As you can see it works like a charm, however for some reason on my website it doesn't seem to work, I have pasted a couple of important code snippets below

I'm a really cool title about
Small Space Living

Lorem ipsum dolor sit amet, consectetur ...esse.

    Learn More

About Us

Solutions

Contact Us

there is a fair amount of css but I can't imagine it being a style problem as the jsfiddle has zero style and still works.
Any help would really be appreciated. Thanks in advance!

A: http://jsfiddle.net/gUWdJ/609/
It works good there. Is it possible that you have some other js error that block this script?
@EDIT: Try this code: you miss a point in class definition!! $('.navi a').
$(document).ready(function(){
$('.navi a').on('click', function() {

var scrollAnchor = $(this).attr('data-scroll'),
    scrollPoint  = $('section[data-anchor="'+scrollAnchor+'"]').offset().top -10;

$('body,html').animate({
   scrollTop: scrollPoint
}, 500);

return false;

});
});

If you don't want any animation you can use this easy anchor with a:

TOP

NEWS

PRODUCTS

CONTACT

http://jsfiddle.net/gUWdJ/608/

A: I created a file with the following in it:

    TOP

    NEWS

    PRODUCTS

    CONTACT

TOP

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.

Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.

NEWS

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.

Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.

PRODUCTS

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.

Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.

CONTACT

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.

Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a id tellus. Morbi accumsan magna sit amet velit ultricies ut dapibus justo rutrum. Ut et ante dui, vel pellentesque velit.

Then I saved it as index.html.  Opened it, and it worked.
The main problem you had was $('navi a') which I changed to '$('nav a')`.  I think a tiny typo got you.
Edit
I feel I should explain a little better.  You should not use .navi, as that refers to the class of an object: .  You shouldn't use #navi as that refers to the id of an object: .  Using navi refers to a  object.  Since you wanted to refer to a  tag, we use $('nav').  Hope this clarifies a little.


text:
Q: Blackberry component libraries Blackberry UI components look so poor after seeing the iPhone, Android and Windows Phone 7 platforms.
Are there any third-party UI component libraries for BlackBerry?

A: Article How to implement advanced BB UI contains many ready-to-use components!


text:
Q: node.js: using process.env to store whole app configuration Well maybe a little bit strange and basic question but..
As usual in my application I have some configurations parameters specific for current environment like dbs, paths, keys, logins etc.
There is an access to process.env object that may contain any number of string properties, so why not use it for storing all the config information and use it across the application?
I've seen people are using some custom config files or some modules like nconf (https://github.com/flatiron/nconf).
nconf seems to be very robust,  but I don't really see where I may use its power, as I just need to be able init some shared parameters and use it in different app's modules.
So the question is init and store configuration parameters in process.env and use across all application code just in sake of simplicity?

A: You could just use global, adding a new variable into the global scope. Just be careful with it ;-)


text:
Q: Prevent overlap on multiple rows of `Position: sticky;` headers (without calculating/hardcoding heights) I want to have multiple rows of headers (say, h1 through h6), where each sub-header sticks directly below the header above it (Each h6 sticks to the bottom of the currently stickied h5, which sticks to the bottom of the currently stickied h4, etc).
When using position: sticky; top: 0; on all the sticky headers, they will overlap at the top of the page. The overlap is not desired:
h1, h2 {
  position: sticky;
  top: 0;
}

h1, h2 {
  position: sticky;
  top: 0;
}

div>div {
  margin-left: 2em;
}

a header

a content

a content

a content

a content

a content

a content

a1 header

a1 content

a1 content

a1 content

a1 content

a1 content

a1 content

a2 header

a2 content

a2 content

a2 content

a2 content

a2 content

a2 content

a3 header

a3 content

a3 content

a3 content

a3 content

a3 content

a3 content

b header

b content

b content

b content

b content

b content

b content

b1 header

b1 content

b1 content

b1 content

b1 content

b1 content

b1 content

b2 header

b2 content

b2 content

b2 content

b2 content

b2 content

b2 content

b3 header

b3 content

b3 content

b3 content

b3 content

b3 content

b3 content

c header

c content

c content

c content

c content

c content

c content

c1 header

c1 content

c1 content

c1 content

c1 content

c1 content

c1 content

c2 header

c2 content

c2 content

c2 content

c2 content

c2 content

c2 content

c3 header

c3 content

c3 content

c3 content

c3 content

c3 content

c3 content

If the h2 header is changed to top: 30px, the overlap is removed, but this only works if all the h1 heights are known to be exactly 30px. This looks better, but the hardcoded value 30px is not desired:
h1, h2 {
  position: sticky;
  top: 0;
}
h2 {
  top: 30px;
}

h1, h2 {
  position: sticky;
  top: 0;
}
h2 {
  top: 30px;
}
div>div {
  margin-left: 2em;
}

a header

a content

a content

a content

a content

a content

a content

a1 header

a1 content

a1 content

a1 content

a1 content

a1 content

a1 content

a2 header

a2 content

a2 content

a2 content

a2 content

a2 content

a2 content

a3 header

a3 content

a3 content

a3 content

a3 content

a3 content

a3 content

b header

b content

b content

b content

b content

b content

b content

b1 header

b1 content

b1 content

b1 content

b1 content

b1 content

b1 content

b2 header

b2 content

b2 content

b2 content

b2 content

b2 content

b2 content

b3 header

b3 content

b3 content

b3 content

b3 content

b3 content

b3 content

c header

c content

c content

c content

c content

c content

c content

c1 header

c1 content

c1 content

c1 content

c1 content

c1 content

c1 content

c2 header

c2 content

c2 content

c2 content

c2 content

c2 content

c2 content

c3 header

c3 content

c3 content

c3 content

c3 content

c3 content

c3 content

Is it possible to prevent this overlap without knowing the height of the h1? Does position: sticky provide any means of doing this (without resorting to javascript to calculate the h1 height)?

A: I've cooked up a little JQuery code to help with your issue of hardcoding the heights. Instead of hardcoding and adjusting it again and again, you could make use of the .height() function to find the height and apply it using javascript itself like shown in the code snippet below.
Hope, it helps.

$(document).ready(function() {
  var h2 = $('h2').height();
  var h3 = $('h3').height() + h2;
  var h4 = $('h4').height() + h3;
  var h5 = $('h5').height() + h4;
  var h6 = $('h6').height() + h5;
  $("h2").css("top", h2);
  $("h3").css("top", h3);
  $("h4").css("top", h4);
  $("h5").css("top", h5);
  $("h6").css("top", h6);
});
h1,
h2,
h3,
h4,
h5,
h6 {
  position: sticky;
  top: 0;
}

div>div {
  margin-left: 2em;
}

a header

a content

a content

a content

a content

a content

a content

a1 header

a1 content

a1 content

a1 content

a1 content

a1 content

a1 content

a3 header

a3 content

a3 content

a3 content

a4 header

a4 content

a4 content

a4 content

a5 header

a5 content

a5 content

a5 content

a6 header

a6 content

a6 content

a6 content

a2 header

a2 content

a2 content

a2 content

a2 content

a2 content

a2 content

a3 header

a3 content

a3 content

a3 content

a3 content

a3 content

a3 content

b header

b content

b content

b content

b content

b content

b content

b1 header

b1 content

b1 content

b1 content

b1 content

b1 content

b1 content

b2 header

b2 content

b2 content

b2 content

b2 content

b2 content

b2 content

b3 header

b3 content

b3 content

b3 content

b3 content

b3 content

b3 content

c header

c content

c content

c content

c content

c content

c content

c1 header

c1 content

c1 content

c1 content

c1 content

c1 content

c1 content

c2 header

c2 content

c2 content

c2 content

c2 content

c2 content

c2 content

c3 header

c3 content

c3 content

c3 content

c3 content

c3 content

c3 content


text:
Q: calculating the time diffrence of the Column in hive with the current row and the previous row values? Hi I would like to compute the difference of the date time column which will have the value like below I want to find the difference .
Name       start_time            rownumber   TIME DIFFERENCE
Vijay      null                       1        0
Vijay      null                       1        0
Vijay      12-03-2018:00:00:00        2        64
Vijay      NULL                       1        0
Vijay      15-03-2018:00:00:00        3        48
VIJAY      17-03-2018:00:00:00        4        null

I need a hive command to compute the same

A: use LAG over
SELECT name,start_time,
(unix_timestamp(start_time) - unix_timestamp(LAG(start_time,2) OVER (PARTITION BY name ORDER BY starttime)))/3600 lag_in_hour
FROM customer;


text:
Q: Extending psc metrics Let $S^1$ denote the circle with the non-trivial spin structure, i.e. $0\neq[S^1]\in\Omega^{Spin}_1$. Considering characteristic numbers it is easy so see that $S^1\times\mathbb{H}P^3$ is spin null bordant, say via $W$. (If you wish you can take $W$ simply connected.) Now let $g$ be the standard metric of positive scalar curvature on $\mathbb{H}P^3$, then $dt^2\times g$ is a metric of positive scalar curvature on $\partial W=S^1\times\mathbb{H}P^3$.
Is it possible to extend $dt^2\times g$ to a metric of positive scalar curvature on $W$?
A possible answer may use the 'obstruction groups' $R_n$ introduced by Stolz (in: Concordance classes of positive scalar curvature metrics). However, there are hardly computable. In addition, eventual index obstructions vanish for dimensional reasons, as $\dim W\equiv6\mod{8}$.
Although I believe that this is a quite hard question I am grateful for any comments in advance.


text:
Q: How to avoid client caching with CDN Working on a project in AS3 I require to stream a few files for bandwidth testing purposes. The files needs to come from the CDN (the clients closest proxy) in order to make the bandwidth test reliable.
Of course if the remote files get cached in the clients browser the bandwidth test would not be reliable.
Usually I would add a time-stamp in the GET variables in order to trick the clients cache. But I can imagine this is a very bad practice working with a CDN.
So my question is :
how to force bypass the clients cache to retrieve a new version of a file without really changing the request ?
Thanks in advance,
T
EDIT :
The ideal would be to send a cache-control header in URLRequest (thanks Assaf!). Unfortunately I've been trying it out for a little while and it doesn't seem to work within FlashPlayer. Even on the web, people seems to be pessimistic about the subject.
Quick example :
var headers:Array = new Array(new URLRequestHeader("Cache-Control", "no-cache"));
urlRequest.requestHeaders = headers;
urlRequest.load(url);

Anybody ever managed to make something similar to work ?

A: The proper way of doing it is specifying cache http control headers in your request, or configuring no-caching on the server.
If you have control over the server you can specify pragma no-cache, or something equivalent, so that certain files are never cached.
The timestamp is indeed not such a good idea, because it might screw with all kinds of caches along the way.


text:
Q: how to tell google geocode() that you are looking for an administrative_area address and not a city? If you were to do a reverse lookup for a region (States or Province) and that region happen to have a city with the same name, then Google geocoder will return the information on the city instead of the region.
How would you pass parameters to Google telling it that you are indeed interested in the region and not the city?
Calling Google WebAPI would be something like this:
http://maps.google.com/maps/api/geocode/json?components=administrative_area:Durango|country:MX&sensor=false
But instead, we want to call geocoder.
_geocoder = new google.maps.Geocoder();
_geocoder.geocode(request_dict, function(results, status) { ... }

How do you form the "request_dict"?


text:
Q: JPQL with specific column returning Object array I have repository method where i am trying to fetch specific column from table.
when i call findAllNamesAndID method i get Object array in return where i am expecting List of Customwidgets.
I am not sure whats wrong with below code.
I can use use constructor of Customwidgets in query annotation but i want to avoid that. Is there any workaround.
I have below domain class :-
public class Customwidgets implements Serializable {
    @Id
    private UUID id;

    @NotNull
    @Column(name = "name", nullable = false)
    private String name;

---
---
}

My Repository class :-
@Repository
public interface CustomwidgetsRepository extends JpaRepository<Customwidgets, UUID>, JpaSpecificationExecutor<Customwidgets> {

    @Query("select o.id, o.name from Customwidgets o")
    List<Customwidgets> findAllNamesAndID();

}

A: You can create an interface to define your projection. For instance:
public interface CustomWidgetsProjection {

   String getId();

   String getName();

}

Then you can return this interface you created instead of CustomWidgets:
@Query("select o.id, o.name from Customwidgets o")
List<CustomWidgetsProjection> findAllNamesAndID();


text:
Q: Why am I frequently getting disconnected from wifi after some time of use? I use a Lenovo g50-45 with Realtek Semiconductor Co., Ltd. RTL8723BE PCIe Wireless Network Adapter. I am connected to the wifi and can access the Internet for like 10-5 min and then the wifi will still be connected but there will be no Internet.
Here are some details and analysis report's wireless-info.txt


text:
Q: multiple combobox with event onchange I have a problem when populate combobox with data from query.
And when I change the combobox, I want to set value in the textbox or hidden with selected onchange combobox.
When the first combobox that work but when I change the second combobox, not set value to textbox or hidden value.
<script type='text/javascript'>
  $(function() {
    $('#myselect').change(function() {
      var x = $(this).val();
      $('#myhidden').val(x);
    });
  });
</script>

<input type='text' id='myhidden' value=''>

<?php
    $result2 = mysql_query("select id_users, fullname from users where status='1'");
    echo'<select name="iduserowner" class=form-control id=myselect>';
    while($data2 = mysql_fetch_array($result2)) {
      echo '<option  value="'.$data2['id_users'].'">'.$data2['fullname'].'</option>';
    }
    echo '</select>';
?>

A: as I understand you want to put your selected value into your hidden input.
try this:
<?php $sql = "SELECT id_users, fullname
               FROM users
               WHERE status = '1'";

        $res = mysql_query( $sql );
    ?>

    <input type="text" id="myhidden" value="">
    <select onChange="hideSelected();" name="iduserowner" class="form-control" id="myselect" >

    <? while( $result = mysql_fetch_array( $res, MYSQL_ASSOC )){ ?>

        <option value="<?= $result[ 'id_users' ]; ?>"><?= $result[ 'fullname' ]; ?></option>

    <? } ?>
    </select>

    <script>

    function hideSelected(){

        $("#myhidden").val( $("#myselect option:selected").val() );
    }

    </script>


text:
Q: How i can save the char data directly to blob db? I need to save an wxBitmap to SQLite to a blob type without save to disk or on some media.
i have mybitmap as wxBitmap;
First must convert to wxImage and get data.
Ok until now i hope, but how i can  save the char data directly to blob db?
In sql must have

update mytable SET blob_column='??????' WHERE id='1'

or something like that. How must construct query?
wxImage img=mybitmap.ConvertToImage();
unsigned char* data=img.GetData();
int datalength=img.GetWidth()*img.GetHeight()*3;
char *myBuffer = (char *)data;

The code bellow is for wxSQLite3 ...
    wxMemoryOutputStream mo;
img.SaveFile( mo, wxBITMAP_TYPE_PNG );

wxSQLite3Statement stmt = db.PrepareStatement("UPDATE mytable SET blob_column='?' WHERE id='1'");
stmt.Bind(0, (unsigned char *)mo.GetOutputStreamBuffer()->GetBufferStart(), mo.GetOutputStreamBuffer()->GetBufferSize());
stmt.ExecuteUpdate();

But how to translate for SQLite?


text:
Q: I cannot use PyBioMed in Jupyterlab even though it's installed and importing perfectly. It's showing the error HTTP Error 403: Forbidden I cannot use PyBioMed in Jupyterlab even though it's installed and importing perfectly.
I've already cleared cache (following instructions from a similar error reported on github), already reinstalled, and everything is ok with rdkit too, but this is still happening.
In jupyterlab it's running:
from PyBioMed.PyGetMol import Getmol
But when I try
DrugBankID = 'DB01014'
Getmol.GetMolFromDrugbank(DrugBankID)

I get this error:
HTTPError                                 Traceback (most recent call last)
Input In [3], in <cell line: 2>()
      1 DrugBankID = 'DB01014'
----> 2 Getmol.GetMolFromDrugbank(DrugBankID)

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\pybiomed-1.0-py3.9.egg\PyBioMed\PyGetMol\Getmol.py:197, in GetMolFromDrugbank(dbid)
    192 """
    193 Downloading the molecules from http://www.drugbank.ca/ by dbid (dbid).
    194 """
    195 dbid = dbid.strip()
--> 197 localfile = urlopen("http://www.drugbank.ca/drugs/" + dbid + ".sdf")
    198 temp = localfile.readlines()
    199 f = file("temp.sdf", "w")

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:214, in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    212 else:
    213     opener = _opener
--> 214 return opener.open(url, data, timeout)

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:523, in OpenerDirector.open(self, fullurl, data, timeout)
    521 for processor in self.process_response.get(protocol, []):
    522     meth = getattr(processor, meth_name)
--> 523     response = meth(req, response)
    525 return response

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:632, in HTTPErrorProcessor.http_response(self, request, response)
    629 # According to RFC 2616, "2xx" code indicates that the client's
    630 # request was successfully received, understood, and accepted.
    631 if not (200 <= code < 300):
--> 632     response = self.parent.error(
    633         'http', request, response, code, msg, hdrs)
    635 return response

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:555, in OpenerDirector.error(self, proto, *args)
    553     http_err = 0
    554 args = (dict, proto, meth_name) + args
--> 555 result = self._call_chain(*args)
    556 if result:
    557     return result

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:494, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args)
    492 for handler in handlers:
    493     func = getattr(handler, meth_name)
--> 494     result = func(*args)
    495     if result is not None:
    496         return result

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:747, in HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
    744 fp.read()
    745 fp.close()
--> 747 return self.parent.open(new, timeout=req.timeout)

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:523, in OpenerDirector.open(self, fullurl, data, timeout)
    521 for processor in self.process_response.get(protocol, []):
    522     meth = getattr(processor, meth_name)
--> 523     response = meth(req, response)
    525 return response

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:632, in HTTPErrorProcessor.http_response(self, request, response)
    629 # According to RFC 2616, "2xx" code indicates that the client's
    630 # request was successfully received, understood, and accepted.
    631 if not (200 <= code < 300):
--> 632     response = self.parent.error(
    633         'http', request, response, code, msg, hdrs)
    635 return response

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:561, in OpenerDirector.error(self, proto, *args)
    559 if http_err:
    560     args = (dict, 'default', 'http_error_default') + orig_args
--> 561     return self._call_chain(*args)

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:494, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args)
    492 for handler in handlers:
    493     func = getattr(handler, meth_name)
--> 494     result = func(*args)
    495     if result is not None:
    496         return result

File ~\AppData\Local\Programs\Python\Python39\lib\urllib\request.py:641, in HTTPDefaultErrorHandler.http_error_default(self, req, fp, code, msg, hdrs)
    640 def http_error_default(self, req, fp, code, msg, hdrs):
--> 641     raise HTTPError(req.full_url, code, msg, hdrs, fp)

HTTPError: HTTP Error 403: Forbidden