text:
Q: how to get access to post data incoming inside a Django middleware? I am writing a middleware due to which i need to access post data but none of the answers are solving my doubt, i am reading the data like this  but this is working in postman but giving error in  browser
  dict_str = request.body.decode("UTF-8")

any help is highly appreciated
error
RawPostDataException at /accounts/api/v1/register/
You cannot access body after reading from request's data stream

A: You can get by reqeust.data, once POST body parsed on DRF, accessing to body is hindered.

A: You can try this, i hope this will work
import json
import ast
def CustomMiddleware(get_response):
    def middleware(request):
        bytes_request_data = getattr(request, '_body', request.body)
        if bytes_request_data:
            request_data = ast.literal_eval(bytes_request_data.decode('utf-8'))
            print(request_data)

A: This exception is raised if you try to access the body after reading the request with HttpRequest.read() or HttpRequest.readline().
The request is probably read in a previous middleware.
From Django's documentation https://docs.djangoproject.com/en/4.1/ref/request-response/#django.http.HttpRequest.POST:~:text=You%20can%20also%20read%20from%20an%20HttpRequest%20using%20a%20file%2Dlike%20interface%20with%20HttpRequest.read()%20or%20HttpRequest.readline().%20Accessing%20the%20body%20attribute%20after%20reading%20the%20request%20with%20either%20of%20these%20I/O%20stream%20methods%20will%20produce%20a%20RawPostDataException.:
You can also read from an HttpRequest using a file-like interface with HttpRequest.read() or HttpRequest.readline(). Accessing the body attribute after reading the request with either of these I/O stream methods will produce a RawPostDataException.


text:
Q: Ipad won't load local SWF file from As3 I have 2 SWF files that is inside the app, i packeged it with AIR 14.0 to an IPA, it is just an image of a loading screen, but it won't load, when i publish it to test on my ipad.
I am not sure what to do.
loader.load(new URLRequest("com/clark/LoadingScreen.swf"));

        loader.contentLoaderInfo.addEventListener(Event.COMPLETE,swfIn);

        e.target.loader.content.width = stage.stageWidth/2;
                e.target.loader.content.scaleY = e.target.loader.content.scaleX;
        e.target.loader.content.x = (stage.width/2)-(e.target.loader.content.width/2);
        e.target.loader.content.y = (stage.height/2)-(e.target.loader.content.height*1.5);

        addChild(loader);

A: here is some information from adobe about this topic http://blogs.adobe.com/airodynamics/2012/11/09/packaging-and-loading-multiple-swfs-in-air-apps-on-ios/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set of natural numbers Let $A$ be a nonempty subset of $\omega$, the set of natural numbers. If $\bigcup A=A$ then $A=\omega$.
I have proved '$\bigcup n^+ = n$ for any $n\in\omega$' and '$\bigcup\omega = \omega$'
I think this question should be proved with the above results..
Help please

A: Lemma: If $A$ is a set of ordinals, then $\bigcup A$ is an ordinal.
The proof appears here.
Suppose that $A\subseteq\omega$ then $\bigcup A$ is an ordinal. If $A=\bigcup A$ then $A$ was an ordinal, that is either $n\in\omega$ or $\omega$ itself.
However you know that for $n\neq 0$, $\bigcup n\neq n$, so you are only left with the option $A=\omega$.

To prove this directly in this case you can argue that if $n\in A$ then $n\subseteq\bigcup A$. From this follows that if $A$ is non-empty and $\bigcup A=A$ for every $k\in\omega$ such there is $n\in A$ and $k<n$ we have $k\in\bigcup A$, and therefore $k\in A$. So if $A$ is unbounded $A=\omega$; if $A$ is bounded then $A=n$ but we know that $\bigcup n\neq n$ which is a contradiction.


text:
Q: Why is my executor memory usage stuck at 0? I have a pretty simple Spark job that looks like this:
JavaPairRDD<Key,Value> rawData = newAccumuloRDD(...);
JavaPairRDD<Key,Value> indexSrc =
    rawData.filter(new IndexFilter()).cache();
JavaPairRDD<Key,Value> indexEntries =
    indexSrc.mapPartitionsToPair(new IndexBuilder(numPartitions));
JavaPairRDD<Key,Value> reverseIndexEntries =
    indexSrc.mapPartitionsToPair(new ReverseIndexBuilder(numPartitions));
JavaPairRDD<Key,Value> dataEntries =
    rawData.mapPartitionsToPair(new DataBuilder(numPartitions)).cache();

dataEntries.union(indexEntries)
  .union(reverseIndexEntries)
  .repartitionAndSortWithinPartitions(new PartitionedIndexRDDPartitioner(NUM_BINS))
  .saveAsNewAPIHadoopFile(pidxBulk.toString(), Key.class, Value.class,
      AccumuloFileOutputFormat.class, conf);

Where Key and Value are Apache Accumulo's Key and Value classes (using the KryoSerializer).
I'm not sure where exactly to put the calls to cache(), or even if they're needed at all. But I'm concerned that my executors don't seem to be using much of the memory that I've allocated to them:

And the "Storage" page in the application UI is empty.
Am I doing something wrong, or has Spark decided that it can't make this job go any faster by storing my RDDs?

A: Memory used means memory used for caching.
In your code you are performing only one action and indexSrc or dataEntries are not used again, so there is not point of caching it.
To prove it, you can add
indexSrc.count(); and dataEntries.count(); after declaring them and then check executor/storage page.
JavaPairRDD<Key,Value> rawData = newAccumuloRDD(...);
JavaPairRDD<Key,Value> indexSrc = rawData.filter(new IndexFilter()).cache();
indexSrc.count();
JavaPairRDD<Key,Value> indexEntries = indexSrc.mapPartitionsToPair(new IndexBuilder(numPartitions));
JavaPairRDD<Key,Value> reverseIndexEntries = indexSrc.mapPartitionsToPair(new ReverseIndexBuilder(numPartitions));
JavaPairRDD<Key,Value> dataEntries = rawData.mapPartitionsToPair(new DataBuilder(numPartitions)).cache();
dataEntries.count();

dataEntries.union(indexEntries)
  .union(reverseIndexEntries)
  .repartitionAndSortWithinPartitions(new PartitionedIndexRDDPartitioner(NUM_BINS))
  .saveAsNewAPIHadoopFile(pidxBulk.toString(), Key.class, Value.class,
      AccumuloFileOutputFormat.class, conf);


text:
Q: Lodash isEqual returns false for identical objects I'm using React Native memo to decide whether my component should re-render or not. My props need more than a shallow compare so I figured I can use Lodash isEqual. However, for some reason it returns false for identical objects. The issue is a prop userChildren which is an array of objects. To get it to work I need to remap the whole array which I don't understand why that would be needed.
const areEqual = (
  { userChildren: prevChildren, ...prevProps },
  { userChildren: nextChildren, ...nextProps }
) => {
  console.log(
    _.isEqual(
      prevChildren.map((p) => ({ ...p })),
      nextChildren.map((p) => ({ ...p }))
    )
  ); // Returns true
  console.log(_.isEqual(prevChildren, nextChildren)); // Returns false
  console.log(prevChildren);
  console.log(nextChildren);
  return (
    _.isEqual(prevProps, nextProps) &&
    _.isEqual(
      prevChildren.map((p) => ({ ...p })),
      nextChildren.map((p) => ({ ...p }))
    )
  );
};

export default memo(RootNavigator, areEqual);

The log output can be seen below:
 LOG  true
 LOG  false
 LOG  [{"birthDate": "2022-09-14", "firstName": null, "gender": null, "id": "189", "showGender": null, "userId": "XXX"}]
 LOG  [{"birthDate": "2022-09-14", "firstName": null, "gender": null, "id": "189", "showGender": null, "userId": "XXX"}]

EDIT
There seems to be something with nextProps that breaks the isEqual:
console.log(
  'nextChildren',
  _.isEqual(
    [
      {
        birthDate: '2022-09-14',
        firstName: null,
        gender: null,
        id: '189',
        showGender: null,
        userId: 'XXX',
      },
    ],
    nextChildren
  )
);
console.log(
  'prevChildren',
  _.isEqual(prevChildren, [
    {
      birthDate: '2022-09-14',
      firstName: null,
      gender: null,
      id: '189',
      showGender: null,
      userId: 'XXX',
    },
  ])
);

Gives the log output:
LOG  nextChildren false
LOG  prevChildren true


text: Q: How do I get the username of the currently displayed profile in a SharePoint Webpart for MySites I am writing a web part that will be displayed in public SharePoint My Sites.  This part will display some 3rd party information for the user whose profile is being displayed.  For example, if UserA is viewing UserB's profile, then it will show some information about UserB.  How do I go about getting the username 'UserB' in the webpart code?  Is it safe to use the 'accountName' query string param, or is there another, better way to do this from the SP object model?


text:
Q: Etymology for "positive handoff" or "positive hand-off" What's the etymology/origin of the phrase "positive handoff" (or "hand-off", meaning an explicit transfer of something (objects or currency or information or responsibility) between two parties that both are actively engaged in, so that the sender can be sure that the receiver gets the thing and is aware of receiving it.
As an example, the actions of a process server would constitute a positive handoff.
Usage examples:

For freight rail, the rule will ensure the positive handoff of security-sensitive materials as well as establish security protocols for custody transfers of security-sensitive material rail cars.
(https://www.joc.com/regulation-policy/dhs-releases-rail-security-final-rule_20081112.html)

Finally, I expect a positive handoff to test.  By this I mean a detailed TRD (test release document) that describes what the feature does, what works, what doesn't work, and suggestions for testing the feature.
https://nathanbrixius.wordpress.com/2007/07/23/what-makes-a-good-software-developer/

Have your child use a bathroom in the gate area at some point before boarding.  If traveling under unaccompanied-minor procedures, he or she will be escorted onto the airplane during pre-boarding.  Airline policies call for a positive hand-off of your child from one employee to the next.  At the destination, the person meeting your child may have to show ID (many airlines require photo ID).  Even a parent may have to show ID when picking up the child at the end of the trip.
http://avstop.com/news_july_2010/when_kids_fly_alone.htm

Throughout the exercise series, the participants have developed tactics, techniques and procedures to effectively notify, coordinate, and conduct positive handoff of a hijacked aircraft flying through Russian, Canadian and American airspace, Viens told reporters during a teleconference today.
https://archive.defense.gov/news/newsarticle.aspx?id=120694

When aircraft cross into a new ATC Control Sector, they are handed off to a new controller on a separate frequency. In some places, this process is entirely automated. But when an emergency is in progress, these automated processes largely disappear. Controllers use a landline connection to speak with the next controller before handing off the emergency aircraft to them. This is an important step in guaranteeing a positive handoff between controllers. It's also a way for controllers to brief each other on the specifics of the situation which they might not be aware of.
https://www.boldmethod.com/learn-to-fly/regulations/what-happens-when-you-declare-an-emergency-with-atc/

A simple technique from aviation, the "positive handoff," can be beneficial, even life-saving. Here's how it works. When a plane moves from one airspace to the next, air traffic control provides the pilot with the new communication frequency. The pilot confirms the frequency, then checks in with the next set of controllers. ATC and the pilot all know and agree on who is responsible for communication as the flight is handed off from one zone to the next.
Similarly, if there are two or more pilots on a flight, it's essential to know who is in charge. A pilot who needs to consult a chart or check the weather may say to his or her partner, "Your airplane." "My airplane" is the confirmation. There is no ambiguity about who is flying the airplane.
Parents can adopt this practice poolside to securely transfer supervision from one adult to another. When it is "your baby," acknowledge that out loud and take the responsibility seriously. No looking at your phone, no "just running inside for a second," no goofing around with friends, no doing anything that distracts you from your supervisory obligation. Take turns with other adults so you have time to enjoy the party, too. When your shift is over, the positive handoff makes it clear who is now in charge of a baby or toddler. That eliminates the possibly tragic confusion of the "I thought you were watching him!" "No, I thought YOU were watching him!" scenario.
https://www.safebeesideme.com/blogs/news/don-t-let-a-pool-party-turn-into-a-tragedy

Is it from military use? football? first responders / hospital ER? Air traffic control? (as three of the examples might suggest)

A: I can't find any definitive origin, but the earliest mentions I can find were in Senate hearings in 1961:
From Hearings Before the Aviation Subcomittee of the Committee on Interstate and Foreign Commerce, United States Senate, Eighty-seventh Congress, First Session on Air Safety (Feb 20 - Mar 8, 1961):

Senator MONRONEY. I am not so concerned with that. I am concerned with United approaching Preston and this handoff at that point, whether, if there is known instrumentation in the bright display, where this target could have been carried in and observed going beyond Preston by an area man, or at the point if he had not already passed Preston have been turned over and given a positive radar handoff to the control tower at Idlewild?
Mr THOMAS. Electronic means there is not today, and this is an electronic contract Mr. Anast was speaking of that we hope to have in 12 months.
Senator MONRONEY. In 12 months?
Mr THOMAS. Yes, sir.
Senator MONRONEY. The old system that was developed at the CAA center would not be adaptable?
As I understand, that was an electric pencil?
Mr THOMAS. Yes, sir.
Senator MONRONEY. I thought there was a new one which they had devised, a sort of a joystick application, with which you could follow internally the progress of the plane as the control tower man brought it along, keeping it circled and in the scope.
The question was, to my mind, could that be wired into the approach control from the area control?
Mr. THOMAS. This is the development that is underway at present time essentially. We have the problem of registration between two radars looking at airplanes from different perspectives and therefore giving different locations, too.
Senator MONRONEY. This is on the same airport I am talking about.
Mr. THOMAS. But they are separate radars.
Senator MONRONEY. But they are not too far separate. In other words, it seems to me like it would even pay, if a positive radar handoff is required, to have this on the scope even in the control tower so that the air traffic controller bringing it in would be able to pick him up positively on his approach radar then from reference to perhaps the long-range radar that is piped in. Maybe it is a captive or slave television set working there, but some way to perfect a positive handoff.
Mr. THOMAS. Sir, we want this desperately.

and from Hearings Before the Subcomittee of the Committee on Appropriations, United States Senate, Eighty-seventh Congress, First Session on H.R. 7446 Making Appropriations for Sundry Independent Executive Bureaus, Boards, Commissions, Corporations, Agencies, and Offices, for the Fiscal Year ending June 30 1962, and for Other Purposes, June 1961 (specifically the transcript of Tuesday, June 20, 1961)

Mr. HALABY. There are two principal experiments, Senator, which derive from work within the Agency and the disclosures in the unfilled mint of ideas developed during your hearings on safety last winter.
One is technique for passing and airplane which is on one radarscope in one sector of the airspace over to another, and to assure that there is a continuous control in the process of flow of that aircraft.
Senator MONRONEY. Positive radar handoff.
Mr. HALABY. Positive radar handoff, as it is called. What that means is to provide additional personel to enable one radar position, one radar control, to positively identify a particular radar target to another, and insure the handing off of radar control to the second position before ending his own surveillance.


text:
Q: How to click on a bootstrap button as per the HTML through Selenium and Python I am trying to click a button on webpage using selenium script but it is giving me following error using this line:
driver.find_element_by_class_name('btn-primary').click()

Error is as follows:
ElementNotInteractableException: Message: Element <button class="btn-primary btn-text  sort-filter-clear-button" type="button"> could not be scrolled into view

HTML of the button element:
<button type="submit" class="btn-primary btn-action bookButton" id="bookButton" data-track="FLT.RD.Book.Bottom">Continue Booking</button>

A: Try to wait for element:
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "bookButton")))
button.click()

It will wait at least 10 seconds, until element will be clickable.
Note: you have to add some exports:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

EDIT: you can try also js executor like this:
button = driver.find_element_by_id("bookButton")
driver.execute_script("arguments[0].click();", button)

in case your button is inside an iframe/frame, firstly you have to switch to this frame and only then you can interact with this element:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME("frame_name"))))
# do your stuff
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "bookButton")))
button.click()
driver.switch_to.default_content() # switch back to default content

A: As per the HTML you have shared and as you mentioned of bootstrap button, moving forward as you are trying to invoke click() on the desired element you need to induce WebDriverWait for the element to be clickable and you can use either of the following solutions:

*

*CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn-primary.btn-action.bookButton#bookButton>span.btn-label"))).click()

*XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn-primary btn-action bookButton' and @id='bookButton']/span[@class='btn-label'][contains(.,'Continue Booking')]"))).click()

Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: How to insert custom class item to map C++ I have a class, how can i add one object of this class to map, and find it by id?
Class code:
class Client {
    int FileDescriptor, Id, cryptcode;
    unsigned char CustomData[256];

    void PrepareClient()
    {
        // init code
    }
  public:
    AnticheatClient (int fd, int id, int crypt_code)
    {
        FileDescriptor = fd;
        Id = id;
        cryptcode = crypt_code;
        PrepareCrypt();
    }

    void OwnCryptEncrypt(unsigned char* data, int len)
    {
 //...
    }

    void OwnCryptDecrypt(unsigned char* data, int len)
    {
 //...
    }
};

std::map<int, Client> ClientTable;

int main()
{
 int id = 1;
 Client c(1, id, 1);
 // how can i add this client to map and how can i find it by id?
}

I tried so many example codes but not with custom class so they didn't work.
Thanks!

A: For adding a Client with key=10:
ClientTable[10] = Client(1, id, 1);

For find an element with key=10:
std::map<int, Client>::iterator it = ClientTable.find(10);
if (it != ClientTable.end()) {
    int key = it->first;
    Client c = it->second;
}

You can also use:
Client c = ClientTable[10];

but calling operator[] is not const. So, that is most probably not what you want to use if you just want to find an element.

A: 1) "how can i add one object of this class to map?"
ClientTable[id] = c;

Well, technically, it adds a copy of the object to the map.
2) "and find it by id?"
Client lookerUpper = ClientTable[id];


text:
Q: htaccess rewriting subdomain to a folder I want to rewrite my main domain to a path and if no query is appended then to a different path. I have a wildcard C name in place to support subdomains.
www.xxx.com => works normally
abc.xxx.com => point to a folder
abc.xxx.com/abc-xyz => point to www.xxx.com and should work normally
This is what i have right now :
<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On

    RewriteCond %{HTTP_HOST} !^([w]{3,3}[.]{1,1}){0,1}example.com$
    RewriteCond %{HTTP_HOST} ^([0-9a-zA-Z-]*)[.]example.com$
    RewriteRule ^$ portfolio/index.php?pageDetailId=%1 [NC,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]

    RewriteCond %{HTTP_HOST} !^([w]{3,3}[.]{1,1}){0,1}example.com$
    RewriteCond %{HTTP_HOST} ^([0-9a-zA-Z-]*)[.]example.com$
    RewriteRule ^(.*)$ $1?pageDetailId=%1 [QSA,L]
</IfModule>

As we can see, i need that abc as variable in abc.example.com/abc-xyz. Please reply with doubts with any, i tried many ways its not working. This same htaccess works on 1 domain smoothly but when i created a new domain its not working on that. Thanks.
NOTE: It works on httpd but not on apache2

A: Have it like this:
Options +FollowSymlinks
RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(?!www\.)([\w-]+)\.example\.com$ [NC]
RewriteRule ^(index\.php)?$ portfolio/index.php?pageDetailId=%1 [NC,L,QSA]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteCond %{HTTP_HOST} ^(?!www\.)([\w-]+)\.example\.com$ [NC]
RewriteRule ^(.+)$ index.php?pageDetailId=%1&/$1 [L,QSA]

RewriteRule ^(.*)$ index.php?/$1 [L,QSA]


text:
Q: Run Nodejs App Every 6 Hours with Aysnc Await I want to run a Script every 6 Hours
const { IgApiClient } = require("instagram-private-api")
const ig = new IgApiClient()

const USERNAME = "abc"
const PASSWORD = "xyz"

ig.state.generateDevice(USERNAME)
const main = async () => {
    var birthday = new Date(2069, 05, 14);
    var today = new Date();
    birthday.setFullYear(today.getFullYear());
    if (today > birthday) {
    birthday.setFullYear(today.getFullYear() + 1);
    }
    var daystill = Math.floor((birthday - today) / (1000*60*60*24))

    await ig.simulate.preLoginFlow()
    await ig.account.login(USERNAME, PASSWORD)
    process.nextTick(async () => await ig.simulate.postLoginFlow())
    await ig.account.setBiography(`${daystill} Days till my Birthday, Today is ${new Date().getDate()}/${new Date().getMonth()}/${new Date().getFullYear()}. (AutoGenerated)`)
}
main()

instagram-private-api
About Script: update my Instagram Bio with Async Await
Problem / Goal:
I Tried using node-cron, but It returns some Error (I think Async is causing the Problem), I also tried while loops and setInterval()s
I want this Script/File to run every 6 Hours, I have a heroku account (if that helps)
Error when i use node-cron:
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);

Code for node-cron:
cron.schedule('* * * * *', () => { // this is not every 6hrs
    const main = async () => {
       //same as above
    }

    main()
})

A: Doing it the async await way as the title says.
// used to measure time
import { performance } from 'perf_hooks';

const interval = 1000; // in ms

(async function main(){
    let start_time = performance.now();

    // do stuff

    let stop_time = performance.now();

    let timeout = interval - (stop_time - start_time);
    setTimeout(main, timeout);
})();

edit:
To explain the syntax behind the main function.
()(); will automatically call the function inside of first braces on script start.


text:
Q: MainPage fails to Load properly I have this code to set the Mainpage of my Application.
 public async Task  LoadMainPage()
    {
        try
        {

          signedin = Auth.IsUserSignedIn();
            if (signedin)
                registered = await Firestore.IsUserRegistered();

            if (!signedin)
            {
                MainPage = new NavigationPage(new MainPage());
            }
            else if (signedin && !(registered))
            {
                MainPage = new NavigationPage(new RegistrationPage());
            }
            else if (signedin && (registered))
            {
                MainPage = new NavigationPage(new FlyoutPage1());
            }

        }
        catch (Exception ex) { await App.Current.MainPage.DisplayAlert("Error", ex.Message, "OK"); }
    }

I am calling this method from App.Xaml.cs Onstart method
 protected  override  async void OnStart()
    {
        base.OnStart();
        await LoadMainPage();

    }

the problem is when the Application is launched the Mainpage fails to Load Properly.
it appears only when i tap the triple line icon on my phone wait for some time and tap the application again to launch it.
the code for Firestore.IsUserRegistered is as below
 public async Task<bool> IsUserRegistered()
    {

       FirebaseFirestore collection = FirebaseFirestore.Instance;
        string email = FirebaseAuth.Instance.CurrentUser.Email;
        Android.Gms.Tasks.Task task = collection.Collection("User").WhereEqualTo("Email", email)
                .Limit(1).Get().AddOnSuccessListener(this);
        for (int i = 0; i < 25; i++)
        {
          await  Task.Delay(100);
            if (isregistered ) break;
        }

        return isregistered;
    }
  public void OnSuccess(Java.Lang.Object result)
    {

            var documents = (QuerySnapshot)result;
            isregistered = !documents.IsEmpty;

    }

A: You can add await LoadMainPage(); to OnResume() just like Splash Screen.
It said:

The startup work is performed asynchronously in OnResume. This is necessary so that the startup work does not slow down or delay the appearance of the launch screen. When the work has completed, SplashActivity will launch MainActivity and the user may begin interacting with the app.


text:
Q: Magento 2 How to get category tree with checkbox to select only one category? I want to call the categories into my custom admin form for admin. How can I call that?

I want to show all categories into my custom form in admin and it will allow selecting only one category.
I used the below code but it is showing nothing in my form what is wrong here?
<referenceContainer name="content">
    <block class="Name\Module\Block\Adminhtml\Category\DuplicateForm\Categories" name="name.dupcat.categorydropdown">
        <uiComponent name="categories_form"/>
    </block>
</referenceContainer>

-- view/adminhtml/ui_component/categories_form.xml
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="general">
        <field name="categories" component="Name/Module/js/select-category" sortOrder="20" formElement="select" >
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filterOptions" xsi:type="boolean">true</item>
                    <item name="multiple" xsi:type="boolean">false</item>
                    <item name="showCheckbox" xsi:type="boolean">true</item>
                    <item name="disableLabel" xsi:type="boolean">true</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
                <elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
                <label translate="true">Select Category</label>
                <dataScope>categories</dataScope>
                <componentType>field</componentType>
                <listens>
                    <link name="${ $.nametdupcat }.${ $.nametdupcat }:responseData">setParsed</link>
                </listens>
            </settings>
            <formElements>
                <select>
                    <settings>
                        <options class="Name\Module\Ui\Component\Form\Category\Options"/>
                    </settings>
                </select>
            </formElements>
        </field>
    </fieldset>
</form>

-- \Ui\Component\Form\Category\Options.php
<?php
namespace Name\Module\Ui\Component\Form\Category;

use Magento\Framework\Data\OptionSourceInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\Framework\App\RequestInterface;

class Options implements OptionSourceInterface
{
    protected $categoryCollectionFactory;
    protected $request;
    protected $categoryTree;

    public function __construct(
        CategoryCollectionFactory $categoryCollectionFactory,
        RequestInterface $request
    ) {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->request = $request;
    }

    public function toOptionArray()
    {
        return $this->getCategoryTree();
    }

    protected function getCategoryTree()
    {
        if ($this->categoryTree === null) {
            $collection = $this->categoryCollectionFactory->create();

            $collection->addAttributeToSelect('name');

            foreach ($collection as $category) {
                $categoryId = $category->getEntityId();
                if (!isset($categoryById[$categoryId])) {
                    $categoryById[$categoryId] = [
                        'value' => $categoryId
                    ];
                }
                $categoryById[$categoryId]['label'] = $category->getName();
            }
            $this->categoryTree = $categoryById;
        }
        return $this->categoryTree;
    }
}

-- view\adminhtml\web\js\select-category.js
define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
    setParsed: function (data) {
        var option = this.parseData(data);
        if (data.error) {
            return this;
        }
        this.options([]);
        this.setOption(option);
        this.set('newOption', option);
    },

    parseData: function (data) {
        return {
            value: data.category.entity_id,
            label: data.category.name
        };
    }
});
});


text:
Q: How to get H1 tag value under a class I wish to get the "Testing 2" text inside a class called "inner" as shown below.
<div _ngcontent-c6="" class="inner">
    <h1 _ngcontent-c6=""> Testing 2
    </h1>
</div>

I tried "return element(by.css('.inner')).element(by.css("h1")).getText();" and "return element(by.className('inner')).element(by.css("h1")).getText();" but both codes are not working.
When running the said codes I got the same error saying "Failed: No element found using locator: By(css selector, h1)"
How can I get the value of h1 inside a div with a class name?

A: Try wait for a while.
var EC = protractor.ExpectedConditions;
var target = element(by.css('div.inner > h1'));

browser.wait(EC.presenceOf(target), 15*1000);

target.getText().then(function(txt){
    console.log('H1: ' + txt);
});


text:
Q: Time-critical sampling of a source observable with RxJava? I'd like to be able to sample emissions from a source observable at consistent intervals, regardless of CPU-intensive work further down the chain. This code demonstrates the problem: it samples reliably at 500ms intervals with doSlowOperation() commented out, and then starts to lag and give inconsistent results when it is uncommented.
    @Test
    fun `test sample operator lag`() {
        Observable.interval(100, TimeUnit.MILLISECONDS)
            .sample(500, TimeUnit.MILLISECONDS)
            .timestamp(TimeUnit.MILLISECONDS)
            .map {
                doSlowOperation()
                it
            }
            .take(4)
            .toList()
            .subscribe { item ->
                val itemsWithNormalisedTimestamps = item.map {
                    val timeSinceStartMs = (it.time() - item.first().time())
                    "${timeSinceStartMs}ms"
                }
                println("Got items: $itemsWithNormalisedTimestamps")
            }

        Thread.sleep(20000)
    }

    private fun doSlowOperation() {
        val list = mutableListOf<Int>()
        for (i in 0..10000000) list.add(i)
    }

Output with doSlowOperation() commented:
Got items: [0ms, 500ms, 1001ms, 1499ms]

Output with doSlowOperation() uncommented:
Got items: [0ms, 1610ms, 2093ms, 3157ms]

Note that although it would be good if the slow operation were performed more-or-less in real-time, it's not so time-sensitive as the sampling itself. I.e. it doesn't matter if a backlog of sample emissions accumulate into some kind of queue to be processed when they can, so long as the sampling continues to occur at precise intervals.
I've tried making the source observable hot (with publish() and connect()) and also tried moving the slow operation onto another scheduler with observeOn(Schedulers.newThread()) without any luck.


text:
Q: Trying to get KeyBindings to work I am trying to get a simple KeyBindings program to work. I followed the instructions from java doc, and tried to test the stuff answered in this (Java Key Bindings Not Working) thread, but i just cant get it to work. I want to output "test" to the console when "F1" is pressed. Can anyone spot my mistake?
JFrame frame = new JFrame("shit");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

JPanel jPanel = new JPanel();
jPanel.getInputMap().put(KeyStroke.getKeyStroke("F1"), "focus");
jPanel.getActionMap().put("focus", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("test");
    }
});

frame.add(jPanel);

A: *

*Components should be added to the frame BEFORE the frame is made visible.

*If that doesn't work then use a different InputMap. Read the section from the Swing tutorial on How Key Bindings Work to see how the 3 different InputMaps are used.


text:
Q: How to pass list of arguments in criteria query , jpa? I am new in JPA but have to implement my project in that technology
what I'm trying to do is build via CriteriaQuery some db query, but have no idea how to pass list Of parameters to the code below :
CriteriaBuilder qb = em.getCriteriaBuilder();
    CriteriaQuery<MyClass> c = qb
            .createQuery(MyClass.class);
    Root<MyClassPK> p = c
            .from(MyClass.class);

    c.where(qb.equal(qb.trim((p.<MyClass> get("id")).<String> get("Name")),
    HERE LIST OF ARGS HOW TO PASS ?? ));
TypedQuery<MyClass> q = em.createQuery(c);

the code looks pretty complex cause of complex database architecutre. Could somebody tell me how to resolve my problem ? Or maybe only one solution is for (...) ?

A: If I understood well your question, you need an "in" condition:
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<MyClass> c = qb.createQuery(MyClass.class);
Root<MyClassPK> p = c.from(MyClass.class);

// c.where(qb.equal(qb.trim((p.<MyClass> get("id")).<String> get("Name")), HERE LIST OF ARGS HOW TO PASS ?? ));

List<String> names = new ArrayList<String>();
names.add("name1");
names.add("name2");
names.add("name3");
c.where(qb.trim((p.<MyClass> get("id")).<String> get("Name")).in(names));

TypedQuery<MyClass> q = em.createQuery(c);


text:
Q: Can not move QGraphicsScene object using addRect function Hi I am trying a very simple QGraghicsScene code in QT. But the addRect function is not working, as I try to add it to specific coordinate. It is always at the centre. I also have tried with setPos. But same result.
MainWindow::MainWindow(QWidget * parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    {
        ui -> setupUi(this);

        scene = new QGraphicsScene(this);
        ui -> graphicsView -> setScene(scene);
        QBrush greenBrush(Qt::green);
        QBrush blueBrush(Qt::gray);
        QPen outlinePen(Qt::black);
        outlinePen.setWidth(2);
        scene -> update();
        rectangle = scene -> addRect(20,200,100,100,outlinePen,greenBrush);
        scene - >update();
    }

MainWindow::~MainWindow()
{
    delete ui;
}


text:
Q: Read and Write data from/to BLOB in MS SQL using Visual C++ and OLE DB ca you help me? I am looking for example how to insert and get data from BLOB in MS SQL Server 2008.
I am using OLE DB and Visual C++.
Thanks

A: There's detailed info on that topic (the write side anyway) here: Sending BLOB Data to SQL SERVER Using IROWSETFASTLOAD and ISEQUENTIALSTREAM.

Most of the available samples are too
simplistic and don't demonstrate
varying data length per row or using
ISequentialStream. In this sample,
you'll see both techniques in one
source file.  By default, the sample
shows how to use IRowsetFastLoad to
send variable length BLOB data per row
using in-line bindings.  In this case,
the in-line BLOB data must fit in
available memory.  This method has
better performance when the BLOB data
is a few bytes to a few MB, because
there is no additional stream
overhead.  For larger data, especially
where the data is not necessarily all
available at once in a block,
streaming is a better choice.

For readback there is background and sample code on MSDN here.

The SQL Server Native Client OLE DB
provider does not retrieve large data
from SQL Server until requested to do
so by the consumer. The consumer
should bind all short data in one
accessor, and then use one or more
temporary accessors to retrieve large
data values as required.


text:
Q: Excecute "taskkill /f /im chrome.exe" even when no chrome process is running I execute this command
taskkill /f /im chrome.exe

In order to stop all chrome process and it works fine only when there is a chrome process running. Most of time I need to run the command even when there is no process of chrome running. How is it possible using command line?
PS: When I run the command and no chrome process is running I got an error like
chrome.exe not found

A: Actually the command does execute, as you would not get an error message otherwise.
Anyway, I suppose you basically want to suppress the error message, which can be accomplished by appending 2> nul to the command line (separated by a SPACE):
taskkill /f /im chrome.exe 2> nul

If you want to reset the exit code (ErrorLevel), write ver> nul into the next line (this works because ver is a command that never fails and resets the ErrorLevel value):
taskkill /f /im chrome.exe
ver > nul

Or in a single line:
taskkill /f /im chrome.exe & ver > nul

Of course you may combine these two measures:
taskkill /f /im chrome.exe 2> nul & ver > nul

A: In Powershell, you can simply do one of the following:
Get-Process Chrome -ErrorAction SilentlyContinue | Stop-Process -Force
or
Stop-Process Chrome -Force -ErrorAction SilentlyContinue


text:
Q: Find the largest subarray length with delimiter I'm trying to solve this problem:
Given two parameters: an array a and integer i, find the largest array length where the sum of all elements is <= i.
For example, having the following array: [3, 1, 2, 1], and i = 4, all the combinations that are <= i are: [3], [1], [2], [3, 1], [1, 2], [1, 2, 1]. The largest subarray is [1, 2, 1], so the return of the function should be 3 (the array length).
What would be a an efficient approach to solve this problem?
This is my algorithm until now, but I know that I'm missing something:
function sumArray(a) {
    return a.reduce((a, b) => a + b, 0)
}

function maxLength(a, i) {
   let max = 0
   let array = [a[0]]
   a.splice(1, a.length).forEach(number => {
     array.push(number)
     if (sumArray(array) <= k) max = array.length
     else array.splice(array.indexOf(Math.max.apply(null, array)), 1)
   })
   return max
}

A: Here's how I would do it.
First, we'll get the longest sub-array by taking only the smallest elements out of the original, because that way the sum will be smallest possible as we go along. So:

const original = [3, 1, 2, 1];
const maxsum = 4;

// To make sure we take only the smallest, let's just
// sort the array straight away. That way the smallest
// element will always be the first.

// The .slice call is to make a copy, so we don't change
// the original:
const sorted = original.slice().sort();

// Here's your sum function. Looks legit.
function sumArray(a) {
    return a.reduce((a, b) => a + b, 0)
}

// Now take items from the front of the sorted array and
// put them in the new array until either the original is
// empty or the max is reached.
let subarray = [];
while (sorted.length) {
    // Get the next smallest element. It's always the
    // first one because of the sort.
    const smallest = sorted.shift();

    // If the sum of what we have plus this new element
    // is bigger than the max, our work is done:
    if (sumArray(subarray) + smallest > maxsum) break;

    // Otherwise, add it to our sub array and continue.
    subarray.push(smallest)
}

// Once that loop has run, either we ran out of elements,
// or we hit the max. Either way, our job is done.
console.log("Original array:", original);
console.log("Maximal subset:", subarray);
console.log("Maximal subset length:", subarray.length);

Finally, if you want to get fancy, you can even do this with a single .reduce call:

const original = [3, 1, 2, 1];
const maxsum = 4;

const maximalSubset = original.slice().sort().reduce((subset, current) => {
    if (subset.reduce((s, c) => s + c, 0) + current <= maxsum) subset.push(current);
    return subset;
}, []);

console.log("Orignal:", original);
console.log("Maximal subset:", maximalSubset);
console.log("Maximal subset length:", maximalSubset.length);

Although while shorter, that second snippet has the downside that we have to iterate the entire array before we get the result, whereas the first one will stop once the maximum is reached.
EDIT:
It turns out that the subarray needs to be a continuous piece of the original, so changing the order of the original won't work since we need to make sure the result is a continuous slice of the original.
To do that, instead, just check each subslice of the array, and keep the best one:

let original = [74,659,931,273,545,879,924,710,441,166,493,43,988,504,328,730,841,613,304,170,710,158,561,934,100,279,817,336,98,827,513,268,811,634,980,150,580,822,968,673,394,337,486,746,229,92,195,358,2,154,709,945,669,491,125,197,531,904,723,667,550];
const maxsum = 22337;

function arraySum(arr) {
    return arr.reduce((p, c) => p + c, 0);
}

// Double for loop will do the trick.
let bestSoFar = [];
for (let i = 0; i < original.length; i++) {
    for (let j = i+1; j < original.length; j++) {
        if (j-i > bestSoFar.length && arraySum(original.slice(i, j)) < maxsum) {
            bestSoFar = original.slice(i, j);
        }
    }
}

console.log("Longest continuous subarray is:", bestSoFar.length);

A: A brute force approach is likely the best solution to this problem. Start at each entry and see how far you can go before arriving at a sum > i and if it's better than the best you've seen so far save it. I provided a sample Java solution below, I haven't actually run it so one or two of my indices may be off but I think you can get the gist. Runtime is O(n^2), memory is O(n) (both occurring with, for example, #getMaxSubArray(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1000000))
private int[] getMaxSubArray(int[] a, int i) {
  int minIndex = 0;
  int maxIndex = -1;
  for (int j = 0; j < a.length; j+=1) {
    if (a[j] > i) {
      continue;
    }

    int sum = a[j];
    for (int k = j + 1; k < a.length; k++) {
      if (sum + a[k] > i) {
        if ((k - 1) - j > maxIndex - minIndex) {
          maxIndex = k - 1;
          minIndex = j;
        }
        break;
      }
      sum += a[k];
    }
  }

  if (maxIndex - minIndex < 0) {
    return null;
  }
  int[] result = new int[maxIndex - minIndex + 1];
  for (int p = minIndex; p <= maxIndex; p += 1) {
    result[p - minIndex] = a[p];
  }
  return result;
}

A: This is my solution. It will return the max length of the subarray. Can you please take a look, guys?
function maxLength(a, k) {
const sortedArray = a.sort((i,j) => i - j);
let sum = 0;
let length = 0;
const subArray = [];
for (let i=0; i < sortedArray.length; i++) {
   sum = sum + sortedArray[i];
   if (sum <= k) {
      length++;
      subArray.push(sortedArray[i]);
   } else {
       return length;
   }
}
return length;
}


text:
Q: error is preventing me from building an array of values I am receiving a parse error which is this:
Parse error: syntax error, unexpected T_VARIABLE in ... on line 91 which is this line:
$stmt->execute($parameters);

But what I want to know is what is causing this error from the code below and what do I need to change?
$parameters = array();

    $stmt=$mysqli->prepare($questionquery);
    $parameters[] = ($each)
    $stmt->execute($parameters);
    $stmt->bind_result($dbQuestionId,$dbQuestionContent,$dbOptionType,$dbNoofAnswers,$dbAnswer,$dbReplyType,$dbQuestionMarks);
    $questionnum = $stmt->num_rows();

A: You're missing a ; in the line before that.
 $parameters[] = ($each)

Should be
$parameters[] = ($each);


text:
Q: how to load images in a javascript variable locally I had help with this background carousel made with jquery for a website and it works just great.. except that i find that the page can take a while to load initially.. i thought that if i actually downloaded the pictures that i'm using for the background instead of loading them via 'http://www.whatever.jpg', that the page might load faster.. but i'm kind of a noob still.. and haven't been able to figure out why this isn't working.. Here is my code:
var images = [
//even though I downloaded the picture and its in the same folder as this file.js, the background just loads a black page, then the other 2 load fine.
"bg1-orig.jpg",
"http://www.desktopaper.com/wp-content/uploads/Cool-Hd-Wallpapers-2.jpg",
"http://wallpaperscraft.com/image/restaurant_table_interior_modern_style_39288_1920x1080.jpg"
];

var $body = $("body"),
$bg = $("#bg"),
n = images.length,
c = 0; // Loop Counter
num = 200;

// Preload Array of images...
for(var i=0; i<n; i++){
var tImg = new Image();
tImg.src = images[i];
}

$body.css({backgroundImage : "url("+images[c]+")"});

(function loopBg(){
  $bg.hide().css({backgroundImage : "url("+images[++c%n]+")"}).delay(7000).fadeTo(2200, 1,      function(){
$body.css({backgroundImage : "url("+images[c%n]+")"});
loopBg();
});
}());

i've searched around for a while now... thanks for the help!

A: You do yourself no favors trying to pre-load the images right before they are loaded for display in your CSS.  In either case, the images have to be loaded first before you can see them, so there is going to be a delay regardless.

A: If the only thing that you want to change is the src attribute of the imgs to be a local folder, then I assume the only change to otherwise working code is the strings in your images array point to local files.
If that's the case, and if you want to resolve the location correctly without adding some sort of directory changes (../, img/ or the like), then you will need those images to be in the same directory as the html file, not the file.js file.


text:
Q: Remove node from XML Document <Address>
    <value xsi:type="..." xmlns:ns3="..." xmlns:xsi="....">
        <item>
            <Country>USA</Country>
            <City>New York</City>
            <Street>Sunrise Av.</Street>
            <Number>164</Number>
        </item>
    </value>
</Address>
<University>
    <value xsi:type="..." xmlns:ns3="..." xmlns:xsi="....">
        <item>
            <Name>Cambridge</Name>
            <Location>UK</Location>
            <Department>IT</Department>
        </item>
    </value>
</University>
<Work>
    <value xsi:type="..." xmlns:ns3="..." xmlns:xsi="....">
</Work>

I have the above XML stored in a Java String. I want to remove the <value> tag from all of the nodes. Do you have any solution as to how I can do this?
The result that I want is as follows:
<Address>
    <item>
        <Country>USA</Country>
        <City>New York</City>
        <Street>Sunrise Av.</Street>
        <Number>164</Number>
    </item>
</Address>
<University>
    <item>
        <Name>Cambridge</Name>
        <Location>UK</Location>
        <Department>IT</Department>
    </item>
</University>
<Work>
</Work>

A: Below is a snippet based on XPath and VTD-XML
import com.ximpleware.*;
import java.io.*;
public class removeTag {
    public static void main(String[] args) throws VTDException,IOException {
        // TODO Auto-generated method stub
        VTDGen vg = new VTDGen();
        AutoPilot ap=new AutoPilot();
        ap.selectXPath("//value");
        XMLModifier xm = new XMLModifier();
        if (!vg.parseFile("d:\\xml\\tag.xml", false)){
            System.out.println("error in xml");
            return;
        }
        VTDNav vn = vg.getNav();
        xm.bind(vn);
        ap.bind(vn);
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.remove();//remove value fragment
            long l = vn.getContentFragment(); //replace value with everything it encloses
            xm.insertBeforeElement(vn.getXML().getBytes(), l);
        }
        xm.output("d:\\xml\\newTag.xml");
    }
}


text:
Q: Why doesn't the bundle install command work? $ bundle install

Traceback (most recent call last):
    2: from /usr/local/bin/bundle:23:in `<main>'
    1: from /usr/local/lib/site_ruby/2.5.0/rubygems.rb:308:in `activate_bin_path'
/usr/local/lib/site_ruby/2.5.0/rubygems.rb:289:in `find_spec_for_exe': can't find gem bundler (>= 0.a) with executable bundle (Gem::GemNotFoundException)

$ sudo gem update --system
Updating rubygems-update
Successfully installed rubygems-update-3.2.14
Parsing documentation for rubygems-update-3.2.14
Done installing documentation for rubygems-update after 0 seconds
Parsing documentation for rubygems-update-3.2.14
Done installing documentation for rubygems-update after 0 seconds
Installing RubyGems 3.2.14
Traceback (most recent call last):
    4: from setup.rb:23:in `<main>'
    3: from setup.rb:23:in `require'
    2: from /var/lib/gems/2.5.0/gems/rubygems-update-3.2.14/lib/rubygems.rb:1348:in `<top (required)>'
    1: from /var/lib/gems/2.5.0/gems/rubygems-update-3.2.14/lib/rubygems.rb:1348:in `require'
/usr/lib/ruby/vendor_ruby/rubygems/defaults/operating_system.rb:43:in `<top (required)>': uninitialized constant Gem::BasicSpecification (NameError)

A: Please try command. Thank you.
$ bundle update

A: $ bundle update

Traceback (most recent call last):
    2: from /usr/local/bin/bundle:23:in `<main>'
    1: from /usr/local/lib/site_ruby/2.5.0/rubygems.rb:308:in `activate_bin_path'
/usr/local/lib/site_ruby/2.5.0/rubygems.rb:289:in `find_spec_for_exe': can't find gem bundler (>= 0.a) with executable bundle (Gem::GemNotFoundException)


text:
Q: Is matrix polynomial of a self adjoint operator necessarily self adjoint?
Let $A$ be a self adjoint matrix on $\Bbb C^n$ and $p(x)$ be a non constant complex polynomial. Then can we say that $p(A)$ is also self adjoint?

I think the above is not necessarily true in general. For instance if I take the polynomial $p(x)=ix$. Then $p(A)=iA$. Then for any $x,y \in \Bbb C^n$ we have $\left <iAx,y \right >=i\left <Ax,y \right >$ whereas $\left <x,iAy \right >=-i\left <Ax,y \right >$. If $p(A)$ was self adjoint we should have $2i\left <Ax,y \right >=0$ for any $x,y \in \Bbb C^n$. In particular if we take $y=Ax$ then $\left <Ax,y \right > > 0$. But then we should have $2i=0$ which can't be true.

A: Your counterexample is O.K.
It is easy to se that if $A$ is self-adjoint and p is a complex polynomial, then $p(A)$ is normal.


text:
Q: How to aggregate from a snowflake pivot where keys have distinct value for each row? Using snowflake is it possible to pivot table as follows?
I.e. given table A:
+----+-----+-------+
| id | key | value |
+----+-----+-------+
|  1 | k1  |    11 |
|  1 | k2  |    12 |
|  2 | k1  |    21 |
|  2 | k2  |    22 |
|  3 | k2  |     3 |
+----+-----+-------+

returns:
+----+------+----+
| id |  k1  | k2 |
+----+------+----+
|  1 | 11   | 12 |
|  2 | 21   | 22 |
|  3 | null |  3 |
+----+------+----+

I suspect the query looks like the following but I am not sure how to aggregate:
select id, distinct(key)
  from table_a
    pivot table_a on value for value in distinct(key)
      as p
  order by id;

A: Just use conditional aggregation.  It is more flexible and lacks ideosynchracies:
select id,
       max(case when key = 'k1' then value end) as k1,
       max(case when key = 'k2' then value end) as k2
from t
group by id;


text:
Q: JBoss EAP7 server throws ClassNotFoundException:org.apache.commons.beanutils eventhough EAR contains beanutils.jar My Project structure is
  parent
     |---ejb-app.jar
     |---restapi-app.war
     |---ear-app.ear

I am using commons-beanutils to map the JavaEntity Bean to normal POJO class(DTO). The implementation of commons-beanutils is available inside ejb-app.jar.
Example: BeanUtils.copyProperties(destination, source);

My ear-app.ear aaplication packages the two modules such as ejb-app.jar & restapi-app.war. Below I have added pom.xml of ear-app.ear
 <?xml version="1.0" encoding="UTF-8"?>

    <parent>
        <groupId>migration</groupId>
    <artifactId>migration-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../migration-parent/pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <groupId>org.ear.app</groupId>
    <artifactId>ear-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>ear</packaging>

    <name>ear-app</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.ejb.app</groupId>
            <artifactId>ejb-app</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <type>ejb</type>
        </dependency>
        <dependency>
            <groupId>org.restapi.app</groupId>
            <artifactId>restapi-app</artifactId>

            <version>0.0.1-SNAPSHOT</version>
            <type>war</type>
        </dependency>
   <dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.2.redhat-1</version>
</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.10.1</version>
                <configuration>
                    <modules>
                        <ejbModule>
                            <groupId>org.ear.app</groupId>
                            <artifactId>ear-app</artifactId>
                            <bundleFileName>ejb-app-0.0.1-SNAPSHOT.jar</bundleFileName>
                        </ejbModule>
                        <webModule>
                            <groupId>org.restapi.app</groupId>
                            <artifactId>restapi-app</artifactId>
                            <contextRoot>/</contextRoot>
                        </webModule>
                    </modules>
                </configuration>

            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>

                </configuration>
            </plugin>

            <!-- WildFly plug-in to deploy EAR -->
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <configuration>
                    <skip>false</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Problem:
When I deploy my aaplication in RedHat JBoss EAP7 server, I am getting the following error:
Caused by: java.lang.ClassNotFoundException: org.apache.commons.beanutils.BeanUtils from [Module "deployment.ear-app-0.0.1-SNAPSHOT.ear.ejb-app-0.0.1-SNAPSHOT.jar:main" from Service Module Loader]


text:
Q: Errors in microcontroller delay routine I have an issue with a delay routine that I am writing for use on a PIC32, the PIC32MX664F128H in particular.
I have two separate delay functions, which use the same lower-level delay routine: one for a millisecond delay and another for a microsecond delay. Below follows the code for each function:
void TIMER_DelayMillisec(unsigned int duration)
{
    unsigned int timerCount;

    /* Timer counter for 1 millisecond delay */
    timerCount = (MILLISECOND * systemClock);

    /* Run the timer routine */
    timerRoutine(duration, timerCount);
} /* TIMER_DelayMillisec() */

and...
void TIMER_DelayMicrosec(unsigned int duration)
{
    unsigned int timerCount;

    /* Timer counter for 1 microsecond delay */
    timerCount = (MICROSECOND * systemClock);

    /* Run the timer routine */
    timerRoutine(duration, timerCount);
} /* TIMER_DelayMicrosec() */

In the above two functions, the values for the defines are MILLISECOND = 0.001 and MICROSECOND = 0.000001. The variable "systemClock" gets initialized on startup. In this particular case, this value is 80 000 000 (for 80 MHz). Below follows the code for the lower-level delay routine:
static void timerRoutine(unsigned int duration,
                         unsigned int timerCount)
{
    unsigned int divCount = 2u;

    /* If the timer counter is less than 1, round it up to the nearest integer,
     * i.e. 1 */
    if (timerCount < 1)
    {
        timerCount = 1;
    } /* if */

    /* If the timerCount value is larger than 0xFFFF,
     * divide the value by 2 until it is within this range. */
    if (timerCount > 0xFFFF)
    {
        timerCount = timerCount / divCount;
        duration = duration * divCount;
    }

    /* Set the PR register to the max value */
    PR1 = 0xFFFF;

    /* Enable the timer */
    T1CONbits.ON = 1;
    TMR1 = 0u;

    /* Loop the amount of times required for the delay */
    while(duration > 0)
    {
        /* Wait until timer reaches the required value */
        while(TMR1 < timerCount);
        duration--;

        /* Reset timer */
        TMR1 = 0u;
    } /* while */

    /* Disable the timer */
    T1CONbits.ON = 0;
} /* timerRoutine() */

Some explanation on the above routine: The delay routine uses the PIC32's Timer1 (which is a 16-bit timer). The TMR1 register gets incremented with each tick of the peripheral bus clock (PBCLK), which is set to 80 MHz. Therefore, the period of one clock tick is:
$$T_{PBCLK} = 1/f_{PBCLK} = 1/80 MHz$$
For example, for a 1 millisecond delay, the equivalent amount of clock ticks would then be:
$$ timerCount = (1 sec/1000 millisec) / T_{PBCLK} $$
thus, $$ timerCount  = 0.001 / T_{PBCLK} = 0.001 * f_{PBCLK}$$
$$ timerCount = MILLISECOND * f_{PBCLK}$$
Therefore, timerCount is the amount of clock ticks for the "unit" time delay (of either a millisecond or microsecond). The timerRoutine() function then uses this value of timerCount to perform the delay by comparing the TMR1 register against this value. When the TMR1 register value reaches the value of timerCount, the correct amount of time for the "unit" delay has passed, and the TMR1 register is re-initialized. The total duration, denoted by the variable duration is obtained by repeating this loop for duration amount of times. The part where the values of timerCount and duration are manipulated (by division and multiplication, respectively), is there for when the value of timerCount exceeds the maximum 16-bit value (of 0xFFFF) for long delays. The values of these two variables are adjusted accordingly.
These routines are tested by toggling one of the PIC32's I/O pins at a specified rate, which is obtained by calling the particular delay function in-between the changing of the I/O pin states, and then measuring the actual time difference between the I/O pin states:
unsigned int delay = 1u;
while (TRUE)
{
    IOPin = HIGH;
    TIMER_DelayMillisec(delay);
    IOPin = LOW;
    TIMER_DelayMillisec(delay);
}

The same concept is used to test the microsecond delay routine, by calling TIMER_DelayMicrosec() instead of TIMER_DelayMillisec() with the required delay value.
Herewith follows some test results. First, the millisecond delay routine is tested.
For 1 millisecond:

For 5 milliseconds:

It can be seen from the above two images that the delay routine for the millisecond delay function is essentially spot-on, with equal delay between the HIGH and LOW pulses.
However, something totally different happens for the microsecond delay function.
For 1000 microseconds (which should equal 1 millisecond as above):

For 500 microseconds:

For 250 microseconds:

For 100 microseconds:

As can be seen from the above images for the microsecond delay function, there is a difference between the delay time of the HIGH and LOW pulses, with the delay from the ON-to-OFF pulse being significantly higher than the delay from the OFF-to-ON pulse. Furthermore, this effect gets more prominent as the delay time decreases.
Considering that, for example, for a delay of 1 millisecond, the delay loop for the millisecond delay routine executes exactly the same amount of times as for the microsecond delay routine for a delay of 1000 microseconds. Therefore, the actual delay times should be equal.
The only thing that comes to mind that could cause this variance in actual delay times is the amount of overhead during the whole of the delay routine. Consequently, the expected "drifting" effect should have been worse for the millisecond delay routine than for the microsecond delay routine, since it involves more iterations of the delay loop for a longer delay. However, rather counter-intuitively, the observed results point to the exact opposite, which indicates that there is probably something else causing the "drifting" effect.
What could be happening here and how can this be fixed?
UPDATE:
Through further thorough investigation I have found the problem. Perhaps I should've mentioned it from the very start, but the particular I/O pin that I used for this testing is optically isolated (due to the nature of the application). Probing the PIC's I/O pin directly yielded perfect square waves for my delay test values. My measurements were all at the output of the optocoupler. The problem is undoubtedly due to the optocoupler's switching characteristics, and is thus not software related.
Nevertheless, thank you to those who have made suggestions in improving the delay routine. These suggestions will certainly be considered.

A: Through further thorough investigation I have found the problem. Perhaps I should've mentioned it from the very start, but the particular I/O pin that I used for this testing is optically isolated (due to the nature of the application). Probing the PIC's I/O pin directly yielded perfect square waves for my delay test values. My measurements were all at the output of the optocoupler, where the peculiar results were obtained from. The problem is undoubtedly due to the optocoupler's switching characteristics, and is thus not software related.
Nevertheless, thank you to those who have made suggestions in improving the delay routine. These suggestions will certainly be considered.
UPDATE (for the curious-minded):
Herewith follows the output of the PIC's I/O (green signal) vs. the optocoupler output (yellow signal):

It can be clearly seen that the optocoupler has a turn OFF-time of about 56 microseconds - almost right on par with what the datasheet says (typ. 40 microseconds)! This is one of the reasons why the timing overall looked inaccurate. Furthermore, the phenomenon of the "drifting" effect that worsens with shorter delays, is due to the fact that the optocoupler output still takes about 56 microseconds to turn off, regardless of the delay length. By the time that the optocoupler output reaches the OFF state, the next ON-pulse seems to occur earlier than it should, when in actual fact the optocoupler output turned off later than it should.
ALWAYS read the datasheet!


text:
Q: Node.js fs.readdir, fs.stat I'm working through some tutorials and cannot understand why this line "self.only_dirs.push(files[i]);" is causing an error about it being 'undefined'.  This must be a variable scope problem but nothing I have tried has worked.  How to do I need to declare variables so that these embedded callback functions recognize them?

function load_album_list(callback, callback2)
{
 var self = this;
 fs.readdir
 (
  'albums',
  function (err, files)
  {
   if(err)
   {
    callback(err, null);
    return;
   }

   var only_dirs = [];
   var remaining = files.length;
   for (var i = 0; i < files.length; i++)
   {

    fs.stat("albums/" + files[i],
      function(err, stats)
      {
       if(stats.isDirectory())
       {
        self.only_dirs.push(files[i]);
       }
       console.log("remaining: " + self.remaining);
       self.remaining -= 1;
       if (self.remaining == 0)
        callback(null, self.only_dirs);
      }
     );

   }

   callback(null, only_dirs);
  }
 );
}

A:

function load_album_list(callback, callback2)
{
 var self = this;
    self.only_dirs = []; //<----- declare only_dirs in this scope
 fs.readdir
 (
  'albums',
  function (err, files)
  {
   if(err)
   {
    callback(err, null);
    return;
   }

   //var only_dirs = []; <--- remove this reference
   var remaining = files.length;
   for (var i = 0; i < files.length; i++)
   {

    fs.stat("albums/" + files[i],
      function(err, stats)
      {
       if(stats.isDirectory())
       {
        self.only_dirs.push(files[i]);
       }
       console.log("remaining: " + self.remaining);
       self.remaining -= 1;
       if (self.remaining == 0)
        callback(null, self.only_dirs);
      }
     );

   }

   callback(null, self.only_dirs);
  }
 );
}


text:
Q: Watson Conversation autogenerate Android app - 'Unknown pattern character 'X'' I'm using the auto generated example from IBM Watson Mobile App, but when i tried to run it, it shows an error in the following part of code. I found similar errors around SO, but i think this is another one different.
public ServiceCall<MessageResponse> message(String workspaceId, MessageRequest request) {
Validator.isTrue((workspaceId != null) && !workspaceId.isEmpty(), "'workspaceId' cannot be null or empty");

RequestBuilder builder = RequestBuilder.post(String.format(PATH_MESSAGE, workspaceId));
builder.query(VERSION_PARAM, versionDate);
if (request != null) {
  //the error shows here
  builder.bodyJson(GsonSingleton.getGson().toJsonTree(request).getAsJsonObject());
} else {
  builder.bodyJson(new JsonObject());
}
return createServiceCall(builder.build(), ResponseConverterUtils.getObject(MessageResponse.class));
}

The following is my build.gradle file:
apply plugin:'base'
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.ibm.watson_conversation"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        manifestPlaceholders = ['appIdRedirectScheme': android.defaultConfig.applicationId]
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        warning 'InvalidPackage'
        abortOnError false
    }
}

dependencies {
    compile ('com.ibm.mobilefirstplatform.clientsdk.android:core:[2.0.0,3.0.0)')
    compile 'com.ibm.watson.developer_cloud:conversation:3.8.0'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
}

A: The issue was fixed in 3.9.0.
You just need to update the dependency version to be 3.9.1:
compile 'com.ibm.watson.developer_cloud:conversation:3.9.1'


text:
Q: GO-QT Binding g++: error: unrecognized command line option '-marm' I am using QT Binding/Wrapper for Go in my project. Project is compiling fine for amd64 but when I try to compile project for arm devices, it gives me below error
 github.com/therecipe/qt/core
# github.com/therecipe/qt/core
 g++: error: unrecognized command line option '-marm'

Please find below my go environment variables setup
GOARCH="arm"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/minhaj/GoLang"
GORACE=""
GOROOT="/usr/local/go"
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
GOARM=""
CC="arm-linux-gnueabi-gcc"
GOGCCFLAGS="-fPIC -marm -pthread -fmessage-length=0 -fdebug-prefix-
 map=/tmp/go-build277718108=/tmp/go-build -gno-record-gcc-switches"
CXX="g++"
CGO_ENABLED="1"
PKG_CONFIG="pkg-config"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"


text:
Q: asp:Listbox needs to fire an event OnMouseDoubleClick - ASP.NET Framework 4 The project I am working on is in ASP.NET 4. With 4.5, the regular ListBox has an attribute called OnMouseDoubleClick. I was wondering what would be the best way to emulate this functionality using an asp:ListBox in ASP.Net 4.

A: The following link really helped me: How to add Double Click mouse event to listbox? After finding it, I rewrote the C# code in VB.net.
.aspx file:
<asp:ListBox ID="hiddenColumns" runat="server" ondblclick="hiddenColumns_DoubleClick()"></asp:ListBox>
<script type="text/javascript">
    function hiddenColumns_DoubleClick() {
        document.forms[0].hiddenHidden.value = "doubleclicked"
        document.forms[0].submit()
    }
</script>
<input type="hidden" name="hiddenHidden" />

.aspx.vb file:
If Not Request.Params("hiddenHidden") Is Nothing And Request.Params("hiddenHidden") = "doubleclicked" Then
    'Desired actions here
End If


text:
Q: Cancel form closing by user selection In a vb.net windows application, I need user to confirm before closing application. I have this code in FormClosing event
If BackgroundWorker1.IsBusy Then
    Dim UserSelection As Integer = MsgBox("Do you want Cancel Processing and Exit Application?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo, "Exit Application")
    If UserSelection = 6 Then
        BackgroundWorker1.CancelAsync()
        e.Cancel = True
    Else
        ????
    End If
End If

How can I cancel form closing if user clicked No?
Tried e.Cancel = false but it didn't work (exits application).

A: e.Cancel = True would stop the form closing.

A: According to documentation "e.Cancel = True" PREVENTS the form from closing

A: This is full code for cancel form closed. We should use FormClosing Event.
Private Sub Frm1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If MessageBox.Show("Do you want to closed", Me.Text, MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.Cancel Then
            e.Cancel = True
        End If
    End Sub


text:
Q: Enumerable Objects (key value maps) in Ember.js Is there a key value object in Ember that supports Ember.Array / Ember.Enumerable?
I would like to iterate over them with {{#each}} in my Handlebars templates.
My use case is displaying arbitrary JSON (user define fields) from the server (example given below). I can recursively create views from nested arrays (using the each helper) but I can't iterate over an object. My plan is to find (or write) an object that will wrap JSON objects and allow them to be enumerable. What would be the best way to go about doing this?
My idea so far is so combination of  extending/mixing Enumerable/Array/ArrayProxy/ObjectProxy, storing the underlying key-value store as an Ember.Array, and adding a keys field to store the keys for the object. I can then use setUnknownProperty and unknownProperty to set/get the underlying value and keep the keys in sync. Is this approach sound?
Format of JSON from the server
Here's an example (user documents their own workout data). Note that this is just one example; the format is entirely flexible, so I can't create Ember-data models to model these user defined fields. Overall, the data can be arbitrarily complex JSON (any degree of nesting of hashes, arrays, primitives)
{
   "bench_press":[
      {
         "weight":95,
         "repetitions":5,
         "tags":[
            "warmup"
         ]
      },
      {
         "weight":135,
         "repetitions":3,
         "tags":[
            "warmup"
         ]
      },
      {
         "weight":155,
         "repetitions":3,
         "tags":[
            "warmup"
         ]
      },
      {
         "weight":165,
         "repetitions":2,
         "tags":[
            "warmup"
         ]
      },
      {
         "weight":185,
         "repetitions":1,
         "tags":[
            "warmup"
         ]
      },
      {
         "weight":195,
         "repetitions":1,
         "tags":[
            "warmup",
            "overshoot"
         ]
      },
      {
         "weight":190,
         "repetitions":5,
         "tags":[

         ]
      },
      {
         "weight":190,
         "repetitions":5,
         "tags":[

         ]
      },
      {
         "weight":190,
         "repetitions":5,
         "tags":[

         ]
      },
      {
         "weight":190,
         "repetitions":3,
         "tags":[

         ]
      },
      {
         "weight":190,
         "repetitions":2,
         "tags":[
            "negatives"
         ]
      }
   ]
}

A: As far as I get Ember.js philosophy, declarative Handlebars templates are conservative enough to emphasize using less logic in your templates.
In the above case I suggest you using ContainerView providing JSON as a context for it.


text:
Q: How do you search through a map? I have a map:
Map<String, String> ht = new HashMap();

and I would like to know how to search through it and find anything matching a particular string.  And if it is a match store it into an arraylist.  The map contains strings like this:
1,2,3,4,5,5,5
and the matching string would be 5.
So for I have this:
  String match = "5";
  ArrayList<String> result = new ArrayList<String>();

 Enumeration num= ht.keys();
     while (num.hasMoreElements()) {
        String number = (String) num.nextElement();

        if(number.equals(match))
        {
           result.add(number);
        }

     }

A: Not quite sure if I understand you, but I guess you are looking for containsKey?
ht.containsKey("5");

A: I am guessing you want to find keys from values.
Simple code:
List<String> matches = new ArrayList<String>();
for (Map.Entry<String,String> entry : map.keys()) {
    if (targetValue.equals(entry.getValue())) {
        matches.add(entry.getKey());
    }
}

Better perhaps would be to use a second map for the reverse mapping, or a bidirectional map from a third-party library.

A: Apparently you are trying to find in values. So here is something that would work:
Map<String, String> m = new HashMap<String, String>();
..

List<String> result = new ArrayList<String>();
    for(String s: m.values()){
        if(s.equals("5")){
            result.add(s);
        }
    }

Also, watch for nulls in your if statement.

A: Map API does not encourage you to use Enumeration any more as its a pretty old interface and was expected to be replaced by COllection interfaces, but legacy is still a concern.
KeySet method returns you a Set back and you can directly use contains method of set for the comparison


text:
Q: how do i keep the active image center in the slick slider? I have a slick slider with the image and some text. The image is positioned and the the first image is centered but the next images are slowly moving towards the left side.How do i keep every active images centered aligned?By the way there must showing only two images in the slider and one text for the active images.Here is the link:-http://165.22.181.70/test-8/ ,Please look at the client testimonials section.(P.S :- Only three images at a time should be shown in the carousel). Please help.

jQuery('.slider-for').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  arrows: false,
  fade: true,
  asNavFor: '.slider-nav'
});
jQuery('.slider-nav').slick({
  slidesToShow: 2,
  slidesToScroll: 1,
  asNavFor: '.slider-for',
  dots: true,
  centerMode: true,
  focusOnSelect: true
});
.testimonials .slider-nav .slick-slide {
  width: 150px !important;
  margin: 8px 2.4em;
}

.slider-nav {
  width: 600px;
  margin: 0 auto;
  display: block;
  max-width: 100%;
}

.testimonials .slider-nav .slider-img {
  border-radius: 50%;
  border: 1px solid transparent;
}

.testimonials .slick-prev,
.testimonials .slick-next {
  display: none !important;
}

.testimonials .slick-dots {
  bottom: -219px !important;
}

.testimonials .slider-nav .slick-current .slider-img {
  border: 3px solid #00c590;
  transform: scale(1.1);
}

.testimonials .slider-for {
  text-align: center;
}

.testimonials .slick-dots li {
  width: 20px;
  border: 1px solid transparent;
  border-radius: 50%;
  height: 20px;
}

.testimonials .slick-dots .slick-active {
  width: 20px;
  border: 1px solid #bf9b30;
  border-radius: 50%;
  height: 20px;
}

.testimonials .slide-text p {
  width: 1000px;
  max-width: 100%;
  margin: 0 auto;
}

.testimonials .slick-dots li button {
  width: 10px;
  background: #d5d5d5 !important;
  border-radius: 50%;
  height: 10px;
  position: absolute;
  top: 4px;
  left: 4px;
}

.testimonials .slick-dots .slick-active button {
  width: 10px;
  background: #bf9b30 !important;
  border-radius: 50%;
  height: 10px;
  position: absolute;
  top: 4px;
  left: 4px;
}

* {
  box-sizing: border-box;
}

.slider {
  width: 50%;
  margin: 100px auto;
}

.slick-slide {
  margin: 0px 20px;
}

.slick-slide img {
  width: 100%;
}

.slick-prev:before,
.slick-next:before {
  color: black;
}

.slick-slide {
  transition: all ease-in-out .3s;
  opacity: .2;
}

.slick-active {
  opacity: .5;
}

.slick-current {
  opacity: 1;
}

        <img src="<?php echo get_stylesheet_directory_uri();?>/images/girl2.png" class="slider-img">

        <img src="<?php echo get_stylesheet_directory_uri();?>/images/girl2.png" class="slider-img">

        <img src="<?php echo get_stylesheet_directory_uri();?>/images/girl2.png" class="slider-img">

        <img src="<?php echo get_stylesheet_directory_uri();?>/images/girl2.png" class="slider-img">

        <img src="<?php echo get_stylesheet_directory_uri();?>/images/girl2.png" class="slider-img">

"Magellan Consulting Group helped us to realize our potential of production capacity. With the same number of employees, last month we were able to increase production by 14% compared to our previous production record. This performance should
          be our reference moving forward, so we can meet our budget objectives."

Supply Chain Manager

"This performance should be our reference moving forward, so we can meet our budget objectives"

Supply Chain Manager

"Magellan Consulting Group helped us to realize our potential of production capacity. With the same number of employees, last month we were able to increase production by 14% compared to our previous production record. This performance should
          be our reference moving forward, so we can meet our budget objectives."

Supply Chain Manager

"With the same number of employees, last month we were able to increase production by 14% compared to our previous production record."

Supply Chain Manager

"With the same number of employees, last month we were able to increase production by 14% compared to our previous production record."

Supply Chain Manager

A: Center mode work well with odd number. Use with odd numbered slidesToShow counts.


text:
Q: I need to rotate (scroll) images using the galleria module I am using galleria & jCarousel and need to have the slideshow scroll through the images. Does anyone know a simple javascript that I can use for that?

A: Never mind I figured it out... with a simple javascript...
$(function(){
var slideshow,
    slideshowPause =  5 //seconds
        $('#slideshow').fadeIn()
        slideshow = window.setInterval(function(){
            $.galleria.next()
    }, slideshowPause * 1000)
});

A: As far as I'm concerned, there's nothing better than jQuery Tools Scrollable:
http://flowplayer.org/tools/demos/scrollable/index.html


text:
Q: If $R$ is a right-Noetherian ring and the Jacobson radical satisfies the right Artin-Rees property, then $\bigcap^{\infty}_{n=1}\text{Jac}(R)^n = 0$ A (two-sided) ideal $I$ of a ring with identity $R$ has the right Artin-Rees property if for any right-ideal $E$ of $R$, there exists an integer $n\geq1$ such that $E\cap I^n\subseteq EI$.

If $R$ is a right-Noetherian ring and the Jacobson radical $\text{Jac}(R)$ satisfies the right Artin-Rees property, then $\bigcap^{\infty}_{n=1}\text{Jac}(R)^n = 0$.

I've somehow proved this without the Noetherian property, so my proof most likely is wrong.
Let $J:=\bigcap^{\infty}_{n=1}\text{Jac}(R)^n$ and suppose $J\not= 0$. Let $x\in J\setminus 0$ and consider the right ideal $xR$. By assumption, we have that $xR \cap \text{Jac}(R)^k \subseteq xR\cdot\text{Jac}(R)$ for some $k$. But $xR\subseteq J\subseteq \text{Jac}(R)^k$ so we get that $xR\subseteq x\text{Jac}(R)$.
Therefore, since $1\in R$, we have that $x=xj$ for some $j\in\text{Jac}(R)$. As the Jacobson radical is right-quasi-regular, $1-j$ has a right inverse $y$. In particular, $x(1-j)=0$ and hence $x(1-j)y=x=0$, contradicting the assumption $x\not=0$.
Is this correct? What is missing?

A: I guess your teacher was thinking to Nakayama's lemma. By assumption, there exists $n$ such that
$$
J\cap (\operatorname{Jac}(R))^n\subseteq J\operatorname{Jac}(R)
$$
On the other hand, $J=J\cap (\operatorname{Jac}(R))^n$ and $J\operatorname{Jac}(R)\subseteq J$, so we conclude
$$
J\operatorname{Jac}(R)=J
$$
Since $J$ is finitely generated, because $R$ is right Noetherian, we have $J=0$ by Nakayama's lemma.
You showed instead that every cyclic submodule of $J$ is zero (using an abridged version of Nakayama's lemma) and the proof is correct. So the hypothesis that $R$ is right Noetherian can be removed.


text:
Q: Data mask and other HTML features are not applying on input field with Django Forms I am using Django forms to apply some basic html feature such as data mask and input pattern. Below is the code on the forms.py for one of the input fields.
'contact_person' : forms.TextInput(
                attrs={'class':'form-control capitalize','pattern':'[a-zA-Z]*'}),

or data mask
'primary_phone_no' : forms.TextInput(
                attrs={'class':'form-control','data-mask':"000 000 000"}),

Once I make the changes and see the changes on the browser, inspect element and locate that field, I can clearly see the changes had been applied on the HTML but when I put the input I see no changes has taken place. Means nor of the feature such as datamask or pattern is happening.
Its a very strange thing I am facing. Did someone came across this and is there something am I missing?
Thank you

A: It might be related to the order of where you set the widget settings. This works:
class MyForm(forms.Form):
    contact_person = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control capitalize',
        'pattern': '[a-zA-Z]*'
    }))
    primary_phone_no = forms.CharField(widget=forms.TextInput(attrs={
        'class': 'form-control',
        'data-mask': '000 000 000'
    }))


text:
Q: Cypress web sockets error: 'Sec-WebSocket-Accept' header is missing I am trying to test a VueJs application with Cypress.
Everything works well except the websocket connection that fails with the message:
Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing
On dev or deployed, it works without issue and the 'Sec-WebSocket-Accept' header is present but no clue why it fails with Cypress.
Any idea?


text:
Q: remove an element from list object I have a List object which holds 10 elements, i have to do conditional check and remove some of the elements from the list. I have done as below, but it is not working as expected, any inputs?
List<MyDTO> myList = new ArrayList<MyDTO>(); //myist.size () is 10

I want to check as below:
for(MyDTO res : myList){
    if(res.getResult().equals("cancel")){
     myList.remove()
  }
}

As shown in above code, if res.getResult() is "cancel" i want to remove that particular object from the list(myList). Is it the correct way to remove an element completely from list based on conditional check?

A: Simply use removeIf on your list, for example if you had list of Integers ranging from 1 to 10 and you wanted to remove Integers larger than 4, you would do:
yourListHere.removeIf(x -> x > 4);

Resulting list would contain: 1, 2, 3 and 4
Read here about removeIf:
https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-
BONUS
Additional resources if you are unfamiliar with Java 8 features:
Lambdas - https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Functional Interfaces - https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

A: As an alternative to removeIf you can use the Java stream solution:
List<MyDTO> newList = myList.stream()
                            .filter(s -> !s.getResult().equals("cancel"))
                            .collect(Collectors.toList());

This might be more convenient when the length of the input list and the number of elements to remove is relatively large.

A: Use removeIf:
default boolean removeIf(Predicate<? super E> filter)

Removes all of the elements of this collection that satisfy the given
  predicate. Errors or runtime exceptions thrown during iteration or by
  the predicate are relayed to the caller.

In your example:
myList.removeIf(res -> res.getResult().equals("cancel"));

A: If use Java 8:
myList.removeIf(x -> x.getResult().equals("cancel"));

If older (6,7):
public class MyDTO {

    private String result;
    (...)

    public MyDTO(String result) {
        this.result = result;
    }

    public String getResult() {
        return result;
    }

    (...)

    @Override
    public int hashCode() {
        return 31;
    }

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

        return !((this.result == null) ? (other.result != null) : !this.result.equals(other.result));
    }

    (...)

}

then:
MyDTO toRemove = new MyDTO("cancel");

while(myList.contains(toRemove))
    myList.remove(toRemove);

or:
List<MyDTO> toRemove = new ArrayList<MyDTO>();

for(MyDTO res : myList){
    if(res.getResult().equals("cancel")){
     toRemove.add(res);
  }
}
myList.removeAll(toRemove);

Without overriding the equals method:
for(int i = 0; i < myList.size() ; i++)
    if(myList.get(i).getResult().equals("cancel"))
       myList.remove(i);

or:
Iterator<MyDTO> i = myList.iterator();

while (i.hasNext())
    if(i.next().getResult().equals("cancel"))
         i.remove();


text:
Q: iOS custom framework run time showing Symbol not found: I added swifty tesseract to one of my custom framework using pod. Created a pod spec and uploaded it in one location.
Now i created a dummy app and tried to pull my custom framework from that particular location and am getting following run time error
dyld: Symbol not found: _$s15SwiftyTesseract10EngineModeO21tesseractLstmCombinedyA2CmFWC

  Referenced from: /private/var/containers/Bundle/Application/601F5612-4BCB-456D-BCCF-71AC522668D5/DemoApp.app/Frameworks/custom.framework/custom

  Expected in:
  /private/var/containers/Bundle/Application/601F5612-4BCB-456D-BCCF-71AC522668D5/DemoApp.app/Frameworks/SwiftyTesseract.framework/SwiftyTesseract

 in

 /private/var/containers/Bundle/Application/601F5612-4BCB-456D-BCCF-71AC522668D5/DemoApp.app/Frameworks/custom.framework/custom

dyld: launch, loading dependent libraries
DYLD_LIBRARY_PATH=/usr/lib/system/introspection
DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib

Can anyone help me with what is this error ? iam not understanding the issue


text:
Q: Multiple versions of a project in the same solution? I have a  product with a few clients. Currently this product is the same for all of them in terms of look and functionality.I need to implement a few new features called the beta features and make them available to only a few of my clients, rest of the clients will be using the older version and their maintenance requests will be done too. I don't want to duplicate the entire solution for this. What is the best approach for this problem ?. Is maintaining solution with visual studio configuration manager and #if   the only way ?

A: If beta-features are planned to roll out finally to all customers this sounds like version control branching issue.  With modern Version Control System like Git you can create beta branches to handle different development paths.
While your master development branch goes on during maintenance, you can make feature branches where you implement beta-features to certain customers and finally merge them to master branch.
If you try handle this issue in single branch by #iffing your source-code, you have chosen complex path which is error-prone and difficult to scale up.


text:
Q: Linq to objects using 'not exists' and 'group by'? I've been assigned a new project at work which uses NHibernate. A query that I can easily write in sql has me totally stumped on how to do it in linq, which is how I've been told to do it.
So, here's the query:
select  ts.BatchID, COUNT(distinct ts.UniqID) SurveyCount
from    TeleformStaging.TeleformStaging ts
where   ts.IsRescan = 0
and     not exists (select  bfr.BatchID
                    from    TeleformStaging.BatchesForRescan bfr
                    where   bfr.BatchTrack = ts.BatchID)
group by ts.BatchID
order by ts.BatchID

I believe I could get the 'group by' portion, but no idea on the subquery.
Thanks for any advice...

A: Maybe something like this:
var result= (
        from ts in db.TeleformStaging
        where ts.IsRescan == false //if is a boolean else == 0
        &&
        !(
            from bfr in db.BatchesForRescan
            select bfr.BatchTrack
        ).Contains(ts.BatchID)
        orderby ts.BatchID
        group ts by ts.BatchID into g
        select new
        {
            BatchID=g.Key,
            SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
        }
    );

where db is the linq data context
Edit
You could also do it with .Any(). Like this:
var result= (
        from ts in db.TeleformStaging
        where ts.IsRescan == false //if is a boolean else == 0
        &&
        !(
            from bfr in db.BatchesForRescan
            where ts.BatchID==bfr.BatchTrack
            select bfr.BatchTrack
        ).Any()
        orderby ts.BatchID
        group ts by ts.BatchID into g
        select new
        {
            BatchID=g.Key,
            SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
        }
    );

Edit 1
Useful links:

*

*Contains

*Any

*Simple group by

*Basic LINQ Query Operations (C#)

*Order by

A: from fs in context.TeleformStaging
where !ts.IsRescan && !context.BatchesForRescan.Any(bfr=>bfr.BatchTrack == ts.BatchID)
group ts by ts.BatchID into g
    select new
    {
        BatchID=g.Key,
        SurveyCount=g.Select (x =>x.UniqID).Distinct().Count()
    }

with group by

A: LINQ is slightly reversed, but does offer the complexity with a few lambda expressions; how does this look:
var result = from ts in TeleformStaging.TeleformStaging
                where !ts.IsRescan && !TeleformStaging.BatchesForRescan.Any(bfr => bfr.BatchID == ts.BatchID)
                group ts by ts.BatchID into tsGrouped
                orderby tsGrouped.Key
                select new
                {
                    BatchId = tsGrouped.Key,
                    SurveyCount = tsGrouped.Select(x => x.UniqID).Distinct().Count()
                };


text:
Q: Most Efficient way to get the  of a URL? It's simple to do a webrequest, get the page and parse the html to get the title of the page.
But I'm wondering if there is a more efficient way that is faster, and doesn't require downloading the whole html?

A: One of the ways is to write a custom parser which immediately aborts parsing and closes the connection when the </title> has been passed in the stream. You'll only need to ensure that the code doesn't buffer the entire stream in memory beforehand.

A: Unless the author has added some kind of x-title header, you will have to stream the html to at least the title tag.


text:
Q: Bash scripting variable not populating I made a simple script to guess the word for wordle using letter elimination. This script works perfects on my Zorin OS laptop but when I try it on an Ubuntu 20.04 server it fails.  As near as I can tell the its failing because a variable isn't getting populated in Ubuntu when it does in Zorin.
echo "Enter ther letters to eliminate."
read Eletters
echo $Eletters >> /tmp/letters.txt
echo "Eliminated Letters"
tr -d '\n' < /tmp/letters.txt | tee /tmp/letters.txt
EL=$(cat /tmp/letters.txt)
grep -Evi "([$EL])" /tmp/wordleguesses.txt > /tmp/wordleguesses2.txt

If I do an echo $EL I get nothing in Ubuntu but in Zorin I get the letters stored in /tmp/letters.txt.
I'm not sure why Ubuntu doesn't accept this. Can anyone help?


text:
Q: Error parsing media type '*; charset=UTF-8' when try to getType() Im doing a REST call with jersey but the response media type is '*; charset=UTF-8', what throws a exception when I try response.getEntity(String.class);"
ps:. the response status is 200.
     ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        WebResource webResource = client
                 .resource("http://" + server);
    String inf = "username=" + user + "&target_site=" + targetSite;
    ClientResponse response = webResource.type("text/plain; charset=UTF-8")
                .post(ClientResponse.class, inf);

I simulate the same call with curl and I could see "Content-Type: *; charset=UTF-8"
Any idea what I need to do?
UPDATE1
I tryed configure a filter like this below, but the exception still happen
client.addFilter(new ClientFilter() {
    @Override
    public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
        request.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, "application/json");
        return getNext().handle(request);
    }
});

I realize that the exception happen within getType() method. It seems that the content type needed to be "*/*; charset=UTF-8", and not just "*; charset=UTF-8"


text:
Q: I want initialize two variables to a 2d Array in C language I am trying to initialize a 2D array to two variable values but it's giving me an error, Maybe I am not initializing it right line number 15 is where I am getting the error.
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  int r, i,j,l[i][j],M = 18, Ma = 30, array[7][2];
  srand (time(NULL));

  for(i=0; i < 7 ; i++)
  {
  for (int j=0; j<2;j++)
  { int x=Ma + rand() / (RAND_MAX / (M - Ma + 1) + 1);
    int y=rand() % 10 + 1;
    l[i][j]={x,y};
    array[i][j] = l[i][j];
    printf("%d\t",array[i][j]);
  }
  printf("\n");

  }
  printf("\n") ;
  return 0;;
}

A: in initialization you can't write variables so in place of l[i][j] mention l[10][10] then error will not occur.