text:
Q: in C#, how do I order items in a list where the "largest" values are in the middle of the list I have been stumped on this one for a while.  I want to take a List and order the list such that the Products with the largest Price end up in the middle of the list.  And I also want to do the opposite, i.e. make sure that the items with the largest price end up on the outer boundaries of the list.
Imagine a data structure like this.. 1,2,3,4,5,6,7,8,9,10
In the first scenario I need to get back  1,3,5,7,9,10,8,6,4,2
In the second scenario I need to get back 10,8,6,4,2,1,3,5,7,9
The list may have upwards of 250 items, the numbers will not be evenly distributed, and they will not be sequential, and I wanted to minimize copying.  The numbers will be contained in Product objects, and not simple primitive integers.
Is there a simple solution that I am not seeing?
Any thoughts.
So for those of you wondering what I am up to, I am ordering items based on calculated font size.  Here is the code that I went with...
The Implementation...
private void Reorder()
{
    var tempList = new LinkedList<DisplayTag>();
    bool even = true;
    foreach (var tag in this) {
        if (even)
            tempList.AddLast(tag);
        else
            tempList.AddFirst(tag);

        even = !even;
    }

    this.Clear();
    this.AddRange(tempList);
}

The Test...
[TestCase(DisplayTagOrder.SmallestToLargest, Result=new[]{10,14,18,22,26,30})]
[TestCase(DisplayTagOrder.LargestToSmallest, Result=new[]{30,26,22,18,14,10})]
[TestCase(DisplayTagOrder.LargestInTheMiddle, Result = new[] { 10, 18, 26, 30, 22, 14 })]
[TestCase(DisplayTagOrder.LargestOnTheEnds, Result = new[] { 30, 22, 14, 10, 18, 26 })]
public int[] CalculateFontSize_Orders_Tags_Appropriately(DisplayTagOrder sortOrder)
{
    list.CloudOrder = sortOrder;
    list.CalculateFontSize();

    var result = (from displayTag in list select displayTag.FontSize).ToArray();
    return result;
}

The Usage...
public void CalculateFontSize()
{
    GetMaximumRange();
    GetMinimunRange();
    CalculateDelta();

    this.ForEach((displayTag) => CalculateFontSize(displayTag));

    OrderByFontSize();
}

private void OrderByFontSize()
{
    switch (CloudOrder) {
        case DisplayTagOrder.SmallestToLargest:
            this.Sort((arg1, arg2) => arg1.FontSize.CompareTo(arg2.FontSize));
            break;
        case DisplayTagOrder.LargestToSmallest:
            this.Sort(new LargestFirstComparer());
            break;
        case DisplayTagOrder.LargestInTheMiddle:
            this.Sort(new LargestFirstComparer());
            Reorder();
            break;
        case DisplayTagOrder.LargestOnTheEnds:
            this.Sort();
            Reorder();
            break;
    }
}

A: C# Iterator version
(Very simple code to satisfy all conditions.)
One function to rule them all! Doesn't use intermediate storage collection (see yield keyword). Orders the large numbers either to the middle, or to the sides depending on the argument. It's implemented as a C# iterator
// Pass forward sorted array for large middle numbers,
//  or reverse sorted array for large side numbers.
//
public static IEnumerable<long> CurveOrder(long[] nums) {

    if (nums == null || nums.Length == 0)
        yield break; // Nothing to do.

    // Move forward every two.
    for (int i = 0;  i < nums.Length;  i+=2)
        yield return nums[i];

    // Move backward every other two. Note: Length%2 makes sure we're on the correct offset.
    for (int i = nums.Length-1 - nums.Length%2;  i >= 0;  i-=2)
        yield return nums[i];
}

Example Usage
For example with array long[] nums = { 1,2,3,4,5,6,7,8,9,10,11 };
Start with forward sort order, to bump high numbers into the middle.
Array.Sort(nums); //forward sort
// Array argument will be:  { 1,2,3,4,5,6,7,8,9,10,11 };
long[] arrLargeMiddle = CurveOrder(nums).ToArray();

Produces: 1 3 5 7 9 11 10 8 6 4 2
Or, Start with reverse sort order, to push high numbers to sides.
Array.Reverse(nums); //reverse sort
// Array argument will be:  { 11,10,9,8,7,6,5,4,3,2,1 };
long[] arrLargeSides = CurveOrder(nums).ToArray();

Produces: 11 9 7 5 3 1 2 4 6 8 10
Significant namespaces are:
using System;
using System.Collections.Generic;
using System.Linq;

Note: The iterator leaves the decision up to the caller about whether or not to use intermediate storage. The caller might simply be issuing a foreach loop over the results instead.

Extension Method Option
Optionally change the static method header to use the this modifier public static IEnumerable<long> CurveOrder(this long[] nums) {  and put it inside a static class in your namespace;
Then call the order method directly on any long[ ] array instance like so:
Array.Reverse(nums); //reverse sort
// Array argument will be:  { 11,10,9,8,7,6,5,4,3,2,1 };
long[] arrLargeSides = nums.CurveOrder().ToArray();

Just some (unneeded) syntactic sugar to mix things up a bit for fun. This can be applied to any answers to your question that take an array argument.

A: Something like this?
public IEnumerable<int> SortToMiddle(IEnumerable<int> input)
{
    var sorted = new List<int>(input);
    sorted.Sort();
    var firstHalf = new List<int>();
    var secondHalf = new List<int>();

    var sendToFirst = true;
    foreach (var current in sorted)
    {
        if (sendToFirst)
        {
            firstHalf.Add(current);
        }
        else
        {
            secondHalf.Add(current);
        }
        sendToFirst = !sendToFirst;
    }
    //to get the highest values on the outside just reverse
    //the first list instead of the second
    secondHalf.Reverse();
    return firstHalf.Concat(secondHalf);
}

For your specific (general) case (assuming unique keys):
public static IEnumerable<T> SortToMiddle<T, TU>(IEnumerable<T> input, Func<T, TU> getSortKey)
{
    var sorted = new List<TU>(input.Select(getSortKey));
    sorted.Sort();
    var firstHalf = new List<TU>();
    var secondHalf = new List<TU>();

    var sendToFirst = true;
    foreach (var current in sorted)
    {
        if (sendToFirst)
        {
            firstHalf.Add(current);
        }
        else
        {
            secondHalf.Add(current);
        }
        sendToFirst = !sendToFirst;
    }
    //to get the highest values on the outside just reverse
    //the first list instead of the second
    secondHalf.Reverse();
    sorted = new List<TU>(firstHalf.Concat(secondHalf));

    //This assumes the sort keys are unique - if not, the implementation
    //needs to use a SortedList<TU, T>
    return sorted.Select(s => input.First(t => s.Equals(getSortKey(t))));

}

And assuming non-unique keys:
public static IEnumerable<T> SortToMiddle<T, TU>(IEnumerable<T> input, Func<T, TU> getSortKey)
{
    var sendToFirst = true;
    var sorted = new SortedList<TU, T>(input.ToDictionary(getSortKey, t => t));
    var firstHalf = new SortedList<TU, T>();
    var secondHalf = new SortedList<TU, T>();

    foreach (var current in sorted)
    {
        if (sendToFirst)
        {
            firstHalf.Add(current.Key, current.Value);
        }
        else
        {
            secondHalf.Add(current.Key, current.Value);
        }
        sendToFirst = !sendToFirst;
    }
    //to get the highest values on the outside just reverse
    //the first list instead of the second
    secondHalf.Reverse();
    return(firstHalf.Concat(secondHalf)).Select(kvp => kvp.Value);
}

A: I might go for something like this
static T[] SortFromMiddleOut<T, U>(IList<T> list, Func<T, U> orderSelector, bool largestInside) where U : IComparable<U>
{
    T[] sortedArray = new T[list.Count];

    bool add = false;
    int index = (list.Count / 2);
    int iterations = 0;

    IOrderedEnumerable<T> orderedList;
    if (largestInside)
        orderedList = list.OrderByDescending(orderSelector);
    else
        orderedList = list.OrderBy(orderSelector);

    foreach (T item in orderedList)
    {
        sortedArray[index] = item;
        if (add)
            index += ++iterations;
        else
            index -= ++iterations;

        add = !add;
    }

    return sortedArray;
}

Sample invocations:
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int[] sortedArray = SortFromMiddleOut(array, i => i, false);
foreach (int item in sortedArray)
    Console.Write("{0} ", item);

Console.Write("\n");

sortedArray = SortFromMiddleOut(array, i => i, true);
foreach (int item in sortedArray)
    Console.Write("{0} ", item);

With it being generic, it could be a list of Foo and the order selector could be f => f.Name or whatever you want to throw at it.

A: The fastest (but not the clearest) solution is probably to simply calculate the new index for each element:
        Array.Sort(array);

        int length = array.Length;
        int middle = length / 2;
        int[] result2 = new int[length];

        for (int i = 0; i < array.Length; i++)
        {
            result2[middle + (1 - 2 * (i % 2)) * ((i + 1) / 2)] = array[i];
        }

A: The appropriate data structure is a LinkedList because it allows you to efficiently add to either end:
        LinkedList<int> result = new LinkedList<int>();

        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        Array.Sort(array);

        bool odd = true;

        foreach (var x in array)
        {
            if (odd)
                result.AddLast(x);
            else
                result.AddFirst(x);
            odd = !odd;
        }

        foreach (int item in result)
            Console.Write("{0} ", item);

No extra copying steps, no reversing steps, ... just a small overhead per node for storage.

A: Simplest solution - order the list descending, create two new lists, into the first place every odd-indexed item, into the other every even indexed item.  Reverse the first list then append the second to the first.

A: Okay, I'm not going to question your sanity here since I'm sure you wouldn't be asking the question if there weren't a good reason :-)
Here's how I'd approach it. Create a sorted list, then simply create another list by processing the keys in order, alternately inserting before and appending, something like:
sortedlist = list.sort (descending)
biginmiddle = new list()
state = append
foreach item in sortedlist:
    if state == append:
        biginmiddle.append (item)
        state = prepend
    else:
        biginmiddle.insert (0, item)
        state = append

This will give you a list where the big items are in the middle. Other items will fan out from the middle (in alternating directions) as needed:
1, 3, 5, 7, 9, 10, 8, 6, 4, 2

To get a list where the larger elements are at the ends, just replace the initial sort with an ascending one.
The sorted and final lists can just be pointers to the actual items (since you state they're not simple integers) - this will minimise both extra storage requirements and copying.

A: Maybe its not the best solution, but here's a nifty way...
Let Product[] parr be your array.
Disclaimer It's java, my C# is rusty.
Untested code, but you get the idea.
int plen = parr.length
int [] indices = new int[plen];
for(int i = 0; i < (plen/2); i ++)
    indices[i] = 2*i + 1;   // Line1
for(int i = (plen/2); i < plen; i++)
    indices[i] = 2*(plen-i); // Line2

for(int i = 0; i < plen; i++)
{
    if(i != indices[i])
        swap(parr[i], parr[indices[i]]);
}

The second case, Something like this?
int plen = parr.length
int [] indices = new int[plen];
    for(int i = 0; i <= (plen/2); i ++)
       indices[i] = (plen^1) - 2*i;
    for(int i = 0; i < (plen/2); i++)
       indices[i+(plen/2)+1] = 2*i + 1;

for(int i = 0; i < plen; i++)
{
    if(i != indices[i])
        swap(parr[i], parr[indices[i]]);
}


text:
Q: Wicket : render/refresh RepeatingView without having html tag So i have FormControl inside Repeating View and i set html for Repeating view as Wicket:container
I am trying to refresh formControl but because i am stripping wicket tags in output
it gives JS error.
i know wicket:container can not be refreshed. but i am not able to refresh control inside it. I tried setting
control.setOutputMarkupPlaceholderTag(true);
control.setOutputMarkupId(true);

And Html is Something like this
<form wicket:id="form">
        <wicket:container wicket:id="repeatingContainer">
        </wicket:container>
</form>

here is error i am getting
Cannot bind a listener for event "change" on element "id1a3" because the element is not in the DOM

i want to remove repeatingContainer html tag from output so it follows bootstrap form layout.
Update:
This code is inside the RepeaterView
<wicket:panel>

        <wicket:child/>

</wicket:panel>

This code wicket Child

    <input wicket:id="input"/>

A: ok so i am able to tackle this down.
I updated component Group div to wicket:container and leave the Repeater as div. So now i am able to refresh. and it works alright.
So this is how it will look like
<form wicket:id="form">

        <wicket:container wicket:id="componentGroup">

                <input wicket:id="input"/>

        </wicket:container>

</form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a MySql binary dump format? Or anything better than plain text INSERT statements? Is there anything better (faster or smaller) than pages of plain text CREATE TABLE and INSERT statements for dumping MySql databases? It seems awfully inefficient for large amounts of data.
I realise that the underlying database files can be copied, but I assume they will only work in the same version of MySql that they come from.
Is there a tool I don't know about, or a reason for this lack?

A: Not sure if this is what you're after, but I usually pipe the output of mysqldump directly to gzip or bzip2 (etc).  It tends to be a considerably faster than dumping to stdout or something like that, and the output files are much smaller thanks to the compression.
mysqldump --all-databases (other options) | gzip > mysql_dump-2010-09-23.sql.gz

It's also possible to dump to XML with the --xml option if you're looking for "portability" at the expense of consuming (much) more disk space than the gzipped SQL...

A: Sorry, no binary dump for MySQL. However the binary logs of MySQL are specifically for backup and database replication purposes http://dev.mysql.com/doc/refman/5.5/en/binary-log.html . They are not hard to configure. Only changes such as update and delete are logged, so each log file (created authomatically by MySQL) is also an incremental backup of the changes in the DB. This way you can save from time to time a whole snapshot of the db (once in a month?), and then store just the log files, and in case of crash, restore the latest snapshot and run through the logs.

A: It's worth noting that MySQL has a special syntax for doing bulk inserts. From the manual:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

Would insert 3 rows in a single operation. So loading this way isn't as inefficient as it might otherwise be with one statement per row, and instead of 129 bytes in 3 INSERT statements, this is 59 bytes, and that advantage only gets bigger the more rows you have.

A: I've never tried this, but aren't mysql tables just binary files on the hard drive? Couldn't you just copy the table files themselves? Presumably that's essentially what you are asking for.
I don't know how to stitch that together, but it seems to me a copy of /var/lib/mysql would do the trick


text:
Q: could not find this command '--andriod-licenses' After trying many attempts like update sdk manager and their tools still i have getting this problem
dont know why my system is not find this command so that i can accept this licenses and remove the error from flutter doctor please help!
here are the images and my tools i installed :-
Error image
Sdk Tool
watched every video on youtube but not a 1 video helped me all are just accept licenses and done.
Please tell me anyone how to [update/accept] andriod licenses from local directory so that i try and also their file.

A: You misspelled '--android-licenses' ;)


text:
Q: Use python date function inside SQLAlchemy column property I have these models in SQLAlchemy. it is defining a simple action of my system which is liking a post by an account, so each account can like several posts and also a post can be liked by many accounts(Many-to-Many), Every looks fine execpt likes_per_day column property that I want it to show number of likes each day of an account. when I run this code and keep this running, it looks like date.today() will execute at run time and always shows me the number of likes of rundate, not today.
So I'm planning to get number of likes for each day using column property. what is the correct way to do this?
class Account(Base):
    __tablename__ = 'account'

    id = Column(
        Integer,
        primary_key=True
    )

    likes_per_day = column_property(
        select([func.count(Like.id)])
        .where(Like.account_id == id)
        .where(func.date(Like.created_at) == date.today()) # Problem is here
        .correlate_except(Like)
    )

class Like(Base):
    __tablename__ = 'like'

    id = Column(
        Integer,
        primary_key=True
    )

    post_id = Column(
        Integer,
        ForeignKey('post.id')
    )
    account_id = Column(
        Integer,
        ForeignKey('account.id')
    )
    created_at = Column(
        DateTime,
        nullable=False,
        default=datetime.utcnow,
    )

A: How about to use:
    likes_per_day = column_property(
        select([func.count(Like.id)])
        .where(Like.account_id == id)
        .where(func.date(Like.created_at) == bindparam(
            'today',
            callable_=lambda:date.today().isoformat()
            )
        )
        .correlate_except(Like),
        deferred=True
    )

the date function returns the iso format of a DateTime, on the other hand the date.today() is an object of date that sqlalchemy doesn't know how should parse because of various date formats.
So by declaring the date format explicitly you should get the result you want.


text:
Q: How to get result of shell script in webpage using javascript? I am trying to set up a local server for maintaining local git repositories.
I have already written several shell scripts for a command line utility that returns the output that I want. I would like to run these from the webpage by using javascript if possible. (Server will run the script, NOT the client)
I didn't write the scripts for the purpose of displaying info on a webpage, but wanted to implement them if possible as to not rewrite the code again.
I have this javascript code:
test.js
var exec = require('child_process').exec;

function test() {
    exec("ssh git@raspberrypi 'ls ~/Git/'",
      function (error, stdout, stderr) {
        console.log(stdout);
        // document.write(stdout);
      });
}

test()

If I run this with node test.js
I get the output of the command printed to console.

git_folder1.git
git_folder2.git
git_folder3.git

However, If I uncomment the line document.write(stdout), and call it from HTML, I get no output.
test.html
<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <script>test()</script>
    </body>
</html>

If I put document.write("Hello") before the exec "Hello" gets written to the document, but if put at the bottom of the function (or inside), it doesn't.
Am I doing something wrong?
Is there a better way to go about getting the output of a shell script in a webpage?


text:
Q: Not able to implement selenium grid Below is my code which I am using to pass browser, node and hub port to launch browser and execute the tests but i get exception although I am able to set up selenium server. I paste error below of the code too. I use mac book, Selenium 3.4, Firefox 55 and Gecko 0.18.0
public synchronized WebDriver setUp(String browser, String
nodePort, String hubPort) throws MalformedURLException{

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setPlatform(Platform.MAC);
capabilities.setCapability(CapabilityType.BROWSER_NAME, browser);
capabilities.setCapability(ForSeleniumServer.PROXYING_EVERYTHING,
true);
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(CapabilityType.SUPPORTS_ALERTS, true);
capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT,
true);

if(browser.equals("firefox"))
    System.setProperty("webdriver.gecko.driver",
System.getProperty("user.dir")+"//geckoDriver//geckodriver");
else if(browser.equals("chrome"))
    System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir")+"//chromeDriver//chromeDriver");
driver = new RemoteWebDriver(new
URL("http://localhost:"+nodePort+"/wd/hub"), capabilities);
driver.get("https://www.bookbaby.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
System.out.println(driver.toString());
return driver;

Error is

org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
  Command duration or timeout: 1.41 seconds
  Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
  System info: host: 'Refaques-MacBook-Pro.local', ip: '192.168.108.206', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
  Driver info: driver.version: Driver
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
      at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$new$0(JsonWireProtocolResponse.java:53)
      at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$getResponseFunction$2(JsonWireProtocolResponse.java:91)
      at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$22(ProtocolHandshake.java:365)
      at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
      at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
      at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
      at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
      at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
      at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
      at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
      at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
      at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
      at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:368)
      at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:159)
      at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
      at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
      at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
      at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:137)
      at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:174)
      at com.bookbaby.driver.Driver.setUp(Driver.java:55)
      at com.bookbaby.executor.RunCukesByFeatureForFirefox.setUpClass(RunCukesByFeatureForFirefox.java:45)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
      at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
      at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
      at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
      at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:178)
      at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
      at org.testng.TestRunner.privateRun(TestRunner.java:782)
      at org.testng.TestRunner.run(TestRunner.java:632)
      at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
      at org.testng.SuiteRunner.access$000(SuiteRunner.java:39)
      at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:400)
      at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
      at java.lang.Thread.run(Thread.java:748)
  Caused by: java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
      at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
      at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
      at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
      at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115)
      at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
      at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
      at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:108)
      at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:137)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
      at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
      at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor(FirefoxDriverProvider.java:81)
      at org.openqa.selenium.remote.server.FirefoxDriverProvider.newInstance(FirefoxDriverProvider.java:63)
      at org.openqa.selenium.remote.server.DefaultDriverFactory.newInstance(DefaultDriverFactory.java:60)
      at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:222)
      at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:209)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
      ... 3 more

Below is my log from command prompt
13:25:14.249 INFO - Selenium build
info: version: '3.4.0', revision: 'unknown'
13:25:14.249 INFO - Launching a Selenium Grid node
2017-09-12 13:25:14.814:INFO::main: Logging initialized @833ms to
org.seleniumhq.jetty9.util.log.StdErrLog
13:25:14.864 INFO - Driver provider
org.openqa.selenium.ie.InternetExplorerDriver registration is skipped:
registration capabilities Capabilities [{ensureCleanSession=true,
browserName=internet explorer, version=, platform=WINDOWS}] does not
match the current platform MAC
13:25:14.864 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver
registration is skipped:
registration capabilities Capabilities [{browserName=MicrosoftEdge,
version=, platform=WINDOWS}] does not match the current platform MAC
13:25:14.864 INFO - Driver class not found:
com.opera.core.systems.OperaDriver
13:25:14.864 INFO - Driver provider com.opera.core.systems.OperaDriver
registration is skipped:
 Unable to create new instances on this machine.
13:25:14.865 INFO - Driver class not found:
com.opera.core.systems.OperaDriver
13:25:14.865 INFO - Driver provider com.opera.core.systems.OperaDriver
is not registered
2017-09-12 13:25:14.899:INFO:osjs.Server:main: jetty-9.4.3.v20170317
2017-09-12 13:25:14.938:INFO:osjsh.ContextHandler:main: Started
o.s.j.s.ServletContextHandler@e056f20{/,null,AVAILABLE}
2017-09-12 13:25:14.963:INFO:osjs.AbstractConnector:main: Started
ServerConnector@39529185{HTTP/1.1,[http/1.1]}{0.0.0.0:5556}
2017-09-12 13:25:14.963:INFO:osjs.Server:main: Started @982ms
13:25:14.963 INFO - Selenium Grid node is up and ready to register to
the hub
13:25:14.983 INFO - Starting auto registration thread. Will try to
register every 5000 ms.
13:25:14.983 INFO - Registering the node to the hub:
http://localhost:4445/grid/register
13:25:15.044 INFO - The node is registered to the hub and ready to use
13:25:20.205 INFO - SessionCleaner initialized with
 insideBrowserTimeout 0 and clientGoneTimeout 1800000 polling every
180000
13:26:11.724 INFO - Executing: [new session: Capabilities
[{proxyEverything=true, acceptSslCerts=true, marionette=true,
acceptInsecureCerts=true, browserName=firefox, javascriptEnabled=true,
handlesAlerts=true, version=, platform=MAC}]])
13:26:11.738 INFO - Creating a new session for Capabilities
[{proxyEverything=true, acceptSslCerts=true, marionette=true,
acceptInsecureCerts=true, browserName=firefox, javascriptEnabled=true,
handlesAlerts=true, version=, platform=MAC}]
13:26:11.770 WARN - Exception thrown
java.util.concurrent.ExecutionException:
org.openqa.selenium.WebDriverException:
java.lang.reflect.InvocationTargetException
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'XXXXXX-MacBook-Pro.local', ip: '192.168.108.206',
os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6',
java.version: '1.8.0_144'
Driver info: driver.version: unknown

13:26:11.777 WARN - Exception: The path to the driver executable must
be set by the webdriver.gecko.driver system property; for more
information, see https://github.com/mozilla/geckodriver. The latest
version can be downloaded from
https://github.com/mozilla/geckodriver/releases

A: please set environment variable webdriver.gecko.driver in your machine and its value.
or you can pass the parameter webdriver.gecko.driver while starting your hub or registering your node. like
java -Dwebdriver.gecko.driver="path to the gecko driver" {jar} -role node/hub

A: Firstly say the issue in your code, if you want to use the selenium server/grid please specify the webdriver path in command line when start selenium server,rather than specify by code.  so below code is unnecessary, they are only necessary when you choose run test not using selenium server/grid, we call it 'directConnect' (your script communicate directly with webdriver.exe)
if(browser.equals("firefox"))
        System.setProperty("webdriver.gecko.driver",
    System.getProperty("user.dir")+"//geckoDriver//geckodriver");
    else if(browser.equals("chrome"))
        System.setProperty("webdriver.chrome.driver",
    System.getProperty("user.dir")+"//chromeDriver//chromeDriver");

register node to hub argument example to specify webdriver.exe path:
java
-Dwebdriver.chrome.driver=C:\selenium\chromedriver_2.32.exe
-Dwebdriver.gecko.driver=C:\selenium\geckodriver-v0.18.0.exe
-jar C:\selenium\selenium-server-standalone-3.4.0.jar
-role node
-port 4446

Reminder: please check the standalone.jar, specified webdriver.exe and browser on node are compatible with each other, otherwise the node will fail to launch browser in testing.


text:
Q: Running two web server at the same time in one go programm In a go program, I want to run two web servers at the same time,
obviously they will be serving on two different ports (and ip addresses if necessary),
the problem is with the call to http.handle, when I try to register handler for '/' for the second server, it panics and says there is already a handler associated with '/',
I guess I need to create a mux in addition to the DefaultServeMux and I tried to do it using the gorillaMux but couldn't figure it out,
Is there something fundamentally wrong with running two web servers in the same program/process.
To make it more clear, one of the two web servers is a being used as a regular web server, I need the second one to act as an RPC server to communicate stuff between instances of the program running on different nodes of a cluster,
EDIT: to make it a bit more clear, this is not the actual code but it is the gist
myMux := http.NewServeMux()
myMux.HandleFunc("/heartbeat", heartBeatHandler)

http.Handle("/", myMux)

server := &http.Server{
    Addr:    ":3400",
    Handler: myMux,
}
go server.ListenAndServe()

gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", indexHandler)
gorillaMux.HandleFunc("/book", bookHandler)

http.Handle("/", gorillaMux)

server := &http.Server{
    Addr:    ":1234",
    Handler: gorillaMux,
}

log.Fatal(server.ListenAndServe())

A: I think you just need remove these lines:
http.Handle("/", myMux)
http.Handle("/", gorillaMux)

All routes are already defined in myMux and gorillaMux.
Check this: http://play.golang.org/p/wqn4CZ01Z6


text:
Q: I'm trying to understand the "rep scasb byte [edi]" instruction In this statement, is the value pointed to by edi the one that compares byte by byte, with the value pointed to by eax?
rep scasb byte [edi]

A: See https://www.felixcloutier.com/x86/scas:scasb:scasw:scasd and https://www.felixcloutier.com/x86/rep:repe:repz:repne:repnz.
But note that rep scasb is not encodeable.
With scasb, the two rep prefixes are repe and repne.  The prefix byte that means rep with stos/movs means repe with scas and cmps.
REPE keeps repeating while ECX!=0 and ZF==1.  i.e. repeat while equal.
repne scasb implements memchr: find the first occurrence (if any) in a fixed-size buffer.
repe scasb finds the first byte != AL, or stops at the limit set by ECX.  So it's a bit like strspn, but still for an explicit size buffer, not a zero terminated C-string.

A: rep means repeat until ecx is 0. scasb means 'scan byte', i.e: compare al with the byte at memory location edi, increment edi and decrement ecx.
What this means in effect is that before this line is run ecx has been set to a value that dictates how many times the rep will run for and if the characters match the zero flag ZF (which is also used for determining equality, hence why je and jz are equivalent) will be set.


text:
Q: Ajax request cors and cookies steps I have a client front end at localhost:1841 and a back end at localhost:9000.
My authentication system use a simple couple username/password that delivers a Json Web Token(jwt).
When my client receives the token, i ask him to save it in the cookie with javascript. But when i make XmlhttpRequest call from my client (:1841) to my server (:9000), there is no cookies in the request. So my server delivers a 401 (behavior is ok).
I know that is normal, none information from the cookies is sent because of the SAME-ORIGIN-POLICY.
I m using extjs 6 as client and node js as server.
What are all the steps to configure in the server side and client side to make this working ?
In server side i have already authorize cors request.
I have heard of httpOnly ? but i don't know how to deal with it?
Call for login from localhost:1841 (extjs client):
    Ext.Ajax.request({
        url: 'http://localhost:9000/api/users/authenticate/',
        method: 'POST',
        params: params,
        success: function(response){
            var text = response.responseText;
            var data = Ext.decode(text, true);

            if(data.access_token){
                me.saveToken(data.access_token);
                me.createInterface();
            } else {
                if(data.message){
                    Ext.Msg.alert("Bummer", data.message);
                } else {
                    Ext.Msg.alert("Bummer", "Something went wrong.");
                }
            }
        },

Config for cors:
cors = require('cors');
...
...
...
var whitelist = ['http://127.0.0.1:9000', 'http://localhost:8080', 'http://localhost:9000', 'http://127.0.0.1:8080', 'http://localhost:1841', 'http://127.0.0.1:1841']
 var corsOptionsDelegate = function (req, callback) {
    var corsOptions;
     if (whitelist.indexOf(req.header('Origin')) !== -1) {
        corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
    }else{
        corsOptions = { origin: false } // disable CORS for this request
 }
    callback(null, corsOptions) // callback expects two parameters: error and options
}
...

module.exports = function(app) {
....
app.use(cors(corsOptionsDelegate));

}

Other call from client:
Ext.ajax.request({
  url : 'http://localhost:9000/api/users/'
  method : 'POST'
  success: function(response){
        var text = response.responseText;
        var data = Ext.decode(text, true);
        ...
        ...
        }
    },
})

Validation from server:
function isAuthenticated() {
    return compose()
//     Validate jwt
        .use(function (req, res, next) {

            ....
            ....
            console.log(req.headers.authorization);

            validateJwt(req, res, function (err) {

                if (err) {
                    console.log(err.inner.name);
                    if (err.inner.name === "TokenExpiredError") {
                        // client have to request token with his refresh_token
                        return next({"error":err.inner.name});
                    }
                }
                next();
            });

    })
    .use(function (req, res, next) {
        ....

        });
    });

Edit 1:
I have added Set-Cookie in node and Set-Cookie appears in response headers AND in preview cookies from DevTools.  But cookies is not set in browser.
exports.authenticate = function(req, res, next){
    User.findOne({
        fullName: req.body.username
    }, function(err, user) {
    ....
        if (!user) {
            res.status(401).json({
                success: false,
                message: 'Authentication failed. User not found.'
            });
        } else {
            // Check if password matches

            if(user.authenticate(req.body.password)){
                var access_token = jwt.sign(user, config.secrets.session, {
                    expiresIn: 60 // in seconds
               });

               res.cookie('access_token',access_token);

               res.status(200).json({
                   "success": true,
                   "access_token" : access_token
                   //token: 'JWT ' + token
                   });
            }else{
              ....
            }
        }
    });
}

A: As per you using ExtJS Ajax so you can use defaultXhrHeader property to sending token from client side to sever side.

Firstly as you are calling authenticate request for getting token. Here you can use ExtJS Cookies for set and get token or cookies.

Ext.Ajax.request({
     url: 'http://localhost:9000/api/users/authenticate/',
     params: params,
     method: 'POST',
     success: function(response, opts) {
         var data = Ext.decode(response.responseText;);
         if (data.access_token) {
             //Set cookie in our client side using Utility class for setting/reading values from browser cookies.
             Ext.util.Cookies.set('access_token', data.access_token);
         } else {
             if (data.message) {
                 Ext.Msg.alert("Bummer", data.message);
             } else {
                 Ext.Msg.alert("Bummer", "Something went wrong.");
             }
         }
     },
     failure: function(response, opts) {
         console.log('server-side failure with status code ' + response.status);
     }
 });

Now you need to pass same token Ajax request using defaultXhrHeader

Here is example:-
Ext.Ajax.request({
     url: 'http://localhost:9000/api/users/',
     method: 'POST', //As per method acceptance you can use (GET,PUT,DELETE).
     //send cookie sever side using defaultXhrHeader
     defaultHeaders: {
         'access_token': Ext.util.Cookies.get('access_token'),
         'Content-Type': 'application/json;charset=utf-8'
     },
     success: function(response, opts) {
         var data = Ext.decode(response.responseText;);
         //Put your logic here.
     },
     failure: function(response, opts) {
         console.log('server-side failure with status code ' + response.status);
     }
 });

As you using NodeJs in server side so you can get token from header.

A: Client-side JavaScript can only set cookies for the current origin.
Other origins will have their own set of cookies.
You will need to either:

*

*Set the cookie from the :9000 origin using HTTP or

*Pass the data through some other mechanism (such as a value in a POST body).


text:
Q: Is there a name for this type of expression? Forgive me if this seems like a silly question. I know that the following expression is an example of a polynomial: $a_{4}x^{4}+a_{3}x^{3}+a_{2}x^{2}+a_{1}x+a_{0}$ but I am wondering if there is a name for one that takes this form: $a_{4}\sqrt[4]{x}+a_{3}\sqrt[3]{x}+a_{2}\sqrt{x}+a_{1}x+a_{0}$.

A: There's no name in common use for the set of expressions in exactly the form you quote. One problem with the concept is that they are not closed under multiplication, like polynomials are. For example we have
$$ (a_2\sqrt x + a_1x)(b_2\sqrt x + b_1 x) = a_2b_2 x + (a_1b_2+a_2b_1) x^{3/2} + a_1b_1 x^2 $$
where the middle term looks neither like $ax^n$ nor $a\sqrt[n]x$.
We can speak of things that look like general polynomials, but where we allow arbitrary (nonnegative) rational exponents rather than just natural numbers. This would be closed under multiplication and addition, and include your linear combinations of higher roots of $x$ as a special case.
But this generalized concept still doesn't seem to have a commonly used name of its own. As Robert Israel suggests, they can be described as "finite Puiseux series", but googling shows that this is a quite rare term. If you want to be understood, saying "polynomials in $\sqrt[n]x$ for some $n$" instead would probably be advisable.

A: You could call it a Puiseux polynomial.

A: It is a polynomial in $y=x^{\frac 1{12}}$ namely $$p(y)=a_4y^3+a_3y^4+a_2y^6+a_1y^{12}+a_0$$and is thus an element of the polynomial ring obtained by adjoining a $12^{th}$ root of $x$ to the original polynomial ring.


text:
Q: React Touch events in Internet Explorer are not working I build and application using React,
this app works fine over IOS,Android, Chrome, Firefox,
but I found that in IE , the touch events
(onTouchCancel onTouchEnd onTouchMove onTouchStart)
 are not firing.
I tested some examples of react at react-rocks page
like http://swizec.github.io/react-particles-experiment/
it doesn't  works over IE.
So in conclusion my question is, Does react support IE touch Events?
Is there a way to implement or subscribe the events to a component?
I appreciate any help, thanks.

A: I decided to use react-hammerjs to avoid this kind of troubles in my cross-platform application.
https://github.com/JedWatson/react-hammerjs
http://hammerjs.github.io/api/


text:
Q: Symfony2 authentication automatically on Controller or elsewhere
Possible Duplicate:
Automatic post-registration user authentication

I made an authentication using my database users and using my own form. The password is encrypted using md5. It worked PERFECTLY.
What i need is authenticate a user by my code on a controller or elsewhere... something like that:
$x = $this->get('security.context');
$x->getToken()->setUser($user)->authenticate();

If you see, the setUser exists, but i need a really authenticate method.
Thanks


text:
Q: Unity3d RotateTowards only on z axis I have GameObject that I need to rotate arouns Z axis. It needs to face the cursor all the time. But it rotates on all axis. Here is the code:
Vector3 mouseClickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = mouseClickPos - transform.position;
Vector3 h1dir = Vector3.RotateTowards(hand1.transform.forward, dir, 6.0f, 1.0f);
hand1.transform.rotation = Quaternion.LookRotation(h1dir);


text:
Q: Using Web crawler for price comparison I need a open source java based web crwaler which I can extend for price comparison?
How do I do the price comparison?
Is there any open source code for that?

A: Take a look at web harvest, you will have to use it's slightly odd and peculiar syntax for processing web pages, but it should be fairly to extend it to do some price comparison:
http://web-harvest.sourceforge.net/samples.php?num=2

A: Building something that scrapes price information from a large number of different sites is going to be a lot of work, whether you scrape from the stores themselves or from existing comparison sites.

*

*Everyone's website layout will be different, requiring you to configure your crawler separately for each one.

*Some websites may present the price information in ways that make scraping difficult; e.g. using AJAX.
Some website owners will put the relevant pages into their robots.txt files to tell you to stay away.  And if you ignore that, there are various things they can do to make life difficult for you.
Scraping lots of people's websites without permission is likely to make you unpopular.  It might attract threats of lawsuits, or actual lawsuits from people who perceive that you are harming their business model.  Or other responses ...
Are you really sure you want to do this?  Really??

A: Any reason you can't just get your data from one of the hundreds of price comparison sites already out there? Seems like would be simpler to scrape nextag or froogle or whatever instead of writing a crawler to scrape billions of store websites.

A: Nobody wants their site to get overloaded without getting any benefit. I think you should create a crawler for your need. However, be aware that most of them may block you or make your responses slower. you need to behave like you are not one and eating their bandwidth...

A: Someone here wrote about the legal issues. The legal issues are not simple. Stephen C wrote about lawsuits but that goes both ways. There is a large body of law related to anti-competitive conduct. If someone wants their prices to be not reported because they are involved in price-fixing or making false claims, then the websites themselves face severe penalties. The law is not something to trivially quote. You can google price fixing and see the large fines already imposed on countless companies.


text:
Q: How to run a rdlc using coding I have created an rdlc where I have used dataset taken as a new item in solution explorer for designing my report. After binding my report from that datasource which is named as Dataset1. I have created its object and tried to fill this datasource using coding. Now when I runs the following code I am not getting any result.
What can be the issue?
reportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Local;
LocalReport localReport = reportViewer1.LocalReport;
localReport.DataSources.Clear();
localReport.ReportPath = @"E:\Projects\Manojp\AARFID_SSRS_Report\WindowsFormsApplication1\WindowsFormsApplication1\Local Report\rptTest.rdlc";

// DataSet dataset = new DataSet("AARFID_Report");
DataSet1 ds = new DataSet1();

// fill the Data Set from DataBase.
//ds.Tables.Remove("M_GUEST");
ds.Tables.Clear();
GetData(ref ds);

//
// Create a report data source for the sales order data

ReportDataSource rds = new ReportDataSource();
rds.Name = "AA";
rds.Value = ds.Tables[0];
localReport.DataSources.Add(rds);
// reportViewer1.LocalReport.DataSources.Add(rds);

reportViewer1.RefreshReport();
localReport.DataSources.Clear();

GetData() do this:
connection.Open();
ad.Fill(ds,"M_GUEST");
connection.Close();

In the report view a message is shown as:

A data source instance has not been supplied for the data source 'dtaset1_m_guest'

A: Make sure the names of datasets in the rdl file and the report generator match!
The easiest way would be to have a DataSet, DataSource and the instances named "M_GUEST". Also, do not clear the data sources before rendering.

A: This line
rds.Name = "AA";

must match the name of the data set defined in the report. In your case, that would be
rds.Name = "dtaset1_m_guest";

A: When you add .rdlc report in your project by wizard then by default it take dataset name as 'DataSet1' . Now if you want to bind dynamically new dataset then name of that dataset must be 'DataSet1'. Try change it and also check that Table[0] contains some data(Rows) for which DataType get matched with original dataType of 'DataSet1'. If DataType doesn't matches then data wont come in your ReportViewer. Try this code:-
string exeFolder = (Path.GetDirectoryName(Application.StartupPath)).Substring(0, (Path.GetDirectoryName(Application.StartupPath)).Length - 3);
string reportPath = Path.Combine(exeFolder, @"Reports\SessionReport.rdlc");
Microsoft.Reporting.WinForms.ReportDataSource rds = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", ds.Tables[0]);
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.LocalReport.ReportPath = reportPath;
this.reportViewer1.RefreshReport();

For more detail about .rdlc report(Core logic) refer following link
How to create report (RDLC) without database?

A: If the DataSource in binding is named "Dataset1" then the one you your in code should also name the same.
I add it like this works perfectly do this as below:
 reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Dataset1", ds.Tables[0]));


text:
Q: The easiest way to write NSData to a file NSData *data;
data = [self fillInSomeStrangeBytes];

My question is now how I can write this data on the easiest way to an file.
(I've already an NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes)

A: You also have writeToFile:options:error: or writeToURL:options:error: which can report error codes in case the saving of the NSData failed for any reason. For example:
NSError *error;

NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
if (!folder) {
    NSLog(@"%s: %@", __FUNCTION__, error);        // handle error however you would like
    return;
}

NSURL *fileURL = [folder URLByAppendingPathComponent:filename];
BOOL success = [data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (!success) {
    NSLog(@"%s: %@", __FUNCTION__, error);        // handle error however you would like
    return;
}

A: Notice that writing NSData into a file is an IO operation that may block the main thread. Especially if the data object is large.
Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:
// Use GCD's background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // Generate the file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"yourfilename.dat"];

     // Save it into file system
    [data writeToFile:dataPath atomically:YES];
});

A: writeToURL:atomically: or writeToFile:atomically: if you have a filename instead of a URL.

A: NSData has a method called writeToURL:atomically: that does exactly what you want to do. Look in the documentation for NSData to see how to use it.

A: The easiest way, if you want to do this a few times manually instead of coding, is to only use your mouse:

*

*Put a breakpoint one line after your NSdata are fulfilled.

*Hold your mouse over your NSData variable, click on the Eye button, and then export.

*After that chose the storage details (name/extension/location of the file).

*Click on "Save" and you are done!


text:
Q: python openssl: how to upgrade the openssl version while installing plugin in blender I have this plugin which I want to install, but somehow the installation always breaks due to the error:
urllib.error.URLError: <urlopen error [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:720)>
So I think the problem is maybe that the SSL version is too old, so I printed the version information out:
OpenSSL 0.9.8zh 14 Jan 2016

And after seeing some answers,enter link description here, enter link description here, enter link description here now I have the newest SSL on my mac, but it seems like this plugin is using some external python which is not installed on my disk, and this python always tries to use its own SSL. I found this python which blender uses, Show Package Contents -> Burrow down to Contents -> Resources -> 2.79 -> python, seems like it's python 3.5, and I have python 3.7 installed on the disk.
Here's the installation code of the plugin:
import bpy
import os
import addon_utils

from subprocess import call

from urllib.request import urlretrieve

from zipfile import ZipFile
from tempfile import TemporaryDirectory
from shutil import copytree,rmtree
from os.path import join

python_exec = bpy.app.binary_path_python
path_to_addons = bpy.utils.user_resource('SCRIPTS', "addons")

print('Install Pip')

try:
    import pip
except:
    rc = call([python_exec,"-m","ensurepip","--default-pip", "--upgrade"])
    import pip

print('Download RD')

import ssl
print(ssl.OPENSSL_VERSION)

URL = "https://github.com/HBPNeurorobotics/BlenderRobotDesigner/archive/master.zip"
addon_dir = 'robot_designer_plugin'
zip_dir = "BlenderRobotDesigner-master"

print('Unzip RD')
with TemporaryDirectory() as tmp:
    zip_file = join(tmp,"master.zip")

    print(zip_file)
    urlretrieve(URL,zip_file)
    print('Downloaded!')

    rc = call([python_exec,"-m","zipfile","-e",zip_file,tmp])

    with ZipFile(zip_file, "r") as z:
        z.extractall(tmp)

    print('Unzip finished')
    addon_dir_src = join(tmp,zip_dir,addon_dir)
    addon_dir_dst = join(path_to_addons,addon_dir)

    print('remove previous addon')
    rmtree(addon_dir_dst,True)

    print('add latest addon')
    copytree(addon_dir_src,addon_dir_dst)

    print('enable addon')
    addon_utils.enable("robot_designer_plugin", persistent=True)
    bpy.ops.wm.save_userpref()

    with open(join(addon_dir_src,"requirements.txt")) as f:
        for line in f:
            rc = call([python_exec,"-m","pip","install",line])
            #pip.main(['install', line])
print('RD Installation Done!')

Und this is the error raised in the terminal:
Install Pip
Download RD
OpenSSL 0.9.8zh 14 Jan 2016
Unzip RD
/var/folders/nm/9nfcg98x4hxf1kh08dj8p92h0000gn/T/tmpvd4k0lfi/master.zip
Traceback (most recent call last):
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 1254, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/http/client.py", line 1107, in request
    self._send_request(method, url, body, headers)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/http/client.py", line 1152, in _send_request
    self.endheaders(body)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/http/client.py", line 1103, in endheaders
    self._send_output(message_body)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/http/client.py", line 934, in _send_output
    self.send(msg)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/http/client.py", line 877, in send
    self.connect()
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/http/client.py", line 1261, in connect
    server_hostname=server_hostname)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/ssl.py", line 385, in wrap_socket
    _context=self)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/ssl.py", line 760, in __init__
    self.do_handshake()
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/ssl.py", line 996, in do_handshake
    self._sslobj.do_handshake()
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/ssl.py", line 641, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:720)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/gaoyingqiang/Downloads/installer.blend/Text", line 40, in <module>
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 188, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 466, in open
    response = self._open(req, data)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 484, in _open
    '_open', req)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 1297, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/urllib/request.py", line 1256, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:720)>
Error: Python script fail, look in the console for now...

I really don't know where goes wrong since the plugin provides no further imformation on this issue. How can I fix this?
New edition:
I now want to solve the issue of how to upgrade the openssl version in the python which is in the Blender. Blender brings python3.5 with it and how can I brew install openssl to this python but not the python on my disk?


text:
Q: The 'romantic approach' of Goro Shimura? In the Wikipedia page of Shimura. There is an interesting sentence without reference (3rd paragraph under the section Life and career):

He also argues for a 'romantic' approach, something he finds lacking in the younger generation of mathematician.

I'm curious about what did he mean exactly in this context, since, half-seriously, I'm young and would like to grow into a 'romantic' mathematician, a number theorist in particular.
I shall appreciate any comment.


text:
Q: How to write dataframe below an existing Excel sheet without losing slicer of excel in pivot table sheet? I am using openpyxl module to append pandas dataframe below an existing excel sheet. But problem is my slicer of excel sheet in pivot table is getting destroyed while doing this task. I have tried many ways to find the solution of it, but I think there is no way available with openpyxl to avoid this situation.
I am using following method to achieve it with openpyxl-
#HELPER FUNCTION TO APPEND DATAFRAME BELOW EXCEL FILE
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False,
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None
    """
    from openpyxl import load_workbook

    import pandas as pd

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl', index=False)

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError

    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename,data_only=True)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 1

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

I have seen that xlwings and win32com is available to do it, but not sure how to do it with these libraries. I want to ask how to append dataframe below existing excel file without losing slicer in pivot sheet of my excel
The way by which we can do it without using openpyxl because I think there is no way available with openpyxl.
I am getting following warning with openpyxl
C:\Users\Desktop\PycharmProjects\MyProject\venv\lib\site-packages\openpyxl\worksheet\_reader.py:292: UserWarning: Slicer List extension is not supported and will be removed
      warn(msg)

A: I have tried all the possible solutions and finally I can say that it is not possible with openpyxl. In alternate to xlwings we can use openpyxl library.xlwings library is very fast in processing. We can append the dataframe below the excel sheet with the help of following code.By this way slicer values do not loose or remove.
import xlwings as xw
import pandas as pd
df = pd.read_excel("File_to_append.xlsx")
wb = xw.Book(r"Existing_Excel.xlsx")
ws = wb.sheets('Sheet1')  #Name of sheet where to append df
ws.cells(cell_row_number,cell_column_number).options(index=False, header=False).value = df
#Here cell_row_number and cell_column_number are integer valuesof row number and column number to append data

Hope I am clear .This is the best solution I have found


text:
Q: WPF to WCF returns 'The HTTP request was forbidden' with large file upload We have a WPF application that connects to a WCF Web Service...
IIS 10 on Server 2016
If a user tries to upload a large(ish) file it will return
The HTTP request was forbidden with client authentication scheme 'Anonymous'.

We have been able to reproduce this error with a pdf file of 23,486,000 bytes but so far have been unable to pin it down.
The maxReceivedMessageSize in Web.config is set to 524,288,000 bytes and IIS Request Filtering is set to the default 30,000,000 bytes
Making the assumption that file size is causing this as it's the only time the error is thrown...
Any ideas?
Thanks


text:
Q: "POST" method is not allowed in Python web page using Flask I'm trying to make a form using this code.
from flask import Flask,render_template, request

app = Flask(__name__, template_folder="Templates")

@app.route("/form", methods=["POST"])
def form():
    name = request.form.get("name")
    return render_template("form.html", name=name)

if __name__=="__main__":
    app.run(debug=True)

also use form.html code
{% extends "index.html" %}

{% block heading %}
Hello
{% endblock %}

{% block body %}
Hi ! {{name}}
{% endblock %}

and this is layout file called index.html
<!DOCTYPE html>
<html>
    <head>
        <title>My WebSite</title>
    </head>
    <body>
        <h1>{% block heading %}{% endblock %}</h1>

        {% block body %}
        {% endblock %}
    </body>
<html>

but it shows an error on my web page saying that the method is now allowed, taking a look to flask log shows the next information:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [22/Apr/2020 08:31:19] "GET /form HTTP/1
.1" 405 -

then, how can I solve this problem? Please help guys!!!


text:
Q: #file_links["C:\Frazes.txt",1,N]: #file_links["C:\Links.txt",1,N] recieve as a field data through gravity form I am using gravity form plugin into my wordpress site. Today I have received a query which contain these #file_links["C:\Frazes.txt",1,N]: #file_links["C:\Links.txt",1,N] lines into the email.
I have apply all the validation into my contact form.

A: I also receive similar queries regularly via my WordPress forms (I use wpforms). After a bit of research, these seem to be an attempt by a spammer to use the GSA software development kit (see their manual here) in order to generate a spam response to your form. However, in such cases the spammer didn't configure their spam macro correctly and therefore you see the spam macro (e.g. #file_links) instead of the actual spam content that would've been generated by that macro. You (and I!) should configure a good captcha in each form in order to block most of this spam. Cheers.

A: The best way I've found to block these is to use the BSK Gravity Forms Blacklist plugin. You can prevent submit of your form if the any of the fields contain the query, by creating a blacklist that checks any of the following items: Frazes.txt, #file_links, #file_links["C:\Frazes.txt",1,N]: #file_links["C:\Links.txt",1,N. Once you've created the blacklist, apply it to the email field (or any other field) in your form, make sure to choose the case-insensitive contains comparison. Hope this helps!


text:
Q: How to write unit test case for code inside catch block c# in XUnit As below code I have few logic written in catch block and for that I have to write unit test.
Code
try
{
    var localResults = await _repository.GetData(Key).ConfigureAwait(false);

    return localResults;
}
catch (EntityNotFoundException)
{
    var results = await _adapter.GetData(Key).ConfigureAwait(false);

    return results;
}

when I am trying to setup repository to return exception by below code it is not working as expected.
_repository.Setup(x => x.GetData(It.IsAny<key>())).Throws(new EntityNotFoundException());


text:
Q: SendGrid V3 api with C#. email not sending is there something wrong with this code? I already put my email in my code but I don't get any email.
I have a hint that is it not working because I am using API key ID instead of API key because I can't see my API key because of its only show just once. if is that the reason why is this code not working. Is there no way to view your API key again?
   public string SendEmailMain()
        {
            SendEmail().Wait();

        }
 static async Task SendEmail()
        {
            common com = new common();
            var apiKey = com.sendGridAPI;
            var client = new SendGridClient(apiKey);
            var from = new EmailAddress("testmail@gmail.com", "test user");
            var subject = "Sending with SendGrid is Fun";
            var to = new EmailAddress("testemai@gmail.com", "teset user");
            var plainTextContent = "and easy to do anywhere, even with C#";
            var htmlContent = "and easy to do anywhere, even with C#";

            var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(msg);

        }

A: the code is working pretty well. The thing is i'm using the API key ID because instead of the API key that generated by sendgrid.
Please refer to this thread for more info


text:
Q: R - Group by, then iterate through group and extract original column values My dataframe (df):
ID1 | ID2 |  V1  |  V2 |  V3
A   | B   | var1 | foo |  1
C   | D   | var2 | bar |  2
E   | F   | var3 | foo |  3
G   | F   | var3 | foo |  3
H   | I   | var4 | zap |  2
...

ID1 and ID2 contain overlapping values, as it's a long format version of an upper matrix triangle with identical comparsions (eg A, A) removed and some additional metadata (V1,V2,V3) added.
The above must be grouped by V1, V2 & V3, and the final output is to be a list of IDs (ID1 and ID2 contain overlapping variables) that make up each group (with each list being a seperate file).
So far, I've grouped the variables but stuck on how to go on about iterating through each of dplyr's groups and obtaining the values for each.
A pseudocode of what I have in mind is below:
# Group
cluster <- df %>% group_by(V1,V2,V3)

[?] # loop through each group in cluster

    [?] # get group values as x, y and z

    # Get IDs into lists and merge
    ID1 <- df %>% filter(V1 == x, V2 ==y, V3 == z) %>%
           pull(ID1)

    ID2 <- df %>% filter(V1 == x, V2 ==y, V3 == z) %>%
           pull(ID2)

    merged <- c(ID1,ID2)

    merged_unique <- unique(unlist(merged))

    # Print out to file
    fileConn <- file(paste(X ,Y, Z,"txt", sep="."))
    writeLines(merged_unique, fileConn)
    close(fileConn)

I would like my final output to be:

*

*file var1.foo.1.txt :

A
B

*

*file var2.bar.2.txt :

C
D

*

*file var3.foo.3.txt :

E
F
G

*

*file var4.zap.2.txt :

H
I

Any help is appreciated.

A: I am not sure about the expected output. Hope the code below could help a bit
lapply(
  split(
    df[c("ID1", "ID2")],
    with(df, do.call(paste, list(V1, V2, V3)))
  ),
  function(v) unique(unlist(v))
)

which gives
$`var1 foo 1`
[1] "A" "B"

$`var2 bar 2`
[1] "C" "D"

$`var3 foo 3`
[1] "E" "G" "F"

$`var4 zap 2`
[1] "H" "I"

If you want to save all the groups into different *.txt files, you can try the code below
lst <- lapply(
  split(
    df[c("ID1", "ID2")],
    with(df, do.call(paste, list(V1, V2, V3,sep = "_")))
  ),
  function(v) unique(unlist(v))
)

sapply(seq_along(lst),function(k) writeLines(lst[[k]],paste0(names(lst[k]),".txt")))

A: Generating your "data":
df <- data.frame("ID1" = c("A","B","C","E","G","H"), "ID2" = c("B","B","D","Fe","Fe","I"), "V1" = c("var1","var1","var2","var3","var3","var4"),"V2" = c("foo","foo","bar","foo","foo","zed"), "V3" = c(1,1,2,3,3,2))

Clustering the data and getting the unique clusters:
library(dplyr)
df_clust <- df %>% group_by(V1,V2,V3)
df_tally <- df_clust %>% tally()

Looping through, assuming only two ID columns and 3 feature columns, and printing each result to a new file:
for (i in c(1:nrow(df_tally))){
    pull1 <- df %>% filter(V1 == unlist(df_tally[i,1]), V2 == unlist(df_tally[i,2]), V3 == unlist(df_tally[i,3])) %>% pull(ID1)
    pull2 <- df %>% filter(V1 == unlist(df_tally[i,1]), V2 == unlist(df_tally[i,2]), V3 == unlist(df_tally[i,3])) %>% pull(ID2)
    mergeID <- c(type.convert(pull1,as.is = TRUE),type.convert(pull2,as.is = TRUE))
    mergeID <- unique(mergeID)

    filename <- paste("TEST_",i, ".txt", sep="")
    fileConn<-file(filename)
    writeLines(mergeID, fileConn)
    close(fileConn)
}


text:
Q: Salvando ID de uma tabela com duas Primary Keys com Hibernate Olá, eu estou tendo um problema ao salvar dados em uma última tabela.
Bom, essa tabela tem duas foreign keys e as mesmas são primary keys:

Ao ir no Controller, salvar a tabela, eu uso os códigos a seguir:
 itv.setId();
    itv.setIngresso(ing);
    itv.setVenda(ven);
    itv.setItvqtde(Integer.valueOf(request.getParameter("txtqtde")));

    itvDao.salvarItemVenda(itv);
    response.sendRedirect("my-tickents-buy.jsp");

Aqui está o meu ItemVendaDao:
 public void salvarItemVenda(ItemVenda itv){

    try {

    s = new ConnectionFactory().getSessionFactory();
    tx = s.beginTransaction();
    s.save(itv);
    tx.commit();
    s.close();

    JOptionPane.showMessageDialog(null, "Item venda salva com sucesso");

    } catch (Exception e) {

        tx.rollback();

      JOptionPane.showMessageDialog(null, "Erro ao salvar item venda" +e.getMessage());
      s.close();

    }

}

O que é preciso colocar no itv.setId()?
Quando mapeio ele cria esse método para salvar o Id do item venda, sendo que o ID do item venda são dois: o objeto do ingresso e o objeto da venda, ambos já estão sendo salvos acima com o código:
 itv.setIngresso(ing);
    itv.setVenda(ven);

Novamente, o que é preciso colocar no itv.setId()?
Aqui está o ItemVenda.java (mapeado automaticamente pelo hibernate)
public class ItemVenda  implements java.io.Serializable {

 private ItemVendaId id;
 private Ingresso ingresso;
 private Venda venda;
 private int itvqtde;

public ItemVenda() {
}

public ItemVenda(ItemVendaId id, Ingresso ingresso, Venda venda, int itvqtde) {
   this.id = id;
   this.ingresso = ingresso;
   this.venda = venda;
   this.itvqtde = itvqtde;
}

public ItemVendaId getId() {
    return this.id;
}

public void setId(ItemVendaId id) {
    this.id = id;
}
public Ingresso getIngresso() {
    return this.ingresso;
}

public void setIngresso(Ingresso ingresso) {
    this.ingresso = ingresso;
}
public Venda getVenda() {
    return this.venda;
}

public void setVenda(Venda venda) {
    this.venda = venda;
}
public int getItvqtde() {
    return this.itvqtde;
}

public void setItvqtde(int itvqtde) {
    this.itvqtde = itvqtde;
}

E o ItemVendaId.java está da seguinte forma:
public class ItemVendaId  implements java.io.Serializable {

 private int itvvencodigo;
 private int itvingressocodigo;

public ItemVendaId() {
}

public ItemVendaId(int itvvencodigo, int itvingressocodigo) {
   this.itvvencodigo = itvvencodigo;
   this.itvingressocodigo = itvingressocodigo;
}

public int getItvvencodigo() {
    return this.itvvencodigo;
}

public void setItvvencodigo(int itvvencodigo) {
    this.itvvencodigo = itvvencodigo;
}
public int getItvingressocodigo() {
    return this.itvingressocodigo;
}

public void setItvingressocodigo(int itvingressocodigo) {
    this.itvingressocodigo = itvingressocodigo;
}

A: Inicialmente, vou recomendar você ter uma chave primária para cada tabela. essa chave primária seria seria um campo de ID.
Se precisar que suas chaves estrangeiras sejam únicas na tabela use o atributo UNIQUE.
Vou recomendar você usar anotações JPA nas suas tabelas para auxiliar o Hibernate (se já estiver usando xml recomendo mudar para Anotações):
@Entity
public class ItemVenda  implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name = "ingresso_id")
    private Ingresso ingresso;

    @ManyToOne
    @JoinColumn(name = "venda_id")
    private Venda venda;

    private int qtde;

    //getters e setters omitidos
}

Você teria também as classes Venda e Ingresso com seus respectivos campos.
E teria apenas estas três tabelas. A tabela ItemVenda ficaria com os campos:
id, ingresso_id, venda_id, qtde
Sempre deixando o Hibernate tomar conta disso para você.
Neste caso o seu método setId() da classe ItemVenda só seria utilizado em casos de update.

A: Se o conjunto de duas ou mais colunas que, combinadas, nunca se repetirão, você não precisa (e nem deve) criar uma coluna extra somente para servir como chave primária (como @Shura16 sugeriu). Você só estará criando uma coluna totalmente desnecessária visando somente a sua facilidade no desenvolvimento e fugindo da performance e boa integridade de dados no banco de dados.
No seu caso, você precisa criar uma chave composta. Simples assim.
Na JPA existem duas formas de fazer isso. Uma é através de IdClass e a outra, que eu recomendo, é através de EmbeddedId e Embeddable.
Digamos que você tem uma Classe A, uma Classe B e, uma terceira, Classe C onde a sua chave primária é composta da união de Classe A e B.
Ficaria assim:
Classe A:
@Entity
@Table(name = "CLASSE_A")
public class ClasseA {

    @Id
    @Column(name = "CLASSE_A_ID")
    private Long id;

}

Classe B:
@Entity
@Table(name = "CLASSE_B")
public class ClasseB {

    @Id
    @Column(name = "CLASSE_B_ID")
    private String id;

}

Antes de criar a classe C, você deverá criar uma classe que irá incorporar a Classe A e Classe B. Esta classe que irá representar a sua chave composta.
Classe C PK:
@Embeddable
public class ClasseCPK {

    @Column(name = "CLASSE_A_ID", nullable = false)
    private Long classeAId;

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

}

Observe a anotação @Embeddable em ClasseCPK. Isto serve para informar ao JPA que esta classe servirá como uma chave composta.
Repare também que os seus atributos são somente uma referência ao tipo dos atributos de Classe A e B. Ou seja, Long e String.
Finalmente a nossa Classe C ficará assim:
Classe C:
@Entity
@Table(name = "CLASSE_C")
public class ClasseC {

    @EmbeddedId
    private ClasseCPK pk = new ClasseCPK();

    @ManyToOne
    @JoinColumn(name = "CLASSE_A_ID", referencedColumnName = "CLASSE_A_ID", nullable = false, updatable = false, insertable = false)
    private ClasseA classeA;

    @ManyToOne
    @JoinColumn(name = "CLASSE_B_ID", referencedColumnName = "CLASSE_B_ID", nullable = false, updatable = false, insertable = false)
    private ClasseB classeB;

}

E isto termina o mapeamento.
Mais um detalhe. Só mande o Hibernate criar as tabelas/colunas para você se o seu projeto for pequeno/amador. Se for um projeto grande e importante, como para uma instituição financeira e afins, nunca deixe o Hibernate interferir na estrutura do banco de dados, pois este mesmo banco de dados poderá (e muito provavelmente será) ser utilizado em outros sistemas e de diferentes linguagens.
Bônus: Caso uma entidade sua referencie uma outra que possui chave composta, você deverá usar a anotação @JoinColumns.

A: Olá,
Respondendo diretamente a sua pergunta "..o que é preciso colocar no itv.setId()?"
Conforme o seu código esse ID é formado por um objeto ItemVendaId, então basta instanciá-lo no momento de gravar que tudo deve funcionar.
Como você não mostrou o código das classes Ingresso e Venda, estou chutando o nomes dos ID's deles. Segue exemplo:
itv.setId(new ItemVendaId(ven.getitvvencodigo(), ing.getitvingressocodigo()));
itv.setIngresso(ing);
itv.setVenda(ven);
itv.setItvqtde(Integer.valueOf(request.getParameter("txtqtde")));
itvDao.salvarItemVenda(itv);
response.sendRedirect("my-tickents-buy.jsp");

Em todo caso, assim como os outros colegas que responderam antes, não recomendo esse tipo de mapeamento.


text:
Q: I want to use NetInfo React Native, my NetInfo function can be used in all components?  componentDidMount() {

    NetInfo.isConnected.addEventListener(
        'connectionChange',
        this._handleConnectivityChange

    );

    NetInfo.isConnected.fetch().done((isConnected) => {

      if(isConnected == true)
      {
        this.setState({connection_Status : "Online"})
      }
      else
      {
        this.setState({connection_Status : "Offline"})
      }

    });
  }

  componentWillUnmount() {

    NetInfo.isConnected.removeEventListener(
        'connectionChange',
        this._handleConnectivityChange

    );

  }

  _handleConnectivityChange = (isConnected) => {

    if(isConnected == true)
      {
        this.setState({connection_Status : "Online"})
      }
      else
      {
        this.setState({connection_Status : "Offline"})
      }
  };

In the application that I made, it has many components, but I want to check whether the user has internet access and call the Netinfo function in all components, without writing it down again


text:
Q: Windows Phone app stopped showing what's on my phone When I first installed the Windows Phone app, it showed the contents of my phone when I plugged the phone into a USB port. Recently that stopped working. The app starts okay, and it definitely reacts to the phone being plugged in, but I only see the phone status, "In the Store" and "On the Web" panels. It doesn't show files on the PC or the phone.
If I run the app first, and then plug in the phone, the app shows an empty "On your phone" panel for a few seconds, then it disappears. The first (status) panel, showing the the phone model, battery status, and software version, only appears if I start the app before plugging the phone in.
I've tried the Windows Phone app for desktop, and it shows what's on the phone, but a) it doesn't show previews of photos, b) it shows all phone files in one long list (no folders), and c) the app doesn't appear in the list of AutoPlay options, limiting its usefulness for auto syncing content. Oddly, when I installed the desktop version, it said "You can only sync with one computer at a time. Would you like to stop syncing with your other computer and use this one instead?" - despite the fact that I have never synced this phone with any other computer.
What I've tried:

*

*rebooting the phone

*rebooting the Windows 8 PC

*uninstalling and reinstalling the Windows Phone app

*other sync tools (they typically don't work because they only work with drive letters, and the Windows Phone device doesn't get a drive letter)

*checked the app's preferences

*checked the phone's settings

I can still use Explorer to copy files to and from the phone via the "Windows Phone" device that appears in Explorer when the phone is plugged in, but I'd like to use the Windows Phone app's syncing features to automate the process.
Side note: searching the web for "Windows Phone app" is problematic, since all apps that run on Windows phones are "Windows Phone apps".


text:
Q: Display total sum of rows values in arraycollection - Adobe Flex I want to display total sum of rows values in an arraycollection. For example:
Definition     Value
Product 1      20.00
Product 2      50.00
Product 3      30.00

Total          100.00

I have this code:
    <mx:DataGrid id="srcgrid">
        <mx:columns>
            <mx:DataGridColumn dataField="Definition"/>
            <mx:DataGridColumn dataField="Value"/>
        </mx:columns>
    </mx:DataGrid>

    <s:Form>
        <s:FormItem label="Total">
            <s:Label text="{total()}"/>
        </s:FormItem>
    </s:Form>

And the script:
public function total():String {
    var i:Number = 0;
    for each(var obj:Object in ArrayCollection(DataGrid(srcgrid).dataProvider)){
        i = i + obj.Value;
    }

    return i.toString();
}

Any idea?
Thanks in advance

A: The total() function was called before there was anything inside the dataProvider.
Also srcgrid.dataProvider can be looped as an Object
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="addInitData(event)">

    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
        <mx:DataGrid id="srcgrid">
        <mx:columns>
            <mx:DataGridColumn dataField="Definition"/>
            <mx:DataGridColumn dataField="Value"/>
        </mx:columns>
    </mx:DataGrid>

    <s:Form x="250">
        <s:FormItem label="Total">
            <s:Label id="total"/>
        </s:FormItem>
    </s:Form>
    <fx:Script>
        <![CDATA[
            import flash.events.Event;
            import mx.collections.ArrayList;

            private function addInitData(e:Event = null):void{
                var dataProvider:ArrayList = new ArrayList();
                for (var i:int = 0; i < 12; i++){
                    dataProvider.addItem({Definition : 'item_' + i, Value : i});
                }
                srcgrid.dataProvider = dataProvider;
                updTotal();
            }

            private function updTotal():void{
                var sum:Number = 0;
                for (var k:String in srcgrid.dataProvider){
                    sum += srcgrid.dataProvider[k]['Value'];
                }
                total.text = sum.toString();
            }
        ]]>
    </fx:Script>
</s:Application>


text:
Q: Formating file changes encoding on Redhat system I have a bash script which extract data from an oracle database. I use spool to extract data. After extraction I format the file by removing and replacing some characters. My problem is after formating the files are in ANSI encoding instead of ut8.

*

*Extraction with spool. The file is utf8

*Format with cat and tr command and redirect in another file. This file is ansi.

The same process works fine on Aix system. I try iconv but it doesnt work. Do you please have an idea why the encoding changes from utf8 to ansi ? How to correct it please ?

A: You should consequently use either ISO-8859-1 or UTF-8. In the latter case, don't use tr as it doesn't (yet?) support multi-byte characters, use sed instead (e.g sed 's/deletethis//g').
ISO-8859-1:
export LC_CTYPE=fr_FR.ISO-8859-1
export NLS_LANG=French_France.WE8ISO8859P1

# fetch data from Oracle, emulated by the following line
echo 'âêîôû' >test.latin1 # 5 bytes (+lineend)

# perform formatting, eg:
sed 's/ê/[e-circumflex]/g' test.latin1

# or the same with hex-codes:
sed $'s/\xea/[e-circumflex]/g' test.latin1

UTF-8:
export LC_CTYPE=fr_FR.UTF-8
export NLS_LANG=French_France.AL32UTF8

# fetch data from Oracle, emulated by the following line
echo 'âêîôû' >test.utf8 # 10 bytes (+lineend)

# perform formatting, eg:
sed 's/ê/[e-circumflex]/g' test.utf8

# or the same with hex-codes:
sed $'s/\xc3\xaa/[e-circumflex]/g' test.utf8

Note: no conversion (iconv, recode, etc) is required, just make sure NLS_LANG and LC_CTYPE are compatible. (Also, your terminal(emulator) should be set accordingly; for PuTTY it is Configuration/Category/Window/Translation/Remote-character-set.)
Original answer:
I cannot tell what's wrong with the formatting you perform, but here is a method to damage the utf8-encoded text:
$ echo 'ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP' | iconv -f iso-8859-2 -t utf-8 | xxd
00000000: c381 5256 c38d 5a54 c5b0 52c5 9020 54c3  ..RV..ZT..R.. T.
00000010: 9c4b c396 5246 c39a 52c3 9347 c389 500a  .K..RF..R..G..P.

$ echo 'ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP' | iconv -f iso-8859-2 -t utf-8 | tr -d $'\200-\237' | xxd
00000000: c352 56c3 5a54 c5b0 52c5 2054 c34b c352  .RV.ZT..R. T.K.R
00000010: 46c3 52c3 47c3 500a                      F.R.G.P.

Here the tr -d $'\200-\237' part deleted half of the utf8-sequences (c381 became c3, c590 became c5), rendering the text unusable.


text:
Q: Typescript: Call constructor when passing class as an object So I have a class that needs to take in another class as an option. I have the following
class MyClass
{
    interface IOptions
    {
        factory? : Function;
    }

    constructor(data: any, options: IOptions)
    {
        this._factory = new options.factory();
    }
}

options.factory can be passed to this a couple of different ways but it should be a class that can then be called with new.
I am trying to pass across the class like:
this._options.factory = MyOtherClass;
var myClass= new MyClass(data, this._options);

Where MyOtherClass is a class with a constructor.
The error in my IDE when I try options.factory() is
Cannot use 'new' with an expression whose type lacks a call or construct signature.

Which makes sense, but how can I do this?


text:
Q: I want to Implement flutter_bloc and connectivity_plus to check for network connections. how to do it? I have tried out tons of blogs and stuff to do this but none of them work or are outdated or throw unknown errors.
I am instructed to create network connection checker using bloc.
however, I have little to no knowledge of bloc.
Please share any git repo or code that explains how to do this.
#Flutter

A: Register a streamSubscription in bloc and listen connections changed.
When connections changed, run event to update state
class NetworkChangeBloc extends Bloc<NetworkChangeEvent,        NetworkChangeState> {
final ConnectivityService _service;
late StreamSubscription<bool> _subscription;

NetworkChangeBloc()
  : _service = ConnectivityService(),
    super(NetworkChangeInitial()) {
on<NetworkChangeEvent>(_mapEventNetworkChange);
_subscription = _service.initStream().listen((isNetworkConnected) {
  add(NetworkChangeEvent(isNetworkConnected));
});
}

@override
Future<void> close() async {
  await _service.dispose();
  await _subscription.cancel();
  return super.close();
}

void _mapEventNetworkChange(
  NetworkChangeEvent event,
  Emitter<NetworkChangeState> emit,
) async {
  bool isNetworkConnected = event.isNetworkConnected;
  emit(NetworkChangeState(isConnected: isNetworkConnected));
}
}

I don't use connectivity_plus package here but you can apply this solution


text:
Q: Cannot find the declaration of element 'beans' Error in in xml file I'm following the tutorial on https://www.journaldev.com/3524/spring-hibernate-integration-example-tutorial and all I've done is copy and paste yet I'm getting the error below:
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 7 in XML document from class path resource [spring.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 7; columnNumber: 107; cvc-elt.1.a: Cannot find the declaration of element 'beans'.
This is what my XML file looks like up until thee 7th line where the error is referencing to:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:aop="https://www.springframework.org/schema/aop"
    xmlns:tx="https://www.springframework.org/schema/tx"
    xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

This is my pom.xml:
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.samples</groupId>
    <artifactId>SpringHibernateExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>

        <!-- Generic properties -->
        <java.version>1.6</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Spring -->
        <spring-framework.version>4.0.3.RELEASE</spring-framework.version>

        <!-- Hibernate / JPA -->
        <!-- <hibernate.version>4.3.5.Final</hibernate.version> -->
        <hibernate.version>3.6.9.Final</hibernate.version>

        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

    </properties>

    <dependencies>
        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Spring ORM support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>
</project>

Does anyone know what's causing this error? Thanks in advance.
Please let me know if u need any more information to answer this.


text:
Q: What mechanism does WordPress use to keep constants from being redefined? I recently posted a comment on a general tech group about this line of code:
define('WP_POST_REVISIONS', true);

Someone replied, "If the original coders don't know that you can't redefine a constant than why would you even trust any of their other code?"
That made me wonder, what mechanism in WordPress keeps themes/plugins/etc from redefining constants? I'm guessing that it has to do with the order in which code loads.

A:
What mechanism does WordPress use to keep constants from being redefined?

None. Constants are not a WordPress feature, they're a part of the PHP programming language.

Someone replied, "If the original coders don't know that you can't redefine a constant than why would you even trust any of their other code?"

I think this is them suggesting that if the authors don't know that you cannot redefine a constant, then they might not be very good at PHP

That made me wonder, what mechanism in WordPress keeps themes/plugins/etc from redefining constants? I'm guessing that it has to do with the order in which code loads.

Once a constant is defined, it can't be changed. PHP enforces this, otherwise constants would just be fancy variables that can change on a whim.
Generally, it's considered poor practice to define those constants in plugins and themes. They're intended for wp-config.php and should be set by the user. I would treat any plugin or theme that defines WP constants with great suspicion and skepticism.


text:
Q: how to create the sql sentence to obtain the following result I have the following table in my data base
The table name is "product_question"
product_question_id int(11) No
product_id  int(11) No
user_name   varchar(100)    No
user_email  varchar(200)    No
envipor varchar(100)    No
company_name    varchar(100)    No
product_name    varchar(100)    No
question    text    No
product_image   varchar(500)    No
date    timestamp   No  CURRENT_TIMESTAMP

and i have the following sql statement
the sentenced SQL in my .php page is that is
SELECT*
FROM product_question
WHERE company_name = $_SESSION['company_name']

but I want the results on my .php page, into a simple statement shown in this way
product: xbox 360
question: what is the price? - user_name: brian

product: ps3
question: has availability? - user_name: carlos

product: xbox 360
question: has games? - michael

product: ps3
question: what is the price? - user_name: luke

product:  smartphone
question : brings android? - selena

product: xbox 360
question: how many games? - user_name: daniel

I want the outcome of the sentence is displayed in this way
product: xbox 360
question: what is the price? - user_name: brian
question: has games? - michael
question: how many games? - user_name: daniel

product: ps3
question: has availability? - user_name: carlos
question: what is the price? - user_name: luke

product:  smartphone
question : brings android? - selena

but, I do not know to create the sql sentence to obtain the desired result.

A: As stated in the comments the method to get your results from the database in the format that you require you require you would issue a query that looked like this. This is assuming  you are using the procedural style of mysqli.
$sql = "select CONCATENATE('question: ', question, ' - ', user_name) as questionText ".
       "from product_question ".
       "WHERE company_name = '".mysqli_real_escape_string($dbConnection, $_SESSION['company_name'])."'";