text:
Q: dismissViewControllerAnimated called from a UIAlertController sends me to the RootViewController I've been trying to dismiss my alert view by calling dismissViewControllerAnimated but unfortunately I'm not getting what I want since it sends me to the rooviewController ("UsersSwippingViewControllerUsers"/"Users") instead of staying in the view controller that presented it (chatViewController)..
Could You please help me out here.
I have attached screenshots of the code I'm using to call dismissViewControllerAnimated and my storyboard to give you a rough idea of what my app looks like. The view controller that the app is taking me to is "UsersSwippingViewControllerUsers"/"Users" when it should be staying in/taking me to ChatViewController.
ScreenShots:
This is a preview of my app's storyboard
Here is the code I'm using dismissViewControllerAnimated in the handler of the UIAlertAction

A: Don't use dismissViewControllerAnimated method in UIAlertController action. Doing this you telling your parent view controller instance to be dismissed (note why you use self in closure!). And UIAlertController have default approach to be dismissed automatically after any button pressed.

A: Change the type of action to .Cancel instead of .Default for the CancelAction and it should work.
self.dismissViewControllerAnimated would only work if called from the presenter view controller, not the presented one.
Hope it helps


text:
Q: Frequently timeout in retrofit I have a PHP backend for my android app, there is a strange problem; With Postman websevice works fine but in the app most of requests with retrofit occures 504 Gateway Timeout.It's also ok in localhost. what's the problem?
G.java

public class G extends Application {

    public static APIService service;

    @Override
    public void onCreate() {
        super.onCreate();
            service= ApiClient.getClient().create(APIService.class);
    }

}

ApiClient.java
public class ApiClient {

  private static final String BASE_URL="http://*.com/caspian/index.php/";

  private static Retrofit retrofit = null;

  public static Retrofit getClient() {

    if (retrofit==null) {
      OkHttpClient client=new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build();
      retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

    }
    return retrofit;
  }

}

APIService.java
public interface APIService {

    @Headers({
            "content-type: application/x-www-form-urlencoded"

    })
    @POST("loginUser")
    @FormUrlEncoded
    Call<MyResponse> loginUser(@Field("action") String action,
                                 @Field("username") String username,
                                 @Field("password") String password);
}

MyResponse.java
public class MyResponse implements Serializable {

  @SerializedName("status")
  private int status;

  @SerializedName("message")
  private String message;

  public MyResponse(int status, String message) {
    this.status = status;
    this.message = message;

  }
  public int getStatus() {
    return status;
  }
  public int getLast_id() {return last_id;}

}

LoginActivity.php
void loginUser() {
    Call<MyResponse> call = G.service.loginUser("loginUser",edtUsername.getText().toString(),edtPassword.getText().toString());
    call.enqueue(new RetrofitCallback<>(LoginActivity.this, new Callback<MyResponse>() {
      @Override
      public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {

        try {
          MyResponse token = response.body();
          Log.i("TAG", "status " + token.getStatus());

          Log.i("TAG", "message " + token.getMessage());

          }

        } catch (Exception e) {
          Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
      }

      @Override
      public void onFailure(Call<MyResponse> call, Throwable t) {

        Log.i("TAG", "onFailure=" + t.getLocalizedMessage() + " " + call.toString());
      }
    }, false,true
    ));

  }

login.php
<?php

        $response["status"] = 1;
        $response["message"] ='Ok';
        echo json_encode($response);

?>

I use Retrofit2 V2.4.0

A: High up time out
Error 504 is due to the speed of your Internet or server int
OkHttpClient client=new OkHttpClient.Builder()
        .readTimeout(120, TimeUnit.SECONDS)
        .connectTimeout(120, TimeUnit.SECONDS)
        .writeTimeout(120, TimeUnit.SECONDS)
        .build();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where to find error logs in detail for Apache Ignite? I'm using Apache Ignite to cluster our web sessions. Occasionally one of our caches crashes, and I keep receiving the following exception messages in my Tomcat application log file:
2016-05-23 15:04:02,200 ERROR root/error 495 - Failed to update web session: null
java.lang.IllegalStateException: Cache has been closed or destroyed: session-cache
        at org.apache.ignite.internal.processors.cache.GridCacheGateway.enter(GridCacheGateway.java:160)
        at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.onEnter(IgniteCacheProxy.java:1923)
        at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.get(IgniteCacheProxy.java:855)
        at org.apache.ignite.cache.websession.WebSessionFilter.doFilter0(WebSessionFilter.java:341)
        at org.apache.ignite.cache.websession.WebSessionFilter.doFilter(WebSessionFilter.java:315)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
2016-05-23 15:04:06,497 ERROR root/error 495 - Failed to update web session: null
java.lang.IllegalStateException: Cache has been closed or destroyed: session-cache
...

It worries me because I cannot find any further error messages explaining the cause of the crash, not even in the folder IGNITE_HOME/work
(By the way this crash happened before due to running out of memory, and I fixed it by increasing the application JVM heap size.)
My questions are:

*

*Where I can find the logs that explain the cause of the crash?

*If no logs available, shall I need to register certain events so as to receive the notification/explanation of the crash, how?

*When receiving such notification in the event of such cache crash, is there any way to restore the cache without having to restart the whole application?

Many thanks!
Update (2016-08-04)
As Valentin pointed out, by default Ignite inherits the application's logging settings if the node is embedded in the application. And indeed Ignite writes its logs in the same application log file.
If I would like to output Ignite logs to a separate log file, I could add configuration to log4j.properties as below:
log4j.appender.IGNITE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.IGNITE.File=${IGNITE_HOME}/work/logs/${tomcat.hostname}/ignite.log
log4j.appender.IGNITE.DatePattern='.'yyyy-MM-dd
log4j.appender.IGNITE.Threshold=DEBUG
log4j.appender.IGNITE.layout=org.apache.log4j.PatternLayout
log4j.appender.IGNITE.layout.ConversionPattern=[%d{ABSOLUTE}][%-5p][%t][%c{1}] %m%n

log4j.logger.org.apache.ignite=INFO, IGNITE

But there is still one thing I do not quite understand still is that, the configuration aforementioned would output the Ignite logging information to both ignite.log as specified above and the application's log file. @Valentin, wonder if you know why? Thanks. Is there any way that I could output the Ignite logs to ignite.log only, not to the application's log file at all?

A: If a node is embedded in the application, it will by default inherit the its logging settings. So most likely Ignite writes the log in the same file where the application writes it.
Note that if you're using Log4J, you should include ignite-log4j dependency in you project.
As for restoring the data, you should not lose any data if only one node in the cluster fails and you have at least one backup. To add backups use CacheConfiguration.backups configuration property.

A: I don't know if this will solve your specific problem but I found logs in IGNITE_HOME/work/logs


text:
Q: SudsLibrary Robot Framework : incorrect WSDL parsing It seems that my request SOAP object is being parsed incorrectly by SudsLibrary 0.8. Given that I have the following complex type:
<complexType name="getSchoolRequest">
    <sequence>
        <element name="school_name" type="xsd:string"/>
        <element maxOccurs="1" minOccurs="0" name="school_type" type="xsd:string"/>
        <element name="requestee" type="xsd:string"/>
        <element maxOccurs="1" minOccurs="0" name="requestee_age" type="xsd:int"/>
    </sequence>
</complexType>
<element name="getSchoolRequest" type="impl:getSchoolRequest"/>

I generate the SOAP message with the following code:
Check SOAP Service Functional
    create soap client  ${WSDL_ENDPOINT}

    ${mySchoolRequest}=  create wsdl object  getSchoolRequest
    ${mySchoolResponse}=  call soap method  getSchoolResponse  ${mySchoolRequest}

As a result, I get this SOAP message as the final creation:
<SOAP-ENV:Envelope xmlns:ns0="http://jaxws.webservices.my.srv/schemas" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <ns1:Body>
      <ns0:getSchoolRequest>
         <ns0:school_name>
            <ns0:school_name/>
            <ns0:requestee/>
         </ns0:school_name>
         <ns0:requestee/>
      </ns0:getSchoolRequest>
   </ns1:Body>
</SOAP-ENV:Envelope>

What I expect to see instead is something like this:
<SOAP-ENV:Envelope xmlns:ns0="http://jaxws.webservices.my.srv/schemas" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <ns1:Body>
      <ns0:getSchoolRequest>
        <ns0:school_name/>
        <ns0:school_type/>
        <ns0:requestee/>
        <ns0:requestee_age/>
      </ns0:getSchoolRequest>
   </ns1:Body>
</SOAP-ENV:Envelope>

SoapUI confirms that the version I expect is the one that generates. Am I missing something with SudsLibrary in making this generation accurate?


text:
Q: React Native persisting user data In my app I have 2 components (Page and Home).
Home extends Page like so:
export default class Home extends Page
and Page just extends Component.
In Page I have a method to get user data from AsyncStorage
async getUser() {
  // get from storage
  this.setState({user});
}

The above is called on the constructor of Page.
The problem I have is that Home has a method on componentWillMount that relies on this.state.user. Obviously this isn't going to work since the getUser method is async.
Is there a way I can get the user information and only call specific methods once I have that info?
export default class Page extends Component {
  async getUser() {
    // get from AsyncStorage
    this.setState({user});
  }
  componentWillMount() {
    this.getUser();
  }
}

export default class Home extends Page {
  async foo(user_id) {
    this.setState({something});
  }

  componentWillMount() {
    this.foo(this.state.user);
  }

  render() {
    return <Text>{this.state.something}</Text>;
  }
}

A:
Is there a way I can get the user information and only call specific
  methods once I have that info?

Not in a general sense, but of course there are some solutions. What this comes down to is that you have an async data dependency. You need to write the code in such a way that a call to dependent functions is only made after the data becomes available.
Perhaps the easiest way to do this is to use componentWillUpdate instead of componentDidMount and check if you are receiving the required data:
componentWillUpdate(nextProps, nextState) {
    if (nextState.user != null && this.state.user !== nextState.user) {
        this.prepareForUser(nextState.user);
    }
}

(Note that you can't setState directly in componentWillUpdate, but since your method is async it won't happen until later. You can use componentDidUpdate to chain another setState call.)
Another option (which I like to use) is to use composition instead of inheritance. This makes the life-cycle easier to control through rendering: the parent can only render a child when all the child's dependent data is loaded, then the child does not need to worry about any timing issues related to the initial loading of data and can do whatever it wants from its componentDidMount:
class UserContainer extends Component {
    state = {};
    componentDidMount() {
        this.getUser();
    }
    async getUser() {
        // get user from async store
        this.setState({user});
    }
    render() {
        return (
            <div>
                { this.state.user ? <UserView user={this.state.user} /> : <Spinner /> }
            </div>
        );
    }
}

class UserView extends Component {
    componentDidMount() {
        this.props.user != null
    }
}

This is pretty much the "container component" pattern.


text:
Q: How do I make a bootable USB from Windows? I've downloaded the daily Ubuntu 12.04 iso.
I currently have windows 7 x64 operating system installed.
How can I make a bootable usb from the Ubuntu iso?

A: With UNetBootIN, for example. I like Pendrive Linux Easy USB Creator very much, but it doesn't support béta's without some tips 'n tricks. Testing an alpha isn't as simple as you think by the way, some experience is useful ;)
Download for Windows

Unetbootin is available for Windows, Mac, Linux (Lots of distros)

A: In order to make an Ubuntu live USB for installing Ubuntu in Windows, use Rufus. Rufus is the recommended application at the official Ubuntu website for making a bootable live Ubuntu USB on Windows. The USB flash drive you use should be 2GB or larger and formatted to FAT32. For Ubuntu 18.04 and later the USB flash drive should be 4GB or larger. The formatting procedure will delete all of the files that are already on the flash drive.
The instructions for preparing an Ubuntu live USB are found at the official Ubuntu How to create a bootable USB stick... webpage (see the step-by-step instructions below).

*

*Open Rufus and select your USB stick in the Device dropdown menu.

*Click the CD-ROM icon next to the FreeDOS dropdown menu, then find your downloaded Ubuntu ISO and click Open and then Start.

*Click Yes when it asks to download Syslinux software.

*Click OK to write in ISO Image mode.

*Confirm that your USB stick is selected and then click OK to continue. It is very important to verify that the device that you are installing the Ubuntu live USB to is indeed your flash drive, so that you don't overwrite any of your system or personal files which may make your operating system unbootable.

*When it is finished, just restart your computer and start using Ubuntu, or you can install Ubuntu.

The Ubuntu live USB flash drive that you make this way will be bootable from a PC. In order to enable your computer to boot from the USB flash drive, you must enter your BIOS menu by pressing one of these keys: Delete, F2 or F10 as soon as the motherboard splash screen appears when the computer is booting. In the BIOS menu, you need to change the boot order so that the USB flash drive, which is usually called USB-HDD in newer computers, is the first entry in the boot sequence, and then save your new BIOS settings and exit the BIOS setup.

A: you can use universal usb installer
go to http://www.softpedia.com/progDownload/Universal-USB-Installer-Download-186578.html
install it
and then run it and select your linux version
and pendrive which is to be make as statup disk

A: Open Unetbootin ...select daily_live ...that surely will boot.

A: Ubuntu ISOs (since 11.10) are hybrid, they are both CD and USB bootable.
On Linux, you can just cat them to a flash drive.
On windows, follow the instructions here: http://www.ubuntu.com/download/ubuntu/download
Windows 7
Right-click on an ISO image and choose 'Open with > Windows Disc Image Burner'.

Select a disk burner (drive) and choose 'Burn'. If you check 'Verify disc after burning', it will confirm that the ISO image has been burned correctly.

Windows Vista / XP / Server
Download and install the appropriate version of ISO Recorder.
Insert an unformatted DVD into your burner. (Note: You can only burn DVDs with this tool from Vista.)

Open Windows Explorer, find your ISO file, right-click and choose 'Next'.

A: Try Rufus. It's free and works better than unetbootin or live usb creator. It succeeded where both have failed for me.

A: I haven't seen it mentioned, but Linux Live USB Creator is far and away the best I've tried. It's quick, easy, and allows Persistent Mode with no hassle. It is Windows-only, however.

A: In case you are using newer computer there is a good chance it support UEFI.
Now I understand this is an old post, but if someone have the same problem nowadays many of this answers just won't work. So if you want to create a bootable USB from Windows with all the new technologies supported (UEFI, GPT) you should use Rufus.


text:
Q: Reports with parameter working fine independently but not functional in cockpit (composite document) I am a newbie and using spagobi 5.2.
I created PI highchart and birt report.
They are working fine standalone with parameter.
But when I am trying to put them in cockpit they are not working as expected.
I notice two things :
1) Highchart Pie in composit showing a dialogue box - 'Execution Analytical Drivers'
2) PI chart could not able to pass the parameter to the BIRT report in composit document

Following is the composit document details :
<DOCUMENTS_COMPOSITION template_value="/jsp/engines/documentcomposition/template/dynamicTemplate.jsp">
    <DOCUMENTS_CONFIGURATION video_width="1200" video_height="1064">
        <DOCUMENT sbi_obj_label="chartHighJobDesc" local_file_name="chartHighJobDesc.sbichart">
            <PARAMETERS>
                <PARAMETER type="OUT" sbi_par_label="param1" default_value="na" id="1">
                    <REFRESH>
                        <REFRESH_DOC_LINKED labelDoc="rptEmpJobDescription" labelParam="param1" typeCross="INTERNAL"/>
                    </REFRESH>
                </PARAMETER>
            </PARAMETERS>
            <STYLE style="position:absolute;margin:0px;left:0px;top:0px;width:390px;height:420px;" mode="auto"/>
            <id>chartHighJobDesc</id>
        </DOCUMENT>
        <DOCUMENT sbi_obj_label="rptEmpJobDescription" local_file_name="rptEmpJobDescription.rptdesign">
            <PARAMETERS>
                <PARAMETER type="IN" sbi_par_label="param1" id="1">
                    <REFRESH/>
                </PARAMETER>
            </PARAMETERS>
            <STYLE style="position:absolute;margin:0px;left:0px;top:422px;width:990px;height:386px;" mode="auto"/>
            <id>rptEmpJobDescription</id>
        </DOCUMENT>
    </DOCUMENTS_CONFIGURATION>
</DOCUMENTS_COMPOSITION>

I have posted the same to spagobi forum as well at the following link :
https://www.spagoworld.org/jforum/posts/list/4234.page
Thanks in advance for your kind help.

A: I managed to get the answer of my second query. After setting default value to birt report I found both the reports are in composit document and Hicharts (PI) able to send parameter to BIRT chart.
But still I am searching for the answer of the first query, i.e. Highchart PI in cockpit showing a dialogue box - 'Execution Analytical Drivers'. If anybody got a workaround it will be great.


text:
Q: Headers already send Magento 2 multistore addon domain Multiple websites are working on Magento 2.2 with the addon domain method and symlinks.
The theme is visible, etc.
Only thing is that at the bottom I see the following message. Looking for advice.
Exception:
Warning: Cannot modify header information - headers already sent by (output started at /home2/staging/public_html/vendor\
/zendframework/zend-http/src/PhpEnvironment/Response.php:114) in /home2/staging/public_html/vendor/magento/framework/Std\
lib/Cookie/PhpCookieManager.php on line 148in /home2/staging/public_html/vendor/magento/framework/App/ErrorHandler.php:6\
1

Stack trace:
#0 [internal function]: Magento\Framework\App\ErrorHandler->handler(2, 'Cannot modify h...', '/home2/staging/...', 148, \
Array)
#1 /home2/staging/public_html/vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php(148): setcookie('X-Magento-Var\
y', '5c0fe9cddef92d0...', 0, '/', '', false, true)
#2 /home2/staging/public_html/vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php(101): Magento\Framework\Stdlib\
\Cookie\PhpCookieManager->setCookie('X-Magento-Vary', '5c0fe9cddef92d0...', Array)
#3 /home2/staging/public_html/vendor/magento/framework/App/Response/Http.php(95): Magento\Framework\Stdlib\Cookie\PhpCoo\
kieManager->setSensitiveCookie('X-Magento-Vary', '5c0fe9cddef92d0...', Object(Magento\Framework\Stdlib\Cookie\SensitiveC\
ookieMetadata))
#4 /home2/staging/public_html/vendor/magento/module-page-cache/Model/App/Response/HttpPlugin.php(25): Magento\Framework\\
App\Response\Http->sendVary()
#5 /home2/staging/public_html/vendor/magento/framework/Interception/Interceptor.php(121): Magento\PageCache\Model\App\Re\
sponse\HttpPlugin->beforeSendResponse(Object(Magento\Framework\App\Response\Http\Interceptor))
#6 /home2/staging/public_html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Framework\App\Response\
\Http\Interceptor->Magento\Framework\Interception\{closure}()
#7 /home2/staging/public_html/generated/code/Magento/Framework/App/Response/Http/Interceptor.php(26): Magento\Framework\\
App\Response\Http\Interceptor->___callPlugins('sendResponse', Array, Array)
#8 /home2/staging/public_html/vendor/magento/framework/App/Http.php(185): Magento\Framework\App\Response\Http\Intercepto\
r->sendResponse()
#9 /home2/staging/public_html/vendor/magento/framework/App/Http.php(156): Magento\Framework\App\Http->handleDeveloperMod\
e(Object(Magento\Framework\App\Bootstrap), Object(Magento\Framework\Exception\LocalizedException))
#10 /home2/staging/public_html/vendor/magento/framework/App/Bootstrap.php(261): Magento\Framework\App\Http->catchExcepti\
on(Object(Magento\Framework\App\Bootstrap), Object(Magento\Framework\Exception\LocalizedException))
#11 /home2/staging/…………………………………/index.php(143): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http)\
)
#12 {main}


text:
Q: When and why did "patronize" gain the meaning of condescension versus being a customer? To patronize an establishment is generally a good thing, but to be patronized is bad.  I assume that the former meaning was the original, but when did the other come into being and why?

A: It must be remembered that to act as a patron was to be in a superior position to the person one was helping. Largesse could be given or withdrawn at will. Consider Samuel Johnson's definition of a patron:

Is not a patron, my lord, one who looks with unconcern on a man struggling for life in the water, and, when he has reached ground, encumbers him with help? The notice which you have been pleased to take of my labors, had it been early, had been kind; but it has been delayed till I am indifferent, and cannot enjoy it; till I am solitary, and cannot impart it; till I am known, and do not want it. — Letter to Lord Chesterfield

You can see that Lord Chesterton's offer of patronage after Johnson had achieved success was not only spurned, but resented as condescension. But if Chesterfield had offered it earlier, Johnson would very likely have accepted it gratefully.
Read more: http://quotationsbook.com/quote/29572/#ixzz1KMc4zsIS
on Quotations Book —
Letter to Chesterfield

A: etymonline has:

1580s, "to act as a patron towards," from patron + -ize. Meaning "treat in a condescending way" is first attested 1797; sense of "give regular business to" is from 1801.

A: Short answer: this is the other way around and it was probably end of 18th century. The main reason these two meanings coexists is that the verb has evolved two times.
First from the social and historical meaning of patron (going back to Roman antiquity), a wealthy man keeping a group of attached men and giving them money and places, financing familiar artists like Maecenas who was the patron of Virgiles. As these lords or rich bourgeois had the habit to interfere in their protégés' works or to moralize them without being interrupted for fear of losing the protection, hence this meaning of patronize.
Second, the word patron began to be used as a very obsequious term for "customer" in the 17th century by city merchants. This word is now quite neutral but used to be a flattery, implying a status and a wealth high enough to be a protector of artists and craftsmen, not merely purchasing items in the shop but subsidizing art. The verb's meaning has faded with the word's.


text:
Q: Calling Dispose() on task and cancellationtoken in current layout i have the following code and im trying to figure out if its possible to explicitly call dispose on the task and cancellationtoken. Ive read that Microsoft recommends calling dispose()  on tasks unless u have to do odd things in order to call it. I also appreciate that there is probably a better way of doing this but im curious to know if its possible for the current set up.
    public void UpdateSProcList(CancellationToken cancelTask)
    {
        Task parentTask = Task.Factory.StartNew(() =>
            {
                //Call the handling method.
                ChildTaskSync(cancelTask);
            });
    }

    public void ChildTaskSync(CancellationToken cancelTask)
    {
        SProcInformationEventArgs sProcListRetrieval = new SProcInformationEventArgs();

        //Check for cancellation.
        if(!cancelTask.IsCancellationRequested)
        {
            try
            {
                ObtainSProcList(sProcListRetrieval);
            }
            catch (AggregateException AEx)
            {
                if (AEx.InnerException is OperationCanceledException)
                {
                    ....
                }
            }
            finally
            {
                //Call method to raise event.
                OnVerificationCompleted(this, sProcListRetrieval);
            }
        }
        else
        {
            sProcListRetrieval.CarriedOutToCompletion = false;
            OnVerificationCompleted(this, sProcListRetrieval);
        }
    }

First method allows the GUI thread to return and continue updating the UI. Second method retrieves a list of stored procedures.
Thanks for your time.


text:
Q: Find row in matrix, fast and with special conditions with C in matlab I'm using a mex file in matlab to find a fast way to find a row matrix s in a large matrix S. The mexfile written down below does that, but only for a unique s in S. However the row matrix s appears a number of times in large matrix S in my application.
    #include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], mwSize, lastfound)
{
double *S, *s *lastfound;
mwSize n1, n2, i1, i2, k;
  S  = mxGetPr(prhs[0]);
  n1 = mxGetM(prhs[0]);
  // n2 = mxGetN(prhs[0]);
  n2 = 3;
  s  = mxGetPr(prhs[1]);
  for (i1 = lastfound; i1 < n1; i1++) {
     k = i1;
     for (i2 = 0; i2 < n2; i2++) {
        if (S[k] != s[i2]) {
           break;
        }
        k += n1;
     }
     if (i2 == n2) {  // Matching row found:
        plhs[0] = mxCreateDoubleScalar((double) (i1 + 1));
        return;
     }
  }
  // No success:
  plhs[0] = mxCreateDoubleScalar(mxGetNaN());
}

So i tried to use another input 'lastfound' which would enable the code to start at lastfound + 1 (the +1 is added when the function is called), so that when the previous row s is found, and the code start searching the second row s. I do this until the mex file return NaN. It however doesn't work, the code doesn't start the at the lastfound + 1 step. I am a C noob, so i think it is a very small error, but i would immensely appreciate it if somebody could take a look at it.
Thanks in advance :)
Kind regards,
Mark


text:
Q: How to stop Ghostscript and pdfwrite breaking up images into multiple XObjects? Edit: I've done some more investigation and can clarify the problem, I will leave the original question below too.
It seems that when using TIFF image data with multiple strips, pdfwrite produces an output PDF with one XObject per strip. In my case I have 25 rows per strip so the full page image is being broken up into 25-pixel high images. This would be fine except it produces unpleasant visual artefacts.
Using tiffcp to revert the file to one big strip fixes this, but Acrobat Distiller doesn't require this workaround as it maintains the image as one big XObject by default.
Can we make Ghostscript do the same?

I'm attempting to use pdfwrite instead of Acrobat Distiller to convert a PS file to PDF. The file contains many scanned TIFF images that are called with the GetTiff function (I think this was originally supplied by Xerox).
Distiller's output is fine but pdfwrite seems to produce multiple vertical XObjects for each image, instead of just one as Distiller does. They all appear as below in the PDF with the exact same size:
104 0 obj
<</Subtype/Image
/ImageMask true
/Width 2550
/Height 25
/BitsPerComponent 1/Length 7975>>stream

Is there a way to stop this behaviour? The output seems fine when zoomed in a huge amount, or when printed, but on screen at a regular zoom there are rendering artefacts at the boundary between images.
I've tried just a basic command line (no options except -sDEVICE and -sOutputFile) as well as a variety of image options but no difference so far. I've tried versions 9.05 and 8.54.

A: Ghostscript won't consume a TIFF file directly so you must be doing something else with it. My suspicion would be that whichever tool you are using to convert to PostScript this one is producing multiple images. I don't know anything about the 'GetTiff' 'function', but I would be suspicious that this is the problem. Why not simply use libtiff ?
Adobe Acrobat distiller has a feature which 'concatenates' consecutive images if they are the same width and colour space, and contiguous.
pdfwrite doesn't do this.


text:
Q: How to reload function (tempus dominus) after modifying DOM element with jQuery
I am using tempus dominus for date selection in a form in my booking site.
Some dates need to be disabled so I am passing an array of dates to disable from php to twig.
This array is in 2 dimensions:
1) the apartment to rent
2) the unavailable dates for the latter
When the user chooses an apartment, the variable "home" is updated on click with the new value and I update the attribute "hValue" as well in an hidden div.
Then I try to use this "hValue" to access what I want in the array of dates inside datetimepicker disableDatesPerHomeStart[homeValue].
But of course the value is not updated as the function has already been loaded... In other words, inside datetimepicker I always get the initial value of homeValue, not the chosen one in the form.
I tried to trigger an event inside the .click to call again datetimepicker but it doesn't work...
Here is the code:

    {{ form_label(form.startDate) }}

        {{ form_widget(form.startDate, {'attr': {'type': 'text', 'class': 'form-control datetimepicker-input', 'data-target':'#datetimepicker1'}}) }}

$(function () {
    var home = $('#contact_home').val();
    $('.homeValue').attr('hValue', home);
    var homeValue =  $('.homeValue').attr('hValue');
    var disableDatesPerHomeStart = {{ unavailableDatesForStartComplete|json_encode|raw }};
    var disableDatesPerHomeEnd = {{ unavailableDatesForEndComplete|json_encode|raw }};

    $('#contact_home').click(function (c) {
        home = $('#contact_home').val();
        $('.homeValue').attr('hValue', home);
        homeValue = $('.homeValue').attr('hValue');
        var event = jQuery.Event("myEvent");
        $('body').trigger(event);
    });

    $('.dateStart').datetimepicker({
        locale: 'fr',
        format: 'L',
        disabledDates: disableDatesPerHomeStart[homeValue],
        icons: {
                time: "fas fa-clock",
                date: "fas fa-calendar-alt",
                up: "fas fa-angle-up",
                down: "fas fa-angle-down"
            }
    });

    $('.dateEnd').datetimepicker({
        useCurrent: false,
        locale: 'fr',
        format: 'L',
        disabledDates: disableDatesPerHomeEnd[homeValue],
        icons: {
                time: "fas fa-clock",
                date: "fas fa-calendar-alt",
                up: "fas fa-angle-up",
                down: "fas fa-angle-down"
            }
    });

    $('body').on('myEvent',function(){
        $('.dateStart').datetimepicker('disabledDates', disableDatesPerHomeStart[homeValue]);
        $('.dateEnd').datetimepicker('disabledDates', disableDatesPerHomeEnd[homeValue]);
    });
});

I am new to jQuery/javascript so maybe I miss something obvious.
How can I pass the new value to the datetimepicker?
Thanks

A: I think your looking for the setOptions function :
$('.dateStart').datetimepicker('setOptions', {disabledDates: ['01.01.2019','02.01.2019','03.01.2019'] });

It allows to change the options of the datetimepicker.


text:
Q: Bidirectional Protocol for JSON Payloads in a secure fashion I am looking for a secure protocol that supports

*

*(authentication)

*transsport layer security (TLS)

*bidirectional data streams

to exchange JSON-formatted message payloads.
I've already looked at HTTP-based protocols like BOSH and cometD, but the current problem I see when exchanging data frequently is the HTTPS overhead, since the payload consists of very high frequent measurements and control messages.


text:
Q: SQL Server Left Join Counting I got this sample code
create table #Reservation
(id int identity(1,1),
 name varchar(50)
);

create table #Reservation_details
(id int identity(1,1),
 reservation_id int,
 reservation_date date,
 seated tinyint
);

create table #Payment
(id int identity(1,1),
 reservation_id int,
 payment decimal(18,2)
);

insert into #Reservation(name)
values ('Spiderman'),('Superman'),('Batman'),('Hulk');

insert into #Reservation_details(reservation_id,reservation_date,seated)
values (1,'2017-12-07',0),(2,'2017-12-08',0),(3,'2017-12-08',1),(4,'2017-12-08',0);

insert into #Payment(reservation_id,payment)
values(1,220),(2,1000)

select
 A.id,
 A.name,
 B.reservation_date,
 B.seated,
 C.payment
from #Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'

drop table #Reservation
drop table #Reservation_details
drop table #Payment

I wanted to get the count of all reservations where date is '2017-12-08' and seated = 1 or payment is not null
I've tried putting where date is '2017-12-08' and seated = 1 or payment is not
null
but instead it showed me the past date also how do use where as count?

A: Try it
select COUNT(*)
from #Reservation A
inner join #Reservation_details B on B.reservation_id = A.id
left join #Payment C on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'
  and (B.seated=1 or C.payment is not null)

I think you forgot to use brackets (condition1 OR condition2) for OR operation.
See operator precedence - https://learn.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql
In your case if you don't use brackets then
reservation_date = '2017-12-08' and B.seated=1 or C.payment is not null

equals the following
(reservation_date = '2017-12-08' and B.seated=1) or C.payment is not null

A: select
A.id,
A.name,
B.reservation_date,
B.seated,
C.payment
from (#Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id)
where B.reservation_date = '2017-12-08'
AND (B.seated =1 or  C.payment is null)

You can use COUNT function by using HAVING in WHERE clause , it should be last statement and after the GROUP BY clause


text:
Q: Angular TSLint - Cannot find builder "@angular-devkit/build-angular:tslint" When I try to run command ng lint --fix cli throws this error:
An unhandled exception occurred: Cannot find builder "@angular-devkit/build-angular:tslint".
See "C:\Users\MOE89A~1.ZAR\AppData\Local\Temp\ng-Ijc3an\angular-errors.log" for further details.

My lint confing in angular.json:
"lint": {
  "builder": "@angular-devkit/build-angular:tslint",
  "options": {
    "tsConfig": [
      "projects/wepod-app/tsconfig.app.json",
      "projects/wepod-app/tsconfig.spec.json",
      "projects/wepod-app/e2e/tsconfig.json"
    ],
    "exclude": [
      "**/node_modules/**"
    ]
  }
},

My package.json:
{
  "name": "wepod-clients",
  "version": "3.2.3",
  "scripts": {
    "ng": "ng",
    "start": "node patch.js && ng serve",
    "build": "node patch.js && node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng run wepod-app:app-shell:production && ng run wepod-app:auth-standalone:production",
    "server": "npm run build && http-server -p 9090 -c-1 dist",
    "test": "ng test",
    "lint": "ng lint --fix",
    "e2e": "ng e2e",
    "postinstall": "node patch.js && ngcc",
    "postbuild": "node post-build.js",
    "prepare": "husky install",
    "build-latest": "git pull origin production && npm run build"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^13.0.0",
    "@angular/cdk": "^13.0.0",
    "@angular/cli": "^13.0.1",
    "@angular/common": "^13.0.0",
    "@angular/compiler": "^13.0.0",
    "@angular/core": "^13.0.0",
    "@angular/forms": "^13.0.0",
    "@angular/localize": "^13.0.0",
    "@angular/platform-browser": "^13.0.0",
    "@angular/platform-browser-dynamic": "^13.0.0",
    "@angular/platform-server": "^13.0.0",
    "@angular/router": "^13.0.0",
    "@angular/service-worker": "^13.0.0",
    "@types/video.js": "^7.3.27",
    "animate.css": "^4.1.1",
    "assert": "^2.0.0",
    "bowser": "^2.11.0",
    "buffer": "^6.0.3",
    "bundle-loader": "^0.5.6",
    "compare-version": "^0.1.2",
    "constants-browserify": "^1.0.0",
    "crypto-browserify": "^3.12.0",
    "crypto-js": "^4.1.1",
    "d3": "^6.5.0",
    "hammerjs": "^2.0.8",
    "https-browserify": "^1.0.0",
    "jalali-moment": "^3.3.10",
    "lottie-web": "^5.7.13",
    "lzutf8": "^0.6.0",
    "net": "^1.0.2",
    "ng-gallery": "^5.1.1",
    "ng2-jalali-date-picker": "^2.4.2",
    "ngx-device-detector": "^1.5.2",
    "ngx-doughnut-chart": "0.0.4",
    "ngx-infinite-scroll": "^8.0.2",
    "ngx-lottie": "^7.0.4",
    "ngx-owl-carousel-o": "^3.1.1",
    "ngx-skeleton-loader": "^2.10.1",
    "ngx-toastr": "^12.1.0",
    "os-browserify": "^0.3.0",
    "podchat-browser": "^10.14.13",
    "rxjs": "^6.6.7",
    "stream-browserify": "^3.0.0",
    "stream-http": "^3.2.0",
    "tls": "0.0.1",
    "tslib": "^2.0.0",
    "uuid": "^8.3.2",
    "video.js": "^7.15.4",
    "videojs-record": "^4.5.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^13.0.1",
    "@angular-devkit/core": "^13.0.1",
    "@angular/compiler-cli": "^13.0.0",
    "@angular/language-service": "^13.0.0",
    "@egjs/hammerjs": "^2.0.17",
    "@types/hammerjs": "^2.0.40",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "^2.0.10",
    "@types/node": "^12.20.36",
    "codelyzer": "^6.0.0",
    "colors": "^1.4.0",
    "git-tag-version": "^1.3.1",
    "gulp": "^4.0.2",
    "gulp-gzip": "^1.4.2",
    "http-server": "^14.0.0",
    "husky": "^7.0.4",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "^6.3.7",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.0",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "^7.0.0",
    "ts-node": "^8.10.2",
    "tslint": "^6.1.3",
    "typescript": "4.4.4",
    "zip-dir": "^2.0.0"
  },
  "browser": {
    "fs": false,
    "path": false,
    "os": false
  }
}

A: From v13 angular doesn't use tslint anymore due to deprecation.
Run ng add @angular-eslint/schematics to add eslint to your application.
It will use tslint-to-eslint-config to migrate you to eslint automatically.
It will generate a .eslintrc.json file and migrate tslint.json to it.
Nothing else is needed to be done.

A: @MahdiJoon is a great answer! I think that it will work for most projects.
I'm adding this answer for developers who have already deleted tslint manually, like I did.
If you did that, like me, then:

*

*ng add @angular-eslint/schematics to install eslint

*ng g @angular-eslint/schematics:convert-tslint-to-eslint <project-name> to migrate tslint.json config to .eslintrc.json

*(optional) run the previous command for any other project (e.g. e2e)


text:
Q: Codeigniter - call to undefined method I have a project in Ci and I can't get it to recognize my check2() for some reason. CI keeps throwing Fatal error: Call to undefined method CI_Loader::check2()
controller (Login.php)
class Login extends CI_Controller {

 public function index() {
 // Page variables
 $page['title'] = "Analytics Login";
 $this->load->view('header', $page);
 $this->load->view('login');
 $this->load->view('footer');
 }

 public function verify() {

 $verifier = $this->load->model('Verifylogin_model');

 $username = $this->input->post('username');
 $password = $this->input->post('password');

 if((!$verifier->check2($username,$password))) {
 $this->load->view('login');
 } else {
 redirect('home', 'refresh');
 }
 }
}

Model (verifylogin_model.php)
<?php
Class Verifylogin_model extends CI_Model {

 function __construct() {
 parent::__construct();
    }

 public function check2($username, $password) {

 $this->db->select('user_id, user_email');
 $this->db->from('admin_users');
 $this->db->where('user_email', $username);
 $this->db->where('user_pass', md5($password));
 $this->db->limit(1);

 $results = $this->db->get();

 if ($results->num_rows() == 1) {
 return true;
 } else {
 return false;
 }
 }
}
?>

A: CI loader does'nt return the model instance, but the global CI instance.
You can use:
$this->load->model('Verifylogin_model');
$verifier = $this->Verifylogin;

A: Access the model method in following manner
 $this->load->model('verifylogin_model');

 $this->verifylogin_model->check2();

A: CI use "dependency injection" heavily. Loader is not a factory class which you can't get Verifylogin_model instance directly. In CI, you should call the model like the following example
if (!$this->Verifylogin_model->check2($username, $password)) {
 /* your code */
}


text:
Q: ERROR: Reference the counter as the target of an assignment - PL/SQL I'm relatively new to SQL.
I'm trying to print a simple pattern through this code
declare
   n number(2):=5;
   temp number(2):=n;
 begin
   for a in 1..5
       a:=a+1;loop
       for b in 1..temp loop
           b:=b+1;
           dbms_output.put_line(' ');
           temp:=temp-1;
       end loop;
   for c in 1..2*a-1 loop
   c:=c+1;
   dbms_output.put_line('*');
 end loop;
end loop;
end;
/

I keep getting this error:
PLS-00103: Encountered the symbol "A" when expecting one of the following:
* & - + / at loop mod remainder rem <an exponent (**)> ||
multiset

I understand Oracle doesn't allow to reference the counter as the target of an assignment which is why I keep getting error at line 6 but I'm unable to make it work even by declaring another global variable and assigning increment statement in it but  it doesn't work either.
Please help.
Thanks!

A: Modifying the previous answers to actually give you Pascal's triangle, which you mentioned you were attempting in a comment:
set serveroutput on format wrapped
declare
   n number(2):=5;
begin
  for a in 1..n loop
    for b in 1..n-a loop
      dbms_output.put(' ');
    end loop;
    for c in 1..2*a-1 loop
      dbms_output.put('*');
    end loop;
    dbms_output.new_line;
  end loop;
end;
/

    *
   ***
  *****
 *******
*********

PL/SQL procedure successfully completed.

Both your dbms_output.put_line calls needed to be just dbms_output.put, as that was printing each * on a line on its own. But you do need a line break after each time around the a loop, so I've added a dbms_output.newline at the end of that. You were also decrementing temp inside the b loop, which meant it was zero instead of (n-1) for the second time around the a loop; but you don't really need a separate temp variable at all as that is always the same as (n-a)+1 and the +1 just puts an extra space on every line. (I also made the a loop 1..n as I assume you want to change the value of n later in one place only). With n := 8:
       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************

Crucially though you also have to set serveroutput on format wrapped, otherwise the leading spaces you're generating in the b loop are discarded.
You can also do this in plain SQL, though you need to supply the 5 twice, or use a bind or substitution variable:
select lpad(' ', 5 - level, ' ') || rpad('*', (level * 2) - 1, '*') as pascal
from dual
connect by level <= 5

PASCAL
------------------------------
    *
   ***
  *****
 *******
*********

Your b and c loops are just doing a manual lpad really.

A: When I took your code in my editor I first noticed, you tried to increase a before starting the loop, and Oracle gives first error at that point. And also it does not allow you to increase counter variable in for loop, (I don't know why) I checked on the internet and found that you can not set increment step for Oracle for loops also you can not set a value for counter variable in for loop.
The code below works fine for me :
declare
   n number(2):=5;
   temp number(2):=n;
 begin
   for a in 1..5
   loop    --a:=a+1;
       for b in 1..temp loop
           --b:=b+1;
           dbms_output.put_line(' ');
           temp:=temp-1;
       end loop;
   for c in 1..2*a-1 loop
   --c:=c+1;
   dbms_output.put_line('*');
 end loop;
end loop;
end;
/

A: As StephaneM says, loop variables are incremented by the loop itself: you don't need to do a := a + 1, and most of all you CAN'T assign them ! Here is a corrected version:
declare
   n number(2):=5;
   temp number(2):=n;
begin
  for a in 1..5
  loop
    for b in 1..temp loop
      dbms_output.put_line(' ');
      temp:=temp-1;
    end loop;
    for c in 1..2*a-1 loop
      dbms_output.put_line('*');
    end loop;
  end loop;
end;
/


text:
Q: Save response from web-scraping as csv file I downloaded a file from a website with rvest. How can I save the response as a csv file?
Step 1: Monkey patch rvest package like in this thread: How to submit login form in Rvest package w/o button argument
library(tidyverse)
library(rvest)
library(R.utils)

# monkey path submit_form
custom.submit_request <- function (form, submit = NULL)
{
  is_submit <- function(x) {
    if (!exists("type", x) | is.null(x$type)){
      return(F);
    }
    tolower(x$type) %in% c("submit", "image", "button")
  }
  submits <- Filter(is_submit, form$fields)
  if (length(submits) == 0) {
    stop("Could not find possible submission target.", call. = FALSE)
  }
  if (is.null(submit)) {
    submit <- names(submits)[[1]]
    message("Submitting with '", submit, "'")
  }
  if (!(submit %in% names(submits))) {
    stop("Unknown submission name '", submit, "'.\n", "Possible values: ",
         paste0(names(submits), collapse = ", "), call. = FALSE)
  }
  other_submits <- setdiff(names(submits), submit)
  method <- form$method
  if (!(method %in% c("POST", "GET"))) {
    warning("Invalid method (", method, "), defaulting to GET",
            call. = FALSE)
    method <- "GET"
  }
  url <- form$url
  fields <- form$fields
  fields <- Filter(function(x) length(x$value) > 0, fields)
  fields <- fields[setdiff(names(fields), other_submits)]
  values <- pluck(fields, "value")
  names(values) <- names(fields)
  list(method = method, encode = form$enctype, url = url, values = values)
}

reassignInPackage("submit_request", "rvest", custom.submit_request)

Step 2: Download file
# start scraping
url <- "https://aws.state.ak.us/ApocReports/CampaignDisclosure/CDExpenditures.aspx"
session_1 <- html_session(url)
# there are two blue buttons:
session_1 %>%
  html_nodes(".BlueButton") %>%
  html_attr(name = "value")
#> [1] "Search" "Export"

# click export button
form <- html_form(session_1)[[1]]
session_2 <- submit_form(session = session_1, form = form,
                         submit = "M$C$sCDTransactions$csfFilter$btnExport")

# now there are multiple buttons with hyperlinks
# get the link for the csv file
url_csv <- session_2 %>%
  html_nodes(".BlueButton") %>%
  html_attr(name = "href") %>%
  magrittr::extract2(4) %>%
  url_absolute(base = session_2$url)

# download csv file
file <- jump_to(session_2, url_csv)
file$response
#> Response [https://aws.state.ak.us/ApocReports/CampaignDisclosure/CDExpenditures.aspx?exportAll=False&exportFormat=CSV&isExport=True]
#>   Date: 2018-09-22 17:49
#>   Status: 200
#>   Content-Type: text/comma-separated-values; charset=utf-8
#>   Size: 6.34 kB
#> "Result","Date","Transaction Type","Payment Type","Payment Detail","Amou...
#> 1,5/8/2017,Expenditure,Future Campaign Account,,$200.00,US Postal Servic...
#> 2,11/29/2017,Expenditure,Bank Fee,,$12.00,Denali FCU,,440 E 36th Ave,Anc...
#> 3,1/1/2018,Expenditure,Electronic Funds Transfer,,$3.54,Google,,1600 Amp...
#> 4,12/31/2017,Expenditure,Electronic Funds Transfer,,$107.89,PayPal,,1840...
#> 5,1/31/2018,Expenditure,Electronic Funds Transfer,,$16.42,Paypal,,1840 E...
#> 6,2/1/2018,Expenditure,Check,197,$300.00,Corbett,Joshua,2448 Sprucewood ...
#> 7,2/1/2018,Expenditure,Electronic Funds Transfer,,$5.00,Google,,1600 Amp...
#> 8,2/28/2017,Expenditure,Bank Fee,,$4.10,First National Bank Alaska,,646 ...
#> 9,3/31/2017,Expenditure,Bank Fee,,$4.10,First National Bank Alaska,,646 ...
#> ...

Created on 2018-09-22 by the reprex package (v0.2.1)
The response looks promising. How can I save that response directly as csv-file?

A:
httr::content(file$response, as="text") %>% write_lines("file.csv")

I'm answering this so the question can be marked as solved. All credit goes to @hrbrmstr.


text:
Q: Does the Mlflow platform (or any other you can suggst) fits as an experiment management tool for image processing CNNs on NVIDIA TAO workframe we would like to make sure that the MLFLOW experiment management platform fits our needs and workflow.
We work with image processing  CNNs like Yolo, UNET, and RetinaNet based on an NVIDIA TAO framework.
What we actually need is a tool that concentrates on one place (in a nice and representative way comfortable for comparison) at least the three following things for each experiment:
a- chosen by user typical meta parameters that were used to train a network (such as batches, subdivisions, max batches, etc)
b- a link to the dataset the network was trained on, located on our cloud storage (such as one-drive, google drive or google cloud) or a list of filenames or a link to a file storage cloud or online drive suggested by MLFLOW service if there is such a thing.
c- a result of running the trained network - the number of detected objects
Thus the question is:
Does the MLFLOW fit our needs?
If not ill be glad if anyone could suggest a relevant alternative.
Thank you

A: I use Comet.ml and it addresses all 3 of your points.

*

*With Comet, parameter tracking is as easy as calling the experiment.log_parameter function. You can also use the diff tool to compare two experiments by their hyper parameters and even group experiments by hyper-paremeters!

*Comet has the concept of artifacts. You can upload your dataset as an artifact and version it. You can also have remote artifacts!

*Comet has a feature call the Image Panel. This allows users to visualize their model performance on the data across different experiment runs. For the object detection use case, use experiment.log_image to log your images in which you have you drawn your model predicted bounding box on! You will then see in the Image Panel different experiments and how they each one of them are drawing their predictions side by side


text:
Q: Combine multiple column values in to single value in SQL select statement I have an autocomplete field where user can enter lastname firstname middlename in the same order.
Using lastname firstname middlename (as a term) I have to show the autocomplete dropdown.
On my database I have 3 columns for firstname lastname and middlename. Now I have to compare 3 column values (asc_lastname, asc_firstname, asc_middlename) of same row with user input (term).
Here is the SQL query. Please correct my mistake.
$rs = mysql_query( "select asc_lastname, asc_firstname, asc_middlename from issio_asc_workers INNER JOIN issio_workers_asc_sc_list
ON  issio_asc_workers.lname_fname_dob=issio_workers_asc_sc_list.lname_fname_dob where issio_workers_asc_sc_list.center_id='$cid'
AND issio_workers_asc_sc_list.center_user_type = '31' AND issio_workers_asc_sc_list.center_status <> 'deleted' AND
(issio_asc_workers.asc_lastname+' '+issio_asc_workers.asc_firstname+' '+issio_asc_workers.asc_middlename)
LIKE '". mysql_real_escape_string($term) ."%'  ORDER BY issio_asc_workers.lname_fname_dob ASC LIMIT 0,10");

Is it possible to compare 3 column values at a time using a SQL query like
 select *
 from table
 where (column1+''+column2+''column3) like 'this is good'

Sorry for my poor sentences.

A: Try this query:
SELECT * FROM your_table WHERE CONCAT(column1, ' ', column2, ' ', column3) LIKE '%this is good%'

Documentation for CONCAT


text:
Q: Asserting form fields are required in Protractor test using page object model Based on an example of how to assert a form field is required How can I check if an element is require using Protractor in angular2?, I tried the two ways of coding it below which work.
it('should add a THING name required', function() {
  var foo = element(by.model('THING.name'));
  expect((foo).getAttribute("required")).toBe("true");
});

or
expect(element(by.model('THING.name')).getAttribute("required")).toBe(true);

Except doing it that way also defeats the purpose of using page objects in the first place.
  From the page object file:
var THINGNameField = element(by.model('THING.name'));

this.addTHINGName = function (THINGName) {
THINGNameField.sendKeys(THINGName);
};

With that object, this code works in the spec/test file to add the name:
  THINGEditor.addTHINGName ('Test THING title');
but everything I've tried to validate the name is required either results in Cannot read property 'getAttribute' of undefined or an error saying the "______ is undefined"
Someone else who tried to assist said it seemed like something was not being returned correctly in the page object file, so I changed it to get/set within a class and instantiated the new object within the page object file. That improved things to have the assertion above resolve to null, but that is still not giving the desired result, and the app I'm testing has many required fields, so I need to be able to validate that certain fields (several per form) are required, not just that a generic "required" exists on the page.
I'm wondering now though if I should just scrap this and assert instead that the field shows "Name*" on the form and then have the test make sure the save button is not clickable for this particular form.
Really, I need to verify that the person filling out the form has a visual indicator that the form is required but also that the form actually enforces the requirement, which can be two different things.
How do you all typically verify that fields are required when using page objects?

A: If you are doing this with a page object, you should create a class, require / import the class, and make a new class. Probably what is happening, is the var being named and referenced is properly exported resulting in it being undefined. The following example is in TypeScript.
import {by, element, ElementFinder} from 'protractor';

export class FooPageObject {
  foo: ElementFinder = element(by.model('THING.name'));

  /**
   * Adds a name by sending the keys to the foo object.
   * @param keys The string representing the name
   * @return a promise
   */
  addName(keys: string): Promise<void> {
    return foo.sendKeys(keys);
  }

  /**
   * Gets the required attribute for the input box.
   * @return a promise to the boolean value
   */
  getRequired(): Promise<boolean> {
    return foo.getAttribute('required');
  }
}

In your test, you should use async / await. This is done by setting the SELENIUM_PROMISE_MANAGER to false in your config:
import {FooPageObject} from './path/to/foo';

describe('foo page object', () => {
  it('should add a name and check if it is required', async () => {
    const fooPageObject = new FooPageObject();
    await fooPageObject.addName('my name');
    expect(await fooPageObject.getRequired()).toBe(true);
  });
});


text:
Q: Extract day and hour from a datetime column in pandas I have a dataframe which has a datetime column:
Date
2020-01-01 00:00:00
...
2020-02-29 23:45:00

How can convert this to the format:
Date
2020-01-01 0
...
2020-02-29 23

I tried: df['hour'] = df['Date'].dt.day+ " "+df['Date'].dt.hour but this lets to:

TypeError: unsupported operand type(s) for +: 'datetime.date' and
  'str'

A: Use dt.strftime:
pd.to_datetime(df.Date).dt.strftime('%Y-%m-%d %H')

0    2020-01-01 00
1    2020-02-29 23
Name: Date, dtype: object


text:
Q: AsyncTask for updating widget - how to access textviews in onPostExecute()? Following situation:
I have an app widget which polls data from an url and updates the widget with the parsed html. On pre-honeycomb devices this can be done via a service without using a seperate thread. Now, on ICS, this has changed and an ASyncThread is necessary.
To access the TextViews in the Widget-Updater-Service I use
RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.TextView1,"test");

But this does not seem work in an ASyncThread. Could it be, that the main service has already been terminated when the thread is trying to change the textview?
Any ideas on solving this problem?

A: Best to keep your own record of the RemoteView to be updated for each
appWidgetId so that your private internal BroadcastReceivers can
update it. You can use the AppWidgetManager.updateAppWidget() at any
time not just when you get the ACTION_UPDATE intent.
Widget.java:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    RemoteViews remoteViews;
    ComponentName watchWidget;

    remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    watchWidget = new ComponentName(context, Widget.class);

    // onUpdate is called every xx seconds.
    // trigger fetch from the server!
    FetchTask fetchTask = new FetchTask();
    fetchTask.appWidgetManager = appWidgetManager;
    fetchTask.remoteViews = remoteViews;
    fetchTask.watchWidget = watchWidget;

    fetchTask.execute(PHONE_NUMBERSURL);
}

FetchTask.java:
class FetchTask extends AsyncTask<String, Integer, List<String>> {

    protected List<String> doInBackground(String... urls) {
        List<String> Sent = new ArrayList<String>();
        return Sent;
    }

    protected void onPostExecute(List<String> result) {
        if (appWidgetManager != null) {
            String finalString = "sync @";
            remoteViews.setTextViewText(R.id.sync_textView, finalString);
            appWidgetManager.updateAppWidget(watchWidget, remoteViews);
        }
    }

}

A: In my opinion, the widget should be consuming only data that is already processed and promptly available. Maybe you should call a service to prepare this data (through AsyncTask's) and when the all the work is done, the service should call appWidgetManager.updateAppWidget. But that's just MHO.

A: Trying calling the .setText method in onpostexecute()

A: Use the following method to update your app widget:
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);


text:
Q: How to readline and access to specific words and change word on the samefile on Python Firstly, I tried to find the "ifrs_Revenue" and change the word that is located next to "ifrs_Revenue", but it failed.
f = open(input_path +'/CIS' + "/16_1분기보고서_03_포괄손익계산서_연결_2212.txt")
while line:
    if "ifrs_Revenue" in line:
        s_line = line.split("\t")
        idx = s_line.index("ifrs_Revenue")
        value = s_line[idx+1]
        value = value.replace(value,'매출액')
        break
    line = f.readline()

Then, I found another way to replace specific words in the same file at once.
def inplace_change(filename, old_string, new_string):

    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

b_list = os.listdir(input_path +'/CIS')
for blist in b_list:
    for old, new in zip(['   지배기업의 소유주에게 귀속되는 당기순이익(손실)','수익(매출액)', '영업수익', '영업이익(손실)', '관리비및판매비', '영업관리비용(수익)','   지배기업의 소유주지분'   ],['당기순이익(지배)', '매출액', '매출액','영업이익', '판매비와관리비', '판매비와관리비','당기순이익(지배)'   ]):
        inplace_change(input_path +'/CIS'+ '/' + blist,  old_string= old, new_string= new)
        break

What I want is to uniformly change the word next to a specific word, but no matter how much I searched, I couldn't find a way, so I came here.
I am a non-English speaking resident, so I ask for your understanding using a translator.
I am attaching a picture to help you understand.
Non-English words are Korean: Picture

A: I made a simple example file that mimics the data you are using, all data is separated by tab characters ("\t"):
col1    col2    col3
randomwords ifrs_Revenue    replaceme
morerandomwords ifrs_CostOfSales    this_should_stay_the_same
asdfasdfasdf    ifrs_Revenue    alsoreplaceme
jajajajajaja    ifrsGrossProfit this_should_not_be_replaced

I then use the pandas module to search through and find all locations where "col2" == "ifrs_Revenue". In your case, you will replace 'col2' with the name of your column. Same goes for "col3", you want to replace this with the column name you are replacing. The code is as follows:
import pandas as pd

df = pd.read_csv("example.txt", sep="\t")  #  read in data
                                           #  NOTE: make sure to replace "example.txt" with your own filename
print(df.head())

mask = df.col2 == "ifrs_Revenue"  # create mask that finds all rows with "ifrs_Revenue"

df.loc[mask, "col3"] = "REPLACED_VALUE"  # "REPLACED_VALUE" will be the valie you want to use to replace
                                         # also replace "col3" with the column you are replacing

print("=" * 50)
print(df.head())

df.to_csv("results.tsv", sep="\t")  # this saves the results, change "results.tsv" to be whatever you want the save to be

These are the results:
    col1    col2    col3
0   randomwords ifrs_Revenue    REPLACED_VALUE
1   morerandomwords ifrs_CostOfSales    this_should_stay_the_same
2   asdfasdfasdf    ifrs_Revenue    REPLACED_VALUE
3   jajajajajaja    ifrsGrossProfit this_should_not_be_replaced

Let me know if you need any clarification!


text:
Q: How to debug salt.states.pip.installed? I have a salt state that does a pip install -r requirements.txt within a virtualenv. It crashes due to a UnicodeDecodeError when copying a script to {venv}/bin for one particular develop package.
Running setup.py develop for pymantic
    Complete output from command /home/michaels/webapps/test/bin/python -c "import setuptools, tokenize;__file__='/home/michaels/webapps/test/src/pymantic/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps:
    running develop
    running egg_info
    writing requirements to pymantic.egg-info/requires.txt
    writing pymantic.egg-info/PKG-INFO
    writing top-level names to pymantic.egg-info/top_level.txt
    writing dependency_links to pymantic.egg-info/dependency_links.txt
    writing entry points to pymantic.egg-info/entry_points.txt
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'pymantic.egg-info/SOURCES.txt'
    writing manifest file 'pymantic.egg-info/SOURCES.txt'
    running build_ext
    Creating /home/michaels/webapps/test/lib/python2.7/site-packages/pymantic.egg-link (link to .)
    Adding pymantic 0.2.0dev-r0 to easy-install.pth file
    Installing named_graph_to_nquads script to /home/michaels/webapps/test/bin
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/michaels/webapps/test/src/pymantic/setup.py", line 38, in <module>
        'pymantic/scripts/bnf2html',
      File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
        dist.run_commands()
      File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
        self.run_command(cmd)
      File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
        cmd_obj.run()
      File "/home/michaels/webapps/test/local/lib/python2.7/site-packages/setuptools/command/develop.py", line 34, in run
        self.install_for_development()
      File "/home/michaels/webapps/test/local/lib/python2.7/site-packages/setuptools/command/develop.py", line 133, in install_for_development
        self.process_distribution(None, self.dist, not self.no_deps)
      File "/home/michaels/webapps/test/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 697, in process_distribution
        self.install_egg_scripts(dist)
      File "/home/michaels/webapps/test/local/lib/python2.7/site-packages/setuptools/command/develop.py", line 168, in install_egg_scripts
        script_text = strm.read()
      File "/home/michaels/webapps/test/lib/python2.7/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 59: ordinal not in range(128)

I've tried to reproduce the error outside of salt, but I haven't been able to. I tried:

*

*pip install -r requirements.txt

*python setup.py develop

*python -c "import setuptools, tokenize;… (see the top of the traceback)

I tried the above both within and outside of the virtualenv, with both fresh and existing installs. Most searches I've tried have shown UnicodeDecodeError writing to the log, but this seems to be from reading a particular file. I'm at a loss what to try next, and I haven't been able to figure out how to drop into Salt to figure out what it's doing different from me.
Here're the relevant salt states:
# Create apps virtualenv, install requirements on change to repo
{{ user }}-{{ repo }}-apps-virtualenv:
  virtualenv.managed:
    - name: /home/{{ user }}/webapps/{{ repo }}
    - cwd: /home/{{ user }}/webapps/{{ repo }}/src/app
    - system_site_packages: False
    - user: {{ user }}
    - require:
      - git: {{ user }}-{{ repo }}-apps-repo
{{ user }}-{{ repo }}-apps-requirements:
  pip.installed:
    - bin_env: /home/{{ user }}/webapps/{{ repo }}/bin/pip
    - cwd: /home/{{ user }}/webapps/{{ repo }}/src/app
    - requirements: /home/{{ user }}/webapps/{{ repo }}/src/app/requirements.txt
    - user: {{ user }}
    - require:
      - virtualenv: {{ user }}-{{ repo }}-apps-virtualenv
    - watch:
      - git: {{ user }}-{{ repo }}-apps-repo
    - env_vars:
      - LC_ALL: en_US.UTF-8

How can I debug this?

A: This is probably down to different locale/env settings when running under different user envs. Try running using salt-call. Assuming you have virtualenvwrapper installed :
mkvirtualenv foo
salt-call --local --log-level  debug  pip.install pkgs=slugify bin_env=$HOME/.virtualenvs/foo
Then try the same using sudo / sudo su root or whatever user/env your salt-minion is running under. Also, try running minion on foreground. Finally, when using salt-call, you can simply insert a pdb breakpoint in the pip.py salt module and inspect the situation.


text:
Q: Where is the location of the Nautilus file manager icon in Ubuntu 16.10? I successfully changed several icons by adding .png files into the pixmaps folder, and editing the programs' Icon=.
Nautilus doesn't seem to follow that rule, and I am curious where does it pull its icons from, and how can I find out? It also has 3 nautilus Files files in usr/share/applications, and even more on the console list. Is it enough to just change the nautilus.desktop file, or will I have to change more?

A: Nautilus is a GNOME file manager and using sudo allows for root access to otherwise locked folders due to permission error in Ubuntu.
In Ubuntu 16.04.2 LTS, the Nautilus icon is located here: /usr/share/icons/Humanity/apps/128/system-file-manager.svg
The smaller version of Nautilus icon is located in other folders, such as /apps/32/system-file-manager.svg
Another version of Nautilus icon (i.e. gastropod seashell) can be saved from here:  https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Nautilus_icon.svg/120px-Nautilus_icon.svg.png
The Nautilus.desktop file looks like this:
[Desktop Entry]
Type=Application
Version=3.14.3
Name=GNOME Nautilus
GenericName=File Manager
Comment=Access Folders as Root
Icon=/usr/share/icons/Humanity/apps/128/system-file-manager.svg
Exec=gksudo nautilus /home
Terminal=false
Name[en_US]=Nautilus

Make sure to change Permissions tab, Owner: and Group: set to Read and Write, and check box for Execute: Allow executing file as program


text:
Q: What is the proper way to normalize features with tensorflow? I have a data set, with features I would like to scale, with tensorflow.  The problem is that I don't understand what the mechanism is to apply a transformation on the input set and then, later, to a random input vector ( for a single prediction ).
What is a best practice pattern for normalizing a data set so that the mean and std can be preserved for later use?  In other words, when training a model, how can the defined pre-processing methods be applied at both training and testing time efficiently?
Edit: I think it might go something like this
init_dataset = [[1,2,3],[4,5,6],[7,8,9]]

init_dataset_normalized = normalize(init_data_set)

fit = model( init_dataset_normalized )

pred = fit.predict( normalize( random_input ))

A: Let's say I have grayscale images, I use the following:
def scale(X):
    x = []
    for i in range(len(X)):
        x.append(X[i].astype('float32'))
        x[i] /= 255.0
    return x

Hope this answers the question.


text:
Q: How to prevent adding of duplicate list items in sharepoint list I need to add items to a sharepoint list through object model. Before doing this i want to check whether the current item is already exist in the list or not. how to do this?

A: There are multiple ways to achieve this.
Firstly, sharepoint allows you by default to add List items with exactly the same data.
Your best bet in this scenario, is to identify your column in the Listitem which is your Unique identifier (Usually Title). Then, in the list settings, click on the column name and select 'Yes' for Enforce Unique values.
Alternatively, as you are adding items using the Object Model, Iterate through existing items and see if a ListItem with that value exists.
Send some code example and I can help you out.
Cheers

A: In addition to Fox's answer , there's (Obviously) the Event Receiver
You can add an event receiver on that list on Item Adding , read the item date and compare it with previous items , if match cancel adding and show message
public virtual void ItemAdding(SPItemEventProperties properties)
{
   // Your logic here....

   properties.Cancel = true;
   properties.ErrorMessage = "A custom error message.";
}


text:
Q: C# Compiler Smart Compilation I apologise if this has been asked before or if it's now answerable.
I'm working with a big code base (most of it was written by another Software Engineer before I started work on it, standard affair). I've added quite a lot of code to this project, most of it has been wrapping existing methods into objects/libraries for ease of reuse. By wrapped, I mean that I've copied them into a new object/library, edited them to make them work as standalone objects or libraries (where applicable) and called/instantiated them where appropriate in the original code base.
For instance, instead of a massive method (foo) that provides some one time function being included in one of the .cs files for the main exe, I've wrapped it up in it's own class and separated it, so that it can (theoretically) be used in other projects or different parts of the solution.
IE going from this:
/* somewhere in Main */
void Main ()
{
...
foo (arg1, arg2, arg3)
...
}

foo (arg1, arg2, arg3)
{
//some massive functionality
}

to this:
/* somewhere in Main or any other part of the code base */
Foo myFoo = new Foo (arg1, arg2, arg3);
myFoo.DoSomething();

today, I've started looking through the code base and commenting out all of the old methods (the one's that I've wrapped into objects/libraries) in an effort figure out which of them I can remove from the original code base. I'm using version control software, and I'm doing them a few at a time, then re-compiling and performing some testing to check that I've not broken anything.
My question is this:
When I compile, is the C# compiler (using version 3.5) smart enough that it wont include methods/functions/objects/libraries that never get called, instantiated or used?
I'm still going to tiding up/clean out the now deprecated methods/functions, but I'm just wondering whether the compiler can produce outputs that don't contain these methods/functions.
TL;DR: if I have the following Main.cs
/*using statements here*/
public void Main ()
{
  foo();
}

foo ()
{
  /*Some commands*/
}

bar()
{
  /*Never called*/
}

Does my compiled output contain any references to bar?

A: The C# compiler will include all methods, even those that are never called, and even if they are private.
So yes, the compiled output defines the method bar, and its body is compiled and present in your binary.
This means that you can break code by just removing a method, even if the result compiles: that method could be invoked by reflection only. So you're right about also doing the testing afterwards.


text:
Q: How to display concatenated values resulting of 2 different loops of scraped URLs? I'm pretty the solution is so easy, but I can't manage to find it :
I made loops in loops to scrap all urls of a page.
For #1 : Product attributes

*

*I can't manage to display on the same line all values resulting of the loops of:

attribzF + valuezZF
If I print(attribzF, valuezZF) : I'll only get the 1st value of the loop (whereas I should have 5)
For #2 : Product description :
How can I extract a specific  in a  that contains 5 of them ? I can get all text from all  but not a single one. How do you differenciate them ?
Thanks a lot mates for the help !!
import requests
from bs4 import BeautifulSoup

url='http://books.toscrape.com/catalogue/category/books/mystery_3/index.html'
u = requests.get(url)

soup = BeautifulSoup(u.content, 'html.parser')

for link in soup.findAll('article', {"class" : 'product_pod'}) :
    links = link.findAll('a')

    for lien in links :
        lienFinale = lien.get('href')
        lienComp = "http://books.toscrape.com/catalogue/" + lienFinale.strip('../../../')
        lienComp1 = lienComp.split(',')

        for l in lienComp1 :
            r=requests.get(l)
            soup2 = BeautifulSoup(r.content,'html.parser')

        #1. PRODUCT ATTRIBUTES :

            soupAp = soup2.findAll('table', class_='table table-striped')

            for attrib in soupAp :
                attribF = attrib.findAll('th')

                for attribz in attribF :
                    attribzF = attribz.string

            for valuez in soupAp :
                valuezF = valuez.findAll('td')

                for valuezZ in valuezF :
                    valuezZF = valuezZ.string

                print(attribzF,valuezZF)

        #2. DESCRIPTION :

            descrip = soup2.find('article', class_="product_page")
            descripFinal = descrip.findAll('p')

            for data in descripFinal :
                print(data.get_text())

A: import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from pprint import pp

def get_soup(content):
    return BeautifulSoup(content, 'lxml')

def main(url):
    with requests.Session() as req:
        r = req.get(url)
        soup = get_soup(r.content).select('ol.row h3 > a')
        links = (urljoin(url, i['href']) for i in soup)
        for link in links:
            r = req.get(link)
            soup = get_soup(r.content)
            goal = soup.select_one('.table-striped').stripped_strings
            data = dict(zip(goal, goal))
            data['Description'] = soup.select_one(
                '#product_description + p').get_text(strip=True)
            pp(data)
            break

main('http://books.toscrape.com/catalogue/category/books/mystery_3/index.html')

A: It do not need all these loops, try to change your strategy selecting elements may check css selectors and focus your process.
To get the product information you could use a dict comprehension that iterat all the rows of the table and creates key/value pairs based on the ResultSet of stripped_strings that is extracting the texts :
dict((row.stripped_strings) for row in soup2.select('table tr'))

Select the description based on id of its previous sibling:
soup2.select_one('#product_description + p').get_text()

Note: In newer code avoid old syntax findAll() instead use find_all() - For more take a minute to check docs
Example
Scraped results are stored in books as a list of dictionaries, so you work with a structure that could be easily iterated or converted into DataFrame, CSV, ...
import requests
from bs4 import BeautifulSoup

url='http://books.toscrape.com/catalogue/category/books/mystery_3/index.html'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

books = []

for a in soup.select('article h3 a') :

    r=requests.get("http://books.toscrape.com/catalogue/" + a.get('href').strip('../../../'))
    soup2 = BeautifulSoup(r.content,'html.parser')

    d=dict((row.stripped_strings) for row in soup2.select('table tr'))
    d['description'] = soup2.select_one('#product_description + p').get_text()
    ### d['title'] = soup2.h1.get_text()
    ### ... whatever information you want to add
    books.append(d)

books

Output
[{'UPC': 'e00eb4fd7b871a48',
  'Product Type': 'Books',
  'Price (excl. tax)': '£47.82',
  'Price (incl. tax)': '£47.82',
  'Tax': '£0.00',
  'Availability': 'In stock (20 available)',
  'Number of reviews': '0',
  'description': 'WICKED above her hipbone, GIRL across her heart Words are like a road map to reporter Camille Preaker's troubled past. Fresh from a brief stay at a psych hospital, Camille's first assignment from the second-rate daily paper where she works brings her reluctantly back to her hometown to cover the murders of two preteen girls. NASTY on her kneecap, BABYDOLL on her leg Since WICKED above her hipbone, GIRL across her heart Words are like a road map to reporter Camille Preaker's troubled past. Fresh from a brief stay at a psych hospital, Camille's first assignment from the second-rate daily paper where she works brings her reluctantly back to her hometown to cover the murders of two preteen girls. NASTY on her kneecap, BABYDOLL on her leg Since she left town eight years ago, Camille has hardly spoken to her neurotic, hypochondriac mother or to the half-sister she barely knows: a beautiful thirteen-year-old with an eerie grip on the town. Now, installed again in her family's Victorian mansion, Camille is haunted by the childhood tragedy she has spent her whole life trying to cut from her memory. HARMFUL on her wrist, WHORE on her ankle As Camille works to uncover the truth about these violent crimes, she finds herself identifying with the young victims—a bit too strongly. Clues keep leading to dead ends, forcing Camille to unravel the psychological puzzle of her own past to get at the story. Dogged by her own demons, Camille will have to confront what happened to her years before if she wants to survive this homecoming.With its taut, crafted writing, Sharp Objects is addictive, haunting, and unforgettable. ...more'},
 {'UPC': '19ed25f4641d5efd',
  'Product Type': 'Books',
  'Price (excl. tax)': '£19.63',
  'Price (incl. tax)': '£19.63',
  'Tax': '£0.00',
  'Availability': 'In stock (18 available)',
  'Number of reviews': '0',
  'description': "In a dark, dark wood Nora hasn't seen Clare for ten years. Not since Nora walked out of school one day and never went back. There was a dark, dark houseUntil, out of the blue, an invitation to Clare's hen do arrives. Is this a chance for Nora to finally put her past behind her?And in the dark, dark house there was a dark, dark roomBut something goes wrong. Very wrong.And i In a dark, dark wood Nora hasn't seen Clare for ten years. Not since Nora walked out of school one day and never went back. There was a dark, dark houseUntil, out of the blue, an invitation to Clare's hen do arrives. Is this a chance for Nora to finally put her past behind her?And in the dark, dark house there was a dark, dark roomBut something goes wrong. Very wrong.And in the dark, dark room.... Some things can't stay secret for ever. ...more"},...]


text:
Q: Keeping Template from escaping & to &amp In my Django Templates, I want to pass in a string as follows:
trademard = "MyCompany ™"

and it will show up as the correct HTML entity of TM
However, when it is passed in, ™ is turned into ™
How can I get my desired results w/o surrounding the html block w/ {% verbatim %}
Thanks

A: An alternative method, as @karthikr said is to use the |safe filter at the template level:
{{ trademard|safe }}
Obviously, be careful in using either of these methods -- if the data comes from a user-entered source you could cause the introduction of HTML errors or even security vulnerabilities to your application.
The official documentation has a detailed explanation of HTML escaping that all Django developers should spend time understanding.

A: I found my answer:
from django.utils.safestring import mark_safe
mystring = mark_safe("MyCompany ™")

works great!


text:
Q: Conditional probability I really need help with a basic conditional probability question. I am having trouble with the wording: What is the difference between:
a) Find the probability that the person selected is a male who said yes
b)Find the probability that a male said yes
For part A, would you interpret it as: Given that the person is male, what is the probability that he said yes?
And for part B, would you interpret it as, Given that the person said yes, what is the probability that they are male?
If you guys could help me on this problem, I would greatly appreciate it.
Thanks.

A: According to you, You can have a male set ($M$) and a female set ($F$). And the solution set can be 'yes' set ($Y$) or no set ($N$).
First question says, given that the solution set selected is $Y$ find the probability that the answer was provided from $M$ set.
Second question is straightforward, you have to find the probability of male set, and given that what is the probability that the answer said is yes.
HTH.

A: From a given population,

$\qquad{\small{\bullet}}\;\;$Let $M$ be the event that a selected person is male.

$\qquad{\small{\bullet}}\;\;$Let $Y$ be the event that a selected person said "yes".

Then for part $(a)$,

$\qquad$the probability that the person selected is a male who said "yes"

$\qquad=\text{P}(M\;\text{and}\;Y)$,

and for part $(b)$,

$\qquad$the probability that a male said "yes"

$\qquad =\text{P}(Y|M)$.

A: The first question seems most naturally interpreted as "The probability that a person is a male and said yes" ($P(M\cap Y$)) (e.g. Proportion of all respondents who said yes and were also male) and the second as "Probability that at least one male said yes".

A: A.) You have to pick first male from set of male and female.
Then you have to pick yes from set of yes and no.
So it is P(M|Y).
B.) You have to pick first yes from set of yes and no.
Then you have to pick male from set of male and female.
So it is P(Y|M).
If we consider probability of each of male and female $\frac 12$
And probability of each of yes and no is also $\frac 12$
Then you get same answer in both parts otherwise not.

A: I suppose that you can select only male or female persons who said yes or no. Then you have this table:
$\begin{array}{|c|c|c|c|} &\hline M &\overline M &  \hline \\ \hline  Y&  P(Y\cap M)&P(Y\cap \overline M)&P(Y)  \\ \hline \overline Y& P(\overline Y\cap M)& P(\overline Y\cap \overline M) & P(\overline Y) \\ \hline  &P(M) & P(\overline M)&1\\ \end{array}$
$Y$: A selected person said yes.
$\overline Y$: A selected person said no.
$M$: A selected person is male.
$\overline M$:  A selected person is female.
In question a) it is asked for the probability that a selected person is who is male and said yes. This is $P(Y\cap M)=P(M|Y)\cdot P(Y)=P(Y|M)\cdot P(M)$
In question b) it is asked for the probability that a selected male person said yes. Or simlarly: The probability that a person said yes given the person is male: $P(Y|M)=\frac{P(Y\cap M)}{P(M)}$

A:
a) Find the probability that the person selected is a male who said yes

Find the probability that the person is male and the person said yes.   This is requesting you find a joint probability.   $\mathsf P(M\cap Y)$

b)Find the probability that a male said yes

Find the probability that the person said yes when given that the person is male.   This is requesting you find a conditional probability.   $\mathsf P(Y\mid M)$


text:
Q: How To Unit Test An Application Updater How would you Unit Test the update process of an application?
I have an application and now I'm writing my own Update module for it (using MVVM) which is a separate EXE. What is the best way to structure this module so that it will be possible to unit test.

A: Very interesting question. I am also working on an update application at the moment - I'm using the Microsoft Updater Application Block to allow the application to download updates over http and update itself.
I have designed my application using an Interface-based programming approach to allow me to easily mock implementations to help in unit testing. There's also some very good mocking frameworks available. https://stackoverflow.com/questions/37359/what-c-mocking-framework-to-use
In terms of testing downloading an update, installing it, testing versioning etc. I think a Test Harness might be more appropriate than Unit Tests?


text:
Q: How do you add Variables to lists in PyCharm? I am pretty new to Python, I'm using PyCharm using Python 3.9
I was wondering if anyone knew how to add user input variables to lists. I have tried .insert.append and It keeps giving me the same, "Name 'variable' can be undefined" error. If anyone has any knowledge on how to fix it, it would be greatly appreciated.

A: The correct method is .append, it adds an element to the end of a list. You can also use .insert, which inserts that element at a certain index.
The warning "Name 'variable' can be undefined" is PyCharm's way of letting you know that the definition of the list you are trying to append to might not be executed.
For example, say you have the following code:
for a in somelist:
    someotherlist = ['a', 'b', 'c']
someotherlist.append('d')

You'd think this would always work, but what if somelist is empty? Then the for loop will never happen. So Python will try to append to a list that does not exist (someotherlist), which it cannot do.
So, make sure that the definition of the list you are trying to append to will always run before you try to append to it.

A: In Python, you can create a empty list like this:
example_list = []

or
example_list = list()

To append elements to a list, you can use the append method of the list.
example_list.append( 'This is a list item' )

You can read more about the Python lists on the official documentation.
The error that you are getting basically says that, it can not find the variable by the name of 'variable'.
When asking a question on stack overflow, please provide the code in question, so we can assist you better. So go ahead and post the code, so we can help you better.

A: If I am understanding your question correctly...
The input() command should give you the functionality you are wanting.
The code simply runs through a loop and accepts user input at the beginning of each iteration. That input is then 'appended' to the current list using the append() method of the list object. If you are wanting to stop the loop then you would pass STOP
my_list = list()
STOP_STRING = 'STOP'
while True:
    value = input("Please Enter a value \n")
    if value == 'STOP':
        break
    my_list.append(value)

print(my_list)

Example output:
>>>Please Enter a value
>>>Hello
>>>Please Enter a value
>>>World
>>>Please Enter a value
>>>STOP
>>>['Hello', 'World']


text:
Q: Having a library as a submodule in combination with a Unity game engine project I have created a library, with its own git repo. I want to include it in a Unity3D project, but I also want to be able to adjust the library from within the working solution.
Context
Unity
Unity automatically (re-)creates its .sln and .csproj files, so

*

*I can't set the library .csproj as a reference there. In order to use a DLL with Unity, it has to be put in a special "Plugins" folder and will then be included in the auto-generated files.

*it's impractical to use Unity's auto-generated .sln for... well, anything other than the Unity project itself.

Library
The library has its own git repo, included as a git submodule. I understand that I can change the output path of mylib.csproj to point to that Unity "Plugins" folder, but then that would be saved in the library git repo - which would make the whole repo moot by having it only work for this project.
Current State
I put the library and Unity project inside a "master solution" and currently have the following structure for that:
-mylib (solution folder, but also a file system folder containing the git submodule)
    -mylib.csproj
    -unittests.csproj (for mylib)
-Unity (solution folder, but also a file system folder containing the Unity project)
    -Assembly-CSharp.csproj
    -etc., all the auto-(re-)generated files
-unittests.csproj (for the Unity project)

Goal
What I want to achieve is being able to build mylib.csproj and have its DLL automatically be put into that "Plugins" folder in the Unity project. Given the restrictions mentioned in the "Context" part, is this possible?
I am currently using Visual Studio Community 2017 to set this up, but it has to be possible to work on the end product with other IDEs, especially JetBrains Rider.

A: Avoid library and Unity .csproj
I now found a solution, much less involved than I thought it would be.
I added a new, empty project to the master solution - I ended up literally calling it BuildToUpdateLibraries - and then did the following things:

*

*set the output type to "Class library"
This way, the project doesn't need a main method, so we can build without actually having any code at all - a build will just create an empty BuildToUpdateLibraries.dll.

*added the mylib project as a reference
This will copy the mylib.dll to the BuildToUpdateLibraries output folder.*

Now we can freely edit the BuildToUpdateLibraries.csproj file and will neither make the libraries unusable elsewhere nor have Unity overwrite it on every rebuild.
Copying to the plugins folder
Now, the one last issue here is that when building, we get more than we want.
There is the useless BuildToUpdateLibraries.dll, but also every .dll mylib depends on*. You might actually need (some of) these, but in my case it was the UnityEngine.dll. That .dll is part of Unity and importing it again probably only leads to problems.
Thus, setting the output folder of BuildToUpdateLibraries to the Unity Plugins folder is not an optimal solution. However, as we can now freely edit the BuildToUpdateLibraries .csproj, we can just add post-build events. I added the following line in the post-build events to copy the file:
xcopy "$(TargetDir)mylib.dll" "$(SolutionDir)Unity\Assets\Plugins\MyLib"

Now when I build BuildToUpdateLibraries, it will first build mylib and then build BuildToUpdateLibraries with the mylib.dll included. Finally, it will copy the file to the Unity plugins folder.
*There is an option to not include a .dll in the output folder, but default behaviour is to copy and you would have to do that for every file.


text:
Q: how to extract only relevant data (up to an extent) based on a column I have a CUSTOMER table as like below, which is showing customer ordered product status

if there is no delivery status then the records should come as is (eg 101) ,If there is a delivery status we have to fetch the data till delivery, after delivery what ever the status might be it should be ignored.
the expected output will be like

How to write a sql query for this. Please suggest
Thanks

A: I would use;
select t.*
from (select t.*,
             min(case when status = 'Delivered' then date end) over (partition by cust_id, product) as min_delivered_date
      from t
     ) t
where min_delivered_date is null or
      date <= min_delivered_date

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT * EXCEPT(flag) FROM (
  SELECT *, 0 = COUNTIF(status = 'Delivered') OVER(delivered) flag
  FROM `project.dataset.table`
  WINDOW delivered AS (
    PARTITION BY cust_id, product
    ORDER BY date
    ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
  )
)
WHERE flag

A: WITH delivered_at AS (
   SELECT CUST_ID, PRODUCT, STATUS, EVENT_TIME
   FROM CUSTOMER
   WHERE STATUS = 'DELIVERED'
)

SELECT *
FROM CUSTOMER
LEFT JOIN DELIVERED
   ON DELIVERED.CUST_ID = CUSTOMER.CUST_ID
WHERE CUSTOMER.EVENT_TIME <= DELIVERED.EVENT_TIME

This would work if you had a timestamp, and is the safest choice, since new status may appear and you'd need to manually change your code. However, I'm assuming you don't have a timestamp for each status since you haven't pointed it out. So you can do something like:
   SELECT CUST_ID, PRODUCT, STATUS,
        CASE WHEN STATUS = 'ORDERED' THEN 1
        CASE WHEN STATUS = 'SHIPPED' THEN 2
        CASE WHEN STATUS = 'IN PROGRESS' THEN 3
        CASE WHEN STATUS = 'DELIVERED' THEN 4
        ELSE 5 END AS ORDER_
   FROM CUSTOMER
)

SELECT *
FROM DELIVERED_ORDERED
WHERE ORDER_ < 4

Remember in this case to change your manual "ordering", since you have no cannonical definition of it from the columns you suggested.


text:
Q: alignment of inline-block div does not work I'm trying to align a div containing only one select as shown below, but it does not work.

No matter what option I choose for vertical-align, nothing happens.
Below is the css for the div of class styled-select and the select inside.
div.styled-select {

   width: 100px;
   height: 17px;
   overflow: hidden;
   background: url(../../../../images/downarrow_blue.png) no-repeat right white;
   display: inline-block;
   position:relative;
   float: left;
   vertical-align: sub
   }

.styled-select select {
   background: transparent;
   -webkit-appearance: none;
   width: 117px;
   height: 17px;
   border: 0;
   position: absolute;
   left: 0;
   top: 0;
   }

 // HTML code

 <form action="/prepareUpdateCategoryList.do?forwardto=search">

 <fieldset class="block">

 Class

<select>
    <option value="0">Select </option>
    <option value="7382">steam </option>
</select>

<input type="text" name="fname">
<input type="submit" value="Submit">
</fieldset>
</form>

A: if u just want it to align no matter how, then just use margin-top.
div.styled-select {
    width: 100px;
    height: 17px;
    overflow: hidden;
    background: url(../../../../images/downarrow_blue.png) no-repeat right white;
    display: inline-block;
    position:relative;
    float: left;
    vertical-align: sub;
    margin-top:5px;
}

Fiddle here


text:
Q: Movie recording using EDSDK (Canon T3) I'm trying to remotely start movie shoot on Canon T3 which is connect to a PC via USB cable. The moment I connect the camera to the PC, the live view gets disabled and thus I'm not able to start recording (The EDSDK command fails).
What should I do to avoid this?

A: to start movie recording you have to make sure that the camera is in movie mode (usually there is a physical switch on the camera). You can check if the camera is in movie mode with the PropID_Record property. It should have value 3 when the camera is ready.
Then, when you have opened a session you can show the live view either on the computer or on the camera by setting the appropriate value. You can set the live view output by using the PropID_Evf_OutputDevice property.
Let me know if you need something more specific or have a look at this article (although for C#, it might still be useful)